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 = {} configuration['options'] = assemble_options(node) configuration['file_paths'] = assemble_file_paths(node) configuration['schedule'] = assemble_schedule(node) configuration['packs'] = assemble_packs(node) return configuration 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['schedule_splay_percent'] = 10 return options def assemble_file_paths(node): file_paths = {} <|code_end|> , predict the next line using imports from the current file: from collections import namedtuple from operator import itemgetter from os.path import basename, join, splitext from flask import current_app, flash from jinja2 import Markup, Template from doorman.database import db from doorman.models import ( DistributedQuery, DistributedQueryTask, Node, Pack, Query, ResultLog, querypacks, ) import datetime as dt import json import pkg_resources import sqlite3 import string import threading import six and context including class names, function names, and sometimes code from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/models.py # class Tag(SurrogatePK, Model): # class Query(SurrogatePK, Model): # class Pack(SurrogatePK, Model): # class Node(SurrogatePK, Model): # class FilePath(SurrogatePK, Model): # class ResultLog(SurrogatePK, Model): # class StatusLog(SurrogatePK, Model): # class DistributedQuery(SurrogatePK, Model): # class DistributedQueryTask(SurrogatePK, Model): # class DistributedQueryResult(SurrogatePK, Model): # class Rule(SurrogatePK, Model): # class User(UserMixin, SurrogatePK, Model): # def __init__(self, value, **kwargs): # def __repr__(self): # def packs_count(self): # def nodes_count(self): # def queries_count(self): # def file_paths_count(self): # def __init__(self, name, query=None, sql=None, interval=3600, platform=None, # version=None, description=None, value=None, removed=True, # shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, name, platform=None, version=None, # description=None, shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, host_identifier, node_key=None, # enroll_secret=None, enrolled_on=None, last_checkin=None, # is_active=True, last_ip=None, # **kwargs): # def __repr__(self): # def get_config(self, **kwargs): # def get_new_queries(self, **kwargs): # def display_name(self): # def packs(self): # def queries(self): # def file_paths(self): # def to_dict(self): # def __init__(self, category=None, target_paths=None, *args, **kwargs): # def to_dict(self): # def get_paths(self): # def set_paths(self, *target_paths): # def __init__(self, name=None, action=None, columns=None, timestamp=None, # node=None, node_id=None, **kwargs): # def __table_args__(cls): # def __init__(self, line=None, message=None, severity=None, # filename=None, created=None, node=None, node_id=None, # version=None, **kwargs): # def __table_args__(cls): # def __init___(self, sql, description=None, not_before=None): # def __init__(self, node=None, node_id=None, # distributed_query=None, distributed_query_id=None): # def __table_args__(cls): # def __init__(self, columns, distributed_query=None, distributed_query_task=None): # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # def template(self): # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # def set_password(self, password): # def check_password(self, value): # NEW = 0 # PENDING = 1 # COMPLETE = 2 # FAILED = 3 . Output only the next line.
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.name] = query.to_dict() return schedule def assemble_packs(node): packs = {} for pack in node.packs.join(querypacks).join(Query) \ .options(db.contains_eager(Pack.queries)).all(): packs[pack.name] = pack.to_dict() return packs def assemble_distributed_queries(node): ''' Retrieve all distributed queries assigned to a particular node in the NEW state. This function will change the state of the distributed query to PENDING, however will not commit the change. It is the responsibility of the caller to commit or rollback on the current database session. ''' now = dt.datetime.utcnow() query = db.session.query(DistributedQueryTask) \ <|code_end|> using the current file's imports: from collections import namedtuple from operator import itemgetter from os.path import basename, join, splitext from flask import current_app, flash from jinja2 import Markup, Template from doorman.database import db from doorman.models import ( DistributedQuery, DistributedQueryTask, Node, Pack, Query, ResultLog, querypacks, ) import datetime as dt import json import pkg_resources import sqlite3 import string import threading import six and any relevant context from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/models.py # class Tag(SurrogatePK, Model): # class Query(SurrogatePK, Model): # class Pack(SurrogatePK, Model): # class Node(SurrogatePK, Model): # class FilePath(SurrogatePK, Model): # class ResultLog(SurrogatePK, Model): # class StatusLog(SurrogatePK, Model): # class DistributedQuery(SurrogatePK, Model): # class DistributedQueryTask(SurrogatePK, Model): # class DistributedQueryResult(SurrogatePK, Model): # class Rule(SurrogatePK, Model): # class User(UserMixin, SurrogatePK, Model): # def __init__(self, value, **kwargs): # def __repr__(self): # def packs_count(self): # def nodes_count(self): # def queries_count(self): # def file_paths_count(self): # def __init__(self, name, query=None, sql=None, interval=3600, platform=None, # version=None, description=None, value=None, removed=True, # shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, name, platform=None, version=None, # description=None, shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, host_identifier, node_key=None, # enroll_secret=None, enrolled_on=None, last_checkin=None, # is_active=True, last_ip=None, # **kwargs): # def __repr__(self): # def get_config(self, **kwargs): # def get_new_queries(self, **kwargs): # def display_name(self): # def packs(self): # def queries(self): # def file_paths(self): # def to_dict(self): # def __init__(self, category=None, target_paths=None, *args, **kwargs): # def to_dict(self): # def get_paths(self): # def set_paths(self, *target_paths): # def __init__(self, name=None, action=None, columns=None, timestamp=None, # node=None, node_id=None, **kwargs): # def __table_args__(cls): # def __init__(self, line=None, message=None, severity=None, # filename=None, created=None, node=None, node_id=None, # version=None, **kwargs): # def __table_args__(cls): # def __init___(self, sql, description=None, not_before=None): # def __init__(self, node=None, node_id=None, # distributed_query=None, distributed_query_id=None): # def __table_args__(cls): # def __init__(self, columns, distributed_query=None, distributed_query_task=None): # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # def template(self): # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # def set_password(self, password): # def check_password(self, value): # NEW = 0 # PENDING = 1 # COMPLETE = 2 # FAILED = 3 . Output only the next line.
.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('*')): schedule[query.name] = query.to_dict() return schedule def assemble_packs(node): packs = {} for pack in node.packs.join(querypacks).join(Query) \ .options(db.contains_eager(Pack.queries)).all(): packs[pack.name] = pack.to_dict() return packs def assemble_distributed_queries(node): ''' Retrieve all distributed queries assigned to a particular node in the NEW state. This function will change the state of the distributed query to PENDING, however will not commit the change. It is the responsibility of the caller to commit or rollback on the current database session. ''' now = dt.datetime.utcnow() <|code_end|> using the current file's imports: from collections import namedtuple from operator import itemgetter from os.path import basename, join, splitext from flask import current_app, flash from jinja2 import Markup, Template from doorman.database import db from doorman.models import ( DistributedQuery, DistributedQueryTask, Node, Pack, Query, ResultLog, querypacks, ) import datetime as dt import json import pkg_resources import sqlite3 import string import threading import six and any relevant context from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/models.py # class Tag(SurrogatePK, Model): # class Query(SurrogatePK, Model): # class Pack(SurrogatePK, Model): # class Node(SurrogatePK, Model): # class FilePath(SurrogatePK, Model): # class ResultLog(SurrogatePK, Model): # class StatusLog(SurrogatePK, Model): # class DistributedQuery(SurrogatePK, Model): # class DistributedQueryTask(SurrogatePK, Model): # class DistributedQueryResult(SurrogatePK, Model): # class Rule(SurrogatePK, Model): # class User(UserMixin, SurrogatePK, Model): # def __init__(self, value, **kwargs): # def __repr__(self): # def packs_count(self): # def nodes_count(self): # def queries_count(self): # def file_paths_count(self): # def __init__(self, name, query=None, sql=None, interval=3600, platform=None, # version=None, description=None, value=None, removed=True, # shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, name, platform=None, version=None, # description=None, shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, host_identifier, node_key=None, # enroll_secret=None, enrolled_on=None, last_checkin=None, # is_active=True, last_ip=None, # **kwargs): # def __repr__(self): # def get_config(self, **kwargs): # def get_new_queries(self, **kwargs): # def display_name(self): # def packs(self): # def queries(self): # def file_paths(self): # def to_dict(self): # def __init__(self, category=None, target_paths=None, *args, **kwargs): # def to_dict(self): # def get_paths(self): # def set_paths(self, *target_paths): # def __init__(self, name=None, action=None, columns=None, timestamp=None, # node=None, node_id=None, **kwargs): # def __table_args__(cls): # def __init__(self, line=None, message=None, severity=None, # filename=None, created=None, node=None, node_id=None, # version=None, **kwargs): # def __table_args__(cls): # def __init___(self, sql, description=None, not_before=None): # def __init__(self, node=None, node_id=None, # distributed_query=None, distributed_query_id=None): # def __table_args__(cls): # def __init__(self, columns, distributed_query=None, distributed_query_task=None): # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # def template(self): # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # def set_password(self, password): # def check_password(self, value): # NEW = 0 # PENDING = 1 # COMPLETE = 2 # FAILED = 3 . Output only the next line.
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 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 == 'removed' and (cvalue is None or cvalue != value): pass elif action == 'removed' and cvalue == value: node_info.pop(column) elif action == 'added' and (cvalue is None or cvalue != value): node_info[column] = value # only update node_info if there's actually a change if orig_node_info == node_info: return <|code_end|> with the help of current file imports: from collections import namedtuple from operator import itemgetter from os.path import basename, join, splitext from flask import current_app, flash from jinja2 import Markup, Template from doorman.database import db from doorman.models import ( DistributedQuery, DistributedQueryTask, Node, Pack, Query, ResultLog, querypacks, ) import datetime as dt import json import pkg_resources import sqlite3 import string import threading import six and context from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/models.py # class Tag(SurrogatePK, Model): # class Query(SurrogatePK, Model): # class Pack(SurrogatePK, Model): # class Node(SurrogatePK, Model): # class FilePath(SurrogatePK, Model): # class ResultLog(SurrogatePK, Model): # class StatusLog(SurrogatePK, Model): # class DistributedQuery(SurrogatePK, Model): # class DistributedQueryTask(SurrogatePK, Model): # class DistributedQueryResult(SurrogatePK, Model): # class Rule(SurrogatePK, Model): # class User(UserMixin, SurrogatePK, Model): # def __init__(self, value, **kwargs): # def __repr__(self): # def packs_count(self): # def nodes_count(self): # def queries_count(self): # def file_paths_count(self): # def __init__(self, name, query=None, sql=None, interval=3600, platform=None, # version=None, description=None, value=None, removed=True, # shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, name, platform=None, version=None, # description=None, shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, host_identifier, node_key=None, # enroll_secret=None, enrolled_on=None, last_checkin=None, # is_active=True, last_ip=None, # **kwargs): # def __repr__(self): # def get_config(self, **kwargs): # def get_new_queries(self, **kwargs): # def display_name(self): # def packs(self): # def queries(self): # def file_paths(self): # def to_dict(self): # def __init__(self, category=None, target_paths=None, *args, **kwargs): # def to_dict(self): # def get_paths(self): # def set_paths(self, *target_paths): # def __init__(self, name=None, action=None, columns=None, timestamp=None, # node=None, node_id=None, **kwargs): # def __table_args__(cls): # def __init__(self, line=None, message=None, severity=None, # filename=None, created=None, node=None, node_id=None, # version=None, **kwargs): # def __table_args__(cls): # def __init___(self, sql, description=None, not_before=None): # def __init__(self, node=None, node_id=None, # distributed_query=None, distributed_query_id=None): # def __table_args__(cls): # def __init__(self, columns, distributed_query=None, distributed_query_task=None): # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # def template(self): # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # def set_password(self, password): # def check_password(self, value): # NEW = 0 # PENDING = 1 # COMPLETE = 2 # FAILED = 3 , which may contain function names, class names, or code. Output only the next line.
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['schedule_splay_percent'] = 10 return options def assemble_file_paths(node): 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('*')): schedule[query.name] = query.to_dict() return schedule def assemble_packs(node): packs = {} for pack in node.packs.join(querypacks).join(Query) \ <|code_end|> , determine the next line of code. You have imports: from collections import namedtuple from operator import itemgetter from os.path import basename, join, splitext from flask import current_app, flash from jinja2 import Markup, Template from doorman.database import db from doorman.models import ( DistributedQuery, DistributedQueryTask, Node, Pack, Query, ResultLog, querypacks, ) import datetime as dt import json import pkg_resources import sqlite3 import string import threading import six and context (class names, function names, or code) available: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/models.py # class Tag(SurrogatePK, Model): # class Query(SurrogatePK, Model): # class Pack(SurrogatePK, Model): # class Node(SurrogatePK, Model): # class FilePath(SurrogatePK, Model): # class ResultLog(SurrogatePK, Model): # class StatusLog(SurrogatePK, Model): # class DistributedQuery(SurrogatePK, Model): # class DistributedQueryTask(SurrogatePK, Model): # class DistributedQueryResult(SurrogatePK, Model): # class Rule(SurrogatePK, Model): # class User(UserMixin, SurrogatePK, Model): # def __init__(self, value, **kwargs): # def __repr__(self): # def packs_count(self): # def nodes_count(self): # def queries_count(self): # def file_paths_count(self): # def __init__(self, name, query=None, sql=None, interval=3600, platform=None, # version=None, description=None, value=None, removed=True, # shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, name, platform=None, version=None, # description=None, shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, host_identifier, node_key=None, # enroll_secret=None, enrolled_on=None, last_checkin=None, # is_active=True, last_ip=None, # **kwargs): # def __repr__(self): # def get_config(self, **kwargs): # def get_new_queries(self, **kwargs): # def display_name(self): # def packs(self): # def queries(self): # def file_paths(self): # def to_dict(self): # def __init__(self, category=None, target_paths=None, *args, **kwargs): # def to_dict(self): # def get_paths(self): # def set_paths(self, *target_paths): # def __init__(self, name=None, action=None, columns=None, timestamp=None, # node=None, node_id=None, **kwargs): # def __table_args__(cls): # def __init__(self, line=None, message=None, severity=None, # filename=None, created=None, node=None, node_id=None, # version=None, **kwargs): # def __table_args__(cls): # def __init___(self, sql, description=None, not_before=None): # def __init__(self, node=None, node_id=None, # distributed_query=None, distributed_query_id=None): # def __table_args__(cls): # def __init__(self, columns, distributed_query=None, distributed_query_task=None): # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # def template(self): # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # def set_password(self, password): # def check_password(self, value): # NEW = 0 # PENDING = 1 # COMPLETE = 2 # FAILED = 3 . Output only the next line.
.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' options['schedule_splay_percent'] = 10 return options def assemble_file_paths(node): 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('*')): schedule[query.name] = query.to_dict() return schedule def assemble_packs(node): packs = {} <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import namedtuple from operator import itemgetter from os.path import basename, join, splitext from flask import current_app, flash from jinja2 import Markup, Template from doorman.database import db from doorman.models import ( DistributedQuery, DistributedQueryTask, Node, Pack, Query, ResultLog, querypacks, ) import datetime as dt import json import pkg_resources import sqlite3 import string import threading import six and context: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/models.py # class Tag(SurrogatePK, Model): # class Query(SurrogatePK, Model): # class Pack(SurrogatePK, Model): # class Node(SurrogatePK, Model): # class FilePath(SurrogatePK, Model): # class ResultLog(SurrogatePK, Model): # class StatusLog(SurrogatePK, Model): # class DistributedQuery(SurrogatePK, Model): # class DistributedQueryTask(SurrogatePK, Model): # class DistributedQueryResult(SurrogatePK, Model): # class Rule(SurrogatePK, Model): # class User(UserMixin, SurrogatePK, Model): # def __init__(self, value, **kwargs): # def __repr__(self): # def packs_count(self): # def nodes_count(self): # def queries_count(self): # def file_paths_count(self): # def __init__(self, name, query=None, sql=None, interval=3600, platform=None, # version=None, description=None, value=None, removed=True, # shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, name, platform=None, version=None, # description=None, shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, host_identifier, node_key=None, # enroll_secret=None, enrolled_on=None, last_checkin=None, # is_active=True, last_ip=None, # **kwargs): # def __repr__(self): # def get_config(self, **kwargs): # def get_new_queries(self, **kwargs): # def display_name(self): # def packs(self): # def queries(self): # def file_paths(self): # def to_dict(self): # def __init__(self, category=None, target_paths=None, *args, **kwargs): # def to_dict(self): # def get_paths(self): # def set_paths(self, *target_paths): # def __init__(self, name=None, action=None, columns=None, timestamp=None, # node=None, node_id=None, **kwargs): # def __table_args__(cls): # def __init__(self, line=None, message=None, severity=None, # filename=None, created=None, node=None, node_id=None, # version=None, **kwargs): # def __table_args__(cls): # def __init___(self, sql, description=None, not_before=None): # def __init__(self, node=None, node_id=None, # distributed_query=None, distributed_query_id=None): # def __table_args__(cls): # def __init__(self, columns, distributed_query=None, distributed_query_task=None): # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # def template(self): # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # def set_password(self, password): # def check_password(self, value): # NEW = 0 # PENDING = 1 # COMPLETE = 2 # FAILED = 3 which might include code, classes, or functions. Output only the next line.
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 == 'removed' and (cvalue is None or cvalue != value): pass elif action == 'removed' and cvalue == value: node_info.pop(column) elif action == 'added' and (cvalue is None or cvalue != value): node_info[column] = value # only update node_info if there's actually a change if orig_node_info == node_info: return node = Node.get_by_id(node['id']) node.update(node_info=node_info) return def process_result(result, node): if not result['data']: current_app.logger.error("No results to process from %s", node) return for name, action, columns, timestamp, in extract_results(result): <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import namedtuple from operator import itemgetter from os.path import basename, join, splitext from flask import current_app, flash from jinja2 import Markup, Template from doorman.database import db from doorman.models import ( DistributedQuery, DistributedQueryTask, Node, Pack, Query, ResultLog, querypacks, ) import datetime as dt import json import pkg_resources import sqlite3 import string import threading import six and context: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/models.py # class Tag(SurrogatePK, Model): # class Query(SurrogatePK, Model): # class Pack(SurrogatePK, Model): # class Node(SurrogatePK, Model): # class FilePath(SurrogatePK, Model): # class ResultLog(SurrogatePK, Model): # class StatusLog(SurrogatePK, Model): # class DistributedQuery(SurrogatePK, Model): # class DistributedQueryTask(SurrogatePK, Model): # class DistributedQueryResult(SurrogatePK, Model): # class Rule(SurrogatePK, Model): # class User(UserMixin, SurrogatePK, Model): # def __init__(self, value, **kwargs): # def __repr__(self): # def packs_count(self): # def nodes_count(self): # def queries_count(self): # def file_paths_count(self): # def __init__(self, name, query=None, sql=None, interval=3600, platform=None, # version=None, description=None, value=None, removed=True, # shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, name, platform=None, version=None, # description=None, shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, host_identifier, node_key=None, # enroll_secret=None, enrolled_on=None, last_checkin=None, # is_active=True, last_ip=None, # **kwargs): # def __repr__(self): # def get_config(self, **kwargs): # def get_new_queries(self, **kwargs): # def display_name(self): # def packs(self): # def queries(self): # def file_paths(self): # def to_dict(self): # def __init__(self, category=None, target_paths=None, *args, **kwargs): # def to_dict(self): # def get_paths(self): # def set_paths(self, *target_paths): # def __init__(self, name=None, action=None, columns=None, timestamp=None, # node=None, node_id=None, **kwargs): # def __table_args__(cls): # def __init__(self, line=None, message=None, severity=None, # filename=None, created=None, node=None, node_id=None, # version=None, **kwargs): # def __table_args__(cls): # def __init___(self, sql, description=None, not_before=None): # def __init__(self, node=None, node_id=None, # distributed_query=None, distributed_query_id=None): # def __table_args__(cls): # def __init__(self, columns, distributed_query=None, distributed_query_task=None): # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # def template(self): # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # def set_password(self, password): # def check_password(self, value): # NEW = 0 # PENDING = 1 # COMPLETE = 2 # FAILED = 3 which might include code, classes, or functions. Output only the next line.
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' options['schedule_splay_percent'] = 10 return options def assemble_file_paths(node): 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('*')): schedule[query.name] = query.to_dict() return schedule def assemble_packs(node): packs = {} <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import namedtuple from operator import itemgetter from os.path import basename, join, splitext from flask import current_app, flash from jinja2 import Markup, Template from doorman.database import db from doorman.models import ( DistributedQuery, DistributedQueryTask, Node, Pack, Query, ResultLog, querypacks, ) import datetime as dt import json import pkg_resources import sqlite3 import string import threading import six and context: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/models.py # class Tag(SurrogatePK, Model): # class Query(SurrogatePK, Model): # class Pack(SurrogatePK, Model): # class Node(SurrogatePK, Model): # class FilePath(SurrogatePK, Model): # class ResultLog(SurrogatePK, Model): # class StatusLog(SurrogatePK, Model): # class DistributedQuery(SurrogatePK, Model): # class DistributedQueryTask(SurrogatePK, Model): # class DistributedQueryResult(SurrogatePK, Model): # class Rule(SurrogatePK, Model): # class User(UserMixin, SurrogatePK, Model): # def __init__(self, value, **kwargs): # def __repr__(self): # def packs_count(self): # def nodes_count(self): # def queries_count(self): # def file_paths_count(self): # def __init__(self, name, query=None, sql=None, interval=3600, platform=None, # version=None, description=None, value=None, removed=True, # shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, name, platform=None, version=None, # description=None, shard=None, **kwargs): # def __repr__(self): # def to_dict(self): # def __init__(self, host_identifier, node_key=None, # enroll_secret=None, enrolled_on=None, last_checkin=None, # is_active=True, last_ip=None, # **kwargs): # def __repr__(self): # def get_config(self, **kwargs): # def get_new_queries(self, **kwargs): # def display_name(self): # def packs(self): # def queries(self): # def file_paths(self): # def to_dict(self): # def __init__(self, category=None, target_paths=None, *args, **kwargs): # def to_dict(self): # def get_paths(self): # def set_paths(self, *target_paths): # def __init__(self, name=None, action=None, columns=None, timestamp=None, # node=None, node_id=None, **kwargs): # def __table_args__(cls): # def __init__(self, line=None, message=None, severity=None, # filename=None, created=None, node=None, node_id=None, # version=None, **kwargs): # def __table_args__(cls): # def __init___(self, sql, description=None, not_before=None): # def __init__(self, node=None, node_id=None, # distributed_query=None, distributed_query_id=None): # def __table_args__(cls): # def __init__(self, columns, distributed_query=None, distributed_query_task=None): # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # def template(self): # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # def set_password(self, password): # def check_password(self, value): # NEW = 0 # PENDING = 1 # COMPLETE = 2 # FAILED = 3 which might include code, classes, or functions. Output only the next line.
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(CRUDMixin, db.Model): """Base model class that includes CRUD convenience methods.""" __abstract__ = True # From Mike Bayer's "Building the app" talk # https://speakerdeck.com/zzzeek/building-the-app class SurrogatePK(object): """A mixin that adds a surrogate integer 'primary key' column named ``id`` to any declarative-mapped class.""" __table_args__ = {'extend_existing': True} id = db.Column(db.Integer, primary_key=True) @classmethod def get_by_id(cls, record_id): """Get record by ID.""" if any( <|code_end|> . Write the next line using the current file imports: from sqlalchemy.dialects.postgresql import ARRAY, JSONB, INET # noqa from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.orm import relationship from doorman.compat import basestring from doorman.extensions import db and context from other files: # Path: doorman/compat.py # PY2 = int(sys.version[0]) == 2 # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # class metaclass(meta): # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): , which may include functions, classes, or code. Output only the next line.
(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_app.logger.debug("Got userinfo: %s", userinfo) if self.allowed_users and userinfo['email'] not in self.allowed_users: current_app.logger.error("%s is not authorized for this application", userinfo['email']) flash(u"{0} is not authorized for this application.".format( userinfo['email']), 'danger') abort(401) if self.allowed_domains and userinfo['hd'] not in self.allowed_domains: current_app.logger.error("%s domain and %s not authorized", userinfo['hd'], userinfo['email']) flash(u"{0} is not authorized for this application.".format( userinfo['email']), 'danger') abort(401) if not userinfo['verified_email']: flash(u"You must verify your email before using this application.", 'danger') abort(401) <|code_end|> using the current file's imports: from flask import abort, current_app, flash, request, session, url_for from requests_oauthlib import OAuth2Session from doorman.models import User and any relevant context from other files: # Path: doorman/models.py # 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=False, default=dt.datetime.utcnow) # # # oauth related stuff # social_id = Column(db.String) # first_name = Column(db.String) # last_name = Column(db.String) # # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # self.username = username # self.email = email # if password: # self.set_password(password) # else: # self.password = None # # self.social_id = social_id # self.first_name = first_name # self.last_name = last_name # # def set_password(self, password): # self.update(password=bcrypt.generate_password_hash(password)) # return # # def check_password(self, value): # if not self.password: # # still do the computation # return bcrypt.generate_password_hash(value) and False # return bcrypt.check_password_hash(self.password, value) . Output only the next line.
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=subject_prefix, match=match, timestamp=dt.datetime.utcnow(), node=node ) ).safe_substitute(**params) body = string.Template( render_template( message_template, match=match, timestamp=dt.datetime.utcnow(), node=node ) ).safe_substitute(**params) message = Message( subject.strip(), recipients=self.recipients, body=body, charset='utf-8', ) <|code_end|> , predict the next line using imports from the current file: import datetime as dt import string from flask import render_template from flask_mail import Message from doorman.extensions import mail from .base import AbstractAlerterPlugin and context including class names, function names, and sometimes code from other files: # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/plugins/alerters/base.py # class AbstractAlerterPlugin(with_metaclass(ABCMeta)): # """ # AbstractAlerterPlugin is the base class for all alerters in Doorman. It # defines the interface that an alerter should implement in order to support # sending an alert. # """ # @abstractmethod # def handle_alert(self, node, match): # raise NotImplementedError() . Output only the next line.
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'] = userdata['givenName'][0] if 'sn' in userdata: kwargs['last_name'] = userdata['sn'][0] return user.update(**kwargs) if user else User.create(**kwargs) @blueprint.route('/login', methods=['GET', 'POST']) def login(): next = request.args.get('next', url_for('manage.index')) if current_user and current_user.is_authenticated: return safe_redirect(next, url_for('manage.index')) if current_app.config['DOORMAN_AUTH_METHOD'] not in (None, 'doorman', 'ldap'): authorization_url = current_app.oauth_provider.get_authorize_url() current_app.logger.debug("Redirecting user to %s", authorization_url) return redirect(authorization_url) <|code_end|> , continue by predicting the next line. Consider current file imports: from urlparse import urlparse, urljoin from urllib.parse import urlparse, urljoin from flask import ( Blueprint, abort, current_app, flash, redirect, render_template, request, session, url_for ) from flask_login import current_user, login_user, logout_user, COOKIE_NAME from oauthlib.oauth2 import OAuth2Error from .forms import LoginForm from doorman.extensions import csrf, ldap_manager, login_manager from doorman.models import User from doorman.utils import flash_errors from doorman.users.mixins import NoAuthUserMixin and context: # Path: doorman/users/forms.py # class LoginForm(Form): # # username = StringField('Username', validators=[DataRequired()]) # password = PasswordField('Password', validators=[DataRequired()]) # 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(LoginForm, self).validate() # if not initial_validation: # return False # # error_message = u'Invalid username or password.' # # if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman': # self.user = User.query.filter_by(username=self.username.data).first() # # if not self.user: # from doorman.extensions import bcrypt # # avoid timing leaks # bcrypt.generate_password_hash(self.password.data) # self.username.errors.append(error_message) # return False # # if not self.user.check_password(self.password.data): # self.username.errors.append(error_message) # return False # # return True # # elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap': # result = ldap_manager.authenticate( # self.username.data, # self.password.data # ) # # if result.status == AuthenticationResponseStatus.fail: # self.username.errors.append(error_message) # return False # # self.user = ldap_manager._save_user( # result.user_dn, # result.user_id, # result.user_info, # result.user_groups # ) # return True # # elif current_app.config['DOORMAN_AUTH_METHOD'] is None: # return True # # return False # # @property # def auth_method(self): # return current_app.config['DOORMAN_AUTH_METHOD'] # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/models.py # 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=False, default=dt.datetime.utcnow) # # # oauth related stuff # social_id = Column(db.String) # first_name = Column(db.String) # last_name = Column(db.String) # # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # self.username = username # self.email = email # if password: # self.set_password(password) # else: # self.password = None # # self.social_id = social_id # self.first_name = first_name # self.last_name = last_name # # def set_password(self, password): # self.update(password=bcrypt.generate_password_hash(password)) # return # # def check_password(self, value): # if not self.password: # # still do the computation # return bcrypt.generate_password_hash(value) and False # return bcrypt.check_password_hash(self.password, value) # # Path: doorman/utils.py # def flash_errors(form): # '''http://flask.pocoo.org/snippets/12/''' # for field, errors in form.errors.items(): # for error in errors: # message = u"Error in the {0} field - {1}".format( # getattr(form, field).label.text, error # ) # flash(message, 'danger') which might include code, classes, or functions. Output only the next line.
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 ('_oauth_state', '_oauth_token'): oauth |= not not session.pop(key, None) response = redirect(url_for('users.login')) if username and not oauth: flash(u"You have successfully logged out.", "info") current_app.logger.info("%s logged out", username) # explicitly log the user out, and clear their remember me cookie cookie_name = current_app.config.get('REMEMBER_COOKIE_NAME', COOKIE_NAME) cookie_path = current_app.config.get('REMEMBER_COOKIE_PATH', '/') response.set_cookie(cookie_name, path=cookie_path, expires=0) return response, 302 <|code_end|> , continue by predicting the next line. Consider current file imports: from urlparse import urlparse, urljoin from urllib.parse import urlparse, urljoin from flask import ( Blueprint, abort, current_app, flash, redirect, render_template, request, session, url_for ) from flask_login import current_user, login_user, logout_user, COOKIE_NAME from oauthlib.oauth2 import OAuth2Error from .forms import LoginForm from doorman.extensions import csrf, ldap_manager, login_manager from doorman.models import User from doorman.utils import flash_errors from doorman.users.mixins import NoAuthUserMixin and context: # Path: doorman/users/forms.py # class LoginForm(Form): # # username = StringField('Username', validators=[DataRequired()]) # password = PasswordField('Password', validators=[DataRequired()]) # 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(LoginForm, self).validate() # if not initial_validation: # return False # # error_message = u'Invalid username or password.' # # if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman': # self.user = User.query.filter_by(username=self.username.data).first() # # if not self.user: # from doorman.extensions import bcrypt # # avoid timing leaks # bcrypt.generate_password_hash(self.password.data) # self.username.errors.append(error_message) # return False # # if not self.user.check_password(self.password.data): # self.username.errors.append(error_message) # return False # # return True # # elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap': # result = ldap_manager.authenticate( # self.username.data, # self.password.data # ) # # if result.status == AuthenticationResponseStatus.fail: # self.username.errors.append(error_message) # return False # # self.user = ldap_manager._save_user( # result.user_dn, # result.user_id, # result.user_info, # result.user_groups # ) # return True # # elif current_app.config['DOORMAN_AUTH_METHOD'] is None: # return True # # return False # # @property # def auth_method(self): # return current_app.config['DOORMAN_AUTH_METHOD'] # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/models.py # 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=False, default=dt.datetime.utcnow) # # # oauth related stuff # social_id = Column(db.String) # first_name = Column(db.String) # last_name = Column(db.String) # # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # self.username = username # self.email = email # if password: # self.set_password(password) # else: # self.password = None # # self.social_id = social_id # self.first_name = first_name # self.last_name = last_name # # def set_password(self, password): # self.update(password=bcrypt.generate_password_hash(password)) # return # # def check_password(self, value): # if not self.password: # # still do the computation # return bcrypt.generate_password_hash(value) and False # return bcrypt.check_password_hash(self.password, value) # # Path: doorman/utils.py # def flash_errors(form): # '''http://flask.pocoo.org/snippets/12/''' # for field, errors in form.errors.items(): # for error in errors: # message = u"Error in the {0} field - {1}".format( # getattr(form, field).label.text, error # ) # flash(message, 'danger') which might include code, classes, or functions. Output only the next line.
@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_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, abort, current_app, flash, redirect, render_template, request, session, url_for ) from flask_login import current_user, login_user, logout_user, COOKIE_NAME from oauthlib.oauth2 import OAuth2Error from .forms import LoginForm from doorman.extensions import csrf, ldap_manager, login_manager from doorman.models import User from doorman.utils import flash_errors from doorman.users.mixins import NoAuthUserMixin and context (class names, function names, or code) available: # Path: doorman/users/forms.py # class LoginForm(Form): # # username = StringField('Username', validators=[DataRequired()]) # password = PasswordField('Password', validators=[DataRequired()]) # 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(LoginForm, self).validate() # if not initial_validation: # return False # # error_message = u'Invalid username or password.' # # if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman': # self.user = User.query.filter_by(username=self.username.data).first() # # if not self.user: # from doorman.extensions import bcrypt # # avoid timing leaks # bcrypt.generate_password_hash(self.password.data) # self.username.errors.append(error_message) # return False # # if not self.user.check_password(self.password.data): # self.username.errors.append(error_message) # return False # # return True # # elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap': # result = ldap_manager.authenticate( # self.username.data, # self.password.data # ) # # if result.status == AuthenticationResponseStatus.fail: # self.username.errors.append(error_message) # return False # # self.user = ldap_manager._save_user( # result.user_dn, # result.user_id, # result.user_info, # result.user_groups # ) # return True # # elif current_app.config['DOORMAN_AUTH_METHOD'] is None: # return True # # return False # # @property # def auth_method(self): # return current_app.config['DOORMAN_AUTH_METHOD'] # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/models.py # 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=False, default=dt.datetime.utcnow) # # # oauth related stuff # social_id = Column(db.String) # first_name = Column(db.String) # last_name = Column(db.String) # # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # self.username = username # self.email = email # if password: # self.set_password(password) # else: # self.password = None # # self.social_id = social_id # self.first_name = first_name # self.last_name = last_name # # def set_password(self, password): # self.update(password=bcrypt.generate_password_hash(password)) # return # # def check_password(self, value): # if not self.password: # # still do the computation # return bcrypt.generate_password_hash(value) and False # return bcrypt.check_password_hash(self.password, value) # # Path: doorman/utils.py # def flash_errors(form): # '''http://flask.pocoo.org/snippets/12/''' # for field, errors in form.errors.items(): # for error in errors: # message = u"Error in the {0} field - {1}".format( # getattr(form, field).label.text, error # ) # flash(message, 'danger') . Output only the next line.
@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, abort, current_app, flash, redirect, render_template, request, session, url_for ) from flask_login import current_user, login_user, logout_user, COOKIE_NAME from oauthlib.oauth2 import OAuth2Error from .forms import LoginForm from doorman.extensions import csrf, ldap_manager, login_manager from doorman.models import User from doorman.utils import flash_errors from doorman.users.mixins import NoAuthUserMixin and context (class names, function names, or code) available: # Path: doorman/users/forms.py # class LoginForm(Form): # # username = StringField('Username', validators=[DataRequired()]) # password = PasswordField('Password', validators=[DataRequired()]) # 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(LoginForm, self).validate() # if not initial_validation: # return False # # error_message = u'Invalid username or password.' # # if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman': # self.user = User.query.filter_by(username=self.username.data).first() # # if not self.user: # from doorman.extensions import bcrypt # # avoid timing leaks # bcrypt.generate_password_hash(self.password.data) # self.username.errors.append(error_message) # return False # # if not self.user.check_password(self.password.data): # self.username.errors.append(error_message) # return False # # return True # # elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap': # result = ldap_manager.authenticate( # self.username.data, # self.password.data # ) # # if result.status == AuthenticationResponseStatus.fail: # self.username.errors.append(error_message) # return False # # self.user = ldap_manager._save_user( # result.user_dn, # result.user_id, # result.user_info, # result.user_groups # ) # return True # # elif current_app.config['DOORMAN_AUTH_METHOD'] is None: # return True # # return False # # @property # def auth_method(self): # return current_app.config['DOORMAN_AUTH_METHOD'] # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/models.py # 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=False, default=dt.datetime.utcnow) # # # oauth related stuff # social_id = Column(db.String) # first_name = Column(db.String) # last_name = Column(db.String) # # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # self.username = username # self.email = email # if password: # self.set_password(password) # else: # self.password = None # # self.social_id = social_id # self.first_name = first_name # self.last_name = last_name # # def set_password(self, password): # self.update(password=bcrypt.generate_password_hash(password)) # return # # def check_password(self, value): # if not self.password: # # still do the computation # return bcrypt.generate_password_hash(value) and False # return bcrypt.check_password_hash(self.password, value) # # Path: doorman/utils.py # def flash_errors(form): # '''http://flask.pocoo.org/snippets/12/''' # for field, errors in form.errors.items(): # for error in errors: # message = u"Error in the {0} field - {1}".format( # getattr(form, field).label.text, error # ) # flash(message, 'danger') . Output only the next line.
@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 the imports in this file: from urlparse import urlparse, urljoin from urllib.parse import urlparse, urljoin from flask import ( Blueprint, abort, current_app, flash, redirect, render_template, request, session, url_for ) from flask_login import current_user, login_user, logout_user, COOKIE_NAME from oauthlib.oauth2 import OAuth2Error from .forms import LoginForm from doorman.extensions import csrf, ldap_manager, login_manager from doorman.models import User from doorman.utils import flash_errors from doorman.users.mixins import NoAuthUserMixin and context (functions, classes, or occasionally code) from other files: # Path: doorman/users/forms.py # class LoginForm(Form): # # username = StringField('Username', validators=[DataRequired()]) # password = PasswordField('Password', validators=[DataRequired()]) # 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(LoginForm, self).validate() # if not initial_validation: # return False # # error_message = u'Invalid username or password.' # # if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman': # self.user = User.query.filter_by(username=self.username.data).first() # # if not self.user: # from doorman.extensions import bcrypt # # avoid timing leaks # bcrypt.generate_password_hash(self.password.data) # self.username.errors.append(error_message) # return False # # if not self.user.check_password(self.password.data): # self.username.errors.append(error_message) # return False # # return True # # elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap': # result = ldap_manager.authenticate( # self.username.data, # self.password.data # ) # # if result.status == AuthenticationResponseStatus.fail: # self.username.errors.append(error_message) # return False # # self.user = ldap_manager._save_user( # result.user_dn, # result.user_id, # result.user_info, # result.user_groups # ) # return True # # elif current_app.config['DOORMAN_AUTH_METHOD'] is None: # return True # # return False # # @property # def auth_method(self): # return current_app.config['DOORMAN_AUTH_METHOD'] # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/models.py # 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=False, default=dt.datetime.utcnow) # # # oauth related stuff # social_id = Column(db.String) # first_name = Column(db.String) # last_name = Column(db.String) # # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # self.username = username # self.email = email # if password: # self.set_password(password) # else: # self.password = None # # self.social_id = social_id # self.first_name = first_name # self.last_name = last_name # # def set_password(self, password): # self.update(password=bcrypt.generate_password_hash(password)) # return # # def check_password(self, value): # if not self.password: # # still do the computation # return bcrypt.generate_password_hash(value) and False # return bcrypt.check_password_hash(self.password, value) # # Path: doorman/utils.py # def flash_errors(form): # '''http://flask.pocoo.org/snippets/12/''' # for field, errors in form.errors.items(): # for error in errors: # message = u"Error in the {0} field - {1}".format( # getattr(form, field).label.text, error # ) # flash(message, 'danger') . Output only the next line.
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)) details = { 'node': node, 'rule_name': match.rule.name, 'rule_description': match.rule.description, 'action': match.result['action'], 'match': match.result['columns'], } headers = { 'Content-type': 'application/json', } payload = json.dumps({ 'event_type': 'trigger', 'service_key': self.service_key, 'incident_key': key, 'description': description, 'client': 'Doorman', "client_url": self.client_url, 'details': details, <|code_end|> , predict the next line using imports from the current file: import json import logging import requests from doorman.utils import DateTimeEncoder from .base import AbstractAlerterPlugin and context including class names, function names, and sometimes code from other files: # Path: doorman/utils.py # class DateTimeEncoder(json.JSONEncoder): # def default(self, o): # if isinstance(o, dt.datetime): # return o.isoformat() # # return json.JSONEncoder.default(self, o) # # Path: doorman/plugins/alerters/base.py # class AbstractAlerterPlugin(with_metaclass(ABCMeta)): # """ # AbstractAlerterPlugin is the base class for all alerters in Doorman. It # defines the interface that an alerter should implement in order to support # sending an alert. # """ # @abstractmethod # def handle_alert(self, node, match): # raise NotImplementedError() . Output only the next line.
}, 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 = reference_col('node', nullable=False) node = relationship( 'Node', backref=db.backref('result_logs', lazy='dynamic') ) def __init__(self, name=None, action=None, columns=None, timestamp=None, node=None, node_id=None, **kwargs): self.name = name self.action = action self.columns = columns or {} self.timestamp = timestamp if node: self.node = node elif node_id: self.node_id = node_id @declared_attr def __table_args__(cls): return ( <|code_end|> . Use current file imports: import datetime as dt import string import uuid from flask_login import UserMixin from doorman.database import ( Column, Table, ForeignKey, Index, Model, SurrogatePK, db, reference_col, relationship, ARRAY, JSONB, INET, declared_attr, ) from doorman.extensions import bcrypt from doorman.utils import assemble_configuration from doorman.utils import assemble_distributed_queries and context (classes, functions, or code) from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): . Output only the next line.
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'), index=True) ) node_tags = Table( 'node_tags', Column('tag.id', db.Integer, ForeignKey('tag.id')), Column('node.id', db.Integer, ForeignKey('node.id'), index=True) ) query_tags = Table( 'query_tags', Column('tag.id', db.Integer, ForeignKey('tag.id')), Column('query.id', db.Integer, ForeignKey('query.id'), index=True) ) file_path_tags = Table( 'file_path_tags', Column('tag.id', db.Integer, ForeignKey('tag.id')), Column('file_path.id', db.Integer, ForeignKey('file_path.id'), index=True) ) <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime as dt import string import uuid from flask_login import UserMixin from doorman.database import ( Column, Table, ForeignKey, Index, Model, SurrogatePK, db, reference_col, relationship, ARRAY, JSONB, INET, declared_attr, ) from doorman.extensions import bcrypt from doorman.utils import assemble_configuration from doorman.utils import assemble_distributed_queries and context: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): which might include code, classes, or functions. Output only the next line.
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'), index=True) ) node_tags = Table( 'node_tags', Column('tag.id', db.Integer, ForeignKey('tag.id')), Column('node.id', db.Integer, ForeignKey('node.id'), index=True) ) query_tags = Table( 'query_tags', Column('tag.id', db.Integer, ForeignKey('tag.id')), Column('query.id', db.Integer, ForeignKey('query.id'), index=True) ) file_path_tags = Table( 'file_path_tags', Column('tag.id', db.Integer, ForeignKey('tag.id')), Column('file_path.id', db.Integer, ForeignKey('file_path.id'), index=True) ) <|code_end|> , predict the immediate next line with the help of imports: import datetime as dt import string import uuid from flask_login import UserMixin from doorman.database import ( Column, Table, ForeignKey, Index, Model, SurrogatePK, db, reference_col, relationship, ARRAY, JSONB, INET, declared_attr, ) from doorman.extensions import bcrypt from doorman.utils import assemble_configuration from doorman.utils import assemble_distributed_queries and context (classes, functions, sometimes code) from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): . Output only the next line.
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 = '' def to_dict(self): return { self.category: self.get_paths() } def get_paths(self): 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=dt.datetime.utcnow) action = Column(db.String) columns = Column(JSONB) <|code_end|> . Write the next line using the current file imports: import datetime as dt import string import uuid from flask_login import UserMixin from doorman.database import ( Column, Table, ForeignKey, Index, Model, SurrogatePK, db, reference_col, relationship, ARRAY, JSONB, INET, declared_attr, ) from doorman.extensions import bcrypt from doorman.utils import assemble_configuration from doorman.utils import assemble_distributed_queries and context from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): , which may include functions, classes, or code. Output only the next line.
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.Integer, ForeignKey('node.id'), index=True) ) query_tags = Table( 'query_tags', Column('tag.id', db.Integer, ForeignKey('tag.id')), Column('query.id', db.Integer, ForeignKey('query.id'), index=True) ) file_path_tags = Table( 'file_path_tags', Column('tag.id', db.Integer, ForeignKey('tag.id')), Column('file_path.id', db.Integer, ForeignKey('file_path.id'), index=True) ) class Tag(SurrogatePK, Model): value = Column(db.String, nullable=False, unique=True) <|code_end|> . Use current file imports: (import datetime as dt import string import uuid from flask_login import UserMixin from doorman.database import ( Column, Table, ForeignKey, Index, Model, SurrogatePK, db, reference_col, relationship, ARRAY, JSONB, INET, declared_attr, ) from doorman.extensions import bcrypt from doorman.utils import assemble_configuration from doorman.utils import assemble_distributed_queries) and context including class names, function names, or small code snippets from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): . Output only the next line.
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 = relationship( 'DistributedQueryTask', backref=db.backref('results', cascade='all, delete-orphan', lazy='joined'), ) distributed_query_id = reference_col('distributed_query', nullable=False) distributed_query = relationship( 'DistributedQuery', backref=db.backref('results', cascade='all, delete-orphan', lazy='joined'), ) def __init__(self, columns, distributed_query=None, distributed_query_task=None): self.columns = columns self.distributed_query = distributed_query self.distributed_query_task = distributed_query_task class Rule(SurrogatePK, Model): name = Column(db.String, nullable=False) <|code_end|> with the help of current file imports: import datetime as dt import string import uuid from flask_login import UserMixin from doorman.database import ( Column, Table, ForeignKey, Index, Model, SurrogatePK, db, reference_col, relationship, ARRAY, JSONB, INET, declared_attr, ) from doorman.extensions import bcrypt from doorman.utils import assemble_configuration from doorman.utils import assemble_distributed_queries and context from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): , which may contain function names, class names, or code. Output only the next line.
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): discovery.append(query.sql) else: queries[query.name] = query.to_dict() return { 'platform': self.platform, 'version': self.version, 'shard': self.shard, 'discovery': discovery, 'queries': queries, } class Node(SurrogatePK, Model): node_key = Column(db.String, nullable=False, unique=True) enroll_secret = Column(db.String) enrolled_on = Column(db.DateTime) host_identifier = Column(db.String) last_checkin = Column(db.DateTime) <|code_end|> , predict the next line using imports from the current file: import datetime as dt import string import uuid from flask_login import UserMixin from doorman.database import ( Column, Table, ForeignKey, Index, Model, SurrogatePK, db, reference_col, relationship, ARRAY, JSONB, INET, declared_attr, ) from doorman.extensions import bcrypt from doorman.utils import assemble_configuration from doorman.utils import assemble_distributed_queries and context including class names, function names, and sometimes code from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): . Output only the next line.
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: queries[query.name] = query.to_dict() return { 'platform': self.platform, 'version': self.version, 'shard': self.shard, 'discovery': discovery, 'queries': queries, } class Node(SurrogatePK, Model): node_key = Column(db.String, nullable=False, unique=True) enroll_secret = Column(db.String) enrolled_on = Column(db.DateTime) host_identifier = Column(db.String) last_checkin = Column(db.DateTime) node_info = Column(JSONB, default={}, nullable=False) is_active = Column(db.Boolean, default=True, nullable=False) <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime as dt import string import uuid from flask_login import UserMixin from doorman.database import ( Column, Table, ForeignKey, Index, Model, SurrogatePK, db, reference_col, relationship, ARRAY, JSONB, INET, declared_attr, ) from doorman.extensions import bcrypt from doorman.utils import assemble_configuration from doorman.utils import assemble_distributed_queries and context: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): which might include code, classes, or functions. Output only the next line.
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=dt.datetime.utcnow) action = Column(db.String) columns = Column(JSONB) node_id = reference_col('node', nullable=False) node = relationship( 'Node', backref=db.backref('result_logs', lazy='dynamic') ) def __init__(self, name=None, action=None, columns=None, timestamp=None, node=None, node_id=None, **kwargs): self.name = name self.action = action self.columns = columns or {} self.timestamp = timestamp if node: self.node = node elif node_id: self.node_id = node_id <|code_end|> with the help of current file imports: import datetime as dt import string import uuid from flask_login import UserMixin from doorman.database import ( Column, Table, ForeignKey, Index, Model, SurrogatePK, db, reference_col, relationship, ARRAY, JSONB, INET, declared_attr, ) from doorman.extensions import bcrypt from doorman.utils import assemble_configuration from doorman.utils import assemble_distributed_queries and context from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): , which may contain function names, class names, or code. Output only the next line.
@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=False, default=dt.datetime.utcnow) # oauth related stuff social_id = Column(db.String) first_name = Column(db.String) last_name = Column(db.String) def __init__(self, username, password=None, email=None, social_id=None, first_name=None, last_name=None): self.username = username self.email = email if password: self.set_password(password) else: self.password = None self.social_id = social_id self.first_name = first_name self.last_name = last_name def set_password(self, password): <|code_end|> , predict the next line using imports from the current file: import datetime as dt import string import uuid from flask_login import UserMixin from doorman.database import ( Column, Table, ForeignKey, Index, Model, SurrogatePK, db, reference_col, relationship, ARRAY, JSONB, INET, declared_attr, ) from doorman.extensions import bcrypt from doorman.utils import assemble_configuration from doorman.utils import assemble_distributed_queries and context including class names, function names, and sometimes code from other files: # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): . Output only the next line.
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.test_request_context() ctx.push() try: yield _app finally: ctx.pop() @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.""" <|code_end|> with the help of current file imports: import pytest import os from webtest import TestApp from doorman.application import create_app from doorman.database import db as _db from doorman.models import Rule from doorman.settings import TestConfig from .factories import NodeFactory, RuleFactory and context from other files: # Path: doorman/application.py # 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_auth_method(app) # register_filters(app) # # return app # # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/models.py # class Rule(SurrogatePK, Model): # # name = Column(db.String, nullable=False) # alerters = Column(ARRAY(db.String), nullable=False) # description = Column(db.String, nullable=True) # conditions = Column(JSONB) # updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # self.name = name # self.description = description # self.alerters = alerters # self.conditions = conditions # self.updated_at = updated_at # # @property # def template(self): # return string.Template("{name}\r\n\r\n{description}".format( # name=self.name, description=self.description or '') # ) # # Path: doorman/settings.py # class TestConfig(Config): # """ # This class specifies a configuration that is used for our tests. # """ # TESTING = True # DEBUG = True # # SQLALCHEMY_DATABASE_URI = 'postgresql://localhost:5432/doorman_test' # # WTF_CSRF_ENABLED = False # # DOORMAN_ENROLL_SECRET = [ # 'secret', # ] # DOORMAN_EXPECTS_UNIQUE_HOST_ID = False # # DOORMAN_AUTH_METHOD = None # # DOORMAN_COLUMN_RENDER = { # 'computer_name': '<a href="https://{{ value | urlencode }}/">{{ value }}</a>' # } # # Path: tests/factories.py # class NodeFactory(BaseFactory): # # class Meta: # model = Node # # class RuleFactory(BaseFactory): # # class Meta: # model = Rule , which may contain function names, class names, or code. Output only the next line.
_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 = app with app.app_context(): _db.create_all() yield _db # Explicitly close DB connection _db.session.close() _db.drop_all() @pytest.fixture def node(db): """A node for the tests.""" <|code_end|> . Use current file imports: (import pytest import os from webtest import TestApp from doorman.application import create_app from doorman.database import db as _db from doorman.models import Rule from doorman.settings import TestConfig from .factories import NodeFactory, RuleFactory) and context including class names, function names, or small code snippets from other files: # Path: doorman/application.py # 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_auth_method(app) # register_filters(app) # # return app # # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/models.py # class Rule(SurrogatePK, Model): # # name = Column(db.String, nullable=False) # alerters = Column(ARRAY(db.String), nullable=False) # description = Column(db.String, nullable=True) # conditions = Column(JSONB) # updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # self.name = name # self.description = description # self.alerters = alerters # self.conditions = conditions # self.updated_at = updated_at # # @property # def template(self): # return string.Template("{name}\r\n\r\n{description}".format( # name=self.name, description=self.description or '') # ) # # Path: doorman/settings.py # class TestConfig(Config): # """ # This class specifies a configuration that is used for our tests. # """ # TESTING = True # DEBUG = True # # SQLALCHEMY_DATABASE_URI = 'postgresql://localhost:5432/doorman_test' # # WTF_CSRF_ENABLED = False # # DOORMAN_ENROLL_SECRET = [ # 'secret', # ] # DOORMAN_EXPECTS_UNIQUE_HOST_ID = False # # DOORMAN_AUTH_METHOD = None # # DOORMAN_COLUMN_RENDER = { # 'computer_name': '<a href="https://{{ value | urlencode }}/">{{ value }}</a>' # } # # Path: tests/factories.py # class NodeFactory(BaseFactory): # # class Meta: # model = Node # # class RuleFactory(BaseFactory): # # class Meta: # model = Rule . Output only the next line.
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 connection _db.session.close() _db.drop_all() @pytest.fixture def node(db): """A node for the tests.""" node = NodeFactory(host_identifier='foobar', enroll_secret='foobar') db.session.commit() return node @pytest.fixture def rule(db): <|code_end|> , predict the immediate next line with the help of imports: import pytest import os from webtest import TestApp from doorman.application import create_app from doorman.database import db as _db from doorman.models import Rule from doorman.settings import TestConfig from .factories import NodeFactory, RuleFactory and context (classes, functions, sometimes code) from other files: # Path: doorman/application.py # 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_auth_method(app) # register_filters(app) # # return app # # Path: doorman/database.py # class CRUDMixin(object): # class Model(CRUDMixin, db.Model): # class SurrogatePK(object): # def create(cls, **kwargs): # def update(self, commit=True, **kwargs): # def save(self, commit=True): # def delete(self, commit=True): # def get_by_id(cls, record_id): # def reference_col(tablename, nullable=False, pk_name='id', **kwargs): # # Path: doorman/models.py # class Rule(SurrogatePK, Model): # # name = Column(db.String, nullable=False) # alerters = Column(ARRAY(db.String), nullable=False) # description = Column(db.String, nullable=True) # conditions = Column(JSONB) # updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # self.name = name # self.description = description # self.alerters = alerters # self.conditions = conditions # self.updated_at = updated_at # # @property # def template(self): # return string.Template("{name}\r\n\r\n{description}".format( # name=self.name, description=self.description or '') # ) # # Path: doorman/settings.py # class TestConfig(Config): # """ # This class specifies a configuration that is used for our tests. # """ # TESTING = True # DEBUG = True # # SQLALCHEMY_DATABASE_URI = 'postgresql://localhost:5432/doorman_test' # # WTF_CSRF_ENABLED = False # # DOORMAN_ENROLL_SECRET = [ # 'secret', # ] # DOORMAN_EXPECTS_UNIQUE_HOST_ID = False # # DOORMAN_AUTH_METHOD = None # # DOORMAN_COLUMN_RENDER = { # 'computer_name': '<a href="https://{{ value | urlencode }}/">{{ value }}</a>' # } # # Path: tests/factories.py # class NodeFactory(BaseFactory): # # class Meta: # model = Node # # class RuleFactory(BaseFactory): # # class Meta: # model = Rule . Output only the next line.
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())) } else: return json.JSONEncoder.default(self, obj) def djson_decoder(obj): if '__type__' in obj: if obj['__type__'] == '__datetime__': return datetime.fromtimestamp(obj['epoch']) return obj # Encoder function def djson_dumps(obj): return json.dumps(obj, cls=DJSONEncoder) # Decoder function def djson_loads(s): <|code_end|> with the help of current file imports: from datetime import datetime from time import mktime from doorman.compat import string_types import json and context from other files: # Path: doorman/compat.py # PY2 = int(sys.version[0]) == 2 # def with_metaclass(meta, *bases): # def __new__(cls, name, this_bases, d): # class metaclass(meta): , which may contain function names, class names, or code. Output only the next line.
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.validate() is True class TestCreateQueryForm: def test_sql_validate_failure(self, testapp, db): <|code_end|> , determine the next line of code. You have imports: from doorman.manage.forms import ( CreateQueryForm, UpdateQueryForm, UploadPackForm, CreateTagForm, ) from .factories import QueryFactory and context (class names, function names, or code) available: # Path: doorman/manage/forms.py # class CreateQueryForm(QueryForm): # # def validate(self): # from doorman.models import Query # initial_validation = super(CreateQueryForm, self).validate() # if not initial_validation: # return False # # query = Query.query.filter(Query.name == self.name.data).first() # if query: # self.name.errors.append( # u"Query with the name {0} already exists!".format( # self.name.data) # ) # return False # # # TODO could do some validation of the sql query # return True # # class UpdateQueryForm(QueryForm): # # def __init__(self, *args, **kwargs): # super(UpdateQueryForm, self).__init__(*args, **kwargs) # self.set_choices() # query = kwargs.pop('obj', None) # if query: # self.packs.process_data([p.name for p in query.packs]) # self.tags.process_data('\n'.join(t.value for t in query.tags)) # # class UploadPackForm(Form): # # pack = FileField(u'Pack configuration', validators=[FileRequired()]) # # class CreateTagForm(Form): # value = TextAreaField('Tag', validators=[DataRequired()]) # # Path: tests/factories.py # class QueryFactory(BaseFactory): # # class Meta: # model = Query . Output only the next line.
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;' ) assert form.validate() is False assert 'sql' in form.errors assert 'name' not in form.errors def test_sql_validate_success(self, testapp, db): form = CreateQueryForm( name='foobar', sql='select * from osquery_info;', ) assert form.validate() is True class TestUpdateQueryForm: def test_sql_validate_failure(self, testapp, db): query = QueryFactory( name='foobar', sql='select * from osquery_info;' ) <|code_end|> . Use current file imports: (from doorman.manage.forms import ( CreateQueryForm, UpdateQueryForm, UploadPackForm, CreateTagForm, ) from .factories import QueryFactory) and context including class names, function names, or small code snippets from other files: # Path: doorman/manage/forms.py # class CreateQueryForm(QueryForm): # # def validate(self): # from doorman.models import Query # initial_validation = super(CreateQueryForm, self).validate() # if not initial_validation: # return False # # query = Query.query.filter(Query.name == self.name.data).first() # if query: # self.name.errors.append( # u"Query with the name {0} already exists!".format( # self.name.data) # ) # return False # # # TODO could do some validation of the sql query # return True # # class UpdateQueryForm(QueryForm): # # def __init__(self, *args, **kwargs): # super(UpdateQueryForm, self).__init__(*args, **kwargs) # self.set_choices() # query = kwargs.pop('obj', None) # if query: # self.packs.process_data([p.name for p in query.packs]) # self.tags.process_data('\n'.join(t.value for t in query.tags)) # # class UploadPackForm(Form): # # pack = FileField(u'Pack configuration', validators=[FileRequired()]) # # class CreateTagForm(Form): # value = TextAreaField('Tag', validators=[DataRequired()]) # # Path: tests/factories.py # class QueryFactory(BaseFactory): # # class Meta: # model = Query . Output only the next line.
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_failure(self, testapp, db): form = CreateQueryForm( name='foobar', sql='select * from foobar;' ) assert form.validate() is False assert 'sql' in form.errors assert 'name' not in form.errors def test_sql_validate_success(self, testapp, db): form = CreateQueryForm( name='foobar', sql='select * from osquery_info;', ) assert form.validate() is True class TestUpdateQueryForm: def test_sql_validate_failure(self, testapp, db): <|code_end|> using the current file's imports: from doorman.manage.forms import ( CreateQueryForm, UpdateQueryForm, UploadPackForm, CreateTagForm, ) from .factories import QueryFactory and any relevant context from other files: # Path: doorman/manage/forms.py # class CreateQueryForm(QueryForm): # # def validate(self): # from doorman.models import Query # initial_validation = super(CreateQueryForm, self).validate() # if not initial_validation: # return False # # query = Query.query.filter(Query.name == self.name.data).first() # if query: # self.name.errors.append( # u"Query with the name {0} already exists!".format( # self.name.data) # ) # return False # # # TODO could do some validation of the sql query # return True # # class UpdateQueryForm(QueryForm): # # def __init__(self, *args, **kwargs): # super(UpdateQueryForm, self).__init__(*args, **kwargs) # self.set_choices() # query = kwargs.pop('obj', None) # if query: # self.packs.process_data([p.name for p in query.packs]) # self.tags.process_data('\n'.join(t.value for t in query.tags)) # # class UploadPackForm(Form): # # pack = FileField(u'Pack configuration', validators=[FileRequired()]) # # class CreateTagForm(Form): # value = TextAreaField('Tag', validators=[DataRequired()]) # # Path: tests/factories.py # class QueryFactory(BaseFactory): # # class Meta: # model = Query . Output only the next line.
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 doorman.rules import ( BaseCondition, EqualCondition, LessCondition, GreaterEqualCondition, LogicCondition, MatchesRegexCondition, Network, NotMatchesRegexCondition, RuleInput, )) and context including class names, function names, or small code snippets from other files: # Path: doorman/rules.py # class Network(object): # class BaseCondition(object): # class AndCondition(BaseCondition): # class OrCondition(BaseCondition): # class LogicCondition(BaseCondition): # class EqualCondition(LogicCondition): # class NotEqualCondition(LogicCondition): # class BeginsWithCondition(LogicCondition): # class NotBeginsWithCondition(LogicCondition): # class ContainsCondition(LogicCondition): # class NotContainsCondition(LogicCondition): # class EndsWithCondition(LogicCondition): # class NotEndsWithCondition(LogicCondition): # class IsEmptyCondition(LogicCondition): # class IsNotEmptyCondition(LogicCondition): # class LessCondition(LogicCondition): # class LessEqualCondition(LogicCondition): # class GreaterCondition(LogicCondition): # class GreaterEqualCondition(LogicCondition): # class MatchesRegexCondition(LogicCondition): # class NotMatchesRegexCondition(LogicCondition): # def __init__(self): # def make_condition(self, klass, *args, **kwargs): # def tupleify(obj): # def make_alert_condition(self, alert, dependent, rule_id=None): # def process(self, entry, node): # def parse_query(self, query, alerters=None, rule_id=None): # def parse_condition(d): # def parse_group(d): # def parse(d): # def __init__(self): # def init_network(self, network): # def run(self, input): # def local_run(self, input): # def __repr__(self): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, key, expected, column_name=None): # def maybe_make_number(self, value): # def local_run(self, input): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # OPERATOR_MAP = { # 'equal': EqualCondition, # 'not_equal': NotEqualCondition, # 'begins_with': BeginsWithCondition, # 'not_begins_with': NotBeginsWithCondition, # 'contains': ContainsCondition, # 'not_contains': NotContainsCondition, # 'ends_with': EndsWithCondition, # 'not_ends_with': NotEndsWithCondition, # 'is_empty': IsEmptyCondition, # 'is_not_empty': IsNotEmptyCondition, # 'less': LessCondition, # 'less_or_equal': LessEqualCondition, # 'greater': GreaterCondition, # 'greater_or_equal': GreaterEqualCondition, # 'matches_regex': MatchesRegexCondition, # 'not_matches_regex': NotMatchesRegexCondition, # } . Output only the next line.
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(None, None, column_name='int_col') condition.local_run(inp) assert condition.compare_val == 1234 condition = TestCondition(None, None, column_name='float_col') condition.local_run(inp) assert condition.compare_val == 56.78 def test_less_with_number_values(self): """ 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 when the column value # posted by osquery ('112') is less than configured in the rule ('12') <|code_end|> , determine the next line of code. You have imports: import json import logging import datetime as dt from collections import defaultdict from doorman.rules import ( BaseCondition, EqualCondition, LessCondition, GreaterEqualCondition, LogicCondition, MatchesRegexCondition, Network, NotMatchesRegexCondition, RuleInput, ) and context (class names, function names, or code) available: # Path: doorman/rules.py # class Network(object): # class BaseCondition(object): # class AndCondition(BaseCondition): # class OrCondition(BaseCondition): # class LogicCondition(BaseCondition): # class EqualCondition(LogicCondition): # class NotEqualCondition(LogicCondition): # class BeginsWithCondition(LogicCondition): # class NotBeginsWithCondition(LogicCondition): # class ContainsCondition(LogicCondition): # class NotContainsCondition(LogicCondition): # class EndsWithCondition(LogicCondition): # class NotEndsWithCondition(LogicCondition): # class IsEmptyCondition(LogicCondition): # class IsNotEmptyCondition(LogicCondition): # class LessCondition(LogicCondition): # class LessEqualCondition(LogicCondition): # class GreaterCondition(LogicCondition): # class GreaterEqualCondition(LogicCondition): # class MatchesRegexCondition(LogicCondition): # class NotMatchesRegexCondition(LogicCondition): # def __init__(self): # def make_condition(self, klass, *args, **kwargs): # def tupleify(obj): # def make_alert_condition(self, alert, dependent, rule_id=None): # def process(self, entry, node): # def parse_query(self, query, alerters=None, rule_id=None): # def parse_condition(d): # def parse_group(d): # def parse(d): # def __init__(self): # def init_network(self, network): # def run(self, input): # def local_run(self, input): # def __repr__(self): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, key, expected, column_name=None): # def maybe_make_number(self, value): # def local_run(self, input): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # OPERATOR_MAP = { # 'equal': EqualCondition, # 'not_equal': NotEqualCondition, # 'begins_with': BeginsWithCondition, # 'not_begins_with': NotBeginsWithCondition, # 'contains': ContainsCondition, # 'not_contains': NotContainsCondition, # 'ends_with': EndsWithCondition, # 'not_ends_with': NotEndsWithCondition, # 'is_empty': IsEmptyCondition, # 'is_not_empty': IsNotEmptyCondition, # 'less': LessCondition, # 'less_or_equal': LessEqualCondition, # 'greater': GreaterCondition, # 'greater_or_equal': GreaterEqualCondition, # 'matches_regex': MatchesRegexCondition, # 'not_matches_regex': NotMatchesRegexCondition, # } . Output only the next line.
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 when the column value # posted by osquery ('112') is less than configured in the rule ('12') condition = LessCondition(None, '12', column_name='val') assert condition.local_run(inp) is False 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_number_values(self): inp = RuleInput(node={}, result_log={ 'columns': { 'val': '112', }, }) # assert that the rule does not alert when the column value # posted by osquery ('112') is less than configured in the rule ('12') <|code_end|> using the current file's imports: import json import logging import datetime as dt from collections import defaultdict from doorman.rules import ( BaseCondition, EqualCondition, LessCondition, GreaterEqualCondition, LogicCondition, MatchesRegexCondition, Network, NotMatchesRegexCondition, RuleInput, ) and any relevant context from other files: # Path: doorman/rules.py # class Network(object): # class BaseCondition(object): # class AndCondition(BaseCondition): # class OrCondition(BaseCondition): # class LogicCondition(BaseCondition): # class EqualCondition(LogicCondition): # class NotEqualCondition(LogicCondition): # class BeginsWithCondition(LogicCondition): # class NotBeginsWithCondition(LogicCondition): # class ContainsCondition(LogicCondition): # class NotContainsCondition(LogicCondition): # class EndsWithCondition(LogicCondition): # class NotEndsWithCondition(LogicCondition): # class IsEmptyCondition(LogicCondition): # class IsNotEmptyCondition(LogicCondition): # class LessCondition(LogicCondition): # class LessEqualCondition(LogicCondition): # class GreaterCondition(LogicCondition): # class GreaterEqualCondition(LogicCondition): # class MatchesRegexCondition(LogicCondition): # class NotMatchesRegexCondition(LogicCondition): # def __init__(self): # def make_condition(self, klass, *args, **kwargs): # def tupleify(obj): # def make_alert_condition(self, alert, dependent, rule_id=None): # def process(self, entry, node): # def parse_query(self, query, alerters=None, rule_id=None): # def parse_condition(d): # def parse_group(d): # def parse(d): # def __init__(self): # def init_network(self, network): # def run(self, input): # def local_run(self, input): # def __repr__(self): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, key, expected, column_name=None): # def maybe_make_number(self, value): # def local_run(self, input): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # OPERATOR_MAP = { # 'equal': EqualCondition, # 'not_equal': NotEqualCondition, # 'begins_with': BeginsWithCondition, # 'not_begins_with': NotBeginsWithCondition, # 'contains': ContainsCondition, # 'not_contains': NotContainsCondition, # 'ends_with': EndsWithCondition, # 'not_ends_with': NotEndsWithCondition, # 'is_empty': IsEmptyCondition, # 'is_not_empty': IsNotEmptyCondition, # 'less': LessCondition, # 'less_or_equal': LessEqualCondition, # 'greater': GreaterCondition, # 'greater_or_equal': GreaterEqualCondition, # 'matches_regex': MatchesRegexCondition, # 'not_matches_regex': NotMatchesRegexCondition, # } . Output only the next line.
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) assert condition.called_run def test_will_cache_result(self): class SubCondition(BaseCondition): def __init__(self): BaseCondition.__init__(self) self.runs = 0 def local_run(self, input): self.runs += 1 condition = SubCondition() condition.run(DUMMY_INPUT) condition.run(DUMMY_INPUT) assert condition.runs == 1 class TestLogicCondition: def test_will_convert_to_numbers(self): <|code_end|> . Use current file imports: import json import logging import datetime as dt from collections import defaultdict from doorman.rules import ( BaseCondition, EqualCondition, LessCondition, GreaterEqualCondition, LogicCondition, MatchesRegexCondition, Network, NotMatchesRegexCondition, RuleInput, ) and context (classes, functions, or code) from other files: # Path: doorman/rules.py # class Network(object): # class BaseCondition(object): # class AndCondition(BaseCondition): # class OrCondition(BaseCondition): # class LogicCondition(BaseCondition): # class EqualCondition(LogicCondition): # class NotEqualCondition(LogicCondition): # class BeginsWithCondition(LogicCondition): # class NotBeginsWithCondition(LogicCondition): # class ContainsCondition(LogicCondition): # class NotContainsCondition(LogicCondition): # class EndsWithCondition(LogicCondition): # class NotEndsWithCondition(LogicCondition): # class IsEmptyCondition(LogicCondition): # class IsNotEmptyCondition(LogicCondition): # class LessCondition(LogicCondition): # class LessEqualCondition(LogicCondition): # class GreaterCondition(LogicCondition): # class GreaterEqualCondition(LogicCondition): # class MatchesRegexCondition(LogicCondition): # class NotMatchesRegexCondition(LogicCondition): # def __init__(self): # def make_condition(self, klass, *args, **kwargs): # def tupleify(obj): # def make_alert_condition(self, alert, dependent, rule_id=None): # def process(self, entry, node): # def parse_query(self, query, alerters=None, rule_id=None): # def parse_condition(d): # def parse_group(d): # def parse(d): # def __init__(self): # def init_network(self, network): # def run(self, input): # def local_run(self, input): # def __repr__(self): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, key, expected, column_name=None): # def maybe_make_number(self, value): # def local_run(self, input): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # OPERATOR_MAP = { # 'equal': EqualCondition, # 'not_equal': NotEqualCondition, # 'begins_with': BeginsWithCondition, # 'not_begins_with': NotBeginsWithCondition, # 'contains': ContainsCondition, # 'not_contains': NotContainsCondition, # 'ends_with': EndsWithCondition, # 'not_ends_with': NotEndsWithCondition, # 'is_empty': IsEmptyCondition, # 'is_not_empty': IsNotEmptyCondition, # 'less': LessCondition, # 'less_or_equal': LessEqualCondition, # 'greater': GreaterCondition, # 'greater_or_equal': GreaterEqualCondition, # 'matches_regex': MatchesRegexCondition, # 'not_matches_regex': NotMatchesRegexCondition, # } . Output only the next line.
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_number_values(self): inp = RuleInput(node={}, result_log={ 'columns': { 'val': '112', }, }) # assert that the rule does not alert when the column value # posted by osquery ('112') is less than configured in the rule ('12') condition = GreaterEqualCondition(None, '12', column_name='val') assert condition.local_run(inp) is True condition = GreaterEqualCondition(None, '112', column_name='val') assert condition.local_run(inp) is True condition = GreaterEqualCondition(None, '113', column_name='val') assert condition.local_run(inp) is False class TestRegexConditions: def test_matches_regex(self): <|code_end|> using the current file's imports: import json import logging import datetime as dt from collections import defaultdict from doorman.rules import ( BaseCondition, EqualCondition, LessCondition, GreaterEqualCondition, LogicCondition, MatchesRegexCondition, Network, NotMatchesRegexCondition, RuleInput, ) and any relevant context from other files: # Path: doorman/rules.py # class Network(object): # class BaseCondition(object): # class AndCondition(BaseCondition): # class OrCondition(BaseCondition): # class LogicCondition(BaseCondition): # class EqualCondition(LogicCondition): # class NotEqualCondition(LogicCondition): # class BeginsWithCondition(LogicCondition): # class NotBeginsWithCondition(LogicCondition): # class ContainsCondition(LogicCondition): # class NotContainsCondition(LogicCondition): # class EndsWithCondition(LogicCondition): # class NotEndsWithCondition(LogicCondition): # class IsEmptyCondition(LogicCondition): # class IsNotEmptyCondition(LogicCondition): # class LessCondition(LogicCondition): # class LessEqualCondition(LogicCondition): # class GreaterCondition(LogicCondition): # class GreaterEqualCondition(LogicCondition): # class MatchesRegexCondition(LogicCondition): # class NotMatchesRegexCondition(LogicCondition): # def __init__(self): # def make_condition(self, klass, *args, **kwargs): # def tupleify(obj): # def make_alert_condition(self, alert, dependent, rule_id=None): # def process(self, entry, node): # def parse_query(self, query, alerters=None, rule_id=None): # def parse_condition(d): # def parse_group(d): # def parse(d): # def __init__(self): # def init_network(self, network): # def run(self, input): # def local_run(self, input): # def __repr__(self): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, key, expected, column_name=None): # def maybe_make_number(self, value): # def local_run(self, input): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # OPERATOR_MAP = { # 'equal': EqualCondition, # 'not_equal': NotEqualCondition, # 'begins_with': BeginsWithCondition, # 'not_begins_with': NotBeginsWithCondition, # 'contains': ContainsCondition, # 'not_contains': NotContainsCondition, # 'ends_with': EndsWithCondition, # 'not_ends_with': NotEndsWithCondition, # 'is_empty': IsEmptyCondition, # 'is_not_empty': IsNotEmptyCondition, # 'less': LessCondition, # 'less_or_equal': LessEqualCondition, # 'greater': GreaterCondition, # 'greater_or_equal': GreaterEqualCondition, # 'matches_regex': MatchesRegexCondition, # 'not_matches_regex': NotMatchesRegexCondition, # } . Output only the next line.
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 imports: import json import logging import datetime as dt from collections import defaultdict from doorman.rules import ( BaseCondition, EqualCondition, LessCondition, GreaterEqualCondition, LogicCondition, MatchesRegexCondition, Network, NotMatchesRegexCondition, RuleInput, ) and context: # Path: doorman/rules.py # class Network(object): # class BaseCondition(object): # class AndCondition(BaseCondition): # class OrCondition(BaseCondition): # class LogicCondition(BaseCondition): # class EqualCondition(LogicCondition): # class NotEqualCondition(LogicCondition): # class BeginsWithCondition(LogicCondition): # class NotBeginsWithCondition(LogicCondition): # class ContainsCondition(LogicCondition): # class NotContainsCondition(LogicCondition): # class EndsWithCondition(LogicCondition): # class NotEndsWithCondition(LogicCondition): # class IsEmptyCondition(LogicCondition): # class IsNotEmptyCondition(LogicCondition): # class LessCondition(LogicCondition): # class LessEqualCondition(LogicCondition): # class GreaterCondition(LogicCondition): # class GreaterEqualCondition(LogicCondition): # class MatchesRegexCondition(LogicCondition): # class NotMatchesRegexCondition(LogicCondition): # def __init__(self): # def make_condition(self, klass, *args, **kwargs): # def tupleify(obj): # def make_alert_condition(self, alert, dependent, rule_id=None): # def process(self, entry, node): # def parse_query(self, query, alerters=None, rule_id=None): # def parse_condition(d): # def parse_group(d): # def parse(d): # def __init__(self): # def init_network(self, network): # def run(self, input): # def local_run(self, input): # def __repr__(self): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, key, expected, column_name=None): # def maybe_make_number(self, value): # def local_run(self, input): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # OPERATOR_MAP = { # 'equal': EqualCondition, # 'not_equal': NotEqualCondition, # 'begins_with': BeginsWithCondition, # 'not_begins_with': NotBeginsWithCondition, # 'contains': ContainsCondition, # 'not_contains': NotContainsCondition, # 'ends_with': EndsWithCondition, # 'not_ends_with': NotEndsWithCondition, # 'is_empty': IsEmptyCondition, # 'is_not_empty': IsNotEmptyCondition, # 'less': LessCondition, # 'less_or_equal': LessEqualCondition, # 'greater': GreaterCondition, # 'greater_or_equal': GreaterEqualCondition, # 'matches_regex': MatchesRegexCondition, # 'not_matches_regex': NotMatchesRegexCondition, # } which might include code, classes, or functions. Output only the next line.
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 column value # posted by osquery ('112') is less than configured in the rule ('12') condition = GreaterEqualCondition(None, '12', column_name='val') assert condition.local_run(inp) is True condition = GreaterEqualCondition(None, '112', column_name='val') assert condition.local_run(inp) is True condition = GreaterEqualCondition(None, '113', column_name='val') assert condition.local_run(inp) is False class TestRegexConditions: def test_matches_regex(self): cond = MatchesRegexCondition('unused', r'a+b+') assert cond.compare('aaaaaabb') is True assert cond.compare('caaaabbb') is False def test_not_matches_regex(self): <|code_end|> , determine the next line of code. You have imports: import json import logging import datetime as dt from collections import defaultdict from doorman.rules import ( BaseCondition, EqualCondition, LessCondition, GreaterEqualCondition, LogicCondition, MatchesRegexCondition, Network, NotMatchesRegexCondition, RuleInput, ) and context (class names, function names, or code) available: # Path: doorman/rules.py # class Network(object): # class BaseCondition(object): # class AndCondition(BaseCondition): # class OrCondition(BaseCondition): # class LogicCondition(BaseCondition): # class EqualCondition(LogicCondition): # class NotEqualCondition(LogicCondition): # class BeginsWithCondition(LogicCondition): # class NotBeginsWithCondition(LogicCondition): # class ContainsCondition(LogicCondition): # class NotContainsCondition(LogicCondition): # class EndsWithCondition(LogicCondition): # class NotEndsWithCondition(LogicCondition): # class IsEmptyCondition(LogicCondition): # class IsNotEmptyCondition(LogicCondition): # class LessCondition(LogicCondition): # class LessEqualCondition(LogicCondition): # class GreaterCondition(LogicCondition): # class GreaterEqualCondition(LogicCondition): # class MatchesRegexCondition(LogicCondition): # class NotMatchesRegexCondition(LogicCondition): # def __init__(self): # def make_condition(self, klass, *args, **kwargs): # def tupleify(obj): # def make_alert_condition(self, alert, dependent, rule_id=None): # def process(self, entry, node): # def parse_query(self, query, alerters=None, rule_id=None): # def parse_condition(d): # def parse_group(d): # def parse(d): # def __init__(self): # def init_network(self, network): # def run(self, input): # def local_run(self, input): # def __repr__(self): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, upstream): # def local_run(self, input): # def __init__(self, key, expected, column_name=None): # def maybe_make_number(self, value): # def local_run(self, input): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # def __init__(self, key, expected, **kwargs): # def compare(self, value): # OPERATOR_MAP = { # 'equal': EqualCondition, # 'not_equal': NotEqualCondition, # 'begins_with': BeginsWithCondition, # 'not_begins_with': NotBeginsWithCondition, # 'contains': ContainsCondition, # 'not_contains': NotContainsCondition, # 'ends_with': EndsWithCondition, # 'not_ends_with': NotEndsWithCondition, # 'is_empty': IsEmptyCondition, # 'is_not_empty': IsNotEmptyCondition, # 'less': LessCondition, # 'less_or_equal': LessEqualCondition, # 'greater': GreaterCondition, # 'greater_or_equal': GreaterEqualCondition, # 'matches_regex': MatchesRegexCondition, # 'not_matches_regex': NotMatchesRegexCondition, # } . Output only the next line.
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 quote('foobar') == '"foobar"' assert quote('foo bar baz') == '"foo bar baz"' assert quote('foobar', quote='`') == '`foobar`' def test_will_escape(self): assert quote(r'foo"bar') == r'"foo\"bar"' assert quote(r'foo\bar') == r'"foo\\bar"' def test_quote_control_characters(self): assert quote("\r\n\t") == r'"\r\n\t"' def test_quote_unprintable_chars(self): assert quote('\x8Ffoo\xA3bar').lower() == r'"\x8Ffoo\xA3bar"'.lower() class TestDateTimeEncoder: def test_will_serialize_datetime(self): time = dt.datetime(year=2016, month=5, day=16, hour=11, minute=11, second=11) data = {'foo': time} <|code_end|> using the current file's imports: import json import datetime as dt import pytest from flask import current_app from doorman.utils import ( DateTimeEncoder, osquery_mock_db, quote, validate_osquery_query, ) and any relevant context from other files: # Path: doorman/utils.py # def assemble_configuration(node): # def assemble_options(node): # def assemble_file_paths(node): # def assemble_schedule(node): # def assemble_packs(node): # def assemble_distributed_queries(node): # def create_query_pack_from_upload(upload): # def get_node_health(node): # def pretty_operator(cond): # def pretty_field(field): # def quote(s, quote='"'): # def create_mock_db(): # def validate_osquery_query(query): # def learn_from_result(result, node): # def process_result(result, node): # def extract_results(result): # def flash_errors(form): # def get_paginate_options(request, model, choices, existing_query=None, # default='id', page=1, max_pp=20, default_sort='asc'): # def default(self, o): # def render_column(value, column): # PRETTY_OPERATORS = { # 'equal': 'equals', # 'not_equal': "doesn't equal", # 'begins_with': 'begins with', # 'not_begins_with': "doesn't begins with", # 'contains': 'contains', # 'not_contains': "doesn't contain", # 'ends_with': 'ends with', # 'not_ends_with': "doesn't end with", # 'is_empty': 'is empty', # 'is_not_empty': 'is not empty', # 'less': 'less than', # 'less_or_equal': 'less than or equal', # 'greater': 'greater than', # 'greater_or_equal': 'greater than or equal', # 'matches_regex': 'matches regex', # 'not_matches_regex': "doesn't match regex", # } # PRETTY_FIELDS = { # 'query_name': 'Query name', # 'action': 'Action', # 'host_identifier': 'Host identifier', # 'timestamp': 'Timestamp', # } # PRINTABLE = string.ascii_letters + string.digits + string.punctuation + ' ' # class DateTimeEncoder(json.JSONEncoder): . Output only the next line.
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/introducing-osquery/ query = 'SELECT DISTINCT process.name, listening.port, listening.address, process.pid FROM processes AS process JOIN listening_ports AS listening ON process.pid = listening.pid;' assert validate_osquery_query(query) is True 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_schema(self): query = 'SELECT * FROM custom_table;' assert validate_osquery_query(query) is False try: # This is a bit hacky, but it clears the mock DB so the next call # will re-create it. <|code_end|> , determine the next line of code. You have imports: import json import datetime as dt import pytest from flask import current_app from doorman.utils import ( DateTimeEncoder, osquery_mock_db, quote, validate_osquery_query, ) and context (class names, function names, or code) available: # Path: doorman/utils.py # def assemble_configuration(node): # def assemble_options(node): # def assemble_file_paths(node): # def assemble_schedule(node): # def assemble_packs(node): # def assemble_distributed_queries(node): # def create_query_pack_from_upload(upload): # def get_node_health(node): # def pretty_operator(cond): # def pretty_field(field): # def quote(s, quote='"'): # def create_mock_db(): # def validate_osquery_query(query): # def learn_from_result(result, node): # def process_result(result, node): # def extract_results(result): # def flash_errors(form): # def get_paginate_options(request, model, choices, existing_query=None, # default='id', page=1, max_pp=20, default_sort='asc'): # def default(self, o): # def render_column(value, column): # PRETTY_OPERATORS = { # 'equal': 'equals', # 'not_equal': "doesn't equal", # 'begins_with': 'begins with', # 'not_begins_with': "doesn't begins with", # 'contains': 'contains', # 'not_contains': "doesn't contain", # 'ends_with': 'ends with', # 'not_ends_with': "doesn't end with", # 'is_empty': 'is empty', # 'is_not_empty': 'is not empty', # 'less': 'less than', # 'less_or_equal': 'less than or equal', # 'greater': 'greater than', # 'greater_or_equal': 'greater than or equal', # 'matches_regex': 'matches regex', # 'not_matches_regex': "doesn't match regex", # } # PRETTY_FIELDS = { # 'query_name': 'Query name', # 'action': 'Action', # 'host_identifier': 'Host identifier', # 'timestamp': 'Timestamp', # } # PRINTABLE = string.ascii_letters + string.digits + string.punctuation + ' ' # class DateTimeEncoder(json.JSONEncoder): . Output only the next line.
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_schema(self): query = 'SELECT * FROM custom_table;' assert validate_osquery_query(query) is False try: # This is a bit hacky, but it clears the mock DB so the next call # will re-create it. osquery_mock_db.db = None current_app.config['DOORMAN_EXTRA_SCHEMA'].append( 'CREATE TABLE custom_table (id INTEGER);' ) assert validate_osquery_query(query) is True 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): <|code_end|> , determine the next line of code. You have imports: import json import datetime as dt import pytest from flask import current_app from doorman.utils import ( DateTimeEncoder, osquery_mock_db, quote, validate_osquery_query, ) and context (class names, function names, or code) available: # Path: doorman/utils.py # def assemble_configuration(node): # def assemble_options(node): # def assemble_file_paths(node): # def assemble_schedule(node): # def assemble_packs(node): # def assemble_distributed_queries(node): # def create_query_pack_from_upload(upload): # def get_node_health(node): # def pretty_operator(cond): # def pretty_field(field): # def quote(s, quote='"'): # def create_mock_db(): # def validate_osquery_query(query): # def learn_from_result(result, node): # def process_result(result, node): # def extract_results(result): # def flash_errors(form): # def get_paginate_options(request, model, choices, existing_query=None, # default='id', page=1, max_pp=20, default_sort='asc'): # def default(self, o): # def render_column(value, column): # PRETTY_OPERATORS = { # 'equal': 'equals', # 'not_equal': "doesn't equal", # 'begins_with': 'begins with', # 'not_begins_with': "doesn't begins with", # 'contains': 'contains', # 'not_contains': "doesn't contain", # 'ends_with': 'ends with', # 'not_ends_with': "doesn't end with", # 'is_empty': 'is empty', # 'is_not_empty': 'is not empty', # 'less': 'less than', # 'less_or_equal': 'less than or equal', # 'greater': 'greater than', # 'greater_or_equal': 'greater than or equal', # 'matches_regex': 'matches regex', # 'not_matches_regex': "doesn't match regex", # } # PRETTY_FIELDS = { # 'query_name': 'Query name', # 'action': 'Action', # 'host_identifier': 'Host identifier', # 'timestamp': 'Timestamp', # } # PRINTABLE = string.ascii_letters + string.digits + string.punctuation + ' ' # class DateTimeEncoder(json.JSONEncoder): . Output only the next line.
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 doorman.utils import ( DateTimeEncoder, osquery_mock_db, quote, validate_osquery_query, ) and any relevant context from other files: # Path: doorman/utils.py # def assemble_configuration(node): # def assemble_options(node): # def assemble_file_paths(node): # def assemble_schedule(node): # def assemble_packs(node): # def assemble_distributed_queries(node): # def create_query_pack_from_upload(upload): # def get_node_health(node): # def pretty_operator(cond): # def pretty_field(field): # def quote(s, quote='"'): # def create_mock_db(): # def validate_osquery_query(query): # def learn_from_result(result, node): # def process_result(result, node): # def extract_results(result): # def flash_errors(form): # def get_paginate_options(request, model, choices, existing_query=None, # default='id', page=1, max_pp=20, default_sort='asc'): # def default(self, o): # def render_column(value, column): # PRETTY_OPERATORS = { # 'equal': 'equals', # 'not_equal': "doesn't equal", # 'begins_with': 'begins with', # 'not_begins_with': "doesn't begins with", # 'contains': 'contains', # 'not_contains': "doesn't contain", # 'ends_with': 'ends with', # 'not_ends_with': "doesn't end with", # 'is_empty': 'is empty', # 'is_not_empty': 'is not empty', # 'less': 'less than', # 'less_or_equal': 'less than or equal', # 'greater': 'greater than', # 'greater_or_equal': 'greater than or equal', # 'matches_regex': 'matches regex', # 'not_matches_regex': "doesn't match regex", # } # PRETTY_FIELDS = { # 'query_name': 'Query name', # 'action': 'Action', # 'host_identifier': 'Host identifier', # 'timestamp': 'Timestamp', # } # PRINTABLE = string.ascii_letters + string.digits + string.punctuation + ' ' # class DateTimeEncoder(json.JSONEncoder): . Output only the next line.
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())) self.tags.process_data('\n'.join(t.value for t in file_path.tags)) class RuleForm(Form): name = StringField('Rule Name', validators=[DataRequired()]) alerters = SelectMultipleField('Alerters', default=None, choices=[ ]) description = TextAreaField('Description', validators=[Optional()]) conditions = HiddenJSONField('Conditions') def set_choices(self): alerter_ids = list(current_app.config.get('DOORMAN_ALERTER_PLUGINS', {}).keys()) self.alerters.choices = [(a, a.title()) for a in alerter_ids] class CreateRuleForm(RuleForm): def validate(self): initial_validation = super(CreateRuleForm, self).validate() if not initial_validation: return False <|code_end|> . Use current file imports: import json from flask import current_app from flask_wtf import FlaskForm as Form from flask_wtf.file import FileField, FileRequired from wtforms.fields import ( BooleanField, DateTimeField, Field, IntegerField, SelectField, SelectMultipleField, StringField, TextAreaField ) from wtforms.validators import DataRequired, Optional, ValidationError from wtforms.widgets import HiddenInput from doorman.models import Rule from doorman.utils import validate_osquery_query from doorman.models import Pack from doorman.models import Query from doorman.models import Node, Tag from doorman.models import Rule and context (classes, functions, or code) from other files: # Path: doorman/models.py # class Rule(SurrogatePK, Model): # # name = Column(db.String, nullable=False) # alerters = Column(ARRAY(db.String), nullable=False) # description = Column(db.String, nullable=True) # conditions = Column(JSONB) # updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # self.name = name # self.description = description # self.alerters = alerters # self.conditions = conditions # self.updated_at = updated_at # # @property # def template(self): # return string.Template("{name}\r\n\r\n{description}".format( # name=self.name, description=self.description or '') # ) # # Path: doorman/utils.py # def validate_osquery_query(query): # # Check if this thread has an instance of the SQLite database # db = getattr(osquery_mock_db, 'db', None) # if db is None: # db = create_mock_db() # osquery_mock_db.db = db # # try: # db.execute(query) # except sqlite3.Error: # current_app.logger.exception("Invalid query: %s", query) # return False # # return True . Output only the next line.
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|> . Write the next line using the current file imports: import json from flask import current_app from flask_wtf import FlaskForm as Form from flask_wtf.file import FileField, FileRequired from wtforms.fields import ( BooleanField, DateTimeField, Field, IntegerField, SelectField, SelectMultipleField, StringField, TextAreaField ) from wtforms.validators import DataRequired, Optional, ValidationError from wtforms.widgets import HiddenInput from doorman.models import Rule from doorman.utils import validate_osquery_query from doorman.models import Pack from doorman.models import Query from doorman.models import Node, Tag from doorman.models import Rule and context from other files: # Path: doorman/models.py # class Rule(SurrogatePK, Model): # # name = Column(db.String, nullable=False) # alerters = Column(ARRAY(db.String), nullable=False) # description = Column(db.String, nullable=True) # conditions = Column(JSONB) # updated_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow) # # def __init__(self, name, alerters, description=None, conditions=None, updated_at=None): # self.name = name # self.description = description # self.alerters = alerters # self.conditions = conditions # self.updated_at = updated_at # # @property # def template(self): # return string.Template("{name}\r\n\r\n{description}".format( # name=self.name, description=self.description or '') # ) # # Path: doorman/utils.py # def validate_osquery_query(query): # # Check if this thread has an instance of the SQLite database # db = getattr(osquery_mock_db, 'db', None) # if db is None: # db = create_mock_db() # osquery_mock_db.db = db # # try: # db.execute(query) # except sqlite3.Error: # current_app.logger.exception("Invalid query: %s", query) # return False # # return True , which may include functions, classes, or code. Output only the next line.
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) # 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 service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): bcrypt.init_app(app) csrf.init_app(app) db.init_app(app) migrate.init_app(app, db) <|code_end|> . Use current file imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context (classes, functions, or code) from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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_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 you want # to only deploy the api as a standalone service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): <|code_end|> . Write the next line using the current file imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value , which may include functions, classes, or code. Output only the next line.
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_extensions(app) register_auth_method(app) register_filters(app) return app def register_blueprints(app): app.register_blueprint(api) <|code_end|> , determine the next line of code. You have imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context (class names, function names, or code) available: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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 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 service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): bcrypt.init_app(app) csrf.init_app(app) <|code_end|> , generate the next line using the imports in this file: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context (functions, classes, or occasionally code) from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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(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 service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): bcrypt.init_app(app) csrf.init_app(app) db.init_app(app) migrate.init_app(app, db) assets.init_app(app) <|code_end|> , predict the next line using imports from the current file: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context including class names, function names, and sometimes code from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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 return render_template('{0}.html'.format(error_code)), error_code for errcode in [401, 403, 404, 500]: app.errorhandler(errcode)(render_error) def register_filters(app): app.jinja_env.filters['health'] = get_node_health app.jinja_env.filters['pretty_field'] = pretty_field app.jinja_env.filters['pretty_operator'] = pretty_operator app.jinja_env.filters['render'] = render_column def register_auth_method(app): app.register_blueprint(views.blueprint) if app.config['DOORMAN_AUTH_METHOD'] is None: login_manager.anonymous_user = NoAuthUserMixin return login_manager.login_view = 'users.login' login_manager.login_message_category = 'warning' if app.config['DOORMAN_AUTH_METHOD'] == 'ldap': <|code_end|> with the help of current file imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value , which may contain function names, class names, or code. Output only the next line.
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 environment variable isn't set, # register the backend blueprint. This is useful when you want # to only deploy the api as a standalone service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): bcrypt.init_app(app) csrf.init_app(app) db.init_app(app) migrate.init_app(app, db) assets.init_app(app) debug_toolbar.init_app(app) <|code_end|> . Use current file imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context (classes, functions, or code) from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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 api as a standalone service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): bcrypt.init_app(app) csrf.init_app(app) db.init_app(app) migrate.init_app(app, db) assets.init_app(app) debug_toolbar.init_app(app) log_tee.init_app(app) rule_manager.init_app(app) mail.init_app(app) make_celery(app, celery) <|code_end|> , predict the immediate next line with the help of imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context (classes, functions, sometimes code) from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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 blueprint. This is useful when you want # to only deploy the api as a standalone service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): bcrypt.init_app(app) csrf.init_app(app) db.init_app(app) migrate.init_app(app, db) assets.init_app(app) debug_toolbar.init_app(app) log_tee.init_app(app) rule_manager.init_app(app) <|code_end|> . Use current file imports: (import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin) and context including class names, function names, or small code snippets from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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 you want # to only deploy the api as a standalone service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): bcrypt.init_app(app) csrf.init_app(app) db.init_app(app) migrate.init_app(app, db) assets.init_app(app) debug_toolbar.init_app(app) log_tee.init_app(app) rule_manager.init_app(app) mail.init_app(app) <|code_end|> , generate the next line using the imports in this file: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context (functions, classes, or occasionally code) from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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): 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 service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): bcrypt.init_app(app) csrf.init_app(app) db.init_app(app) <|code_end|> . Use current file imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context (classes, functions, or code) from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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, # register the backend blueprint. This is useful when you want # to only deploy the api as a standalone service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): bcrypt.init_app(app) csrf.init_app(app) db.init_app(app) migrate.init_app(app, db) assets.init_app(app) debug_toolbar.init_app(app) log_tee.init_app(app) <|code_end|> , determine the next line of code. You have imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context (class names, function names, or code) available: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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 service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): bcrypt.init_app(app) csrf.init_app(app) db.init_app(app) migrate.init_app(app, db) assets.init_app(app) debug_toolbar.init_app(app) log_tee.init_app(app) rule_manager.init_app(app) mail.init_app(app) make_celery(app, celery) login_manager.init_app(app) <|code_end|> . Use current file imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context (classes, functions, or code) from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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 blueprint. This is useful when you want # to only deploy the api as a standalone service. if 'DOORMAN_NO_MANAGER' in os.environ: return app.register_blueprint(backend) def register_extensions(app): bcrypt.init_app(app) csrf.init_app(app) db.init_app(app) migrate.init_app(app, db) assets.init_app(app) debug_toolbar.init_app(app) log_tee.init_app(app) rule_manager.init_app(app) mail.init_app(app) <|code_end|> , predict the next line using imports from the current file: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context including class names, function names, and sometimes code from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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', 'INFO', 'WARN', 'WARNING', 'ERROR', 'CRITICAL'): handler.setLevel(getattr(logging, levelname)) formatter = logging.Formatter(app.config['DOORMAN_LOGGING_FORMAT']) handler.setFormatter(formatter) app.logger.addHandler(handler) def register_errorhandlers(app): """Register error handlers.""" 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 return render_template('{0}.html'.format(error_code)), error_code for errcode in [401, 403, 404, 500]: app.errorhandler(errcode)(render_error) def register_filters(app): <|code_end|> with the help of current file imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value , which may contain function names, class names, or code. Output only the next line.
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', 'INFO', 'WARN', 'WARNING', 'ERROR', 'CRITICAL'): handler.setLevel(getattr(logging, levelname)) formatter = logging.Formatter(app.config['DOORMAN_LOGGING_FORMAT']) handler.setFormatter(formatter) app.logger.addHandler(handler) def register_errorhandlers(app): """Register error handlers.""" 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 return render_template('{0}.html'.format(error_code)), error_code for errcode in [401, 403, 404, 500]: app.errorhandler(errcode)(render_error) def register_filters(app): app.jinja_env.filters['health'] = get_node_health <|code_end|> with the help of current file imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and context from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value , which may contain function names, class names, or code. Output only the next line.
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'): handler.setLevel(getattr(logging, levelname)) formatter = logging.Formatter(app.config['DOORMAN_LOGGING_FORMAT']) handler.setFormatter(formatter) app.logger.addHandler(handler) def register_errorhandlers(app): """Register error handlers.""" 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 return render_template('{0}.html'.format(error_code)), error_code for errcode in [401, 403, 404, 500]: app.errorhandler(errcode)(render_error) def register_filters(app): app.jinja_env.filters['health'] = get_node_health app.jinja_env.filters['pretty_field'] = pretty_field <|code_end|> using the current file's imports: import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin and any relevant context from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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, levelname)) formatter = logging.Formatter(app.config['DOORMAN_LOGGING_FORMAT']) handler.setFormatter(formatter) app.logger.addHandler(handler) def register_errorhandlers(app): """Register error handlers.""" 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 return render_template('{0}.html'.format(error_code)), error_code for errcode in [401, 403, 404, 500]: app.errorhandler(errcode)(render_error) def register_filters(app): app.jinja_env.filters['health'] = get_node_health app.jinja_env.filters['pretty_field'] = pretty_field app.jinja_env.filters['pretty_operator'] = pretty_operator <|code_end|> . Use current file imports: (import os import logging import sys from flask import Flask, render_template from doorman.api import blueprint as api from doorman.assets import assets from doorman.manage import blueprint as backend from doorman.extensions import ( bcrypt, csrf, db, debug_toolbar, ldap_manager, log_tee, login_manager, mail, make_celery, migrate, rule_manager, sentry ) from doorman.settings import ProdConfig from doorman.tasks import celery from doorman.utils import get_node_health, pretty_field, pretty_operator, render_column from flask_sslify import SSLify from logging.handlers import WatchedFileHandler from doorman.users import views from doorman.users.mixins import NoAuthUserMixin from doorman.users.oauth import OAuthLogin) and context including class names, function names, or small code snippets from other files: # Path: doorman/api.py # def node_required(f): # def decorated_function(*args, **kwargs): # def index(): # def enroll(): # def configuration(node=None): # def logger(node=None): # def distributed_read(node=None): # def distributed_write(node=None): # # Path: doorman/assets.py # # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/settings.py # class ProdConfig(Config): # # ENV = 'prod' # DEBUG = False # DEBUG_TB_ENABLED = False # DEBUG_TB_INTERCEPT_REDIRECTS = False # # ENFORCE_SSL = True # # SQLALCHEMY_DATABASE_URI = '' # # DOORMAN_ENROLL_SECRET = [ # # ] # DOORMAN_MINIMUM_OSQUERY_LOG_LEVEL = 1 # # BROKER_URL = '' # CELERY_RESULT_BACKEND = '' # # Path: doorman/tasks.py # def analyze_result(result, node): # def learn_from_result(result, node): # def example_task(one, two): # def notify_of_node_enrollment(node): # def alert_when_node_goes_offline(): # # Path: doorman/utils.py # def get_node_health(node): # checkin_interval = current_app.config['DOORMAN_CHECKIN_INTERVAL'] # if isinstance(checkin_interval, (int, float)): # checkin_interval = dt.timedelta(seconds=checkin_interval) # if (dt.datetime.utcnow() - node.last_checkin) > checkin_interval: # return u'danger' # else: # return '' # # def pretty_field(field): # return PRETTY_FIELDS.get(field, field) # # def pretty_operator(cond): # return PRETTY_OPERATORS.get(cond, cond) # # def render_column(value, column): # renders = current_app.config.get('DOORMAN_COLUMN_RENDER', {}) # if column not in renders: # return value # # template = renders[column] # # try: # if callable(template): # return template(value) # else: # template = Template(template, autoescape=True) # rendered = template.render(value=value) # # # return a markup object so that the template where this is # # rendered is not escaped again # # return Markup(rendered) # except Exception: # current_app.logger.exception( # "Failed to render %s, returning original value", # column # ) # return value . Output only the next line.
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()]) def __init__(self, *args, **kwargs): """Create instance.""" super(LoginForm, self).__init__(*args, **kwargs) self.user = None def validate(self): initial_validation = super(LoginForm, self).validate() if not initial_validation: return False error_message = u'Invalid username or password.' if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman': self.user = User.query.filter_by(username=self.username.data).first() if not self.user: # avoid timing leaks <|code_end|> using the current file's imports: from flask import current_app from flask_ldap3_login import AuthenticationResponseStatus from flask_wtf import FlaskForm as Form from wtforms import BooleanField, PasswordField, StringField from wtforms.validators import DataRequired, Optional from doorman.extensions import bcrypt, ldap_manager from doorman.models import User from doorman.extensions import bcrypt and any relevant context from other files: # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/models.py # 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=False, default=dt.datetime.utcnow) # # # oauth related stuff # social_id = Column(db.String) # first_name = Column(db.String) # last_name = Column(db.String) # # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # self.username = username # self.email = email # if password: # self.set_password(password) # else: # self.password = None # # self.social_id = social_id # self.first_name = first_name # self.last_name = last_name # # def set_password(self, password): # self.update(password=bcrypt.generate_password_hash(password)) # return # # def check_password(self, value): # if not self.password: # # still do the computation # return bcrypt.generate_password_hash(value) and False # return bcrypt.check_password_hash(self.password, value) . Output only the next line.
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(LoginForm, self).validate() if not initial_validation: return False error_message = u'Invalid username or password.' if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman': self.user = User.query.filter_by(username=self.username.data).first() if not self.user: # avoid timing leaks bcrypt.generate_password_hash(self.password.data) self.username.errors.append(error_message) return False if not self.user.check_password(self.password.data): self.username.errors.append(error_message) return False return True elif current_app.config['DOORMAN_AUTH_METHOD'] == 'ldap': <|code_end|> , continue by predicting the next line. Consider current file imports: from flask import current_app from flask_ldap3_login import AuthenticationResponseStatus from flask_wtf import FlaskForm as Form from wtforms import BooleanField, PasswordField, StringField from wtforms.validators import DataRequired, Optional from doorman.extensions import bcrypt, ldap_manager from doorman.models import User from doorman.extensions import bcrypt and context: # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/models.py # 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=False, default=dt.datetime.utcnow) # # # oauth related stuff # social_id = Column(db.String) # first_name = Column(db.String) # last_name = Column(db.String) # # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # self.username = username # self.email = email # if password: # self.set_password(password) # else: # self.password = None # # self.social_id = social_id # self.first_name = first_name # self.last_name = last_name # # def set_password(self, password): # self.update(password=bcrypt.generate_password_hash(password)) # return # # def check_password(self, value): # if not self.password: # # still do the computation # return bcrypt.generate_password_hash(value) and False # return bcrypt.check_password_hash(self.password, value) which might include code, classes, or functions. Output only the next line.
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=[Optional()]) def __init__(self, *args, **kwargs): """Create instance.""" super(LoginForm, self).__init__(*args, **kwargs) self.user = None def validate(self): initial_validation = super(LoginForm, self).validate() if not initial_validation: return False error_message = u'Invalid username or password.' if current_app.config['DOORMAN_AUTH_METHOD'] == 'doorman': <|code_end|> , predict the next line using imports from the current file: from flask import current_app from flask_ldap3_login import AuthenticationResponseStatus from flask_wtf import FlaskForm as Form from wtforms import BooleanField, PasswordField, StringField from wtforms.validators import DataRequired, Optional from doorman.extensions import bcrypt, ldap_manager from doorman.models import User from doorman.extensions import bcrypt and context including class names, function names, and sometimes code from other files: # Path: doorman/extensions.py # class LogTee(object): # class RuleManager(object): # class ContextTask(TaskBase): # def __init__(self, app=None): # def init_app(self, app): # def handle_status(self, data, **kwargs): # def handle_result(self, data, **kwargs): # def __init__(self, app=None): # def init_app(self, app): # def load_alerters(self): # def should_reload_rules(self): # def load_rules(self): # def handle_log_entry(self, entry, node): # def make_celery(app, celery): # def __call__(self, *args, **kwargs): # # Path: doorman/models.py # 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=False, default=dt.datetime.utcnow) # # # oauth related stuff # social_id = Column(db.String) # first_name = Column(db.String) # last_name = Column(db.String) # # def __init__(self, username, password=None, email=None, social_id=None, # first_name=None, last_name=None): # self.username = username # self.email = email # if password: # self.set_password(password) # else: # self.password = None # # self.social_id = social_id # self.first_name = first_name # self.last_name = last_name # # def set_password(self, password): # self.update(password=bcrypt.generate_password_hash(password)) # return # # def check_password(self, value): # if not self.password: # # still do the computation # return bcrypt.generate_password_hash(value) and False # return bcrypt.check_password_hash(self.password, value) . Output only the next line.
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|> , predict the next line using imports from the current file: import os import sys import time import settings from datetime import datetime from sqlalchemy import func from database import db_session from models import * and context including class names, function names, and sometimes code from other files: # Path: database.py # def init_db(): . Output only the next line.
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'], }) if rs: latest_id = rs[-1].id return jsonify({ 'stamp': stamp, 'latest_id': latest_id, 'bar': render_template('build_bar.html', version=v, phase_count=count), 'runs': runs , 'watch': watch, 'auto_refresh': v.status not in ['passed', 'failed'] }) except: return abort(400) @app.route(settings.WEBROOT + '/show/buildlog_<int:id>.html') def download_buildlog(id): l = db_session.query(BuildLog).filter(BuildLog.id == id).first() if not l: return abort(404) path = os.path.join(settings.CORE_BUILD_LOG_PATH, '{:d}.txt'.format(l.id)) if not os.path.exists(path): return abort(404) with open(path) as f: text = f.read() <|code_end|> , determine the next line of code. You have imports: import os import uuid import json import functools import StringIO import settings, utils from datetime import datetime from collections import namedtuple from ansi2html import ansi2html from flask import request, redirect, session, url_for, flash, render_template, jsonify, abort, send_file, Response from web import app from models import * from database import db_session and context (class names, function names, or code) available: # Path: ansi2html.py # def ansi2html(text, palette='solarized'): # def _ansi2html(m): # if m.group(2) != 'm': # return '' # import sys # state = None # sub = '' # cs = m.group(1) # cs = cs.strip() if cs else '' # for c in cs.split(';'): # c = c.strip().lstrip('0') or '0' # if c == '0': # while stack: # sub += '</span>' # stack.pop() # elif c in ('38', '48'): # extra = [c] # state = 'extra' # elif state == 'extra': # if c == '5': # state = 'idx' # elif c == '2': # state = 'r' # elif state: # if state == 'idx': # extra.append(c) # state = None # # 256 colors # color = indexed_style.get(c) # TODO: convert index to RGB! # if color is not None: # sub += '<span style="%s:%s">' % ('color' if extra[0] == '38' else 'background-color', color) # stack.append(extra) # elif state in ('r', 'g', 'b'): # extra.append(c) # if state == 'r': # state = 'g' # elif state == 'g': # state = 'b' # else: # state = None # try: # color = '#' + ''.join('%02X' % c if 0 <= c <= 255 else None for x in extra for c in [int(x)]) # except (ValueError, TypeError): # pass # else: # sub += '<span style="%s:%s">' % ('color' if extra[0] == '38' else 'background-color', color) # stack.append(extra) # else: # if '1' in stack: # style = bold_style.get(c) # else: # style = regular_style.get(c) # if style is not None: # sub += '<span style="%s">' % style # stack.append(c) # Still needs to be added to the stack even if style is empty (so it can check '1' in stack above, for example) # return sub # stack = [] # regular_style, bold_style, indexed_style = _ansi2html_get_styles(palette) # sub = ANSI2HTML_CODES_RE.sub(_ansi2html, text) # while stack: # sub += '</span>' # stack.pop() # return sub # # Path: database.py # def init_db(): . Output only the next line.
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.WEBROOT + '/') def homepage(): return render_template('homepage.html') @app.route(settings.WEBROOT + '/compilers/') def compilers(): <|code_end|> . Use current file imports: (import os import uuid import json import functools import StringIO import settings, utils from datetime import datetime from collections import namedtuple from ansi2html import ansi2html from flask import request, redirect, session, url_for, flash, render_template, jsonify, abort, send_file, Response from web import app from models import * from database import db_session) and context including class names, function names, or small code snippets from other files: # Path: ansi2html.py # def ansi2html(text, palette='solarized'): # def _ansi2html(m): # if m.group(2) != 'm': # return '' # import sys # state = None # sub = '' # cs = m.group(1) # cs = cs.strip() if cs else '' # for c in cs.split(';'): # c = c.strip().lstrip('0') or '0' # if c == '0': # while stack: # sub += '</span>' # stack.pop() # elif c in ('38', '48'): # extra = [c] # state = 'extra' # elif state == 'extra': # if c == '5': # state = 'idx' # elif c == '2': # state = 'r' # elif state: # if state == 'idx': # extra.append(c) # state = None # # 256 colors # color = indexed_style.get(c) # TODO: convert index to RGB! # if color is not None: # sub += '<span style="%s:%s">' % ('color' if extra[0] == '38' else 'background-color', color) # stack.append(extra) # elif state in ('r', 'g', 'b'): # extra.append(c) # if state == 'r': # state = 'g' # elif state == 'g': # state = 'b' # else: # state = None # try: # color = '#' + ''.join('%02X' % c if 0 <= c <= 255 else None for x in extra for c in [int(x)]) # except (ValueError, TypeError): # pass # else: # sub += '<span style="%s:%s">' % ('color' if extra[0] == '38' else 'background-color', color) # stack.append(extra) # else: # if '1' in stack: # style = bold_style.get(c) # else: # style = regular_style.get(c) # if style is not None: # sub += '<span style="%s">' % style # stack.append(c) # Still needs to be added to the stack even if style is empty (so it can check '1' in stack above, for example) # return sub # stack = [] # regular_style, bold_style, indexed_style = _ansi2html_get_styles(palette) # sub = ANSI2HTML_CODES_RE.sub(_ansi2html, text) # while stack: # sub += '</span>' # stack.pop() # return sub # # Path: database.py # def init_db(): . Output only the next line.
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 = subprocess.check_output(cmd, shell=True).strip() except: return False if len(version) != 40: return False return version def do_compiler(compiler): version_sha = get_latest_remote_version(compiler.repo_url) compiler.last_check_time = datetime.utcnow() <|code_end|> using the current file's imports: import os import sys import time import subprocess import settings from datetime import datetime from database import db_session from models import * and any relevant context from other files: # Path: database.py # def init_db(): . Output only the next line.
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 the following command within the current minute') print(' ./maintenance.py initdb %s' % key) sys.exit(1) print('initializing the database') init_db() print('done!') def add_compiler(): if len(sys.argv) != 4: print('usage: ./maintenance.py add_compiler <student> <repo_url>') sys.exit(1) student = sys.argv[2].decode('utf-8') repo_url = sys.argv[3] c = Compiler(student=student, repo_url=repo_url) <|code_end|> , predict the immediate next line with the help of imports: import os import csv import sys import time import json import shutil import codecs import hashlib import StringIO import utils import settings from datetime import datetime from collections import namedtuple from jinja2 import Environment, PackageLoader, select_autoescape, Template from models import * from database import db_session, init_db and context (classes, functions, sometimes code) from other files: # Path: database.py # def init_db(): . Output only the next line.
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] != key: print('please run the following command within the current minute') print(' ./maintenance.py initdb %s' % key) sys.exit(1) print('initializing the database') <|code_end|> , predict the next line using imports from the current file: import os import csv import sys import time import json import shutil import codecs import hashlib import StringIO import utils import settings from datetime import datetime from collections import namedtuple from jinja2 import Environment, PackageLoader, select_autoescape, Template from models import * from database import db_session, init_db and context including class names, function names, and sometimes code from other files: # Path: database.py # def init_db(): . Output only the next line.
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] desc = None elif k == 'cd' and len(s) > 1: desc = s[1] elif k == '$endmodule': l.append((name, desc)) return l class Export: def __init__(self, fn): self.fn = fn def export_footprint(self, interim, timestamp = None): if timestamp is None: timestamp = time.time() <|code_end|> . Use current file imports: import os.path import shlex import math import time import re import mutil.mutil as mutil from inter import inter and context (classes, functions, or code) from other files: # Path: inter/inter.py # def cleanup_js(inter): # def _remove_constructor(item): # def add_names(inter): # def generate_ints(): # def _c(x): # def get_meta(inter): # def prepare_for_display(inter, filter_out): # def _sort(x1, x2): # def convert(x): # def bounding_box(inter): # def oget(m, k, d): # def fget(m, k, d = 0.0): # def circle(shape): # def disc(shape): # def label(shape): # def vertex(shape): # def polygon(shape): # def octagon(shape): # def rect(shape): # def unknown(shape): # def size(inter): # def sort_by_type(inter): # def _sort(x1, x2): # def _count_num_values(pads, param): # def _equidistant(pads, direction): # def _all_equal(pads, direction): # def _sort_by_field(pads, field, reverse=False): # def _sort_by(a, b): # def _clone_pad(pad_in, remove): # def _make_mods(skip, pad, pads): # def _check_single(orig_pads, horizontal): # def _split_dual(pads, direction): # def _one_by_one_equal(r1, r2, direction): # def _check_dual_alt(r1, r2): # def _check_dual(orig_pads, horizontal): # def _split_quad(pads): # def _check_quad(orig_pads): # def _check_sequential(pads): # def _find_pad_patterns(pads): # def find_pad_patterns(inter): # def import_footprint(importer, footprint_name): . Output only the next line.
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" print new_name def import_footprint(remaining): parser = argparse.ArgumentParser(prog=sys.argv[0] + ' import') parser.add_argument('library', help='library file') parser.add_argument('footprint', help='footprint name', nargs='?') args = parser.parse_args(remaining) try: importer = detect.make_importer(args.library) except Exception as ex: print >> sys.stderr, str(ex) return 1 names = map(lambda (a,_): a, importer.list_names()) if args.footprint is None: if len(names) == 1: args.footprint = names[0] else: print >> sys.stderr, "Please specify the footprint name as more then one were found in %s." % (args.library) return 1 elif not args.footprint in names: print >> sys.stderr, "Footprint %s not found in %s." % (args.footprint, args.library) return 1 <|code_end|> with the help of current file imports: import argparse, sys, traceback, os import coffee.pycoffee as pycoffee import coffee.generatesimple as generatesimple import export.detect as detect from inter import inter and context from other files: # Path: inter/inter.py # def cleanup_js(inter): # def _remove_constructor(item): # def add_names(inter): # def generate_ints(): # def _c(x): # def get_meta(inter): # def prepare_for_display(inter, filter_out): # def _sort(x1, x2): # def convert(x): # def bounding_box(inter): # def oget(m, k, d): # def fget(m, k, d = 0.0): # def circle(shape): # def disc(shape): # def label(shape): # def vertex(shape): # def polygon(shape): # def octagon(shape): # def rect(shape): # def unknown(shape): # def size(inter): # def sort_by_type(inter): # def _sort(x1, x2): # def _count_num_values(pads, param): # def _equidistant(pads, direction): # def _all_equal(pads, direction): # def _sort_by_field(pads, field, reverse=False): # def _sort_by(a, b): # def _clone_pad(pad_in, remove): # def _make_mods(skip, pad, pads): # def _check_single(orig_pads, horizontal): # def _split_dual(pads, direction): # def _one_by_one_equal(r1, r2, direction): # def _check_dual_alt(r1, r2): # def _check_dual(orig_pads, horizontal): # def _split_quad(pads): # def _check_quad(orig_pads): # def _check_sequential(pads): # def _find_pad_patterns(pads): # def find_pad_patterns(inter): # def import_footprint(importer, footprint_name): , which may contain function names, class names, or code. Output only the next line.
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) assert eagle_name == expected_name data = exporter.get_pretty_footprint(eagle_name) # print data assert_multi_line_equal(expected, data) # print code, expected return data def _assert_equal_no_meta(expected, actual): a2 = '\n'.join(filter(lambda l: len(l) > 0 and l[0] != '#', actual.splitlines())) e2 = '\n'.join(filter(lambda l: len(l) > 0 and l[0] != '#', expected.splitlines())) assert_multi_line_equal(e2, a2) def _import_eagle_package(eagle_package_xml, import_name, expected): eagle_lib = 'test/foo.lbr' shutil.copyfile('test/eagle_empty.lbr', eagle_lib) try: importer = export.eagle.Import(eagle_lib) # trick to get our package xml into the empty eagle library package_soup = BeautifulSoup(eagle_package_xml, 'xml') package_soup.is_xml = False importer.soup.drawing.packages.append(package_soup) with open(eagle_lib, 'w+') as f: f.write(str(importer.soup)) importer = export.eagle.Import(eagle_lib) <|code_end|> , generate the next line using the imports in this file: from nose.tools import * from functools import partial from bs4 import BeautifulSoup from inter import inter import copy, shutil, os, time import coffee.pycoffee as pycoffee import coffee.generatesimple as generatesimple import export.eagle import export.kicad import export.kicad_old and context (functions, classes, or occasionally code) from other files: # Path: inter/inter.py # def cleanup_js(inter): # def _remove_constructor(item): # def add_names(inter): # def generate_ints(): # def _c(x): # def get_meta(inter): # def prepare_for_display(inter, filter_out): # def _sort(x1, x2): # def convert(x): # def bounding_box(inter): # def oget(m, k, d): # def fget(m, k, d = 0.0): # def circle(shape): # def disc(shape): # def label(shape): # def vertex(shape): # def polygon(shape): # def octagon(shape): # def rect(shape): # def unknown(shape): # def size(inter): # def sort_by_type(inter): # def _sort(x1, x2): # def _count_num_values(pads, param): # def _equidistant(pads, direction): # def _all_equal(pads, direction): # def _sort_by_field(pads, field, reverse=False): # def _sort_by(a, b): # def _clone_pad(pad_in, remove): # def _make_mods(skip, pad, pads): # def _check_single(orig_pads, horizontal): # def _split_dual(pads, direction): # def _one_by_one_equal(r1, r2, direction): # def _check_dual_alt(r1, r2): # def _check_dual(orig_pads, horizontal): # def _split_quad(pads): # def _check_quad(orig_pads): # def _check_sequential(pads): # def _find_pad_patterns(pads): # def find_pad_patterns(inter): # def import_footprint(importer, footprint_name): . Output only the next line.
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 except: return None def _convert_sexp_symbol(d): if ("value" in dir(d)): return d.value() else: return d def _convert_sexp_symbol_to_string(d): return str(_convert_sexp_symbol(d)) class Export: def __init__(self, fn): self.fn = fn def export_footprint(self, interim): <|code_end|> , predict the immediate next line with the help of imports: import glob, math, os.path import sexpdata from sexpdata import Symbol from mutil.mutil import * from inter import inter and context (classes, functions, sometimes code) from other files: # Path: inter/inter.py # def cleanup_js(inter): # def _remove_constructor(item): # def add_names(inter): # def generate_ints(): # def _c(x): # def get_meta(inter): # def prepare_for_display(inter, filter_out): # def _sort(x1, x2): # def convert(x): # def bounding_box(inter): # def oget(m, k, d): # def fget(m, k, d = 0.0): # def circle(shape): # def disc(shape): # def label(shape): # def vertex(shape): # def polygon(shape): # def octagon(shape): # def rect(shape): # def unknown(shape): # def size(inter): # def sort_by_type(inter): # def _sort(x1, x2): # def _count_num_values(pads, param): # def _equidistant(pads, direction): # def _all_equal(pads, direction): # def _sort_by_field(pads, field, reverse=False): # def _sort_by(a, b): # def _clone_pad(pad_in, remove): # def _make_mods(skip, pad, pads): # def _check_single(orig_pads, horizontal): # def _split_dual(pads, direction): # def _one_by_one_equal(r1, r2, direction): # def _check_dual_alt(r1, r2): # def _check_dual(orig_pads, horizontal): # def _split_quad(pads): # def _check_quad(orig_pads): # def _check_sequential(pads): # def _find_pad_patterns(pads): # def find_pad_patterns(inter): # def import_footprint(importer, footprint_name): . Output only the next line.
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 final # eagle XML as eagle does not get rid of heading and trailing \n and such def get_pretty_data(self): return str(self.soup.prettify()) def get_pretty_footprint(self, eagle_name): packages = self.soup.eagle.drawing.packages('package') for some_package in packages: if some_package['name'].lower() == eagle_name.lower(): return str(some_package.prettify()) raise Exception("Footprint not found") def export_footprint(self, interim): # make a deep copy so we can make mods without harm interim = copy.deepcopy(interim) interim = self.add_ats_to_names(interim) interim = clean_floats(interim) <|code_end|> , generate the next line using the imports in this file: import re, copy, math from bs4 import BeautifulSoup, Tag from mutil.mutil import * from inter import inter and context (functions, classes, or occasionally code) from other files: # Path: inter/inter.py # def cleanup_js(inter): # def _remove_constructor(item): # def add_names(inter): # def generate_ints(): # def _c(x): # def get_meta(inter): # def prepare_for_display(inter, filter_out): # def _sort(x1, x2): # def convert(x): # def bounding_box(inter): # def oget(m, k, d): # def fget(m, k, d = 0.0): # def circle(shape): # def disc(shape): # def label(shape): # def vertex(shape): # def polygon(shape): # def octagon(shape): # def rect(shape): # def unknown(shape): # def size(inter): # def sort_by_type(inter): # def _sort(x1, x2): # def _count_num_values(pads, param): # def _equidistant(pads, direction): # def _all_equal(pads, direction): # def _sort_by_field(pads, field, reverse=False): # def _sort_by(a, b): # def _clone_pad(pad_in, remove): # def _make_mods(skip, pad, pads): # def _check_single(orig_pads, horizontal): # def _split_dual(pads, direction): # def _one_by_one_equal(r1, r2, direction): # def _check_dual_alt(r1, r2): # def _check_dual(orig_pads, horizontal): # def _split_quad(pads): # def _check_quad(orig_pads): # def _check_sequential(pads): # def _find_pad_patterns(pads): # def find_pad_patterns(inter): # def import_footprint(importer, footprint_name): . Output only the next line.
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)) if t == 'mi' or t == 'mil': return str(i*0.0254) elif t == 'in': return str(i*25.4) else: return m.group(0) return re.sub('([-+]?[0-9]*\.?[0-9]+)([mi][ni]l?)', repl, code) def compile_coffee(code): try: preprocessed = preprocess_coffee(code) interim = eval_coffee_footprint(preprocessed) if interim != None: <|code_end|> , generate the next line using the imports in this file: import os.path, re, traceback from inter import inter from qtscriptwrapper import JsEngine from qtscriptwrapper import JsEngineException and context (functions, classes, or occasionally code) from other files: # Path: inter/inter.py # def cleanup_js(inter): # def _remove_constructor(item): # def add_names(inter): # def generate_ints(): # def _c(x): # def get_meta(inter): # def prepare_for_display(inter, filter_out): # def _sort(x1, x2): # def convert(x): # def bounding_box(inter): # def oget(m, k, d): # def fget(m, k, d = 0.0): # def circle(shape): # def disc(shape): # def label(shape): # def vertex(shape): # def polygon(shape): # def octagon(shape): # def rect(shape): # def unknown(shape): # def size(inter): # def sort_by_type(inter): # def _sort(x1, x2): # def _count_num_values(pads, param): # def _equidistant(pads, direction): # def _all_equal(pads, direction): # def _sort_by_field(pads, field, reverse=False): # def _sort_by(a, b): # def _clone_pad(pad_in, remove): # def _make_mods(skip, pad, pads): # def _check_single(orig_pads, horizontal): # def _split_dual(pads, direction): # def _one_by_one_equal(r1, r2, direction): # def _check_dual_alt(r1, r2): # def _check_dual(orig_pads, horizontal): # def _split_quad(pads): # def _check_quad(orig_pads): # def _check_sequential(pads): # def _find_pad_patterns(pads): # def find_pad_patterns(inter): # def import_footprint(importer, footprint_name): . Output only the next line.
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.dll',] extra_options = dict( setup_requires=['py2exe'], console=['madparts', 'madparts-cli', 'madparts-import'], options=dict(py2exe=OPTIONS) ) elif sys.platform.startswith('linux'): extra_options = dict( # Normally unix-like platforms will use "setup.py install" # and install the main script as such scripts=['madparts', 'madparts-cli', 'madparts-import'], ) if not arch in ['x86_64']: raise Exception("unsupported arch %s" % (arch)) else: raise Exception("unsupported platform %s" % (sys.platform)) setup( name = 'madparts', description = 'a functional footprint editor', long_description = long_description, author = 'Joost Yervante Damad', author_email = 'joost@damad.be', <|code_end|> using the current file's imports: from main.version import VERSION from setuptools import setup import glob, sys, platform import py2exe and any relevant context from other files: # Path: main/version.py # VERSION="2.0.1" . Output only the next line.
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 imports: import time import json import numpy as np import pqdict from abc import ABCMeta, abstractmethod from Supervised.Astar import Astar from src.SuperMarioBros.simulation import MarioSimulation and context (classes, functions, or code) from other files: # Path: src/SuperMarioBros/simulation.py # class MarioSimulation: # def __init__(self, layout, config=None): # """ # Instantiate physics engine objects # :param layout: Two-dimensional numpy array layout # :param config: Global configuration # """ # # self.layout = layout # self.config = config # # init_pos = np.array([2, 3, 0]) if config is None or "init_pos" not in config else config["init_pos"] # mario_bb = np.array([0.5, 1]) if config is None or "mario_bb" not in config else config["mario_bb"] # # self.mario = CollidableRigid(init_pos, mario_bb, config) # self.brick_bb = layout_tobb(layout, config) # # # Start with gravity # self.mario.reaction(give_gravity) # # def advance_frame(self, action): # """ # Update physics engine object states for next frame # :param action: agent action for current frame # :return: None # """ # if(self.mario.state[0][0] <= 0.5): # return # # Advance a time step # self.mario.update() # # # Locate blocks for collision detections # bb_to_check = collision_proposal(self.mario, self.brick_bb, self.config) # # # gravity = compensate_gravity(self.mario, bb_to_check, self.config) # # if not bb_to_check or gravity: # self.mario.reaction(give_gravity) # # # Resolve collisions # collisions = list(filter(lambda pair: pair[1]['hit'] is not None, # map(lambda bb: (bb.get_center(), bb.collide(self.mario)), bb_to_check))) # # if collisions: # closest_collision = min(collisions, key=lambda pair: pair[1]['hit']['time']) # # self.mario.reaction(collision_resolved, closest_collision[1]["hit"]["delta"]) # # self.mario.reaction(collision_resolved, closest_collision[1]["position"]) # # # Process momentum change # self.mario.reaction(hit_edge_reaction(closest_collision[1])) # # # Grab an action from input and simulate the force # self.mario.reaction(action_mapping[action]) # # if collisions: # return closest_collision # # def get_renderable(self): # return self.mario # # def next_none_time(self, ori): # if(self.mario.state[0][0] <= 0.5): # return ori # ll = [] # for bb in self.brick_bb: # if bb[0] == int(self.mario.state[0][0]): # if bb[1] < int(self.mario.state[1][0]): # ll.append(bb) # ll = sorted(ll,key=lambda x:x[1],reverse=True) # block_below = ll[0] # print self.mario.state, block_below # if self.mario.state[1][0] - block_below[1] > 1.05: # print "self", self.mario.state, block_below # print "END" # return 0 # return ori . Output only the next line.
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.""" httpretty.register_uri( httpretty.POST, self.endpoint_url("/subscription"), content_type='text/json', body='{"status": true, "contributors": true}', status=201, ) <|code_end|> , predict the next line using imports from the current file: import httpretty from paystackapi.subscription import Subscription from paystackapi.tests.base_test_case import BaseTestCase and context including class names, function names, and sometimes code from other files: # Path: paystackapi/subscription.py # class Subscription(PayStackBase): # """docstring for Subscription.""" # # @classmethod # def create(cls, **kwargs): # """ # Create subscription. # # Args: # customer: Customer's email address or customer code # plan: Plan code # authorization: customers authorization code # start_date: the date for the first debit. (ISO 8601 format) # # Returns: # Json data from paystack API. # """ # return cls().requests.post('subscription', data=kwargs) # # @classmethod # def list(cls): # """ # List subscriptions. # # Args: # No argument required. # # Returns: # Json data from paystack API. # """ # return cls().requests.get('subscription') # # @classmethod # def disable(cls, **kwargs): # """ # Disables subscription # Args: # code: Subscription code # token: Email token # returns: # Json data from paystack API # """ # return cls().requests.post('subscription/disable', data=kwargs) # # @classmethod # def enable(cls, **kwargs): # """ # Disables subscription # # Args: # code: Subscription code # token: Email token # # returns: # Json data from paystack API # """ # return cls().requests.post('subscription/enable', data=kwargs) # # @classmethod # def fetch(cls, subscription_id): # """ # Fetch subscription. # # Args: # subscription_id: subscription id. # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f"subscription/{subscription_id}") # # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) . Output only the next line.
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("/bulkcharge"), content_type='applicationn/json', body='{"status": true, "message": "Charges have been queued"}', status=200, ) <|code_end|> with the help of current file imports: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.bulkcharge import BulkCharge and context from other files: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/bulkcharge.py # class BulkCharge(PayStackBase): # # @classmethod # def initiate_bulk_charge(cls, bulkcharge): # """ # Initiate Bulk Charge. # # { # "type": "array", # "description": "", # "format": "" # } # # Args: # authorization: Authorization token # amount: Amount in kobo # # Returns: # Json data from paystack API. # """ # return cls().requests.post('bulkcharge', data=bulkcharge) # # @classmethod # def list(cls, **kwargs): # """ # List Bulk Charge Batches created by the integration. # # Args: # perPage: Number of transfer listed per page for pagination # page: number of pages listed by pagination. # # Returns: # Json data from paystack API. # # """ # return cls().requests.get('bulkcharge', qs=kwargs,) # # @classmethod # def fetch_bulk_batch(cls, id_or_code): # """ This endpoint retrieves a specific batch code. # # It also returns useful information on its progress # by way of the total_charges and pending_charges attributes. # # Args: # id_or_code: An ID or code for the transfer whose # details you want to retrieve. # # Returns: # Json data from paystack API # """ # return cls().requests.get(f"bulkcharge/{id_or_code}") # # @classmethod # def fetch_charges_batch(cls, id_or_code, **kwargs): # """ # Fetch the charges associated with a specified batch code. # # Args: # id_or_code: An ID or code for the batch whose charges you want to retrieve. # status: pending, success or failed # perPage: Number of transfers listed per page for pagination # page: number of pages listed by pagination. # # Returns: # Json data from paystack API. # """ # # return cls().requests.get(f"bulkcharge/{id_or_code}/charges", qs=kwargs) # # @classmethod # def pause_bulk_batch(cls, batch_code): # """ # Pause the proccessing of an ongoing bulk charge batch. # # Args: # batch_code: code of the batch to be paused # # Returns: # Json data from the Paystack API. # """ # return cls().requests.get(f"bulkcharge/pause/{batch_code}") # # @classmethod # def resume_bulk_charge(cls, batch_code): # """ # Resume the proccessing of an already paused bulk charge batch. # # Args: # batch_code: code of the batch to be resumed # # Returns: # Json data from the Paystack API. # """ # return cls().requests.get(f"bulkcharge/resume/{batch_code}") , which may contain function names, class names, or code. Output only the next line.
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/json', body='{"status": true, "message": "Balances retrieved"}', status=201, ) <|code_end|> , continue by predicting the next line. Consider current file imports: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.tcontrol import TransferControl and context: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/tcontrol.py # class TransferControl(PayStackBase): # """docstring for Transfer Control.""" # # @classmethod # def check_balance(cls): # """ # Check Balance. # # Args: # No argument required. # # Returns: # Json data from paystack API. # """ # # return cls().requests.get('balance') # # @classmethod # def resend_otp(cls, **kwargs): # """ # Resend OTP for Transfer. # # Args: # transfer_code: Transfer code # reason: either resend_otp or transfer # # Returns: # Json data from paystack API. # """ # # return cls().requests.post('transfer/resend_otp', data=kwargs,) # # @classmethod # def disable_otp(cls): # """ # Disable OTP requirement for Transfers # # Args: # No arguments required # # Returns: # Json data from paystack API. # """ # # return cls().requests.post('transfer/disable_otp') # # @classmethod # def disable_otp_finalize(cls, **kwargs): # """ # Finalize Disabling of OTP requirement for Transfers # # Args: # otp: OTP sent to business phone to verify disabling OTP requirement # # Returns: # Json data from paystack API. # """ # # return cls().requests.post('transfer/disable_otp_finalize', data=kwargs,) # # @classmethod # def enable_otp(cls, **kwargs): # """ # Enable OTP requirement for Transfers # # Args: # No arguments required # # Returns: # Json data from paystack API. # """ # # return cls().requests.post('transfer/enable_otp', data=kwargs,) which might include code, classes, or functions. Output only the next line.
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.endpoint_url("/transaction/initialize"), content_type='text/json', body='{"status": true, "contributors": true}', status=201, ) <|code_end|> . Use current file imports: (import httpretty from paystackapi.transaction import Transaction from paystackapi.tests.base_test_case import BaseTestCase) and context including class names, function names, or small code snippets from other files: # Path: paystackapi/transaction.py # class Transaction(PayStackBase): # """docstring for Transaction.""" # # @classmethod # def initialize(cls, **kwargs): # """ # Initialize transaction. # # Args: # reference: unique transaction reference # amount: amount # email: email address # plan: specified plan(optional) # # Returns: # Json data from paystack API. # """ # # return cls().requests.post('transaction/initialize', data=kwargs) # # @classmethod # def charge(cls, **kwargs): # """ # Charge authorization. # # Args: # reference: Unique transaction reference # authorization_code: Authorization code for the transaction # email: Email Address of the user with the authorization code # amount: Amount in kobo # # Returns: # Json data from paystack API. # """ # return cls().requests.post('transaction/charge_authorization', # data=kwargs) # # @classmethod # def charge_token(cls, **kwargs): # """ # Charge token. # # Args: # reference: unique transaction reference # token: paystack token # email: Email Address # amount: Amount in Kobo # # Returns: # Json data from paystack API. # """ # return cls().requests.post('transaction/charge_token', data=kwargs) # # @classmethod # def get(cls, transaction_id): # """ # Get a single transaction. # # Args: # transaction_id: Transaction id(integer). # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f"transaction/{transaction_id}") # # @classmethod # def list(cls): # """ # List transactions. # # Args: # No argument required. # # Returns: # Json data from paystack API. # """ # return cls().requests.get('transaction') # # @classmethod # def totals(cls): # """ # Get totals. # # Args: # No argument required. # # Returns: # Json data from paystack API. # """ # return cls().requests.get('transaction/totals') # # @classmethod # def verify(cls, reference): # """ # Verify transactions. # # Args: # reference: a unique value needed for transaction. # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f"transaction/verify/{reference}") # # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) . Output only the next line.
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("/subaccount"), content_type='text/json', body='{"status": true, "message": "Subaccount created"}', status=201, ) <|code_end|> , predict the next line using imports from the current file: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.subaccount import SubAccount and context including class names, function names, and sometimes code from other files: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/subaccount.py # class SubAccount(PayStackBase): # """docstring for SubAccount.""" # # @classmethod # def create(cls, **kwargs): # """ # Function defined to create subaccount. # # Args: # business_name: name of business for subaccount # settlement_bank: name of Bank (accepted banks) # account_number: NUBAN Bank Account number # percentage_charge: default percentage charged on subaccount? # **kwargs # # Returns: # Json data from paystack API. # """ # return cls().requests.post('subaccount', data=kwargs,) # # @classmethod # def list(cls, **kwargs): # """ # List subaccounts # # Args: # perPage: records you want to retrieve per page (Integer) # page: what page you want to retrieve (Integer) # # Returns: # JSON data from paystack's API. # """ # return cls().requests.get("subaccount", qs=kwargs,) # # @classmethod # def fetch(cls, id_or_slug): # """ # Get a single subaccount by id or slug. # # Args: # id_or_slug: id or subaccount_code # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f"subaccount/{id_or_slug}") # # @classmethod # def update(cls, id_or_slug, **kwargs): # """ # Update a single subaccount by id or slug. # # Args: # id_or_slug: id or subaccount_code # business_name: name of business for subaccount # settlement_bank: name of Bank (accepted banks) # account_number: NUBAN Bank Account number # percentage_charge: default percentage charged on subaccount? # **kwargs # # Returns: # Json data from paystack API. # """ # return cls().requests.put(f"subaccount/{id_or_slug}", data=kwargs,) . Output only the next line.
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 processing", "data": {"transaction": {}, "currency": "NGN", "amount": 180000, "status": "pending"}}', status=200, ) <|code_end|> , continue by predicting the next line. Consider current file imports: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.refund import Refund and context: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/refund.py # class Refund(PayStackBase): # # @classmethod # def create(cls, **kwargs): # """ # Function defined to create a refund. # # Args: # transaction: Transaction reference or id # amount: How much in kobo to be refunded to the customer - Optional # currency: Three-letter ISO currency - Optional # customer_note: Customer reason - Optional # merchant_note: Merchant reason - Optional # # Returns: # Json data from paystack API. # """ # # return cls().requests.post('refund', data=kwargs) # # @classmethod # def list(cls, **kwargs): # """ # List Refunds # # Args: # reference: Identifier for transaction to be refunded - Optional # currency: Three-letter ISO currency - Optional # # Returns: # JSON data from paystack's API. # """ # # return cls().requests.get('refund', data=kwargs) # # @classmethod # def fetch(cls, refund_id): # """ # Fetch a Refund # # Args: # refund_id: Identifier for refund to be fetched # # Return: # JSON data from paystack API # """ # # return cls().requests.get(f"refund/{refund_id}") which might include code, classes, or functions. Output only the next line.
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/payment_session_timeout"), content_type='text/json', body='{"status": true, "message": "Payment session timeout retrieved"}', status=201, ) <|code_end|> , generate the next line using the imports in this file: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.cpanel import ControlPanel and context (functions, classes, or occasionally code) from other files: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/cpanel.py # class ControlPanel(PayStackBase): # """docstring for ControlPanel.""" # # @classmethod # def fetch_payment_session_timeout(cls): # """ # Method defined to fetch payment session timeout. # # Args: # No argument required. # # Returns: # Json data from paystack API. # """ # return cls().requests.get('integration/payment_session_timeout') # # @classmethod # def update_payment_session_timeout(cls, **kwargs): # """ # Method defined to update payment session timeout. # # Args: # timeout: Time before stopping session (in seconds). # Set to 0 to cancel session timeouts # # Returns: # Json data from paystack API. # """ # return cls().requests.put('integration/payment_session_timeout', data=kwargs,) . Output only the next line.
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( httpretty.POST, self.endpoint_url("/customer"), content_type='text/json', body='{"status": true, "contributors": true}', status=201, ) <|code_end|> , determine the next line of code. You have imports: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.customer import Customer and context (class names, function names, or code) available: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/customer.py # class Customer(PayStackBase): # """docstring for Customer.""" # # @classmethod # def create(cls, **kwargs): # """ # Function defined to create customer. # # Args: # first_name: customer's first name. # last_name: customer's last name. # email: customer's email address. # phone:customer's phone number. # # Returns: # Json data from paystack API. # """ # return cls().requests.post('customer', data=kwargs,) # # @classmethod # def get(cls, customer_id): # """ # Static method defined to get customers by id. # # Args: # customer_id: paystack customer id. # Returns: # Json data from paystack API. # """ # return cls().requests.get(f"customer/{customer_id}") # # @classmethod # def list(cls): # """ # Static method defined to list paystack customers. # # Args: # No argument required. # Returns: # Json data from paystack API. # """ # return cls().requests.get('customer') # # @classmethod # def update(cls, customer_id, **kwargs): # """ # Static method defined to update paystack customer data by id. # # Args: # customer_id: paystack customer id. # first_name: customer's first name(optional). # last_name: customer's last name(optional). # email: customer's email address(optional). # phone:customer's phone number(optional). # # Returns: # Json data from paystack API. # """ # return cls().requests.put(f"customer/{customer_id}", data=kwargs,) . Output only the next line.
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("/transferrecipient"), content_type='text/json', body='{"status": true, "message": "Recipient created"}', status=201, ) <|code_end|> , predict the next line using imports from the current file: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.trecipient import TransferRecipient and context including class names, function names, and sometimes code from other files: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/trecipient.py # class TransferRecipient(PayStackBase): # """docstring for Transfer Recipient.""" # # @classmethod # def create(cls, **kwargs): # """ # Method defined to create transfer recipient. # # Args: # type: Recipient Type (Only nuban at this time) # name: A name for the recipient # account_number: Required if type is nuban # bank_code: Required if type is nuban. # You can get the list of Bank Codes by calling the List Banks endpoint. # **kwargs # # Returns: # Json data from paystack API. # """ # return cls().requests.post('transferrecipient', data=kwargs,) # # @classmethod # def list(cls, **kwargs): # """ # Method defined to list transfer recipient. # # Args: # perPage: records you want to retrieve per page (Integer) # page: what page you want to retrieve (Integer) # # Returns: # Json data from paystack API. # """ # return cls().requests.get('transferrecipient', qs=kwargs,) . Output only the next line.
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): httpretty.register_uri( httpretty.GET, self.endpoint_url("/transaction/4013"), content_type='text/json', body='{"status": true, "contributors": true}', status=201, ) <|code_end|> with the help of current file imports: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.base import PayStackBase, PayStackRequests and context from other files: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/base.py # class PayStackBase(Borg): # """Base Class used across defined.""" # # def __init__(self, **kwargs): # """Initialize Paystack with secret key.""" # Borg.__init__(self) # secret_key = kwargs.get('secret_key', api.SECRET_KEY) # authorization = kwargs.get( # 'authorization', # f"{api.HEADERS['Authorization'].format(secret_key)}") # headers = dict(Authorization=authorization) # arguments = dict(api_url=api.API_URL, headers=headers) # if not hasattr(self, 'requests'): # req = PayStackRequests(**arguments) # self._shared_state.update(requests=req) # # class PayStackRequests(object): # # def __init__(self, api_url='https://api.paystack.co/', # headers=None): # """Initialize Paystack Request object for browsing resource. # # Args: # api_url: str # headers: dict # """ # self.API_BASE_URL = f"{api_url}" # self.headers = headers # # def _request(self, method, resource_uri, **kwargs): # """Perform a method on a resource. # # Args: # method: requests.`method` # resource_uri: resource endpoint # Raises: # HTTPError # Returns: # JSON Response # """ # data = kwargs.get('data') # qs = kwargs.get('qs') # # response = method( # self.API_BASE_URL + resource_uri, # json=data, headers=self.headers, # params=qs # ) # return response.json() # # def get(self, endpoint, **kwargs): # """Get a resource. # # Args: # endpoint: resource endpoint. # """ # return self._request(requests.get, endpoint, **kwargs) # # def post(self, endpoint, **kwargs): # """Create a resource. # # Args: # endpoint: resource endpoint. # """ # return self._request(requests.post, endpoint, **kwargs) # # def put(self, endpoint, **kwargs): # """Update a resource. # # Args: # endpoint: resource endpoint. # """ # return self._request(requests.put, endpoint, **kwargs) , which may contain function names, class names, or code. Output only the next line.
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', body='{"status": true, "message": "Charge attempted"}', status=201, ) <|code_end|> . Write the next line using the current file imports: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.charge import Charge and context from other files: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/charge.py # class Charge(PayStackBase): # """docstring for Charge.""" # # @classmethod # def start_charge(cls, **kwargs): # """ # Start a charge. # # Args: # email: Customer's email address # amount: Amount in kobo # # Returns: # Json data from paystack API. # """ # return cls().requests.post('charge', data=kwargs,) # # @classmethod # def submit_pin(cls, **kwargs): # """ # Submit PIN to continue a charge. # # Args: # pin: PIN submitted by user # reference: reference for transaction that requested pin # # Returns: # Json data from paystack API. # """ # return cls().requests.post('charge/submit_pin', data=kwargs,) # # @classmethod # def submit_otp(cls, **kwargs): # """ # Submit OTP to complete a charge. # # Args: # otp: OTP submitted by user # reference: reference for ongoing transaction # # Returns: # Json data from paystack API. # """ # return cls().requests.post('charge/submit_otp', data=kwargs,) # # @classmethod # def submit_phone(cls, **kwargs): # """ # Submit Phone when requested. # # Args: # phone: Phone submitted by user # reference: reference for ongoing transaction # # Returns: # Json data from paystack API. # """ # return cls().requests.post('charge/submit_phone', data=kwargs,) # # @classmethod # def submit_birthday(cls, **kwargs): # """ # Submit Birthday when requested. # # Args: # birthday: Birthday submitted by user # reference: reference for ongoing transaction # # Returns: # Json data from paystack API. # """ # return cls().requests.post('charge/submit_birthday', data=kwargs,) # # @classmethod # def check_pending(cls, reference): # """ # Check pending charge # # Args: # reference: The reference to check # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f"charge/{reference}") , which may include functions, classes, or code. Output only the next line.
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_end|> , determine the next line of code. You have imports: import httpretty from paystackapi.misc import Misc from paystackapi.tests.base_test_case import BaseTestCase and context (class names, function names, or code) available: # Path: paystackapi/misc.py # class Misc(PayStackBase): # # @classmethod # def list_banks(cls): # """Static method defined to list banks. # Args: # No argument required. # Returns: # Json data from paystack API. # """ # return cls().requests.get('bank') # # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) . Output only the next line.
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', body='{"status": true, "message": "Transfer requires OTP to continue"}', status=201, ) <|code_end|> , continue by predicting the next line. Consider current file imports: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.transfer import Transfer and context: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/transfer.py # class Transfer(PayStackBase): # """docstring for Transfer.""" # # @classmethod # def initiate(cls, **kwargs): # """ # Initiate a transfer. # # Args: # source: Where should we transfer from? Only balance for now # amount: Amount to transfer in kobo # currency: Currency type to use # recipient: Code for transfer recipient # # Returns: # Json data from paystack API. # """ # # return cls().requests.post('transfer', data=kwargs) # # @classmethod # def list(cls, **kwargs): # """ # List a transfer. # # Args: # perPage: records you want to retrieve per page (Integer) # page: what page you want to retrieve (Integer) # # Returns: # Json data from paystack API. # """ # # return cls().requests.get('transfer', qs=kwargs,) # # @classmethod # def fetch(cls, id_or_code): # """ # Fetch a transfer. # # Args: # id_or_code: An ID or code for the transfer whose details you want to retrieve. # # Returns: # Json data from paystack API. # """ # # return cls().requests.get(f"transfer/{id_or_code}") # # @classmethod # def finalize(cls, **kwargs): # """ # Finalize a transfer. # NB: This step is not required if OTP is disabled # # Args: # transfer_code: Transfer code # otp: OTP sent to business phone to verify transfer # # Returns: # Json data from paystack API. # """ # # return cls().requests.post('transfer/finalize_transfer', data=kwargs) # # @classmethod # def initiate_bulk_transfer(cls, **kwargs): # """ # Initiate bulk transfer. # # Args: # currency: Currency type to use # source: Where should we transfer from? Only balance for now # transfers: Array of transfer objects [ # { # amount: Amount to transfer in kobo # recipient: Code for transfer recipient # }, # { # amount: Amount to transfer in kobo # recipient: Code for transfer recipient # } # ] # # Returns: # Json data from paystack API. # """ # # return cls().requests.post('transfer/bulk', data=kwargs) # # @classmethod # def verify(cls, reference): # """ # Verify a transfer. # # Args: # reference: Transfer reference # # Returns: # Json data from paystack API. # """ # # return cls().requests.get(f"verify/{reference}") which might include code, classes, or functions. Output only the next line.
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_type='text/json', body='{"status": true, "message": "Invoice created"}', status=201, ) <|code_end|> , generate the next line using the imports in this file: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.invoice import Invoice and context (functions, classes, or occasionally code) from other files: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/invoice.py # class Invoice(PayStackBase): # """docstring for Invoice.""" # # @classmethod # def create(cls, **kwargs): # """ # Method defined to create a new invoice. # # Args: # customer: customer id or code # amount: payment request amount.(Integer) # Only useful if line items and tax values are ignored. # Endpoint will throw a friendly warning if neither is available. # due_date: ISO 8601 representation of request due date. # **kwargs # # Returns: # Json data from paystack API. # """ # return cls().requests.post('paymentrequest', data=kwargs,) # # @classmethod # def list(cls, **kwargs): # """ # Method defined to list a new invoice. # # Args: # customer: filter by customer ID # status: filter by invoice status # currency: filter by currency # paid: filter by paid invoice # include_archive: include_archive # # Returns: # Json data from paystack API. # """ # return cls().requests.get('paymentrequest', qs=kwargs,) # # @classmethod # def view(cls, invoice_id_or_code): # """ # Method defined to view an invoice # # Args: # invoice_id_or_code: invoice ID or Code (string) # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f'paymentrequest/{invoice_id_or_code}') # # @classmethod # def verify(cls, invoice_code): # """ # Method defined to verify an invoice # # Args: # invoice_code: invoice Code (string) # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f'paymentrequest/verify/{invoice_code}') # # @classmethod # def send_notification(cls, id_or_code): # """ # Method defined to send notification # # Args: # id_or_code: id or code (string) # # Returns: # Json data from paystack API. # """ # return cls().requests.post(f'paymentrequest/notify/{id_or_code}') # # @classmethod # def dashboard_metrics(cls): # """ # Method defined to get Dashboard metrics. # # Args: # No Arguments required # # Returns: # Json data from paystack API. # """ # return cls().requests.get('paymentrequest/totals') # # @classmethod # def finalize_draft(cls, id_or_code, **kwargs): # """ # Method defined to finalize a draft. # # Args: # id_or_code: ID or Code (string) # send_notification: Indicates whether Paystack sends an email notification to customer. # Defaults to true. (Boolean) # # Returns: # Json data from paystack API. # """ # return cls().requests.post(f'paymentrequest/finalize/{id_or_code}', data=kwargs) # # @classmethod # def update(cls, id_or_code, **kwargs): # """ # Method defined to update a draft. # # Args: # id_or_code: ID or Code # **kwargs # # Returns: # Json data from paystack API. # """ # return cls().requests.put(f'paymentrequest/{id_or_code}', data=kwargs) # # @classmethod # def archive(cls, id_or_code): # """ # Method defined to archive a draft. # # Args: # id_or_code: ID or Code # # Returns: # Json data from paystack API. # """ # return cls().requests.post(f'invoice/archive/{id_or_code}') # # @classmethod # def update_transfer_recipient(cls, recipient_code_or_id, **kwargs): # """ # Method defined to Update transfer recipient a draft. # # Args: # recipient_code_or_id: recipient code or ID # name: a name for the recipient (string) # email: the email address of the recipient (string) # # Returns: # Json data from paystack API. # """ # return cls().requests.post(f'transferrecipient/{recipient_code_or_id}', data=kwargs) . Output only the next line.
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"), content_type='text/json', body='{"status": true, "message": "Product successfully created"}', status=201, ) <|code_end|> using the current file's imports: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.product import Product and any relevant context from other files: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/product.py # class Product(PayStackBase): # """docstring for Product.""" # # @classmethod # def create(cls, **kwargs): # """ # Function defined to create product. # # Args: # name: name of the product # description: description of product # price: price of the product, in kobo(Integer) # currency: currency in which amount should be charged # **kwargs # # Returns: # Json data from paystack API. # """ # return cls().requests.post('product', data=kwargs,) # # @classmethod # def list(cls): # """ # List Products. # # Args: # No argument required. # # Returns: # Json data from paystack API. # """ # return cls().requests.get('product') # # @classmethod # def fetch(cls, product_id): # """ # Get a single product by id. # # Args: # product_id: Product id(integer). # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f"product/{product_id}") # # @classmethod # def update(cls, product_id, **kwargs): # """ # Static method defined to update product by id. # # Args: # product_id: paystack product id. # name: name of the product # description: description of product # price: price of the product, in kobo(Integer) # currency: currency in which amount should be charged # **kwargs # # Returns: # Json data from paystack API. # """ # return cls().requests.put(f"product/{product_id}", data=kwargs,) . Output only the next line.
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', body='{"status": true, "message": "Settlements retrieved"}', status=201, ) <|code_end|> , predict the immediate next line with the help of imports: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.settlement import Settlement and context (classes, functions, sometimes code) from other files: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/settlement.py # class Settlement(PayStackBase): # """docstring for settlement.""" # # @classmethod # def fetch(cls, **kwargs): # """ # Function defined to fetch settlement. # # Args: # from: Lower bound of date range. # Leave undefined to export settlement from day one. # to: Upper bound of date range. # Leave undefined to export settlements till date. # subaccount: code to export only settlements for that subaccount. # Set to none to export only transactions for the account. # # Returns: # Json data from paystack API. # """ # return cls().requests.get("settlement", qs=kwargs) . Output only the next line.
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_type='text/json', body='{"status": true, "message": "Page created"}', status=201, ) <|code_end|> using the current file's imports: import httpretty from paystackapi.tests.base_test_case import BaseTestCase from paystackapi.page import Page and any relevant context from other files: # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) # # Path: paystackapi/page.py # class Page(PayStackBase): # """docstring for Page.""" # # @classmethod # def create(cls, **kwargs): # """ # method defined to create a new page. # # Args: # name: name of page # **kwargs # # Returns: # Json data from paystack API. # """ # return cls().requests.post('page', data=kwargs,) # # @classmethod # def list(cls, **kwargs): # """ # List pages # # Args: # perPage: records you want to retrieve per page (Integer) # page: what page you want to retrieve (Integer) # # Returns: # JSON data from paystack's API. # """ # return cls().requests.get("page", qs=kwargs) # # @classmethod # def fetch(cls, id_or_slug): # """ # Get a single page by id or slug. # # Args: # id_or_slug: id or slug # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f"page/{id_or_slug}") # # @classmethod # def update(cls, id_or_slug, **kwargs): # """ # Update a single page by id or slug. # # Args: # id_or_slug: id or slug # **kwargs # # Returns: # Json data from paystack API. # """ # return cls().requests.put(f"page/{id_or_slug}", data=kwargs,) # # @classmethod # def is_slug_available(cls, slug): # """ # Check if a slug is available. # # Args: # slug: URL slug to be confirmed # # Returns: # Json data from paystack API. # """ # return cls().requests.put(f"page/check_slug_availability/{slug}") # # @classmethod # def add_products(cls, payment_page_id, **kwargs): # """ # Add products to page # # Args: # payment_page_id: Id of the payment page (Integer) # product: Ids of all the products i.e. [473, 292] # # Returns: # Json data from paystack API. # """ # return cls().requests.put(f"page/{payment_page_id}/product", data=kwargs,) . Output only the next line.
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( httpretty.GET, self.endpoint_url("/bank/resolve_bvn/01234567689"), content_type='text/json', body='{"status": true, "contributors": true}', status=200, ) <|code_end|> , determine the next line of code. You have imports: import httpretty from paystackapi.verification import Verification from paystackapi.tests.base_test_case import BaseTestCase and context (class names, function names, or code) available: # Path: paystackapi/verification.py # class Verification(PayStackBase): # """docstring for Verification.""" # # @classmethod # def verify_bvn(cls, bvn): # """ # Verify BVN # # Args: # bvn: customer's BVN number # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f"bank/resolve_bvn/{bvn}") # # @classmethod # def verify_account(cls, **kwargs): # """ # Verify account # # Args: # account_number: customer's account number # bank_code: customer's bank code # # Returns: # Json data from paystack API. # """ # return cls().requests.get("bank/resolve", qs=kwargs,) # # @classmethod # def verify_card_bin(cls, card_bin): # """ # Verify card bin # # Args: # card_bin: customer's card bin number # # Returns: # Json data from paystack API. # """ # return cls().requests.get(f"decision/bin/{card_bin}") # # @classmethod # def verify_phone(cls, **kwargs): # """ # Verify customer phone number # # Args: # verification_type: phone verification type # phone: customer's phone number # callback_url: url to receive verification details # # Returns: # Json data from paystack API. # """ # return cls().requests.post('verifications', data=kwargs) # # Path: paystackapi/tests/base_test_case.py # class BaseTestCase(unittest.TestCase): # # def endpoint_url(self, path): # if path[0] == '/': # return 'https://api.paystack.co{}'.format(path) # return 'https://api.paystack.co/{}'.format(path) . Output only the next line.
response = Verification.verify_bvn(bvn='01234567689')