Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>
# SQLite in Python will complain if you try to use it from multiple threads.
# We create a threadlocal variable that contains the DB, lazily initialized.
osquery_mock_db = threading.local()
def assemble_configuration(node):
configuration = {}... | for file_path in node.file_paths.options(db.lazyload('*')): |
Predict the next line after this snippet: <|code_start|> for file_path in node.file_paths.options(db.lazyload('*')):
file_paths.update(file_path.to_dict())
return file_paths
def assemble_schedule(node):
schedule = {}
for query in node.queries.options(db.lazyload('*')):
schedule[query.na... | .join(DistributedQuery) \ |
Predict the next line after this snippet: <|code_start|> file_paths = {}
for file_path in node.file_paths.options(db.lazyload('*')):
file_paths.update(file_path.to_dict())
return file_paths
def assemble_schedule(node):
schedule = {}
for query in node.queries.options(db.lazyload('*')):
... | query = db.session.query(DistributedQueryTask) \ |
Predict the next line for this snippet: <|code_start|> map(itemgetter(0),
current_app.config['DOORMAN_CAPTURE_NODE_INFO']
)
)
if not capture_columns:
return
node_info = node.get('node_info', {})
orig_node_info = node_info.copy()
for _, action, columns, _, in ext... | node = Node.get_by_id(node['id']) |
Using the snippet: <|code_start|>def assemble_options(node):
options = {}
# https://github.com/facebook/osquery/issues/2048#issuecomment-219200524
if current_app.config['DOORMAN_EXPECTS_UNIQUE_HOST_ID']:
options['host_identifier'] = 'uuid'
else:
options['host_identifier'] = 'hostname'
... | .options(db.contains_eager(Pack.queries)).all(): |
Given snippet: <|code_start|>
def assemble_options(node):
options = {}
# https://github.com/facebook/osquery/issues/2048#issuecomment-219200524
if current_app.config['DOORMAN_EXPECTS_UNIQUE_HOST_ID']:
options['host_identifier'] = 'uuid'
else:
options['host_identifier'] = 'hostname'
... | for pack in node.packs.join(querypacks).join(Query) \ |
Given snippet: <|code_start|> for _, action, columns, _, in extract_results(result):
# only update columns common to both sets
for column in capture_columns & set(columns):
cvalue = node_info.get(column) # current value
value = columns.get(column)
if action == '... | yield ResultLog(name=name, |
Given snippet: <|code_start|>
def assemble_options(node):
options = {}
# https://github.com/facebook/osquery/issues/2048#issuecomment-219200524
if current_app.config['DOORMAN_EXPECTS_UNIQUE_HOST_ID']:
options['host_identifier'] = 'uuid'
else:
options['host_identifier'] = 'hostname'
... | for pack in node.packs.join(querypacks).join(Query) \ |
Here is a snippet: <|code_start|> db.session.add(self)
if commit:
db.session.commit()
return self
def delete(self, commit=True):
"""Remove the record from the database."""
db.session.delete(self)
return commit and db.session.commit()
class Model(CRUDMixi... | (isinstance(record_id, basestring) and record_id.isdigit(), |
Predict the next line after this snippet: <|code_start|> )
response = provider.get('https://www.googleapis.com/oauth2/v1/userinfo')
userinfo = response.json()
if not userinfo:
current_app.logger.error("No userinfo object returned!")
abort(500)
current_ap... | user = User.query.filter_by( |
Given the following code snippet before the placeholder: <|code_start|> params.update(node)
params.update(node.get('node_info', {}))
params.update(match.result['columns'])
subject = string.Template(
render_template(
subject_template,
prefix=sub... | return mail.send(message) |
Given snippet: <|code_start|> return User.get_by_id(int(user_id))
@ldap_manager.save_user
def save_user(dn, username, userdata, memberships):
user = User.query.filter_by(username=username).first()
kwargs = {}
kwargs['username'] = username
if 'givenName' in userdata:
kwargs['first_name'] = ... | form = LoginForm() |
Given snippet: <|code_start|> flash(u'Invalid username or password.', 'danger')
return render_template('login.html', form=form)
@blueprint.route('/logout')
def logout():
username = getattr(current_user, 'username', None)
oauth = False
logout_user()
# clear any oauth state
for key in ... | @csrf.exempt |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
try:
except ImportError:
blueprint = Blueprint('users', __name__)
@login_manager.user_loader
def load_user(user_id):
if current_app.config['DOORMAN_AUTH_METHOD'] is None:
return NoAuthUserMixin()
return User.get_by_id(int(user_id))
<|code... | @ldap_manager.save_user |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
try:
except ImportError:
blueprint = Blueprint('users', __name__)
<|code_end|>
, determine the next line of code. You have imports:
from urlparse import urlparse, urljoin
from urllib.parse import urlparse, urljoin
from flask import (
Blueprint... | @login_manager.user_loader |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
try:
except ImportError:
blueprint = Blueprint('users', __name__)
@login_manager.user_loader
def load_user(user_id):
if current_app.config['DOORMAN_AUTH_METHOD'] is None:
return NoAuthUserMixin()
<|code_end|>
, generate the next line using... | return User.get_by_id(int(user_id)) |
Given the following code snippet before the placeholder: <|code_start|> count=self.incident_count
)
description = match.rule.template.safe_substitute(
match.result['columns'],
**node
).rstrip()
description = ":".join(description.split('\r\n\r\n', 1))
... | }, cls=DateTimeEncoder) |
Continue the code snippet: <|code_start|> self.target_paths = '!!'.join(target_paths)
class ResultLog(SurrogatePK, Model):
name = Column(db.String, nullable=False)
timestamp = Column(db.DateTime, default=dt.datetime.utcnow)
action = Column(db.String)
columns = Column(JSONB)
node_id = refe... | Index('idx_%s_node_id_timestamp_desc' % cls.__tablename__, |
Given snippet: <|code_start|> 'query_packs',
Column('pack.id', db.Integer, ForeignKey('pack.id')),
Column('query.id', db.Integer, ForeignKey('query.id'))
)
pack_tags = Table(
'pack_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('pack.id', db.Integer, ForeignKey('pack.id'), ind... | class Tag(SurrogatePK, Model): |
Based on the snippet: <|code_start|> 'query_packs',
Column('pack.id', db.Integer, ForeignKey('pack.id')),
Column('query.id', db.Integer, ForeignKey('query.id'))
)
pack_tags = Table(
'pack_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('pack.id', db.Integer, ForeignKey('pack.id... | class Tag(SurrogatePK, Model): |
Here is a snippet: <|code_start|>
def __init__(self, category=None, target_paths=None, *args, **kwargs):
self.category = category
if target_paths is not None:
self.set_paths(*target_paths)
elif args:
self.set_paths(*args)
else:
self.target_paths =... | node_id = reference_col('node', nullable=False) |
Next line prediction: <|code_start|>
pack_tags = Table(
'pack_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('pack.id', db.Integer, ForeignKey('pack.id'), index=True)
)
node_tags = Table(
'node_tags',
Column('tag.id', db.Integer, ForeignKey('tag.id')),
Column('node.id', db.In... | nodes = relationship( |
Predict the next line for this snippet: <|code_start|>class DistributedQueryResult(SurrogatePK, Model):
columns = Column(JSONB)
timestamp = Column(db.DateTime, default=dt.datetime.utcnow)
distributed_query_task_id = reference_col('distributed_query_task', nullable=False)
distributed_query_task = relat... | alerters = Column(ARRAY(db.String), nullable=False) |
Given the following code snippet before the placeholder: <|code_start|>
def __repr__(self):
return '<Pack: {0.name}>'.format(self)
def to_dict(self):
queries = {}
discovery = []
for query in self.queries:
if 'discovery' in (t.value for t in query.tags):
... | node_info = Column(JSONB, default={}, nullable=False) |
Given snippet: <|code_start|> return '<Pack: {0.name}>'.format(self)
def to_dict(self):
queries = {}
discovery = []
for query in self.queries:
if 'discovery' in (t.value for t in query.tags):
discovery.append(query.sql)
else:
q... | last_ip = Column(INET, nullable=True) |
Predict the next line for this snippet: <|code_start|> return self.target_paths.split('!!')
def set_paths(self, *target_paths):
self.target_paths = '!!'.join(target_paths)
class ResultLog(SurrogatePK, Model):
name = Column(db.String, nullable=False)
timestamp = Column(db.DateTime, default... | @declared_attr |
Given the following code snippet before the placeholder: <|code_start|> )
class User(UserMixin, SurrogatePK, Model):
username = Column(db.String(80), unique=True, nullable=False)
email = Column(db.String)
password = Column(db.String, nullable=True)
created_at = Column(db.DateTime, nullable=Fa... | self.update(password=bcrypt.generate_password_hash(password)) |
Predict the next line for this snippet: <|code_start|>def api():
"""An api instance for the tests, no manager"""
# the mere presence of the env var should prevent the manage
# blueprint from being registered
os.environ['DOORMAN_NO_MANAGER'] = '1'
_app = create_app(config=TestConfig)
ctx = _app.... | _db.app = app |
Next line prediction: <|code_start|>
@pytest.fixture(scope='function')
def testapp(app):
"""A Webtest app."""
return TestApp(app)
@pytest.fixture(scope='function')
def testapi(api):
return TestApp(api)
@pytest.yield_fixture(scope='function')
def db(app):
"""A database for the tests."""
_db.app ... | node = NodeFactory(host_identifier='foobar', enroll_secret='foobar') |
Based on the snippet: <|code_start|>
@pytest.fixture(scope='function')
def testapi(api):
return TestApp(api)
@pytest.yield_fixture(scope='function')
def db(app):
"""A database for the tests."""
_db.app = app
with app.app_context():
_db.create_all()
yield _db
# Explicitly close DB con... | rule = RuleFactory( |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
class DJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return {
'__type__': '__datetime__',
'epoch': int(mktime(obj.timetuple()))
}
... | if not isinstance(s, string_types): |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
class TestCreateTagForm:
def test_tag_validate_failure(self, testapp):
form = CreateTagForm()
assert form.validate() is False
def test_tag_validate_success(self, testapp):
form = CreateTagForm(value='foo')
assert form... | form = CreateQueryForm( |
Next line prediction: <|code_start|> form = CreateTagForm(value='foo')
assert form.validate() is True
class TestCreateQueryForm:
def test_sql_validate_failure(self, testapp, db):
form = CreateQueryForm(
name='foobar',
sql='select * from foobar;'
)
as... | form = UpdateQueryForm( |
Predict the next line after this snippet: <|code_start|> form = CreateTagForm()
assert form.validate() is False
def test_tag_validate_success(self, testapp):
form = CreateTagForm(value='foo')
assert form.validate() is True
class TestCreateQueryForm:
def test_sql_validate_failu... | query = QueryFactory( |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
DUMMY_INPUT = RuleInput(result_log={}, node={})
class TestNetwork:
def test_will_cache_condition_instances(self):
<|code_end|>
. Use current file imports:
(import json
import logging
import datetime as dt
from collections import defaultdict
from doo... | class TestCondition(BaseCondition): |
Using the snippet: <|code_start|> def compare(self, value):
self.compare_val = value
inp = RuleInput(node={}, result_log={
'columns': {
'int_col': '1234',
'float_col': '56.78',
},
})
condition = TestCondition(No... | condition = LessCondition(None, '12', column_name='val') |
Predict the next line after this snippet: <|code_start|> """ Functional test for LessCondition that it uses the number conversion. """
inp = RuleInput(node={}, result_log={
'columns': {
'val': '112',
},
})
# assert that the rule does not alert whe... | condition = GreaterEqualCondition(None, '12', column_name='val') |
Continue the code snippet: <|code_start|> def __init__(self):
BaseCondition.__init__(self)
self.called_run = False
def local_run(self, input):
self.called_run = True
condition = SubCondition()
condition.run(DUMMY_INPUT)
ass... | class TestCondition(LogicCondition): |
Predict the next line after this snippet: <|code_start|>
condition = LessCondition(None, '112', column_name='val')
assert condition.local_run(inp) is False
condition = LessCondition(None, '113', column_name='val')
assert condition.local_run(inp) is True
def test_greater_or_equal_to... | cond = MatchesRegexCondition('unused', r'a+b+') |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
DUMMY_INPUT = RuleInput(result_log={}, node={})
class TestNetwork:
def test_will_cache_condition_instances(self):
class TestCondition(BaseCondition):
pass
<|code_end|>
, continue by predicting the next line. Consider current file import... | network = Network() |
Using the snippet: <|code_start|> assert condition.local_run(inp) is True
def test_greater_or_equal_to_number_values(self):
inp = RuleInput(node={}, result_log={
'columns': {
'val': '112',
},
})
# assert that the rule does not alert when the c... | cond = NotMatchesRegexCondition('unused', r'c+d') |
Predict the next line after this snippet: <|code_start|> finally:
# Remove final entry from the config.
current_app.config['DOORMAN_EXTRA_SCHEMA'] = \
current_app.config['DOORMAN_EXTRA_SCHEMA'][:-1]
class TestQuote:
def test_will_quote_string(self):
assert q... | s = json.dumps(data, cls=DateTimeEncoder) |
Using the snippet: <|code_start|>
class TestValidate:
def test_simple_validate(self):
query = 'SELECT * FROM osquery_info;'
assert validate_osquery_query(query) is True
def test_complex_validate(self):
# From Facebook's blog post: https://code.facebook.com/posts/844436395567983/intr... | osquery_mock_db.db = None |
Using the snippet: <|code_start|> def test_syntax_error(self):
query = 'SELECT * FROM'
assert validate_osquery_query(query) is False
def test_bad_table(self):
query = 'SELECT * FROM a_table_that_does_not_exist;'
assert validate_osquery_query(query) is False
def test_custom_s... | assert quote('foobar') == '"foobar"' |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class TestValidate:
def test_simple_validate(self):
query = 'SELECT * FROM osquery_info;'
<|code_end|>
using the current file's imports:
import json
import datetime as dt
import pytest
from flask import current_app
from d... | assert validate_osquery_query(query) is True |
Continue the code snippet: <|code_start|> def __init__(self, *args, **kwargs):
super(FilePathUpdateForm, self).__init__(*args, **kwargs)
# self.set_choices()
file_path = kwargs.pop('obj', None)
if file_path:
self.target_paths.process_data('\n'.join(file_path.get_paths()))
... | query = Rule.query.filter(Rule.name == self.name.data).first() |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class ValidSQL(object):
def __init__(self, message=None):
if not message:
message = u'Field must contain valid SQL to be run against osquery tables'
self.message = message
def __call__(self, form, field):
<|code_end|>
. W... | if not validate_osquery_query(field.data): |
Continue the code snippet: <|code_start|>
register_blueprints(app)
register_errorhandlers(app)
register_loggers(app)
register_extensions(app)
register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
... | assets.init_app(app) |
Here is a snippet: <|code_start|>def create_app(config=ProdConfig):
app = Flask(__name__)
app.config.from_object(config)
app.config.from_envvar('DOORMAN_SETTINGS', silent=True)
register_blueprints(app)
register_errorhandlers(app)
register_loggers(app)
register_extensions(app)
register_a... | bcrypt.init_app(app) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
def create_app(config=ProdConfig):
app = Flask(__name__)
app.config.from_object(config)
app.config.from_envvar('DOORMAN_SETTINGS', silent=True)
register_blueprints(app)
register_errorhandlers(app)
register_loggers(app)
register_ex... | csrf.exempt(api) |
Given the code snippet: <|code_start|> app.config.from_object(config)
app.config.from_envvar('DOORMAN_SETTINGS', silent=True)
register_blueprints(app)
register_errorhandlers(app)
register_loggers(app)
register_extensions(app)
register_auth_method(app)
register_filters(app)
return ap... | db.init_app(app) |
Given the following code snippet before the placeholder: <|code_start|> register_blueprints(app)
register_errorhandlers(app)
register_loggers(app)
register_extensions(app)
register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(ap... | debug_toolbar.init_app(app) |
Predict the next line for this snippet: <|code_start|> def render_error(error):
"""Render error template."""
# If a HTTPException, pull the `code` attribute; default to 500
error_code = getattr(error, 'code', 500)
if 'DOORMAN_NO_MANAGER' in os.environ:
return '', 400
... | ldap_manager.init_app(app) |
Continue the code snippet: <|code_start|> register_errorhandlers(app)
register_loggers(app)
register_extensions(app)
register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
# if the DOORMAN_NO_MANAGER en... | log_tee.init_app(app) |
Based on the snippet: <|code_start|> register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
# if the DOORMAN_NO_MANAGER environment variable isn't set,
# register the backend blueprint. This is useful when you want
# to only deploy the ... | login_manager.init_app(app) |
Next line prediction: <|code_start|> register_extensions(app)
register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
# if the DOORMAN_NO_MANAGER environment variable isn't set,
# register the backend bluepr... | mail.init_app(app) |
Given the code snippet: <|code_start|> register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
# if the DOORMAN_NO_MANAGER environment variable isn't set,
# register the backend blueprint. This is useful when yo... | make_celery(app, celery) |
Continue the code snippet: <|code_start|> app.config.from_envvar('DOORMAN_SETTINGS', silent=True)
register_blueprints(app)
register_errorhandlers(app)
register_loggers(app)
register_extensions(app)
register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app)... | migrate.init_app(app, db) |
Using the snippet: <|code_start|> register_loggers(app)
register_extensions(app)
register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
# if the DOORMAN_NO_MANAGER environment variable isn't set,
# regi... | rule_manager.init_app(app) |
Continue the code snippet: <|code_start|>
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
# if the DOORMAN_NO_MANAGER environment variable isn't set,
# register the backend blueprint. This is useful when you want
# to only deploy the api as a standalone s... | sentry.init_app(app) |
Given the following code snippet before the placeholder: <|code_start|> register_auth_method(app)
register_filters(app)
return app
def register_blueprints(app):
app.register_blueprint(api)
csrf.exempt(api)
# if the DOORMAN_NO_MANAGER environment variable isn't set,
# register the backend ... | make_celery(app, celery) |
Predict the next line for this snippet: <|code_start|>
logfile = app.config['DOORMAN_LOGGING_FILENAME']
if logfile == '-':
handler = logging.StreamHandler(sys.stdout)
else:
handler = WatchedFileHandler(logfile)
levelname = app.config['DOORMAN_LOGGING_LEVEL']
if levelname in ('DEBUG',... | app.jinja_env.filters['health'] = get_node_health |
Predict the next line for this snippet: <|code_start|> logfile = app.config['DOORMAN_LOGGING_FILENAME']
if logfile == '-':
handler = logging.StreamHandler(sys.stdout)
else:
handler = WatchedFileHandler(logfile)
levelname = app.config['DOORMAN_LOGGING_LEVEL']
if levelname in ('DEBUG', ... | app.jinja_env.filters['pretty_field'] = pretty_field |
Predict the next line after this snippet: <|code_start|> if logfile == '-':
handler = logging.StreamHandler(sys.stdout)
else:
handler = WatchedFileHandler(logfile)
levelname = app.config['DOORMAN_LOGGING_LEVEL']
if levelname in ('DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'CRITICAL'):
... | app.jinja_env.filters['pretty_operator'] = pretty_operator |
Next line prediction: <|code_start|> handler = logging.StreamHandler(sys.stdout)
else:
handler = WatchedFileHandler(logfile)
levelname = app.config['DOORMAN_LOGGING_LEVEL']
if levelname in ('DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'CRITICAL'):
handler.setLevel(getattr(logging, lev... | app.jinja_env.filters['render'] = render_column |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
class LoginForm(Form):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember = BooleanField('Remember me', validators=[Optional()])
... | bcrypt.generate_password_hash(self.password.data) |
Given snippet: <|code_start|> remember = BooleanField('Remember me', validators=[Optional()])
def __init__(self, *args, **kwargs):
"""Create instance."""
super(LoginForm, self).__init__(*args, **kwargs)
self.user = None
def validate(self):
initial_validation = super(LoginFor... | result = ldap_manager.authenticate( |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class LoginForm(Form):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember = BooleanField('Remember me', validators=[Opt... | self.user = User.query.filter_by(username=self.username.data).first() |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
def do_pending(version):
print 'add testrun for version {0.id}, phase {0.phase}, status {0.status}'.format(version)
<|code_end|>
, pre... | query = db_session.query(TestRun)\ |
Using the snippet: <|code_start|> for r in rs:
if r.id > latest_id:
runs.append({
'html': render_template('build_row.html', r=r, t=ts[r.testcase_id]),
'id': r.id,
'finished': r.status in ['passed', 'failed', 'timeout'],
... | html = ansi2html(text, palette='console') |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
JudgeStatus = namedtuple('JudgeStatus', ['name', 'action', 'time'])
judge_status = {}
def copy_sqlalchemy_object_as_dict(o):
d = dict(o.__dict__)
del d['_sa_instance_state']
return d
@app.route(settings.... | compilers = db_session.query(Compiler).order_by(Compiler.id.asc()).all() |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
def get_latest_remote_version(repo_url):
cmd = 'git ls-remote {} master | grep refs/heads/master | cut -f1'.format(repo_url)
try:
version ... | db_session.commit() |
Based on the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, unicode_literals
def initdb():
key = int(time.time()) // 60
key = hashlib.md5(str(key)).hexdigest()[:6]
if len(sys.argv) != 3 or sys.argv[2] != key:
print('please run ... | db_session.add(c) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, unicode_literals
def initdb():
key = int(time.time()) // 60
key = hashlib.md5(str(key)).hexdigest()[:6]
if len(sys.argv) != 3 or sys.argv[2]... | init_db() |
Continue the code snippet: <|code_start|> 'silk': 21,
'stop': 23,
'docu': 24,
'hole': 28,
}.get(t, 21)
def list_names(fn):
l = []
with open(fn, 'r') as f:
lines = f.readlines()
for line in lines:
s = shlex.split(line)
k = s[0].lower()
if k == '$module':
name = s[1... | meta = inter.get_meta(interim) |
Predict the next line for this snippet: <|code_start|> meta = filter(lambda x: x['type'] == 'meta', interim)[0]
name = meta['name'].replace(' ','_')
dir_name = os.path.dirname(args.footprint)
if dir_name != "":
new_name = os.path.dirname(args.footprint)+"/"+name+".coffee"
else:
new_name = name+".coffee... | interim = inter.import_footprint(importer, args.footprint) |
Given the code snippet: <|code_start|> (error_txt, status_txt, interim) = pycoffee.compile_coffee(code)
assert interim != None
version = export.eagle.check_xml_file(eagle_lib)
assert version == 'Eagle CAD 6.4 library'
exporter = export.eagle.Export(eagle_lib)
eagle_name = exporter.export_footprint(interim)
... | interim = inter.import_footprint(importer, import_name) |
Based on the snippet: <|code_start|>
def detect(fn):
if os.path.isdir(fn) and '.pretty' in fn:
return "3"
try:
l = sexpdata.load(open(fn, 'r'))
if (l[0] == S('module')): return "3"
return None
except IOError:
# allow new .kicad_mod files!
if '.kicad_mod' in fn: return "3"
return None
... | meta = inter.get_meta(interim) |
Given the code snippet: <|code_start|>
def __init__(self, fn):
self.fn = fn
self.soup = _load_xml_file(fn)
_check_xml(self.soup)
def save(self):
_save_xml_file(self.fn, self.soup)
def get_data(self):
return str(self.soup)
# remark that this pretty formatting is NOT what is used in the fina... | meta = inter.get_meta(interim) |
Given the code snippet: <|code_start|> return new_meta + no_meta_coffee
def new_coffee(new_id, new_name):
return """\
#format %s
#name %s
#id %s
#desc TODO
footprint = () ->
[]
""" % (current_format, new_name, new_id)
def preprocess_coffee(code):
def repl(m):
t = m.group(2)
i = float(m.group(1))
i... | interim = inter.cleanup_js(interim) |
Predict the next line after this snippet: <|code_start|> "OpenGL_accelerate.latebind",
"OpenGL_accelerate.nones_formathandler",
"OpenGL_accelerate.numpy_formathandler",
"OpenGL_accelerate.vbo",
"OpenGL_accelerate.wrapper",
]
}
extra_data_files = ['msvcp90.d... | version = VERSION, |
Continue the code snippet: <|code_start|>
__author__ = "Chang Gao"
__copyright__ = "Copyright (c) 2017 Malmactor"
__license__ = "MIT"
class Actor:
__metaclass__ = ABCMeta
def __init__(self, host, layout):
self.host = host
self.world = host.getWorldState()
<|code_end|>
. Use current file impo... | self.sim = MarioSimulation(layout, {"dtype": "float16"}) |
Given the following code snippet before the placeholder: <|code_start|>"""Script defined to test the Subscription class."""
class TestSubscription(BaseTestCase):
"""Class to test subscription actions."""
@httpretty.activate
def test_create(self):
"""Method defined to test subscription creation.... | response = Subscription.create( |
Predict the next line for this snippet: <|code_start|>
class TestBulkCharge(BaseTestCase):
@httpretty.activate
def test_initiate_bulk_charge(self):
""" Method for testing the initiation of a bulk charge"""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("/bul... | response = BulkCharge.initiate_bulk_charge( |
Given snippet: <|code_start|>
class TestTransferControl(BaseTestCase):
@httpretty.activate
def test_check_balance(self):
"""Method defined to test check_balance."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/balance"),
content_type='text/jso... | response = TransferControl.check_balance() |
Next line prediction: <|code_start|>"""Script defined to test the Customer class."""
class TestTransaction(BaseTestCase):
"""Method defined to test transaction initialize."""
@httpretty.activate
def test_initialize(self):
httpretty.register_uri(
httpretty.POST,
self.endp... | response = Transaction.initialize( |
Given the following code snippet before the placeholder: <|code_start|>
class TestSubAccount(BaseTestCase):
@httpretty.activate
def test_subaccount_create(self):
"""Method defined to test subaccount creation."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url... | response = SubAccount.create( |
Given snippet: <|code_start|>
class TestRefund(BaseTestCase):
@httpretty.activate
def test_valid_create(self):
"""Test Refund Create."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("refund"),
content_type='text/json',
body='{"status": true, "message": "Refund has been queued for proce... | response = Refund.create(transaction=1234) |
Given the code snippet: <|code_start|>
class TestPage(BaseTestCase):
@httpretty.activate
def test_fetch_payment_session_timeout(self):
"""Method defined to test fetch payment session timeout."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/integration/pay... | response = ControlPanel.fetch_payment_session_timeout() |
Using the snippet: <|code_start|>"""Script defined to test the Customer class."""
class TestCustomer(BaseTestCase):
"""Class to test customer actions."""
@httpretty.activate
def test_create(self):
"""Method defined to test customer creation."""
httpretty.register_uri(
httpre... | response = Customer.create( |
Given the following code snippet before the placeholder: <|code_start|>
class TestSubAccount(BaseTestCase):
@httpretty.activate
def test_create_trecipient(self):
"""Method defined to test trecipient creation."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url... | response = TransferRecipient.create( |
Predict the next line for this snippet: <|code_start|>"""Script defined to test the Class instance."""
class TestHttpMethods(BaseTestCase):
"""Method defined to test transaction instance."""
def setUp(self):
paystackbase = PayStackBase()
@httpretty.activate
def test_get_method_called(self)... | req = PayStackRequests() |
Here is a snippet: <|code_start|>
class TestCharge(BaseTestCase):
@httpretty.activate
def test_start_charge(self):
"""Method defined to test start charge."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("/charge"),
content_type='text/json',
... | response = Charge.start_charge( |
Using the snippet: <|code_start|>
class TestMisc(BaseTestCase):
@httpretty.activate
def test_list_banks(self):
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/bank"),
content_type='text/json',
body='{"status": true, "message": "Banks retrieved", "data": []}',
status=200,
)
<|code_... | response = Misc.list_banks() |
Given snippet: <|code_start|>
class TestTransfer(BaseTestCase):
@httpretty.activate
def test_initiate(self):
"""Method defined to test transfer initiation."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("/transfer"),
content_type='text/json',
... | response = Transfer.initiate( |
Given the code snippet: <|code_start|>
class TestInvoice(BaseTestCase):
@httpretty.activate
def test_create_invoice(self):
"""Method defined to test create Invoice."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("/paymentrequest"),
content_typ... | response = Invoice.create( |
Predict the next line after this snippet: <|code_start|>
class TestProduct(BaseTestCase):
@httpretty.activate
def test_product_create(self):
"""Method defined to test product creation."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("/product"),
... | response = Product.create( |
Based on the snippet: <|code_start|>
class TestPage(BaseTestCase):
@httpretty.activate
def test_page_fetch(self):
"""Method defined to test fetch."""
httpretty.register_uri(
httpretty.GET,
self.endpoint_url("/settlement"),
content_type='text/json',
... | response = Settlement.fetch( |
Predict the next line after this snippet: <|code_start|>
class TestPage(BaseTestCase):
@httpretty.activate
def test_page_create(self):
"""Method defined to test page creation."""
httpretty.register_uri(
httpretty.POST,
self.endpoint_url("/page"),
content_ty... | response = Page.create( |
Using the snippet: <|code_start|>"""Script defined to test the Verification class."""
class TestVerification(BaseTestCase):
"""Class to test verification actions."""
@httpretty.activate
def test_verify_bvn(self):
"""Method defined to test bvn verification."""
httpretty.register_uri(
... | response = Verification.verify_bvn(bvn='01234567689') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.