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) |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 1