Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|> except Exception: raise finally: if self.enable_profiling: output_path_ = self.output_path if callable(output_path_): self.output_path = output_path_(*args, **kwargs) uid_ = self.uid if callable(uid_): self.uid = uid_() info_ = self.info if callable(info_): self.info = info_(response, *args, **kwargs) self.__exit__(None, None, None) return response return func_wrapper def __enter__(self): pr = None if self.enable_profiling: pr = Profile(sortby=self.sortby) pr.enable() self.pr = pr return pr def __exit__(self, type, value, traceback): if self.enable_profiling: <|code_end|> , generate the next line using the imports in this file: import os import json import subprocess import cProfile import pstats import uuid from functools import wraps from .._compatibility import StringIO from .._logging import get_logger and context (functions, classes, or occasionally code) from other files: # Path: marvin_python_toolbox/_compatibility.py # # Path: marvin_python_toolbox/_logging.py # def get_logger(name, namespace='marvin_python_toolbox', # log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR): # """Build a logger that outputs to a file and to the console,""" # # log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or # os.getenv('LOG_LEVEL', log_level)) # log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or # os.getenv('LOG_DIR', log_dir)) # # logger = logging.getLogger('{}.{}'.format(namespace, name)) # logger.setLevel(log_level) # # formatter = logging.Formatter( # '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # # # Create a console stream handler # console_handler = logging.StreamHandler() # console_handler.setLevel(log_level) # console_handler.setFormatter(formatter) # logger.addHandler(console_handler) # # try: # log_path = os.path.abspath(log_dir) # log_filename = '{name}.{pid}.log'.format( # name=namespace, pid=os.getpid()) # # file_path = str(os.path.join(log_path, log_filename)) # # if not os.path.exists(log_path): # pragma: no cover # os.makedirs(log_path, mode=774) # # # Create a file handler # file_handler = logging.FileHandler(file_path) # file_handler.setLevel(log_level) # file_handler.setFormatter(formatter) # logger.addHandler(file_handler) # except OSError as e: # logger.error('Could not create log file {file}: {error}'.format( # file=file_path, error=e.strerror)) # # return logger . Output only the next line.
pr = self.pr
Based on the snippet: <|code_start|> body='{"error": "deu merda"}', content_type="application/json", status=500) httpretty.register_uri(httpretty.GET, "http://localhost:8000/service1/", body='{"objects": [{"id": "1"}, {"id": "2"}], "total": 3}', content_type="application/json", status=200) response = ApiClient().get_all('/service1/', limit=2) assert len(response) == 3 with pytest.raises(HTTPException): response_list = list(response) @httpretty.activate def test_post_not_ok(self): httpretty.register_uri(httpretty.POST, "http://localhost:8000/service1/", body='[{"error": "name required"}]', content_type='text/json', status=500) response = ApiClient().post('/service1/', {"name": "americanas", "url": "www.americanas.com.br"}) assert not response.ok @httpretty.activate def test_post_ok(self): httpretty.register_uri(httpretty.POST, "http://localhost:8000/service1/", <|code_end|> , predict the immediate next line with the help of imports: import json import pytest import httpretty from httpretty import httpretty as httpretty_object from marvin_python_toolbox.common.http_client import ApiClient, ListResultSet from marvin_python_toolbox.common.exceptions import HTTPException and context (classes, functions, sometimes code) from other files: # Path: marvin_python_toolbox/common/http_client.py # class ApiClient(HttpClient): # """ # Data Api client abstracttion. # See `scanboo_common.http_client.HttpClient` for more info. # """ # # @property # def host(self): # # url = Configuration.get('api.url') # url = 'http://localhost:8000' # return url[:-1] if url.endswith('/') else url # # class ListResultSet(object): # """ # Used to encapsulate the result of requests of lists. # """ # # def __init__(self, path, data=None, limit=50, page=1): # self.path = path # self.params = data or {} # self.limit = limit # self.page = page # # self.response = None # self._objects = [] # # self._process() # # def __len__(self): # return self.response.data.get('total', 0) # # def __iter__(self): # more_results = True # # while more_results: # for item in self._objects: # yield item # # next_page = self._next_page() # if next_page: # self.page = next_page # self._process() # else: # more_results = False # # def _next_page(self): # new_page = None # if math.ceil(self.response.data['total'] / float(self.limit)) >= (self.page + 1): # new_page = self.page + 1 # return new_page # # def _process(self): # url = api_client.url(self.path) # self.params.update({'page': self.page, 'per_page': self.limit}) # # response = requests.get(url, params=self.params, headers=api_client.request_header()) # response = api_client.parse_response(response) # # try: # self._objects = response.data['objects'] # except TypeError: # raise HTTPException(response.errors) # self.response = response # # Path: marvin_python_toolbox/common/exceptions.py # class HTTPException(HTTPExceptionBase): # """ # HTTP exception # """ . Output only the next line.
body='{"success": true}',
Predict the next line after this snippet: <|code_start|> assert response.ok @httpretty.activate def test_delete_not_ok(self): httpretty.register_uri(httpretty.DELETE, "http://localhost:8000/service1/", body='[{"error": "name required"}]', content_type="application/json", status=500) response = ApiClient().delete('/service1/') assert not response.ok @httpretty.activate def test_delete_ok(self): httpretty.register_uri(httpretty.DELETE, "http://localhost:8000/service1/", body='{"success": true}', content_type='text/json', status=200) response = ApiClient().delete('/service1/') assert response.ok @httpretty.activate def test_full_url_path(self): httpretty.register_uri(httpretty.GET, "http://localhost:9999/service_full/", body='[{"id": "1"}]', content_type="application/json", <|code_end|> using the current file's imports: import json import pytest import httpretty from httpretty import httpretty as httpretty_object from marvin_python_toolbox.common.http_client import ApiClient, ListResultSet from marvin_python_toolbox.common.exceptions import HTTPException and any relevant context from other files: # Path: marvin_python_toolbox/common/http_client.py # class ApiClient(HttpClient): # """ # Data Api client abstracttion. # See `scanboo_common.http_client.HttpClient` for more info. # """ # # @property # def host(self): # # url = Configuration.get('api.url') # url = 'http://localhost:8000' # return url[:-1] if url.endswith('/') else url # # class ListResultSet(object): # """ # Used to encapsulate the result of requests of lists. # """ # # def __init__(self, path, data=None, limit=50, page=1): # self.path = path # self.params = data or {} # self.limit = limit # self.page = page # # self.response = None # self._objects = [] # # self._process() # # def __len__(self): # return self.response.data.get('total', 0) # # def __iter__(self): # more_results = True # # while more_results: # for item in self._objects: # yield item # # next_page = self._next_page() # if next_page: # self.page = next_page # self._process() # else: # more_results = False # # def _next_page(self): # new_page = None # if math.ceil(self.response.data['total'] / float(self.limit)) >= (self.page + 1): # new_page = self.page + 1 # return new_page # # def _process(self): # url = api_client.url(self.path) # self.params.update({'page': self.page, 'per_page': self.limit}) # # response = requests.get(url, params=self.params, headers=api_client.request_header()) # response = api_client.parse_response(response) # # try: # self._objects = response.data['objects'] # except TypeError: # raise HTTPException(response.errors) # self.response = response # # Path: marvin_python_toolbox/common/exceptions.py # class HTTPException(HTTPExceptionBase): # """ # HTTP exception # """ . Output only the next line.
status=200)
Using the snippet: <|code_start|>#!/usr/bin/env python # coding=utf-8 # Copyright [2017] [B2W Digital] # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class TestHttpClient: @httpretty.activate def test_list_result_set(self): <|code_end|> , determine the next line of code. You have imports: import json import pytest import httpretty from httpretty import httpretty as httpretty_object from marvin_python_toolbox.common.http_client import ApiClient, ListResultSet from marvin_python_toolbox.common.exceptions import HTTPException and context (class names, function names, or code) available: # Path: marvin_python_toolbox/common/http_client.py # class ApiClient(HttpClient): # """ # Data Api client abstracttion. # See `scanboo_common.http_client.HttpClient` for more info. # """ # # @property # def host(self): # # url = Configuration.get('api.url') # url = 'http://localhost:8000' # return url[:-1] if url.endswith('/') else url # # class ListResultSet(object): # """ # Used to encapsulate the result of requests of lists. # """ # # def __init__(self, path, data=None, limit=50, page=1): # self.path = path # self.params = data or {} # self.limit = limit # self.page = page # # self.response = None # self._objects = [] # # self._process() # # def __len__(self): # return self.response.data.get('total', 0) # # def __iter__(self): # more_results = True # # while more_results: # for item in self._objects: # yield item # # next_page = self._next_page() # if next_page: # self.page = next_page # self._process() # else: # more_results = False # # def _next_page(self): # new_page = None # if math.ceil(self.response.data['total'] / float(self.limit)) >= (self.page + 1): # new_page = self.page + 1 # return new_page # # def _process(self): # url = api_client.url(self.path) # self.params.update({'page': self.page, 'per_page': self.limit}) # # response = requests.get(url, params=self.params, headers=api_client.request_header()) # response = api_client.parse_response(response) # # try: # self._objects = response.data['objects'] # except TypeError: # raise HTTPException(response.errors) # self.response = response # # Path: marvin_python_toolbox/common/exceptions.py # class HTTPException(HTTPExceptionBase): # """ # HTTP exception # """ . Output only the next line.
data = [{'id': str(n)} for n in range(100)]
Given snippet: <|code_start|>class TestDataSourceProvider: @mock.patch("pyspark.sql.SparkSession") def test_get_spark_session(self, mocked_session): spark = get_spark_session() assert spark mocked_session.assert_has_calls([ mock.call.builder.appName('marvin-engine'), mock.call.builder.appName().getOrCreate()] ) spark = get_spark_session(app_name='TestEngine') assert spark mocked_session.assert_has_calls([ mock.call.builder.appName('TestEngine'), mock.call.builder.appName().getOrCreate()] ) spark = get_spark_session(configs=[("spark.xxx", "true")]) assert spark mocked_session.assert_has_calls([ mock.call.builder.appName('TestEngine'), mock.call.builder.appName().getOrCreate()] ) @mock.patch("pyspark.sql.SparkSession") def test_get_spark_session_with_hive(self, mocked_session): spark = get_spark_session(enable_hive=True) assert spark mocked_session.assert_has_calls([ <|code_end|> , continue by predicting the next line. Consider current file imports: import findspark import mock import unittest.mock as mock from pyspark.tests import ReusedPySparkTestCase from marvin_python_toolbox.common.data_source_provider import get_spark_session and context: # Path: marvin_python_toolbox/common/data_source_provider.py # def get_spark_session(enable_hive=False, app_name='marvin-engine', configs=[]): # """Return a Spark Session object""" # # # Prepare spark context to be used # import findspark # findspark.init() # from pyspark.sql import SparkSession # # # prepare spark sesseion to be returned # spark = SparkSession.builder # # spark = spark.appName(app_name) # spark = spark.enableHiveSupport() if enable_hive else spark # # # if has configs # for config in configs: # spark = spark.config(config) # # return spark.getOrCreate() which might include code, classes, or functions. Output only the next line.
mock.call.builder.appName('marvin-engine'),
Here is a snippet: <|code_start|>logger = get_logger('engine_base_training') class EngineBaseTraining(EngineBaseBatchAction): __metaclass__ = ABCMeta _dataset = None _model = None _metrics = None def __init__(self, **kwargs): self._dataset = self._get_arg(kwargs=kwargs, arg='dataset') self._model = self._get_arg(kwargs=kwargs, arg='model') self._metrics = self._get_arg(kwargs=kwargs, arg='metrics') super(EngineBaseTraining, self).__init__(**kwargs) @property def marvin_dataset(self): return self._load_obj(object_reference='_dataset') @marvin_dataset.setter def marvin_dataset(self, dataset): self._save_obj(object_reference='_dataset', obj=dataset) @property def marvin_model(self): return self._load_obj(object_reference='_model') @marvin_model.setter <|code_end|> . Write the next line using the current file imports: from abc import ABCMeta from .._compatibility import six from .._logging import get_logger from .engine_base_action import EngineBaseBatchAction and context from other files: # Path: marvin_python_toolbox/_compatibility.py # # Path: marvin_python_toolbox/_logging.py # def get_logger(name, namespace='marvin_python_toolbox', # log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR): # """Build a logger that outputs to a file and to the console,""" # # log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or # os.getenv('LOG_LEVEL', log_level)) # log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or # os.getenv('LOG_DIR', log_dir)) # # logger = logging.getLogger('{}.{}'.format(namespace, name)) # logger.setLevel(log_level) # # formatter = logging.Formatter( # '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # # # Create a console stream handler # console_handler = logging.StreamHandler() # console_handler.setLevel(log_level) # console_handler.setFormatter(formatter) # logger.addHandler(console_handler) # # try: # log_path = os.path.abspath(log_dir) # log_filename = '{name}.{pid}.log'.format( # name=namespace, pid=os.getpid()) # # file_path = str(os.path.join(log_path, log_filename)) # # if not os.path.exists(log_path): # pragma: no cover # os.makedirs(log_path, mode=774) # # # Create a file handler # file_handler = logging.FileHandler(file_path) # file_handler.setLevel(log_level) # file_handler.setFormatter(formatter) # logger.addHandler(file_handler) # except OSError as e: # logger.error('Could not create log file {file}: {error}'.format( # file=file_path, error=e.strerror)) # # return logger # # Path: marvin_python_toolbox/engine_base/engine_base_action.py # class EngineBaseBatchAction(EngineBaseAction): # __metaclass__ = ABCMeta # # @abstractmethod # def execute(self, params, **kwargs): # pass # # def _pipeline_execute(self, params): # if self._previous_step: # self._previous_step._pipeline_execute(params) # # logger.info("Start of the {} execute method!".format(self.action_name)) # self.execute(params) # logger.info("Finish of the {} execute method!".format(self.action_name)) # # def _remote_execute(self, request, context): # logger.info("Received message from client and sending to engine action...") # logger.debug("Received Params: {}".format(request.params)) # # params = json.loads(request.params) if request.params else self._params # # self._pipeline_execute(params=params) # # self._release_local_saved_objects() # # logger.info("Handling returned message from engine action...") # response_message = BatchActionResponse(message="Done") # # logger.info("Return final results to the client!") # return response_message # # def _prepare_remote_server(self, port, workers, rpc_workers): # server = grpc.server(thread_pool=futures.ThreadPoolExecutor(max_workers=workers), maximum_concurrent_rpcs=rpc_workers) # actions_pb2_grpc.add_BatchActionHandlerServicer_to_server(self, server) # server.add_insecure_port('[::]:{}'.format(port)) # return server , which may include functions, classes, or code. Output only the next line.
def marvin_model(self, model):
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # coding=utf-8 # Copyright [2017] [B2W Digital] # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ['EngineBaseTraining'] logger = get_logger('engine_base_training') class EngineBaseTraining(EngineBaseBatchAction): __metaclass__ = ABCMeta _dataset = None <|code_end|> using the current file's imports: from abc import ABCMeta from .._compatibility import six from .._logging import get_logger from .engine_base_action import EngineBaseBatchAction and any relevant context from other files: # Path: marvin_python_toolbox/_compatibility.py # # Path: marvin_python_toolbox/_logging.py # def get_logger(name, namespace='marvin_python_toolbox', # log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR): # """Build a logger that outputs to a file and to the console,""" # # log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or # os.getenv('LOG_LEVEL', log_level)) # log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or # os.getenv('LOG_DIR', log_dir)) # # logger = logging.getLogger('{}.{}'.format(namespace, name)) # logger.setLevel(log_level) # # formatter = logging.Formatter( # '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # # # Create a console stream handler # console_handler = logging.StreamHandler() # console_handler.setLevel(log_level) # console_handler.setFormatter(formatter) # logger.addHandler(console_handler) # # try: # log_path = os.path.abspath(log_dir) # log_filename = '{name}.{pid}.log'.format( # name=namespace, pid=os.getpid()) # # file_path = str(os.path.join(log_path, log_filename)) # # if not os.path.exists(log_path): # pragma: no cover # os.makedirs(log_path, mode=774) # # # Create a file handler # file_handler = logging.FileHandler(file_path) # file_handler.setLevel(log_level) # file_handler.setFormatter(formatter) # logger.addHandler(file_handler) # except OSError as e: # logger.error('Could not create log file {file}: {error}'.format( # file=file_path, error=e.strerror)) # # return logger # # Path: marvin_python_toolbox/engine_base/engine_base_action.py # class EngineBaseBatchAction(EngineBaseAction): # __metaclass__ = ABCMeta # # @abstractmethod # def execute(self, params, **kwargs): # pass # # def _pipeline_execute(self, params): # if self._previous_step: # self._previous_step._pipeline_execute(params) # # logger.info("Start of the {} execute method!".format(self.action_name)) # self.execute(params) # logger.info("Finish of the {} execute method!".format(self.action_name)) # # def _remote_execute(self, request, context): # logger.info("Received message from client and sending to engine action...") # logger.debug("Received Params: {}".format(request.params)) # # params = json.loads(request.params) if request.params else self._params # # self._pipeline_execute(params=params) # # self._release_local_saved_objects() # # logger.info("Handling returned message from engine action...") # response_message = BatchActionResponse(message="Done") # # logger.info("Return final results to the client!") # return response_message # # def _prepare_remote_server(self, port, workers, rpc_workers): # server = grpc.server(thread_pool=futures.ThreadPoolExecutor(max_workers=workers), maximum_concurrent_rpcs=rpc_workers) # actions_pb2_grpc.add_BatchActionHandlerServicer_to_server(self, server) # server.add_insecure_port('[::]:{}'.format(port)) # return server . Output only the next line.
_model = None
Next line prediction: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. @pytest.fixture def engine_action(): class EngineAction(EngineBaseTraining): def execute(self, **kwargs): return 1 return EngineAction(default_root_path="/tmp/.marvin") class TestEngineBaseTraining: def test_dataset(self, engine_action): engine_action.marvin_dataset = [1] assert engine_action.marvin_dataset == engine_action._dataset == [1] def test_model(self, engine_action): engine_action.marvin_model = [2] assert engine_action.marvin_model == engine_action._model == [2] def test_metrics(self, engine_action): engine_action.marvin_metrics = [3] <|code_end|> . Use current file imports: (import pytest from marvin_python_toolbox.engine_base import EngineBaseTraining) and context including class names, function names, or small code snippets from other files: # Path: marvin_python_toolbox/engine_base/engine_base_training.py # class EngineBaseTraining(EngineBaseBatchAction): # __metaclass__ = ABCMeta # # _dataset = None # _model = None # _metrics = None # # def __init__(self, **kwargs): # self._dataset = self._get_arg(kwargs=kwargs, arg='dataset') # self._model = self._get_arg(kwargs=kwargs, arg='model') # self._metrics = self._get_arg(kwargs=kwargs, arg='metrics') # # super(EngineBaseTraining, self).__init__(**kwargs) # # @property # def marvin_dataset(self): # return self._load_obj(object_reference='_dataset') # # @marvin_dataset.setter # def marvin_dataset(self, dataset): # self._save_obj(object_reference='_dataset', obj=dataset) # # @property # def marvin_model(self): # return self._load_obj(object_reference='_model') # # @marvin_model.setter # def marvin_model(self, model): # self._save_obj(object_reference='_model', obj=model) # # @property # def marvin_metrics(self): # return self._load_obj(object_reference='_metrics') # # @marvin_metrics.setter # def marvin_metrics(self, metrics): # self._save_obj(object_reference='_metrics', obj=metrics) . Output only the next line.
assert engine_action.marvin_metrics == engine_action._metrics == [3]
Predict the next line after this snippet: <|code_start|> load_conf_from_file() ConfigParserMocked.assert_called_once_with(os.environ['DEFAULT_CONFIG_PATH']) @mock.patch('marvin_python_toolbox.common.config.logger') @mock.patch('marvin_python_toolbox.common.config.ConfigObj.__getitem__') def test_load_conf_from_default_path_with_invalid_section(self, ConfigParserGetItemMocked, logger_mocked): filepath = '/path/to/config/file.ini' ConfigParserGetItemMocked.side_effect = NoSectionError('') assert len(load_conf_from_file(filepath, section='invalidsection')) == 0 logger_mocked.warn.assert_called_once_with( "Couldn't find \"invalidsection\" section in \"/path/to/config/file.ini\"" ) @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_get(self, load_conf_from_file_mocked, config_fixture): load_conf_from_file_mocked.return_value = config_fixture assert Config.get('key') == config_fixture['key'] @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_get_invalid_key(self, load_conf_from_file_mocked, config_fixture): load_conf_from_file_mocked.return_value = config_fixture assert 'invalidkey' not in config_fixture with pytest.raises(InvalidConfigException): Config.get('invalidkey') @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_get_invalid_key_with_default(self, load_conf_from_file_mocked, config_fixture): <|code_end|> using the current file's imports: import pytest import os import mock import unittest.mock as mock from marvin_python_toolbox.common.config import Config, load_conf_from_file from marvin_python_toolbox.common.exceptions import InvalidConfigException from configparser import NoSectionError and any relevant context from other files: # Path: marvin_python_toolbox/common/config.py # def load_conf_from_file(path=None, section='marvin'): # def reset(cls): # def _load(cls, section=None): # def get(cls, key, section=None, **kwargs): # def keys(cls, section=None): # DEFAULT_PREFIX = 'marvin.' # DEFAULT_SECT = 'marvin' # PREFIX = DEFAULT_PREFIX # class Configuration(object): # # Path: marvin_python_toolbox/common/exceptions.py # class InvalidConfigException(ConfigException): # """ # Invalid Marvin Config Base Exception # """ . Output only the next line.
load_conf_from_file_mocked.return_value = config_fixture
Using the snippet: <|code_start|> def test_get_invalid_key(self, load_conf_from_file_mocked, config_fixture): load_conf_from_file_mocked.return_value = config_fixture assert 'invalidkey' not in config_fixture with pytest.raises(InvalidConfigException): Config.get('invalidkey') @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_get_invalid_key_with_default(self, load_conf_from_file_mocked, config_fixture): load_conf_from_file_mocked.return_value = config_fixture assert 'invalidkey' not in config_fixture assert Config.get('invalidkey', default='default_value') == 'default_value' @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_get_with_invalid_section(self, load_conf_from_file_mocked, config_fixture): load_conf_from_file_mocked.return_value = {} with pytest.raises(InvalidConfigException): Config.get('key', section='invalidsection') @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_keys_alread_loaded(self, load_conf_from_file_mocked, config_fixture): load_conf_from_file_mocked.return_value = config_fixture Config._load() assert Config.keys() == config_fixture.keys() @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_keys(self, load_conf_from_file_mocked, config_fixture): load_conf_from_file_mocked.return_value = config_fixture assert Config.keys() == config_fixture.keys() @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') <|code_end|> , determine the next line of code. You have imports: import pytest import os import mock import unittest.mock as mock from marvin_python_toolbox.common.config import Config, load_conf_from_file from marvin_python_toolbox.common.exceptions import InvalidConfigException from configparser import NoSectionError and context (class names, function names, or code) available: # Path: marvin_python_toolbox/common/config.py # def load_conf_from_file(path=None, section='marvin'): # def reset(cls): # def _load(cls, section=None): # def get(cls, key, section=None, **kwargs): # def keys(cls, section=None): # DEFAULT_PREFIX = 'marvin.' # DEFAULT_SECT = 'marvin' # PREFIX = DEFAULT_PREFIX # class Configuration(object): # # Path: marvin_python_toolbox/common/exceptions.py # class InvalidConfigException(ConfigException): # """ # Invalid Marvin Config Base Exception # """ . Output only the next line.
def test_keys_with_invalid_section(self, load_conf_from_file_mocked):
Here is a snippet: <|code_start|> load_conf_from_file_mocked.return_value = config_fixture assert 'invalidkey' not in config_fixture with pytest.raises(InvalidConfigException): Config.get('invalidkey') @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_get_invalid_key_with_default(self, load_conf_from_file_mocked, config_fixture): load_conf_from_file_mocked.return_value = config_fixture assert 'invalidkey' not in config_fixture assert Config.get('invalidkey', default='default_value') == 'default_value' @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_get_with_invalid_section(self, load_conf_from_file_mocked, config_fixture): load_conf_from_file_mocked.return_value = {} with pytest.raises(InvalidConfigException): Config.get('key', section='invalidsection') @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_keys_alread_loaded(self, load_conf_from_file_mocked, config_fixture): load_conf_from_file_mocked.return_value = config_fixture Config._load() assert Config.keys() == config_fixture.keys() @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_keys(self, load_conf_from_file_mocked, config_fixture): load_conf_from_file_mocked.return_value = config_fixture assert Config.keys() == config_fixture.keys() @mock.patch('marvin_python_toolbox.common.config.load_conf_from_file') def test_keys_with_invalid_section(self, load_conf_from_file_mocked): <|code_end|> . Write the next line using the current file imports: import pytest import os import mock import unittest.mock as mock from marvin_python_toolbox.common.config import Config, load_conf_from_file from marvin_python_toolbox.common.exceptions import InvalidConfigException from configparser import NoSectionError and context from other files: # Path: marvin_python_toolbox/common/config.py # def load_conf_from_file(path=None, section='marvin'): # def reset(cls): # def _load(cls, section=None): # def get(cls, key, section=None, **kwargs): # def keys(cls, section=None): # DEFAULT_PREFIX = 'marvin.' # DEFAULT_SECT = 'marvin' # PREFIX = DEFAULT_PREFIX # class Configuration(object): # # Path: marvin_python_toolbox/common/exceptions.py # class InvalidConfigException(ConfigException): # """ # Invalid Marvin Config Base Exception # """ , which may include functions, classes, or code. Output only the next line.
load_conf_from_file_mocked.return_value = {}
Here is a snippet: <|code_start|> hdfs_comm_mock.assert_any_call(ssh, "hdfs dfs -ls -R '/home/' | grep -E '^-' | wc -l") hdfs_comm_mock.assert_any_call(ssh, "hdfs dfs -ls -R '/tmp/' | grep -E '^-' | wc -l") logger_mock.debug.assert_not_called() sys_mock.exit.assert_not_called() @mock.patch('marvin_python_toolbox.management.hive.sys') @mock.patch('marvin_python_toolbox.management.hive.logger') @mock.patch('marvin_python_toolbox.management.hive.HiveDataImporter.copy_files') @mock.patch('marvin_python_toolbox.management.hive.HiveDataImporter.delete_files') @mock.patch('marvin_python_toolbox.management.hive.HiveDataImporter._hdfs_commands') @mock.patch('marvin_python_toolbox.management.hive.HiveDataImporter._get_ssh_client') def test_hdfs_dist_copy_error_copy(self, ssh_cli_mock, hdfs_comm_mock, del_files_mock, copy_mock, logger_mock, sys_mock): hdfs_comm_mock.side_effect = [(42, None), (13, None)] copy_mock.return_value = (None, ['error']) ssh = mock.MagicMock() ssh_cli_mock.return_value = ssh force = False hdfs_host = 'hdfs://test.com' hdfs_port = 1234 origin = '/home/' dest = '/tmp/' self.hdi.hdfs_dist_copy(force, hdfs_host, hdfs_port, origin, dest, username=None, password=None) ssh_cli_mock.assert_called_once_with(hdfs_host, hdfs_port, None, None) del_files_mock.assert_not_called() hdfs_comm_mock.assert_any_call(ssh, "hdfs dfs -ls -R '/home/' | grep -E '^-' | wc -l") hdfs_comm_mock.assert_any_call(ssh, "hdfs dfs -ls -R '/tmp/' | grep -E '^-' | wc -l") logger_mock.debug.assert_called_once_with('error') <|code_end|> . Write the next line using the current file imports: import mock import unittest.mock as mock from marvin_python_toolbox.management import hive and context from other files: # Path: marvin_python_toolbox/management/hive.py # def cli(): # def hive_generateconf_cli(ctx): # def hive_generateconf(ctx): # def hive_resetremote_cli(ctx, host, engine, queue): # def hive_resetremote(ctx, host, engine, queue): # def hive_dataimport_cli( # ctx, conf, sql_id, engine, skip_remote_preparation, force_copy_files, validate, force, # force_remote, max_query_size, destination_host, destination_port, destination_host_username, # destination_host_password, destination_hdfs_root_path # ): # def hive_dataimport( # ctx, conf, sql_id, engine, skip_remote_preparation, force_copy_files, validate, force, # force_remote, max_query_size, destination_host, destination_port, destination_host_username, # destination_host_password, destination_hdfs_root_path # ): # def read_config(filename): # def __init__( # self, origin_host, origin_db, origin_queue, target_table_name, sample_sql, engine, # max_query_size, destination_host, destination_port, destination_host_username, destination_host_password, # destination_hdfs_root_path, sql_id # ): # def validade_query(self): # def table_exists(self, host, db, table): # def reset_remote_tables(self): # def print_finish_step(self): # def print_start_step(self, name, step_number, total_steps): # def import_sample(self, create_temp_table=True, copy_files=True, validate_query=True, force_create_remote_table=False): # def temp_table_prefix(self): # def temp_table_name(self): # def full_table_name(self): # def full_temp_table_name(self): # def generate_table_location(self, root_path, host, db_name, table_name): # def clean_ddl(self, ddl, remove_formats=True, remove_general=True): # def get_table_format(self, ddl): # def get_database_info(self, ddl): # def get_createtable_ddl(self, conn, origin_table_name, dest_table_name): # def create_database(self, conn, db): # def drop_table(self, conn, table_name): # def drop_view(self, conn, view_name): # def create_table(self, conn, table_name, ddl): # def _execute_db_command(self, conn, command): # def get_connection(self, host, db='DEFAULT', queue='default'): # def retrieve_data_sample(self, conn, full_table_name, sample_limit=100): # def count_rows(self, conn, sql): # def show_log(self, cursor): # def save_data(self, conn, table, data): # def get_partitions(self, ddl): # def has_partitions(self, sql, partitions): # def populate_table(self, conn, table_name, partitions, sql): # def create_view(self, conn, view_name, table_name): # def refresh_partitions(self, conn, table_name): # def get_table_location(self, conn, table_name): # def delete_files(self, ssh, url): # def copy_files(self, ssh, origin, dest): # def _hdfs_commands(self, ssh, cmd): # def _get_ssh_client(self, hdfs_host, hdfs_port, username, password): # def hdfs_dist_copy(self, force, hdfs_host, hdfs_port, origin, dest, username=None, password=None): # def create_external_table(self, conn, temp_table_name, ddl, parquet_file_location): # class HiveDataImporter(): , which may include functions, classes, or code. Output only the next line.
sys_mock.exit.assert_called_once_with("Stoping process!")
Given snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function __all__ = ['copy'] @click.group('pkg') def cli(): pass @cli.command('pkg-showversion', help='Show the package version.') @click.pass_context def version(ctx): print(get_version(ctx.obj['package_path'])) @cli.command('pkg-showchanges', help='Show the package changelog.') @click.pass_context def log(ctx): os.system('less {}'.format(os.path.join(ctx.obj['base_path'], 'CHANGES.md'))) @cli.command('pkg-showinfo', help='Show information about the package.') <|code_end|> , continue by predicting the next line. Consider current file imports: import os import pip import sys import subprocess import click import re import os.path import errno import shutil import multiprocessing from distutils.version import LooseVersion from .._compatibility import urlparse and context: # Path: marvin_python_toolbox/_compatibility.py which might include code, classes, or functions. Output only the next line.
@click.pass_context
Continue the code snippet: <|code_start|>#!/usr/bin/env python # coding=utf-8 # Copyright [2017] [B2W Digital] # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. @pytest.fixture def engine_action(): class EngineAction(EngineBasePrediction): def execute(self, **kwargs): return 1 <|code_end|> . Use current file imports: import pytest from marvin_python_toolbox.engine_base import EngineBasePrediction and context (classes, functions, or code) from other files: # Path: marvin_python_toolbox/engine_base/engine_base_prediction.py # class EngineBasePrediction(EngineBaseOnlineAction): # __metaclass__ = ABCMeta # # _model = None # _metrics = None # # def __init__(self, **kwargs): # self._model = self._get_arg(kwargs=kwargs, arg='model') # self._metrics = self._get_arg(kwargs=kwargs, arg='metrics') # # super(EngineBasePrediction, self).__init__(**kwargs) # # @property # def marvin_model(self): # return self._load_obj(object_reference='_model') # # @marvin_model.setter # def marvin_model(self, model): # self._save_obj(object_reference='_model', obj=model) # # @property # def marvin_metrics(self): # return self._load_obj(object_reference='_metrics') # # @marvin_metrics.setter # def marvin_metrics(self, metrics): # self._save_obj(object_reference='_metrics', obj=metrics) . Output only the next line.
return EngineAction(default_root_path="/tmp/.marvin")
Given the code snippet: <|code_start|> if sql_id: confs = [x for x in confs if x['sql_id'] == sql_id] for conf in confs: hdi = HiveDataImporter( max_query_size=max_query_size, destination_host=destination_host, destination_port=destination_port, destination_host_username=destination_host_username, destination_host_password=destination_host_password, destination_hdfs_root_path=destination_hdfs_root_path, engine=engine, **conf) if force: table_exists = False else: table_exists = hdi.table_exists(host=hdi.destination_host, db=hdi.origin_db, table=hdi.target_table_name) if not table_exists: hdi.import_sample( create_temp_table=(not skip_remote_preparation), copy_files=force_copy_files, validate_query=validate, force_create_remote_table=force_remote, ) else: <|code_end|> , generate the next line using the imports in this file: import click import time import os import re import sys import json import hashlib from paramiko import SSHClient, AutoAddPolicy from pyhive import hive from slugify import slugify from .._logging import get_logger from .._compatibility import six and context (functions, classes, or occasionally code) from other files: # Path: marvin_python_toolbox/_logging.py # def get_logger(name, namespace='marvin_python_toolbox', # log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR): # """Build a logger that outputs to a file and to the console,""" # # log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or # os.getenv('LOG_LEVEL', log_level)) # log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or # os.getenv('LOG_DIR', log_dir)) # # logger = logging.getLogger('{}.{}'.format(namespace, name)) # logger.setLevel(log_level) # # formatter = logging.Formatter( # '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # # # Create a console stream handler # console_handler = logging.StreamHandler() # console_handler.setLevel(log_level) # console_handler.setFormatter(formatter) # logger.addHandler(console_handler) # # try: # log_path = os.path.abspath(log_dir) # log_filename = '{name}.{pid}.log'.format( # name=namespace, pid=os.getpid()) # # file_path = str(os.path.join(log_path, log_filename)) # # if not os.path.exists(log_path): # pragma: no cover # os.makedirs(log_path, mode=774) # # # Create a file handler # file_handler = logging.FileHandler(file_path) # file_handler.setLevel(log_level) # file_handler.setFormatter(formatter) # logger.addHandler(file_handler) # except OSError as e: # logger.error('Could not create log file {file}: {error}'.format( # file=file_path, error=e.strerror)) # # return logger # # Path: marvin_python_toolbox/_compatibility.py . Output only the next line.
print ("Table {} already exists, skiping data import. Use --force flag to force data importation".format(hdi.full_table_name))
Based on the snippet: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = get_logger('engine_base_data_handler') __all__ = ['KerasSerializer'] class KerasSerializer(object): def _serializer_load(self, object_file_path): if object_file_path.split(os.sep)[-1] == 'model': logger.debug("Loading model {} using keras serializer.".format(object_file_path)) return load_model(object_file_path) else: return super(KerasSerializer, self)._serializer_load(object_file_path) def _serializer_dump(self, obj, object_file_path): if object_file_path.split(os.sep)[-1] == 'model': logger.debug("Saving model {} using keras serializer.".format(object_file_path)) obj.save(object_file_path) else: <|code_end|> , predict the immediate next line with the help of imports: import os from ..._logging import get_logger from keras.models import load_model and context (classes, functions, sometimes code) from other files: # Path: marvin_python_toolbox/_logging.py # def get_logger(name, namespace='marvin_python_toolbox', # log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR): # """Build a logger that outputs to a file and to the console,""" # # log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or # os.getenv('LOG_LEVEL', log_level)) # log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or # os.getenv('LOG_DIR', log_dir)) # # logger = logging.getLogger('{}.{}'.format(namespace, name)) # logger.setLevel(log_level) # # formatter = logging.Formatter( # '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # # # Create a console stream handler # console_handler = logging.StreamHandler() # console_handler.setLevel(log_level) # console_handler.setFormatter(formatter) # logger.addHandler(console_handler) # # try: # log_path = os.path.abspath(log_dir) # log_filename = '{name}.{pid}.log'.format( # name=namespace, pid=os.getpid()) # # file_path = str(os.path.join(log_path, log_filename)) # # if not os.path.exists(log_path): # pragma: no cover # os.makedirs(log_path, mode=774) # # # Create a file handler # file_handler = logging.FileHandler(file_path) # file_handler.setLevel(log_level) # file_handler.setFormatter(formatter) # logger.addHandler(file_handler) # except OSError as e: # logger.error('Could not create log file {file}: {error}'.format( # file=file_path, error=e.strerror)) # # return logger . Output only the next line.
super(KerasSerializer, self)._serializer_dump(obj, object_file_path)
Given snippet: <|code_start|> __all__ = ['EngineBaseDataHandler'] logger = get_logger('engine_base_data_handler') class EngineBaseDataHandler(EngineBaseBatchAction): __metaclass__ = ABCMeta _initial_dataset = None _dataset = None def __init__(self, **kwargs): self._initial_dataset = self._get_arg(kwargs=kwargs, arg='initial_dataset') self._dataset = self._get_arg(kwargs=kwargs, arg='dataset') super(EngineBaseDataHandler, self).__init__(**kwargs) @property def marvin_initial_dataset(self): return self._load_obj(object_reference='_initial_dataset') @marvin_initial_dataset.setter def marvin_initial_dataset(self, initial_dataset): self._save_obj(object_reference='_initial_dataset', obj=initial_dataset) @property def marvin_dataset(self): return self._load_obj(object_reference='_dataset') <|code_end|> , continue by predicting the next line. Consider current file imports: from abc import ABCMeta from .._compatibility import six from .._logging import get_logger from .engine_base_action import EngineBaseBatchAction and context: # Path: marvin_python_toolbox/_compatibility.py # # Path: marvin_python_toolbox/_logging.py # def get_logger(name, namespace='marvin_python_toolbox', # log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR): # """Build a logger that outputs to a file and to the console,""" # # log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or # os.getenv('LOG_LEVEL', log_level)) # log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or # os.getenv('LOG_DIR', log_dir)) # # logger = logging.getLogger('{}.{}'.format(namespace, name)) # logger.setLevel(log_level) # # formatter = logging.Formatter( # '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # # # Create a console stream handler # console_handler = logging.StreamHandler() # console_handler.setLevel(log_level) # console_handler.setFormatter(formatter) # logger.addHandler(console_handler) # # try: # log_path = os.path.abspath(log_dir) # log_filename = '{name}.{pid}.log'.format( # name=namespace, pid=os.getpid()) # # file_path = str(os.path.join(log_path, log_filename)) # # if not os.path.exists(log_path): # pragma: no cover # os.makedirs(log_path, mode=774) # # # Create a file handler # file_handler = logging.FileHandler(file_path) # file_handler.setLevel(log_level) # file_handler.setFormatter(formatter) # logger.addHandler(file_handler) # except OSError as e: # logger.error('Could not create log file {file}: {error}'.format( # file=file_path, error=e.strerror)) # # return logger # # Path: marvin_python_toolbox/engine_base/engine_base_action.py # class EngineBaseBatchAction(EngineBaseAction): # __metaclass__ = ABCMeta # # @abstractmethod # def execute(self, params, **kwargs): # pass # # def _pipeline_execute(self, params): # if self._previous_step: # self._previous_step._pipeline_execute(params) # # logger.info("Start of the {} execute method!".format(self.action_name)) # self.execute(params) # logger.info("Finish of the {} execute method!".format(self.action_name)) # # def _remote_execute(self, request, context): # logger.info("Received message from client and sending to engine action...") # logger.debug("Received Params: {}".format(request.params)) # # params = json.loads(request.params) if request.params else self._params # # self._pipeline_execute(params=params) # # self._release_local_saved_objects() # # logger.info("Handling returned message from engine action...") # response_message = BatchActionResponse(message="Done") # # logger.info("Return final results to the client!") # return response_message # # def _prepare_remote_server(self, port, workers, rpc_workers): # server = grpc.server(thread_pool=futures.ThreadPoolExecutor(max_workers=workers), maximum_concurrent_rpcs=rpc_workers) # actions_pb2_grpc.add_BatchActionHandlerServicer_to_server(self, server) # server.add_insecure_port('[::]:{}'.format(port)) # return server which might include code, classes, or functions. Output only the next line.
@marvin_dataset.setter
Predict the next line after this snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ['EngineBasePrediction'] logger = get_logger('engine_base_prediction') class EngineBasePrediction(EngineBaseOnlineAction): __metaclass__ = ABCMeta _model = None _metrics = None def __init__(self, **kwargs): self._model = self._get_arg(kwargs=kwargs, arg='model') self._metrics = self._get_arg(kwargs=kwargs, arg='metrics') super(EngineBasePrediction, self).__init__(**kwargs) @property def marvin_model(self): <|code_end|> using the current file's imports: from abc import ABCMeta from .._compatibility import six from .._logging import get_logger from .engine_base_action import EngineBaseOnlineAction and any relevant context from other files: # Path: marvin_python_toolbox/_compatibility.py # # Path: marvin_python_toolbox/_logging.py # def get_logger(name, namespace='marvin_python_toolbox', # log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR): # """Build a logger that outputs to a file and to the console,""" # # log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or # os.getenv('LOG_LEVEL', log_level)) # log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or # os.getenv('LOG_DIR', log_dir)) # # logger = logging.getLogger('{}.{}'.format(namespace, name)) # logger.setLevel(log_level) # # formatter = logging.Formatter( # '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # # # Create a console stream handler # console_handler = logging.StreamHandler() # console_handler.setLevel(log_level) # console_handler.setFormatter(formatter) # logger.addHandler(console_handler) # # try: # log_path = os.path.abspath(log_dir) # log_filename = '{name}.{pid}.log'.format( # name=namespace, pid=os.getpid()) # # file_path = str(os.path.join(log_path, log_filename)) # # if not os.path.exists(log_path): # pragma: no cover # os.makedirs(log_path, mode=774) # # # Create a file handler # file_handler = logging.FileHandler(file_path) # file_handler.setLevel(log_level) # file_handler.setFormatter(formatter) # logger.addHandler(file_handler) # except OSError as e: # logger.error('Could not create log file {file}: {error}'.format( # file=file_path, error=e.strerror)) # # return logger # # Path: marvin_python_toolbox/engine_base/engine_base_action.py # class EngineBaseOnlineAction(EngineBaseAction): # __metaclass__ = ABCMeta # # @abstractmethod # def execute(self, input_message, params, **kwargs): # pass # # def _pipeline_execute(self, input_message, params): # if self._previous_step: # input_message = self._previous_step._pipeline_execute(input_message, params) # # logger.info("Start of the {} execute method!".format(self.action_name)) # return self.execute(input_message, params) # logger.info("Finish of the {} execute method!".format(self.action_name)) # # def _remote_execute(self, request, context): # logger.info("Received message from client and sending to engine action...") # logger.debug("Received Params: {}".format(request.params)) # logger.debug("Received Message: {}".format(request.message)) # # input_message = json.loads(request.message) if request.message else None # params = json.loads(request.params) if request.params else self._params # # _message = self._pipeline_execute(input_message=input_message, params=params) # # logger.info("Handling returned message from engine action...") # # if type(_message) != str: # _message = json.dumps(_message) # # response_message = OnlineActionResponse(message=_message) # # logger.info("Return final results to the client!") # return response_message # # def _prepare_remote_server(self, port, workers, rpc_workers): # server = grpc.server(thread_pool=futures.ThreadPoolExecutor(max_workers=workers), maximum_concurrent_rpcs=rpc_workers) # actions_pb2_grpc.add_OnlineActionHandlerServicer_to_server(self, server) # server.add_insecure_port('[::]:{}'.format(port)) # return server . Output only the next line.
return self._load_obj(object_reference='_model')
Predict the next line after this snippet: <|code_start|># See the License for the specific language governing permissions and # limitations under the License. __all__ = ['EngineBasePrediction'] logger = get_logger('engine_base_prediction') class EngineBasePrediction(EngineBaseOnlineAction): __metaclass__ = ABCMeta _model = None _metrics = None def __init__(self, **kwargs): self._model = self._get_arg(kwargs=kwargs, arg='model') self._metrics = self._get_arg(kwargs=kwargs, arg='metrics') super(EngineBasePrediction, self).__init__(**kwargs) @property def marvin_model(self): return self._load_obj(object_reference='_model') @marvin_model.setter def marvin_model(self, model): self._save_obj(object_reference='_model', obj=model) <|code_end|> using the current file's imports: from abc import ABCMeta from .._compatibility import six from .._logging import get_logger from .engine_base_action import EngineBaseOnlineAction and any relevant context from other files: # Path: marvin_python_toolbox/_compatibility.py # # Path: marvin_python_toolbox/_logging.py # def get_logger(name, namespace='marvin_python_toolbox', # log_level=DEFAULT_LOG_LEVEL, log_dir=DEFAULT_LOG_DIR): # """Build a logger that outputs to a file and to the console,""" # # log_level = (os.getenv('{}_LOG_LEVEL'.format(namespace.upper())) or # os.getenv('LOG_LEVEL', log_level)) # log_dir = (os.getenv('{}_LOG_DIR'.format(namespace.upper())) or # os.getenv('LOG_DIR', log_dir)) # # logger = logging.getLogger('{}.{}'.format(namespace, name)) # logger.setLevel(log_level) # # formatter = logging.Formatter( # '%(asctime)s - %(name)s - %(levelname)s - %(message)s') # # # Create a console stream handler # console_handler = logging.StreamHandler() # console_handler.setLevel(log_level) # console_handler.setFormatter(formatter) # logger.addHandler(console_handler) # # try: # log_path = os.path.abspath(log_dir) # log_filename = '{name}.{pid}.log'.format( # name=namespace, pid=os.getpid()) # # file_path = str(os.path.join(log_path, log_filename)) # # if not os.path.exists(log_path): # pragma: no cover # os.makedirs(log_path, mode=774) # # # Create a file handler # file_handler = logging.FileHandler(file_path) # file_handler.setLevel(log_level) # file_handler.setFormatter(formatter) # logger.addHandler(file_handler) # except OSError as e: # logger.error('Could not create log file {file}: {error}'.format( # file=file_path, error=e.strerror)) # # return logger # # Path: marvin_python_toolbox/engine_base/engine_base_action.py # class EngineBaseOnlineAction(EngineBaseAction): # __metaclass__ = ABCMeta # # @abstractmethod # def execute(self, input_message, params, **kwargs): # pass # # def _pipeline_execute(self, input_message, params): # if self._previous_step: # input_message = self._previous_step._pipeline_execute(input_message, params) # # logger.info("Start of the {} execute method!".format(self.action_name)) # return self.execute(input_message, params) # logger.info("Finish of the {} execute method!".format(self.action_name)) # # def _remote_execute(self, request, context): # logger.info("Received message from client and sending to engine action...") # logger.debug("Received Params: {}".format(request.params)) # logger.debug("Received Message: {}".format(request.message)) # # input_message = json.loads(request.message) if request.message else None # params = json.loads(request.params) if request.params else self._params # # _message = self._pipeline_execute(input_message=input_message, params=params) # # logger.info("Handling returned message from engine action...") # # if type(_message) != str: # _message = json.dumps(_message) # # response_message = OnlineActionResponse(message=_message) # # logger.info("Return final results to the client!") # return response_message # # def _prepare_remote_server(self, port, workers, rpc_workers): # server = grpc.server(thread_pool=futures.ThreadPoolExecutor(max_workers=workers), maximum_concurrent_rpcs=rpc_workers) # actions_pb2_grpc.add_OnlineActionHandlerServicer_to_server(self, server) # server.add_insecure_port('[::]:{}'.format(port)) # return server . Output only the next line.
@property
Next line prediction: <|code_start|> os.environ['TESTING'] = 'true' if args: args = args.split(' ') else: args = [os.path.relpath( os.path.join(ctx.obj['base_path'], 'tests'))] if no_capture: args += ['--capture=no'] if pdb: args += ['--pdb'] if partial: args += ['--testmon'] cov_args = [] if cov: cov_args += ['--cov', os.path.relpath(ctx.obj['package_path'], start=ctx.obj['base_path']), '--cov-report', 'html', '--cov-report', 'xml', '--cov-report', 'term-missing', ] command = ['ptw', '-p', '--'] + cov_args + args print(' '.join(command)) env = os.environ.copy() exitcode = subprocess.call(command, cwd=ctx.obj['base_path'], env=env) <|code_end|> . Use current file imports: (import sys import os import os.path import subprocess import shutil import tempfile import click from .pkg import copy) and context including class names, function names, or small code snippets from other files: # Path: marvin_python_toolbox/management/pkg.py # def copy(src, dest, ignore=('.git', '.pyc', '__pycache__')): # try: # shutil.copytree(src, dest, ignore=shutil.ignore_patterns(*ignore)) # except OSError as e: # if e.errno == errno.ENOTDIR: # shutil.copy(src, dest) # else: # print('Directory not copied. Error: %s' % e) . Output only the next line.
sys.exit(exitcode)
Based on the snippet: <|code_start|> @mock.patch('marvin_python_toolbox.management.pkg.shutil.ignore_patterns') @mock.patch('marvin_python_toolbox.management.pkg.shutil.copytree') def test_copy(copytree_mocked, ignore_mocked): src = '/xpto' dest = '/xpto_dest' ignore = ('.git') ignore_mocked.return_value = 1 copy(src, dest, ignore) copytree_mocked.assert_called_once_with(src, dest, ignore=1) ignore_mocked.assert_called_once_with(*ignore) @mock.patch('marvin_python_toolbox.management.pkg.subprocess.PIPE') @mock.patch('marvin_python_toolbox.management.pkg.os.path.curdir') @mock.patch('marvin_python_toolbox.management.pkg.subprocess.Popen') def test_get_git_branch(popen_mocked, curdir_mocked, pipe_mocked): mockx = mock.MagicMock() mockx.stdout.read.return_value = b'branch ' popen_mocked.return_value = mockx branch = get_git_branch() popen_mocked.assert_called_once_with(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], stdout=pipe_mocked, cwd=curdir_mocked) assert branch == 'branch' branch = get_git_branch(path='/tmp') <|code_end|> , predict the immediate next line with the help of imports: import mock import unittest.mock as mock from marvin_python_toolbox.management.pkg import _clone from marvin_python_toolbox.management.pkg import copy from marvin_python_toolbox.management.pkg import get_git_branch from marvin_python_toolbox.management.pkg import is_git_clean from marvin_python_toolbox.management.pkg import get_git_tags from marvin_python_toolbox.management.pkg import get_git_repository_url from marvin_python_toolbox.management.pkg import get_git_tag from marvin_python_toolbox.management.pkg import get_git_commit from marvin_python_toolbox.management.pkg import get_tag_from_repo_url from marvin_python_toolbox.management.pkg import get_repos_from_requirements and context (classes, functions, sometimes code) from other files: # Path: marvin_python_toolbox/management/pkg.py # def _clone(repo): # return repo, git_clone(repo, checkout=False, depth=1) # # Path: marvin_python_toolbox/management/pkg.py # def copy(src, dest, ignore=('.git', '.pyc', '__pycache__')): # try: # shutil.copytree(src, dest, ignore=shutil.ignore_patterns(*ignore)) # except OSError as e: # if e.errno == errno.ENOTDIR: # shutil.copy(src, dest) # else: # print('Directory not copied. Error: %s' % e) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_branch(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-parse --abbrev-ref HEAD'.split() # branch = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return branch.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def is_git_clean(path=None): # if path is None: # path = os.path.curdir # command = 'git diff --quiet HEAD'.split() # exit_code = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return exit_code # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tags(path=None): # if path is None: # path = os.path.curdir # command = 'git tag'.split() # tags = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return sorted(tags.strip().split('\n'), reverse=True) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_repository_url(path=None): # if path is None: # path = os.path.curdir # command = 'git config --get remote.origin.url'.split() # url = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return url.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tag(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-list --tags --max-count=1'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # command = 'git describe --tags {}'.format(commit).split() # tag = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # return tag.strip() # # Path: marvin_python_toolbox/management/pkg.py # def get_git_commit(path=None, tag=None): # if path is None: # path = os.path.curdir # if tag: # command = 'git rev-list -n 1 {tag}'.format(tag=tag).split() # else: # command = 'git rev-parse HEAD'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return commit.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_tag_from_repo_url(repos): # tags = {} # for repo in repos: # if '@' in repo: # repo_parsed = urlparse(repo) # repo_path = repo_parsed.path # tags[repo] = repo_path.split('@')[1] # else: # tags[repo] = None # return tags # # Path: marvin_python_toolbox/management/pkg.py # def get_repos_from_requirements(path): # if path is None: # path = os.path.curdir # with open(os.path.join(path, 'requirements.txt'), 'r') as fp: # repos = [line.strip() for line in fp if 'git@' in line and not line.strip().startswith('#')] # return repos . Output only the next line.
popen_mocked.assert_called_with(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], stdout=pipe_mocked, cwd='/tmp')
Given the following code snippet before the placeholder: <|code_start|> join_mocked.assert_called_with('/path', 'requirements.txt') open_mocked.assert_called_with('/tmp', 'r') def test_get_tag_from_repo_url(): repos = ['http://www.xxx.org:80/tag@/repo.html'] tags = get_tag_from_repo_url(repos) assert tags == {'http://www.xxx.org:80/tag@/repo.html': '/repo.html'} repos = ['http://www.xxx.org:80/tag/repo.html'] tags = get_tag_from_repo_url(repos) assert tags == {'http://www.xxx.org:80/tag/repo.html': None} @mock.patch('marvin_python_toolbox.management.pkg.git_clone') def test_clone(git_mocked): git_mocked.return_value = 1 repo = 'http://xxx.git' result = _clone(repo) assert result == (repo, 1) git_mocked.assert_called_once_with(repo, checkout=False, depth=1) @mock.patch('marvin_python_toolbox.management.pkg.shutil.ignore_patterns') @mock.patch('marvin_python_toolbox.management.pkg.shutil.copytree') <|code_end|> , predict the next line using imports from the current file: import mock import unittest.mock as mock from marvin_python_toolbox.management.pkg import _clone from marvin_python_toolbox.management.pkg import copy from marvin_python_toolbox.management.pkg import get_git_branch from marvin_python_toolbox.management.pkg import is_git_clean from marvin_python_toolbox.management.pkg import get_git_tags from marvin_python_toolbox.management.pkg import get_git_repository_url from marvin_python_toolbox.management.pkg import get_git_tag from marvin_python_toolbox.management.pkg import get_git_commit from marvin_python_toolbox.management.pkg import get_tag_from_repo_url from marvin_python_toolbox.management.pkg import get_repos_from_requirements and context including class names, function names, and sometimes code from other files: # Path: marvin_python_toolbox/management/pkg.py # def _clone(repo): # return repo, git_clone(repo, checkout=False, depth=1) # # Path: marvin_python_toolbox/management/pkg.py # def copy(src, dest, ignore=('.git', '.pyc', '__pycache__')): # try: # shutil.copytree(src, dest, ignore=shutil.ignore_patterns(*ignore)) # except OSError as e: # if e.errno == errno.ENOTDIR: # shutil.copy(src, dest) # else: # print('Directory not copied. Error: %s' % e) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_branch(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-parse --abbrev-ref HEAD'.split() # branch = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return branch.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def is_git_clean(path=None): # if path is None: # path = os.path.curdir # command = 'git diff --quiet HEAD'.split() # exit_code = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return exit_code # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tags(path=None): # if path is None: # path = os.path.curdir # command = 'git tag'.split() # tags = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return sorted(tags.strip().split('\n'), reverse=True) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_repository_url(path=None): # if path is None: # path = os.path.curdir # command = 'git config --get remote.origin.url'.split() # url = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return url.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tag(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-list --tags --max-count=1'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # command = 'git describe --tags {}'.format(commit).split() # tag = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # return tag.strip() # # Path: marvin_python_toolbox/management/pkg.py # def get_git_commit(path=None, tag=None): # if path is None: # path = os.path.curdir # if tag: # command = 'git rev-list -n 1 {tag}'.format(tag=tag).split() # else: # command = 'git rev-parse HEAD'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return commit.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_tag_from_repo_url(repos): # tags = {} # for repo in repos: # if '@' in repo: # repo_parsed = urlparse(repo) # repo_path = repo_parsed.path # tags[repo] = repo_path.split('@')[1] # else: # tags[repo] = None # return tags # # Path: marvin_python_toolbox/management/pkg.py # def get_repos_from_requirements(path): # if path is None: # path = os.path.curdir # with open(os.path.join(path, 'requirements.txt'), 'r') as fp: # repos = [line.strip() for line in fp if 'git@' in line and not line.strip().startswith('#')] # return repos . Output only the next line.
def test_copy(copytree_mocked, ignore_mocked):
Here is a snippet: <|code_start|> get_repos_from_requirements(path='/path') join_mocked.assert_called_with('/path', 'requirements.txt') open_mocked.assert_called_with('/tmp', 'r') def test_get_tag_from_repo_url(): repos = ['http://www.xxx.org:80/tag@/repo.html'] tags = get_tag_from_repo_url(repos) assert tags == {'http://www.xxx.org:80/tag@/repo.html': '/repo.html'} repos = ['http://www.xxx.org:80/tag/repo.html'] tags = get_tag_from_repo_url(repos) assert tags == {'http://www.xxx.org:80/tag/repo.html': None} @mock.patch('marvin_python_toolbox.management.pkg.git_clone') def test_clone(git_mocked): git_mocked.return_value = 1 repo = 'http://xxx.git' result = _clone(repo) assert result == (repo, 1) git_mocked.assert_called_once_with(repo, checkout=False, depth=1) <|code_end|> . Write the next line using the current file imports: import mock import unittest.mock as mock from marvin_python_toolbox.management.pkg import _clone from marvin_python_toolbox.management.pkg import copy from marvin_python_toolbox.management.pkg import get_git_branch from marvin_python_toolbox.management.pkg import is_git_clean from marvin_python_toolbox.management.pkg import get_git_tags from marvin_python_toolbox.management.pkg import get_git_repository_url from marvin_python_toolbox.management.pkg import get_git_tag from marvin_python_toolbox.management.pkg import get_git_commit from marvin_python_toolbox.management.pkg import get_tag_from_repo_url from marvin_python_toolbox.management.pkg import get_repos_from_requirements and context from other files: # Path: marvin_python_toolbox/management/pkg.py # def _clone(repo): # return repo, git_clone(repo, checkout=False, depth=1) # # Path: marvin_python_toolbox/management/pkg.py # def copy(src, dest, ignore=('.git', '.pyc', '__pycache__')): # try: # shutil.copytree(src, dest, ignore=shutil.ignore_patterns(*ignore)) # except OSError as e: # if e.errno == errno.ENOTDIR: # shutil.copy(src, dest) # else: # print('Directory not copied. Error: %s' % e) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_branch(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-parse --abbrev-ref HEAD'.split() # branch = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return branch.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def is_git_clean(path=None): # if path is None: # path = os.path.curdir # command = 'git diff --quiet HEAD'.split() # exit_code = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return exit_code # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tags(path=None): # if path is None: # path = os.path.curdir # command = 'git tag'.split() # tags = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return sorted(tags.strip().split('\n'), reverse=True) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_repository_url(path=None): # if path is None: # path = os.path.curdir # command = 'git config --get remote.origin.url'.split() # url = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return url.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tag(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-list --tags --max-count=1'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # command = 'git describe --tags {}'.format(commit).split() # tag = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # return tag.strip() # # Path: marvin_python_toolbox/management/pkg.py # def get_git_commit(path=None, tag=None): # if path is None: # path = os.path.curdir # if tag: # command = 'git rev-list -n 1 {tag}'.format(tag=tag).split() # else: # command = 'git rev-parse HEAD'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return commit.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_tag_from_repo_url(repos): # tags = {} # for repo in repos: # if '@' in repo: # repo_parsed = urlparse(repo) # repo_path = repo_parsed.path # tags[repo] = repo_path.split('@')[1] # else: # tags[repo] = None # return tags # # Path: marvin_python_toolbox/management/pkg.py # def get_repos_from_requirements(path): # if path is None: # path = os.path.curdir # with open(os.path.join(path, 'requirements.txt'), 'r') as fp: # repos = [line.strip() for line in fp if 'git@' in line and not line.strip().startswith('#')] # return repos , which may include functions, classes, or code. Output only the next line.
@mock.patch('marvin_python_toolbox.management.pkg.shutil.ignore_patterns')
Next line prediction: <|code_start|> # from click.testing import CliRunner try: except ImportError: @mock.patch('marvin_python_toolbox.management.pkg.open') @mock.patch('marvin_python_toolbox.management.pkg.os.path.join') @mock.patch('marvin_python_toolbox.management.pkg.os.path.curdir') def test_get_repos_from_requirements(curdir_mocked, join_mocked, open_mocked): join_mocked.return_value = '/tmp' get_repos_from_requirements(path=None) join_mocked.assert_called_with(curdir_mocked, 'requirements.txt') open_mocked.assert_called_with('/tmp', 'r') get_repos_from_requirements(path='/path') join_mocked.assert_called_with('/path', 'requirements.txt') open_mocked.assert_called_with('/tmp', 'r') def test_get_tag_from_repo_url(): repos = ['http://www.xxx.org:80/tag@/repo.html'] tags = get_tag_from_repo_url(repos) <|code_end|> . Use current file imports: ( import mock import unittest.mock as mock from marvin_python_toolbox.management.pkg import _clone from marvin_python_toolbox.management.pkg import copy from marvin_python_toolbox.management.pkg import get_git_branch from marvin_python_toolbox.management.pkg import is_git_clean from marvin_python_toolbox.management.pkg import get_git_tags from marvin_python_toolbox.management.pkg import get_git_repository_url from marvin_python_toolbox.management.pkg import get_git_tag from marvin_python_toolbox.management.pkg import get_git_commit from marvin_python_toolbox.management.pkg import get_tag_from_repo_url from marvin_python_toolbox.management.pkg import get_repos_from_requirements) and context including class names, function names, or small code snippets from other files: # Path: marvin_python_toolbox/management/pkg.py # def _clone(repo): # return repo, git_clone(repo, checkout=False, depth=1) # # Path: marvin_python_toolbox/management/pkg.py # def copy(src, dest, ignore=('.git', '.pyc', '__pycache__')): # try: # shutil.copytree(src, dest, ignore=shutil.ignore_patterns(*ignore)) # except OSError as e: # if e.errno == errno.ENOTDIR: # shutil.copy(src, dest) # else: # print('Directory not copied. Error: %s' % e) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_branch(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-parse --abbrev-ref HEAD'.split() # branch = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return branch.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def is_git_clean(path=None): # if path is None: # path = os.path.curdir # command = 'git diff --quiet HEAD'.split() # exit_code = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return exit_code # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tags(path=None): # if path is None: # path = os.path.curdir # command = 'git tag'.split() # tags = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return sorted(tags.strip().split('\n'), reverse=True) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_repository_url(path=None): # if path is None: # path = os.path.curdir # command = 'git config --get remote.origin.url'.split() # url = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return url.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tag(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-list --tags --max-count=1'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # command = 'git describe --tags {}'.format(commit).split() # tag = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # return tag.strip() # # Path: marvin_python_toolbox/management/pkg.py # def get_git_commit(path=None, tag=None): # if path is None: # path = os.path.curdir # if tag: # command = 'git rev-list -n 1 {tag}'.format(tag=tag).split() # else: # command = 'git rev-parse HEAD'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return commit.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_tag_from_repo_url(repos): # tags = {} # for repo in repos: # if '@' in repo: # repo_parsed = urlparse(repo) # repo_path = repo_parsed.path # tags[repo] = repo_path.split('@')[1] # else: # tags[repo] = None # return tags # # Path: marvin_python_toolbox/management/pkg.py # def get_repos_from_requirements(path): # if path is None: # path = os.path.curdir # with open(os.path.join(path, 'requirements.txt'), 'r') as fp: # repos = [line.strip() for line in fp if 'git@' in line and not line.strip().startswith('#')] # return repos . Output only the next line.
assert tags == {'http://www.xxx.org:80/tag@/repo.html': '/repo.html'}
Given the following code snippet before the placeholder: <|code_start|> @mock.patch('marvin_python_toolbox.management.pkg.subprocess.PIPE') @mock.patch('marvin_python_toolbox.management.pkg.os.path.curdir') @mock.patch('marvin_python_toolbox.management.pkg.subprocess.Popen') def test_get_git_tags(popen_mocked, curdir_mocked, pipe_mocked): mockx = mock.MagicMock() mockx.stdout.read.return_value = 'git\ntags ' popen_mocked.return_value = mockx tags = get_git_tags() popen_mocked.assert_called_once_with(['git', 'tag'], stdout=pipe_mocked, cwd=curdir_mocked) assert tags == ['tags', 'git'] tags = get_git_tags(path='/tmp') popen_mocked.assert_called_with(['git', 'tag'], stdout=pipe_mocked, cwd='/tmp') @mock.patch('marvin_python_toolbox.management.pkg.subprocess.PIPE') @mock.patch('marvin_python_toolbox.management.pkg.subprocess.Popen') @mock.patch('marvin_python_toolbox.management.pkg.os.path.curdir') def test_is_git_clean(curdir_mocked, popen_mocked, pipe_mocked): mockx = mock.MagicMock() mockx.stdout.read.return_value = 'done' popen_mocked.return_value = mockx clean = is_git_clean() <|code_end|> , predict the next line using imports from the current file: import mock import unittest.mock as mock from marvin_python_toolbox.management.pkg import _clone from marvin_python_toolbox.management.pkg import copy from marvin_python_toolbox.management.pkg import get_git_branch from marvin_python_toolbox.management.pkg import is_git_clean from marvin_python_toolbox.management.pkg import get_git_tags from marvin_python_toolbox.management.pkg import get_git_repository_url from marvin_python_toolbox.management.pkg import get_git_tag from marvin_python_toolbox.management.pkg import get_git_commit from marvin_python_toolbox.management.pkg import get_tag_from_repo_url from marvin_python_toolbox.management.pkg import get_repos_from_requirements and context including class names, function names, and sometimes code from other files: # Path: marvin_python_toolbox/management/pkg.py # def _clone(repo): # return repo, git_clone(repo, checkout=False, depth=1) # # Path: marvin_python_toolbox/management/pkg.py # def copy(src, dest, ignore=('.git', '.pyc', '__pycache__')): # try: # shutil.copytree(src, dest, ignore=shutil.ignore_patterns(*ignore)) # except OSError as e: # if e.errno == errno.ENOTDIR: # shutil.copy(src, dest) # else: # print('Directory not copied. Error: %s' % e) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_branch(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-parse --abbrev-ref HEAD'.split() # branch = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return branch.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def is_git_clean(path=None): # if path is None: # path = os.path.curdir # command = 'git diff --quiet HEAD'.split() # exit_code = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return exit_code # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tags(path=None): # if path is None: # path = os.path.curdir # command = 'git tag'.split() # tags = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return sorted(tags.strip().split('\n'), reverse=True) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_repository_url(path=None): # if path is None: # path = os.path.curdir # command = 'git config --get remote.origin.url'.split() # url = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return url.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tag(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-list --tags --max-count=1'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # command = 'git describe --tags {}'.format(commit).split() # tag = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # return tag.strip() # # Path: marvin_python_toolbox/management/pkg.py # def get_git_commit(path=None, tag=None): # if path is None: # path = os.path.curdir # if tag: # command = 'git rev-list -n 1 {tag}'.format(tag=tag).split() # else: # command = 'git rev-parse HEAD'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return commit.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_tag_from_repo_url(repos): # tags = {} # for repo in repos: # if '@' in repo: # repo_parsed = urlparse(repo) # repo_path = repo_parsed.path # tags[repo] = repo_path.split('@')[1] # else: # tags[repo] = None # return tags # # Path: marvin_python_toolbox/management/pkg.py # def get_repos_from_requirements(path): # if path is None: # path = os.path.curdir # with open(os.path.join(path, 'requirements.txt'), 'r') as fp: # repos = [line.strip() for line in fp if 'git@' in line and not line.strip().startswith('#')] # return repos . Output only the next line.
popen_mocked.assert_called_once_with(['git', 'diff', '--quiet', 'HEAD'], stdout=pipe_mocked, cwd=curdir_mocked)
Given the code snippet: <|code_start|>def test_get_tag_from_repo_url(): repos = ['http://www.xxx.org:80/tag@/repo.html'] tags = get_tag_from_repo_url(repos) assert tags == {'http://www.xxx.org:80/tag@/repo.html': '/repo.html'} repos = ['http://www.xxx.org:80/tag/repo.html'] tags = get_tag_from_repo_url(repos) assert tags == {'http://www.xxx.org:80/tag/repo.html': None} @mock.patch('marvin_python_toolbox.management.pkg.git_clone') def test_clone(git_mocked): git_mocked.return_value = 1 repo = 'http://xxx.git' result = _clone(repo) assert result == (repo, 1) git_mocked.assert_called_once_with(repo, checkout=False, depth=1) @mock.patch('marvin_python_toolbox.management.pkg.shutil.ignore_patterns') @mock.patch('marvin_python_toolbox.management.pkg.shutil.copytree') def test_copy(copytree_mocked, ignore_mocked): src = '/xpto' dest = '/xpto_dest' ignore = ('.git') <|code_end|> , generate the next line using the imports in this file: import mock import unittest.mock as mock from marvin_python_toolbox.management.pkg import _clone from marvin_python_toolbox.management.pkg import copy from marvin_python_toolbox.management.pkg import get_git_branch from marvin_python_toolbox.management.pkg import is_git_clean from marvin_python_toolbox.management.pkg import get_git_tags from marvin_python_toolbox.management.pkg import get_git_repository_url from marvin_python_toolbox.management.pkg import get_git_tag from marvin_python_toolbox.management.pkg import get_git_commit from marvin_python_toolbox.management.pkg import get_tag_from_repo_url from marvin_python_toolbox.management.pkg import get_repos_from_requirements and context (functions, classes, or occasionally code) from other files: # Path: marvin_python_toolbox/management/pkg.py # def _clone(repo): # return repo, git_clone(repo, checkout=False, depth=1) # # Path: marvin_python_toolbox/management/pkg.py # def copy(src, dest, ignore=('.git', '.pyc', '__pycache__')): # try: # shutil.copytree(src, dest, ignore=shutil.ignore_patterns(*ignore)) # except OSError as e: # if e.errno == errno.ENOTDIR: # shutil.copy(src, dest) # else: # print('Directory not copied. Error: %s' % e) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_branch(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-parse --abbrev-ref HEAD'.split() # branch = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return branch.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def is_git_clean(path=None): # if path is None: # path = os.path.curdir # command = 'git diff --quiet HEAD'.split() # exit_code = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return exit_code # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tags(path=None): # if path is None: # path = os.path.curdir # command = 'git tag'.split() # tags = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return sorted(tags.strip().split('\n'), reverse=True) # # Path: marvin_python_toolbox/management/pkg.py # def get_git_repository_url(path=None): # if path is None: # path = os.path.curdir # command = 'git config --get remote.origin.url'.split() # url = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return url.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_git_tag(path=None): # if path is None: # path = os.path.curdir # command = 'git rev-list --tags --max-count=1'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # command = 'git describe --tags {}'.format(commit).split() # tag = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read().decode('utf-8') # return tag.strip() # # Path: marvin_python_toolbox/management/pkg.py # def get_git_commit(path=None, tag=None): # if path is None: # path = os.path.curdir # if tag: # command = 'git rev-list -n 1 {tag}'.format(tag=tag).split() # else: # command = 'git rev-parse HEAD'.split() # commit = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=path).stdout.read() # return commit.strip().decode('utf-8') # # Path: marvin_python_toolbox/management/pkg.py # def get_tag_from_repo_url(repos): # tags = {} # for repo in repos: # if '@' in repo: # repo_parsed = urlparse(repo) # repo_path = repo_parsed.path # tags[repo] = repo_path.split('@')[1] # else: # tags[repo] = None # return tags # # Path: marvin_python_toolbox/management/pkg.py # def get_repos_from_requirements(path): # if path is None: # path = os.path.curdir # with open(os.path.join(path, 'requirements.txt'), 'r') as fp: # repos = [line.strip() for line in fp if 'git@' in line and not line.strip().startswith('#')] # return repos . Output only the next line.
ignore_mocked.return_value = 1
Given snippet: <|code_start|>from __future__ import unicode_literals __all__ = ("Handler",) logger = logging.getLogger("django.request") <|code_end|> , continue by predicting the next line. Consider current file imports: import collections import logging import sys from django import http from django.conf import settings from django.core import exceptions, signals, urlresolvers from django.core.handlers import base from django.utils import encoding, six from django.views import debug from daydreamer.core import lang and context: # Path: daydreamer/core/lang.py # def updated(destination, source, copy=False): # def any(values, falsy=False): # def all(values, truthy=True): which might include code, classes, or functions. Output only the next line.
class Handler(base.BaseHandler):
Given snippet: <|code_start|>from __future__ import unicode_literals __all__ = ( "ArchiveIndexView", "YearArchiveView", "MonthArchiveView", <|code_end|> , continue by predicting the next line. Consider current file imports: from django.views import generic from .base import View and context: # Path: daydreamer/views/generic/base.py # class View(core.HttpMethodDeny, core.HttpMethodAllow): # """ # A replacement for django.views.generic.View. Implements a dispatch system # with improved tools for denying or allowing a request to be processed. # # """ # pass which might include code, classes, or functions. Output only the next line.
"WeekArchiveView", "DayArchiveView", "TodayArchiveView", "DateDetailView",)
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import #from crackling.celery import celery @crackling.celery.celery.task def newjob(engine, hashtype, attacktype, hashes, params): logging.info("Job starting") logging.debug(str(hashtype)) logging.debug(str(attacktype)) logging.debug(str(hashes)) logging.debug(str(params)) if engine == 'hashcat': j = HashCatJob() j.setHashType(hashtype) j.setAttackType(attacktype) j.setParams(params) <|code_end|> using the current file's imports: import crackling.celery import time import logging from crackling.hashcatjob import HashCatJob from crackling.ocllitejob import OclLiteJob and any relevant context from other files: # Path: crackling/hashcatjob.py # class HashCatJob(Job): # hashTypes = {"MD5":0} # path = config.HASHCAT_PATH # validParams = ["minlen", "maxlen", "charset", "threads"] # MSG_STATUS = "\n" # # def validateParams(self, params): # for k,v in params.iteritems(): # if k == "charset": # for c in v: # if c not in string.printable: # raise ValueError("Param 'charset' has non printable character 0x%02x, which, uh, I dont wanna stick into some argv" % ord(c)) # # def getCommandLine(self): # c = [self.path, "-a%d" % self.attackType, "-m%d" % self.hashType] # c.append("--disable-potfile") # if self.attackType == self.attackTypes["bruteforce"]: # c.append("--pw-min=%d" % self.params["minlen"]) # c.append("--pw-max=%d" % self.params["maxlen"]) # try: # c.append('-1 %s' % self.params['one']) # if 'two' in self.params: # c.append('-2 %s' % self.params['two']) # if 'three' in self.params: # c.append('-3 %s' % self.params['three']) # if 'four' in self.params: # c.append('-4 %s' % self.params['four']) # except: # logging.critical("no custom charsets for us") # # Write hashes down to a tempfile # f = tempfile.NamedTemporaryFile(delete=False) # for h in self.hashes: # f.write(h + "\n") # f.flush() # c.append(f.name) # # Keep it open with a handle, it'll get deleted when we get destroyed. # self.ftmp = f # c.append(self.params['mask']) # logging.debug("Command string %s" % str(c)) # return c # # def processLines(self, lines): # for l in lines: # for h in self.hashes: # if l.startswith(h): # self.stat['cracked'][h] = l.split(':',1)[1] # logging.info("Cracked %s:%s" % (h, str(self.stat['cracked'][h]))) # # Path: crackling/ocllitejob.py # class OclLiteJob(Job): # hashTypes = {"MD5":0} # path = config.OCLLITE_PATH # validParams = ["minlen", "maxlen", "charset", "threads"] # MSG_STATUS = "\n" # # def validateParams(self, params): # for k,v in params.iteritems(): # if k == "charset": # for c in v: # if c not in string.printable: # raise ValueError("Param 'charset' has non printable character 0x%02x, which, uh, I dont wanna stick into some argv" % ord(c)) # # def getCommandLine(self): # c = [self.path, "-m%d" % self.hashType] # c.append("--pw-min=%d" % self.params["minlen"]) # c.append("--pw-max=%d" % self.params["maxlen"]) # c.append("--pw-skip=%d" % self.params['skip']) # c.append("--pw-limit=%d" % self.params['limit']) # try: # c.append('-1 "%s"' % self.params['one']) # except: # logging.debug("no custom charsets for us") # c.append(self.hashes[0]) #ocllite there is only one hash # c.append(self.params['mask']) # logging.debug("Command string %s" % str(c)) # return c # # def processLines(self, lines): # for l in lines: # for h in self.hashes: # if l.startswith(h): # self.stat['cracked'][h] = l.split(':',1)[1] # logging.info("Cracked %s:%s" % (h, str(self.stat['cracked'][h]))) . Output only the next line.
j.addHashes(hashes)
Here is a snippet: <|code_start|>from __future__ import absolute_import #from crackling.celery import celery @crackling.celery.celery.task def newjob(engine, hashtype, attacktype, hashes, params): logging.info("Job starting") <|code_end|> . Write the next line using the current file imports: import crackling.celery import time import logging from crackling.hashcatjob import HashCatJob from crackling.ocllitejob import OclLiteJob and context from other files: # Path: crackling/hashcatjob.py # class HashCatJob(Job): # hashTypes = {"MD5":0} # path = config.HASHCAT_PATH # validParams = ["minlen", "maxlen", "charset", "threads"] # MSG_STATUS = "\n" # # def validateParams(self, params): # for k,v in params.iteritems(): # if k == "charset": # for c in v: # if c not in string.printable: # raise ValueError("Param 'charset' has non printable character 0x%02x, which, uh, I dont wanna stick into some argv" % ord(c)) # # def getCommandLine(self): # c = [self.path, "-a%d" % self.attackType, "-m%d" % self.hashType] # c.append("--disable-potfile") # if self.attackType == self.attackTypes["bruteforce"]: # c.append("--pw-min=%d" % self.params["minlen"]) # c.append("--pw-max=%d" % self.params["maxlen"]) # try: # c.append('-1 %s' % self.params['one']) # if 'two' in self.params: # c.append('-2 %s' % self.params['two']) # if 'three' in self.params: # c.append('-3 %s' % self.params['three']) # if 'four' in self.params: # c.append('-4 %s' % self.params['four']) # except: # logging.critical("no custom charsets for us") # # Write hashes down to a tempfile # f = tempfile.NamedTemporaryFile(delete=False) # for h in self.hashes: # f.write(h + "\n") # f.flush() # c.append(f.name) # # Keep it open with a handle, it'll get deleted when we get destroyed. # self.ftmp = f # c.append(self.params['mask']) # logging.debug("Command string %s" % str(c)) # return c # # def processLines(self, lines): # for l in lines: # for h in self.hashes: # if l.startswith(h): # self.stat['cracked'][h] = l.split(':',1)[1] # logging.info("Cracked %s:%s" % (h, str(self.stat['cracked'][h]))) # # Path: crackling/ocllitejob.py # class OclLiteJob(Job): # hashTypes = {"MD5":0} # path = config.OCLLITE_PATH # validParams = ["minlen", "maxlen", "charset", "threads"] # MSG_STATUS = "\n" # # def validateParams(self, params): # for k,v in params.iteritems(): # if k == "charset": # for c in v: # if c not in string.printable: # raise ValueError("Param 'charset' has non printable character 0x%02x, which, uh, I dont wanna stick into some argv" % ord(c)) # # def getCommandLine(self): # c = [self.path, "-m%d" % self.hashType] # c.append("--pw-min=%d" % self.params["minlen"]) # c.append("--pw-max=%d" % self.params["maxlen"]) # c.append("--pw-skip=%d" % self.params['skip']) # c.append("--pw-limit=%d" % self.params['limit']) # try: # c.append('-1 "%s"' % self.params['one']) # except: # logging.debug("no custom charsets for us") # c.append(self.hashes[0]) #ocllite there is only one hash # c.append(self.params['mask']) # logging.debug("Command string %s" % str(c)) # return c # # def processLines(self, lines): # for l in lines: # for h in self.hashes: # if l.startswith(h): # self.stat['cracked'][h] = l.split(':',1)[1] # logging.info("Cracked %s:%s" % (h, str(self.stat['cracked'][h]))) , which may include functions, classes, or code. Output only the next line.
logging.debug(str(hashtype))
Given the following code snippet before the placeholder: <|code_start|> class GetOrNoneManager(models.Manager): def get_or_none(self, **kwargs): try: return self.get(**kwargs) <|code_end|> , predict the next line using imports from the current file: from django.db import models from itertools import chain from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ from django.core.validators import URLValidator, validate_email from rolodex.slug import unique_slugify from taggit.managers import TaggableManager import networkx as nx and context including class names, function names, and sometimes code from other files: # Path: rolodex/slug.py # def unique_slugify(instance, value, slug_field_name='slug', queryset=None, # slug_separator='-'): # """ # Calculates and stores a unique slug of ``value`` for an instance. # # ``slug_field_name`` should be a string matching the name of the field to # store the slug in (and the field to check against for uniqueness). # # ``queryset`` usually doesn't need to be explicitly provided - it'll default # to using the ``.all()`` queryset from the model's default manager. # """ # slug_field = instance._meta.get_field(slug_field_name) # # slug = getattr(instance, slug_field.attname) # slug_len = slug_field.max_length # # # Sort out the initial slug, limiting its length if necessary. # slug = slugify(value) # if slug_len: # slug = slug[:slug_len] # slug = _slug_strip(slug, slug_separator) # original_slug = slug # # # Create the queryset if one wasn't explicitly provided and exclude the # # current instance from the queryset. # if queryset is None: # queryset = instance.__class__._default_manager.all() # if instance.pk: # queryset = queryset.exclude(pk=instance.pk) # # # Find a unique slug. If one matches, add '-2' to the end and try again # # (then '-3', etc). # next = 2 # while not slug or queryset.filter(**{slug_field_name: slug}): # slug = original_slug # end = '%s%s' % (slug_separator, next) # if slug_len and len(slug) + len(end) > slug_len: # slug = slug[:slug_len - len(end)] # slug = _slug_strip(slug, slug_separator) # slug = '%s%s' % (slug, end) # next += 1 # # setattr(instance, slug_field.attname, slug) . Output only the next line.
except self.model.DoesNotExist:
Given the following code snippet before the placeholder: <|code_start|> url(r'^delete-org/(.+)/$', views.delete_org, name='rolodex_delete_org'), # Doc adds url(r'^add-doc/org/(.+)/$', views.new_org_doc, name='rolodex_new_org_doc'), url(r'^add-doc/person/(.+)/$', views.new_person_doc, name='rolodex_new_person_doc'), url(r'^delete-doc/$', views.delete_doc, name='rolodex_delete_doc'), # Relationship maintenance url(r'^add-relationship/org/(.+)/$', views.new_org_relation, name='rolodex_new_org_relation'), url(r'^add-relationship/person/(.+)/$', views.new_person_relation, name='rolodex_new_person_relation'), url(r'^delete-relationship/$', views.delete_relationship, name='rolodex_delete_relation'), url(r'^add-tag/$', views.add_tag, name='rolodex_add_tag'), url(r'^remove-tag/$', views.remove_tag, name='rolodex_remove_tag'), url(r'^search-tag/(.+)/$', views.search_tag, name='rolodex_search_tag'), # network graphs url(r'^person-map/(.+)/$', views.person_map, name='rolodex_person_map'), url(r'^org-map/(.+)/$', views.org_map, name='rolodex_org_map'), url(r'^person-network/(.+)/$', views.person_network, name='rolodex_person_network'), url(r'^org-network/(.+)/$', views.org_network, name='rolodex_org_network'), url(r'^person-network-advanced/person/(.+)/$', views.adv_person_network, name='rolodex_adv_person_network'), url(r'^org-network-advanced/org/(.+)/$', views.adv_org_network, name='rolodex_adv_org_network'), # bloodhound/selectize remote search url(r'^entity-remote/', views.entity_remote_search, name='rolodex_entity_remote_search'), url(r'^org-remote/', views.org_remote_search, name='rolodex_org_remote_search'), url(r'^person-remote/', views.person_remote_search, name='rolodex_person_remote_search'), # api <|code_end|> , predict the next line using imports from the current file: from django.conf.urls import url, include from rolodex import views from rolodex.API import router, views as api_views and context including class names, function names, and sometimes code from other files: # Path: rolodex/views.py # EMPLOYMENT = P2Org_Type.objects.filter(relationship_type='employment').first() # EMPLOYMENT = None # def secure(view): # def home(request): # def new_org(request): # def edit_org(request, org_slug): # def delete_org(request, org_slug): # def search_org(request, org_slug): # def org_map(request, org_slug): # def org_network(request, org_slug): # def adv_org_network(request, org_slug): # def new_org_relation(request, org_slug): # def new_org_doc(request, org_slug=None): # def new_person(request, org_slug=None): # def new_person_no_org(request, org_slug=None): # def edit_person(request, person_slug): # def delete_person(request, person_slug): # def search_person(request, person_slug): # def person_map(request, person_slug): # def person_network(request, person_slug): # def adv_person_network(request, person_slug): # def new_person_relation(request, person_slug): # def new_person_doc(request, person_slug=None): # def delete_relationship(request): # def delete_doc(request): # def add_tag(request): # def remove_tag(request): # def search_tag(request, tag_name=None): # def entity_remote_search(request): # def person_remote_search(request): # def org_remote_search(request): # def org_relate_peep(peeps): # def hierarchy(snode, tnode): # def get_info(n): # def get_relations(nodes): # def net_compiler(nodes, hops=2): # def adv_compile(node, hops): # def user_check(user): # def logger(user, person=None, org=None): # class Output: # # Path: rolodex/API/router.py # # Path: rolodex/API/views.py # class RoleViewSet(viewsets.ModelViewSet): # class ContactRoleViewSet(viewsets.ModelViewSet): # class P2P_TypeViewSet(viewsets.ModelViewSet): # class Org2Org_TypeViewSet(viewsets.ModelViewSet): # class P2Org_TypeViewSet(viewsets.ModelViewSet): # class PersonViewSet(viewsets.ModelViewSet): # class OrgViewSet(viewsets.ModelViewSet): # class ContactViewSet(viewsets.ModelViewSet): # class P2PViewSet(viewsets.ModelViewSet): # class Org2OrgViewSet(viewsets.ModelViewSet): # class Org2PViewSet(viewsets.ModelViewSet): # class P2OrgViewSet(viewsets.ModelViewSet): # class GetEmployees(APIView): # def get(self, request, pk): . Output only the next line.
url(r'^api/', include(router.router.urls)),
Here is a snippet: <|code_start|> pytestmark = pytest.mark.usefixtures('clean_context') LOADED_DATA = { 'systems': [{'celestials': [{'name': 'Primary', 'orbit': 0, 'type': 'star'}, {'name': 'Friesland', 'orbit': 1, 'type': 'oxygen'}], 'commodities': [{'categories': ['chemical', 'illegal'], 'depreciation_rate': 3, 'mean_price': 1, 'name': 'Drugs', 'standard_deviation': 2, 'volume': 4}], 'locations': [{'celestial': 'Primary', 'name': 'Solar Observation Station', 'type': 'orbital'}], 'name': 'Test'}], 'property': [{'depreciation_rate': 3, 'mean_price': 1, <|code_end|> . Write the next line using the current file imports: import builtins import os.path import re import pytest from unittest.mock import mock_open, patch from magnate.savegame import db from magnate.savegame import load from magnate.savegame import data_def from magnate.savegame import base_types and context from other files: # Path: magnate/savegame/db.py # class PricedItem: # class SystemData(Base): # pylint: disable=unused-variable # class CelestialData(Base): # pylint: disable=unused-variable # class LocationData(Base): # pylint: disable=unused-variable # class Commodity(Base): # pylint: disable=unused-variable # class CommodityData(PricedItem, Base): # pylint: disable=unused-variable # class CommodityCategory(Base): # pylint: disable=unused-variable # class Ship(Base): # pylint: disable=unused-variable # class ShipData(PricedItem, Base): # pylint: disable=unused-variable # class Cargo(Base): # pylint: disable=unused-variable # class Property(Base): # pylint: disable=unused-variable # class PropertyData(PricedItem, Base): # pylint: disable=unused-variable # class ShipPart(Base): # pylint: disable=unused-variable # class ShipPartData(PricedItem, Base): # pylint: disable=unused-variable # class EventData(Base): # pylint: disable=unused-variable # class EventCondition(Base): # pylint: disable=unused-variable # class ConditionCategory(Base): # pylint: disable=unused-variable # class Player(Base): # pylint: disable=unused-variable # class World(Base): # pylint: disable=unused-variable # SCHEMA_NAMES = ('SystemData', 'CelestialData', 'LocationData', 'Commodity', 'CommodityData', # 'CommodityCategory', 'Ship', 'ShipData', 'Cargo', 'Property', 'PropertyData', # 'ShipPart', 'ShipPartData', 'EventData', 'EventCondition', 'ConditionCategory', # 'Player', 'World',) # def init_schema(datadir): # def _init_systems(session, systems): # def _init_ships(session, ships): # def _init_property(session, properties): # def _init_parts(session, ship_parts): # def _init_events(session, events): # def init_savegame(engine, game_data): # def create_savegame(savegame, datadir): # def load_savegame(savegame, datadir): # # Path: magnate/savegame/load.py # def init_game(savegame, datadir): # # Path: magnate/savegame/data_def.py # BASE_SCHEMA = None # SYSTEM_SCHEMA = None # SYSTEM_SCHEMA = v.Schema(v.All(system_structure, # known_celestial)) # BASE_SCHEMA = v.Schema(v.All(base_structure, # volume_or_storage)) # def known_celestial(data): # def volume_or_storage(data): # def _define_schemas(datadir): # def load_data_definitions(datadir): # # Path: magnate/savegame/base_types.py # def type_name(value): # def _generic_types_validator(type_enum, value): # def load_base_types(datadir): # def init_base_types(datadir): # DATA_TYPES_SCHEMA = v.Schema({'version': '0.1', # 'types': {type_name: [str]}, }, # required=True) , which may include functions, classes, or code. Output only the next line.
'name': 'property',
Next line prediction: <|code_start|> 'name': 'Solar Observation Station', 'type': 'orbital'}], 'name': 'Test'}], 'property': [{'depreciation_rate': 3, 'mean_price': 1, 'name': 'property', 'standard_deviation': 2, 'storage': 4}], 'ship_parts': [{'depreciation_rate': 12, 'mean_price': 10, 'name': 'add storage', 'standard_deviation': 11, 'storage': 13}, {'depreciation_rate': 22, 'mean_price': 20, 'name': 'take up space', 'standard_deviation': 21, 'volume': 23}], 'ships': [{'depreciation_rate': 1, 'mean_price': 10, 'name': 'ship', 'standard_deviation': 1, 'storage': 0, 'weapon_mounts': 1}], 'events': [{'adjustment': -5, 'affects': ['food', ['illegal', 'chemical']], 'msg': 'price lower'}, {'adjustment': 5, 'affects': [['illegal', 'chemical'], 'food'], 'msg': 'price higher'}], <|code_end|> . Use current file imports: (import builtins import os.path import re import pytest from unittest.mock import mock_open, patch from magnate.savegame import db from magnate.savegame import load from magnate.savegame import data_def from magnate.savegame import base_types) and context including class names, function names, or small code snippets from other files: # Path: magnate/savegame/db.py # class PricedItem: # class SystemData(Base): # pylint: disable=unused-variable # class CelestialData(Base): # pylint: disable=unused-variable # class LocationData(Base): # pylint: disable=unused-variable # class Commodity(Base): # pylint: disable=unused-variable # class CommodityData(PricedItem, Base): # pylint: disable=unused-variable # class CommodityCategory(Base): # pylint: disable=unused-variable # class Ship(Base): # pylint: disable=unused-variable # class ShipData(PricedItem, Base): # pylint: disable=unused-variable # class Cargo(Base): # pylint: disable=unused-variable # class Property(Base): # pylint: disable=unused-variable # class PropertyData(PricedItem, Base): # pylint: disable=unused-variable # class ShipPart(Base): # pylint: disable=unused-variable # class ShipPartData(PricedItem, Base): # pylint: disable=unused-variable # class EventData(Base): # pylint: disable=unused-variable # class EventCondition(Base): # pylint: disable=unused-variable # class ConditionCategory(Base): # pylint: disable=unused-variable # class Player(Base): # pylint: disable=unused-variable # class World(Base): # pylint: disable=unused-variable # SCHEMA_NAMES = ('SystemData', 'CelestialData', 'LocationData', 'Commodity', 'CommodityData', # 'CommodityCategory', 'Ship', 'ShipData', 'Cargo', 'Property', 'PropertyData', # 'ShipPart', 'ShipPartData', 'EventData', 'EventCondition', 'ConditionCategory', # 'Player', 'World',) # def init_schema(datadir): # def _init_systems(session, systems): # def _init_ships(session, ships): # def _init_property(session, properties): # def _init_parts(session, ship_parts): # def _init_events(session, events): # def init_savegame(engine, game_data): # def create_savegame(savegame, datadir): # def load_savegame(savegame, datadir): # # Path: magnate/savegame/load.py # def init_game(savegame, datadir): # # Path: magnate/savegame/data_def.py # BASE_SCHEMA = None # SYSTEM_SCHEMA = None # SYSTEM_SCHEMA = v.Schema(v.All(system_structure, # known_celestial)) # BASE_SCHEMA = v.Schema(v.All(base_structure, # volume_or_storage)) # def known_celestial(data): # def volume_or_storage(data): # def _define_schemas(datadir): # def load_data_definitions(datadir): # # Path: magnate/savegame/base_types.py # def type_name(value): # def _generic_types_validator(type_enum, value): # def load_base_types(datadir): # def init_base_types(datadir): # DATA_TYPES_SCHEMA = v.Schema({'version': '0.1', # 'types': {type_name: [str]}, }, # required=True) . Output only the next line.
}
Here is a snippet: <|code_start|># The idiom for unittests is to use classes for organization # pylint: disable=no-self-use pytestmark = pytest.mark.usefixtures('clean_context') INVALID_DATA = ( ('''{version: "1.0", types: {CommodityType: []}}''', VError, ("not a valid value for dictionary value @ data\\['version']. Got '1.0'",)), ('''{version: "0.1", tpyes: {}}''', VError, ("extra keys not allowed @ data\\['tpyes']", "required key not provided @ data\\['types']")), ('''{version: "0.1", types: []}''', VError, ("expected a dictionary for dictionary value @ data\\['types']",)), ('''{version: "0.1", types: {10: []}}''', VError, <|code_end|> . Write the next line using the current file imports: import enum import re import pytest from unittest.mock import mock_open, patch from voluptuous.error import Error as VError from magnate.savegame import base_types and context from other files: # Path: magnate/savegame/base_types.py # def type_name(value): # def _generic_types_validator(type_enum, value): # def load_base_types(datadir): # def init_base_types(datadir): # DATA_TYPES_SCHEMA = v.Schema({'version': '0.1', # 'types': {type_name: [str]}, }, # required=True) , which may include functions, classes, or code. Output only the next line.
("extra keys not allowed @ data\\['types']\\[10]",)),
Using the snippet: <|code_start|> assert results == [] def test_extra_conf_files_some_exist(self, mocker): mocker.patch('os.path.exists', autospec=True, side_effect=self._sm_paths_exist) results = c._find_config(conf_files=('/srv/sm/magnate.cfg', '~/sm.cfg')) assert results == [ os.path.expanduser('~/sm.cfg') ] class Test_ReadConfig: cfg_keys = frozenset(('data_dir', 'logging', 'state_dir', 'ui_plugin', 'use_uvloop')) ui_and_data_cfg = """ # This is a sample config file # that sets ui_plugin and data directory ui_plugin: the_bestest_widget_set data_dir: /dev/zero """ all_cfg = """ # This is a sample config file # that sets all configuration options ui_plugin: the_bestest_widget_set data_dir: /dev/zero state_dir: /tmp use_uvloop: True """ extra_cfg = """ # This is a sample config file # that sets ui_plugin and data directory <|code_end|> , determine the next line of code. You have imports: import os.path import pytest import twiggy from collections.abc import MutableMapping from magnate import config as c from magnate import errors and context (class names, function names, or code) available: # Path: magnate/config.py # STATE_DIR = os.path.expanduser('~/.stellarmagnate') # USER_DIR = os.path.expanduser('~/.stellarmagnate') # SYSTEM_CONFIG_FILE = '/etc/stellarmagnate/magnate.cfg' # USER_CONFIG_FILE = os.path.join(STATE_DIR, 'magnate.cfg') # LOG_FILE = os.path.join(STATE_DIR, 'magnate.log') # DEFAULT_CONFIG = """ # # Directory in which the game data lives. The data is further divided into subdirectories herein: # # base/ Commodity names and price ranges, ship types, locations, and such. # # schema/ schema for the data files in base *deprecated*, moving to voluptuous # # assets/ Images and other binary files # data_dir: {data_dir}/base # # # Game state dir # # Saves, logs, and other data that changes during operation are saved as subdirs of this # state_dir: {state_dir} # # # Name of the User Interface plugin to use # ui_plugin: urwid # # # Whether to use uvloop instead of the stdlib asyncio event loop # use_uvloop: False # # # Configuration of logging output. This is given directly to twiggy.dict_cnfig() # logging: # version: "1.0" # outputs: # logfile: # output: twiggy.outputs.FileOutput # args: # - {log_file} # emitters: # all: # level: WARNING # output_name: logfile # filters: [] # """.format(data_dir='/usr/share/stellarmagnate', log_file=LOG_FILE, state_dir=STATE_DIR) # TESTING_CONFIG = """ # data_dir: {base_dir} # logging: # version: "1.0" # outputs: # logfile: # output: twiggy.outputs.FileOutput # args: # - {log_file} # emitters: # all: # level: DEBUG # output_name: logfile # """.format(base_dir=os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'data')), # log_file=LOG_FILE) # CONFIG_SCHEMA = Schema({ # 'data_dir': All(str, Length(min=1)), # 'state_dir': All(str, Length(min=1)), # 'ui_plugin': All(str, Length(min=1, max=128)), # 'use_uvloop': bool, # # The logging param is passed directly to twiggy.dict_config() which does its own validation # 'logging': dict, # }, required=False) # def _find_config(conf_files=tuple()): # def _merge_mapping(merge_to, merge_from, inplace=False): # def _read_config(paths, testing=False): # def read_config(conf_files=tuple(), testing=False): # def write_default_config(filename): # # Path: magnate/errors.py # class MagnateError(Exception): # class MagnateConfigError(MagnateError): # class MagnateSaveError(MagnateError): # class MagnateNoSaveGame(MagnateSaveError): # class MagnateInvalidSaveGame(MagnateSaveError): . Output only the next line.
ui_plugin: the_bestest_widget_set
Here is a snippet: <|code_start|> assert results == [] def test_extra_conf_files_some_exist(self, mocker): mocker.patch('os.path.exists', autospec=True, side_effect=self._sm_paths_exist) results = c._find_config(conf_files=('/srv/sm/magnate.cfg', '~/sm.cfg')) assert results == [ os.path.expanduser('~/sm.cfg') ] class Test_ReadConfig: cfg_keys = frozenset(('data_dir', 'logging', 'state_dir', 'ui_plugin', 'use_uvloop')) ui_and_data_cfg = """ # This is a sample config file # that sets ui_plugin and data directory ui_plugin: the_bestest_widget_set data_dir: /dev/zero """ all_cfg = """ # This is a sample config file # that sets all configuration options ui_plugin: the_bestest_widget_set data_dir: /dev/zero state_dir: /tmp use_uvloop: True """ extra_cfg = """ # This is a sample config file # that sets ui_plugin and data directory <|code_end|> . Write the next line using the current file imports: import os.path import pytest import twiggy from collections.abc import MutableMapping from magnate import config as c from magnate import errors and context from other files: # Path: magnate/config.py # STATE_DIR = os.path.expanduser('~/.stellarmagnate') # USER_DIR = os.path.expanduser('~/.stellarmagnate') # SYSTEM_CONFIG_FILE = '/etc/stellarmagnate/magnate.cfg' # USER_CONFIG_FILE = os.path.join(STATE_DIR, 'magnate.cfg') # LOG_FILE = os.path.join(STATE_DIR, 'magnate.log') # DEFAULT_CONFIG = """ # # Directory in which the game data lives. The data is further divided into subdirectories herein: # # base/ Commodity names and price ranges, ship types, locations, and such. # # schema/ schema for the data files in base *deprecated*, moving to voluptuous # # assets/ Images and other binary files # data_dir: {data_dir}/base # # # Game state dir # # Saves, logs, and other data that changes during operation are saved as subdirs of this # state_dir: {state_dir} # # # Name of the User Interface plugin to use # ui_plugin: urwid # # # Whether to use uvloop instead of the stdlib asyncio event loop # use_uvloop: False # # # Configuration of logging output. This is given directly to twiggy.dict_cnfig() # logging: # version: "1.0" # outputs: # logfile: # output: twiggy.outputs.FileOutput # args: # - {log_file} # emitters: # all: # level: WARNING # output_name: logfile # filters: [] # """.format(data_dir='/usr/share/stellarmagnate', log_file=LOG_FILE, state_dir=STATE_DIR) # TESTING_CONFIG = """ # data_dir: {base_dir} # logging: # version: "1.0" # outputs: # logfile: # output: twiggy.outputs.FileOutput # args: # - {log_file} # emitters: # all: # level: DEBUG # output_name: logfile # """.format(base_dir=os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'data')), # log_file=LOG_FILE) # CONFIG_SCHEMA = Schema({ # 'data_dir': All(str, Length(min=1)), # 'state_dir': All(str, Length(min=1)), # 'ui_plugin': All(str, Length(min=1, max=128)), # 'use_uvloop': bool, # # The logging param is passed directly to twiggy.dict_config() which does its own validation # 'logging': dict, # }, required=False) # def _find_config(conf_files=tuple()): # def _merge_mapping(merge_to, merge_from, inplace=False): # def _read_config(paths, testing=False): # def read_config(conf_files=tuple(), testing=False): # def write_default_config(filename): # # Path: magnate/errors.py # class MagnateError(Exception): # class MagnateConfigError(MagnateError): # class MagnateSaveError(MagnateError): # class MagnateNoSaveGame(MagnateSaveError): # class MagnateInvalidSaveGame(MagnateSaveError): , which may include functions, classes, or code. Output only the next line.
ui_plugin: the_bestest_widget_set
Next line prediction: <|code_start|> @pytest.fixture def clean_context(): old_engine = db.engine db.engine = None old_types = {} for key, value in base_types.__dict__.items(): if key.endswith('Type'): old_types[key] = value old_system_schema = data_def.SYSTEM_SCHEMA old_base_schema = data_def.BASE_SCHEMA yield data_def.SYSTEM_SCHEMA = old_system_schema data_def.BASE_SCHEMA = old_base_schema <|code_end|> . Use current file imports: (import os.path import pytest from magnate.savegame import base_types, db, data_def) and context including class names, function names, or small code snippets from other files: # Path: magnate/savegame/base_types.py # def type_name(value): # def _generic_types_validator(type_enum, value): # def load_base_types(datadir): # def init_base_types(datadir): # DATA_TYPES_SCHEMA = v.Schema({'version': '0.1', # 'types': {type_name: [str]}, }, # required=True) # # Path: magnate/savegame/db.py # class PricedItem: # class SystemData(Base): # pylint: disable=unused-variable # class CelestialData(Base): # pylint: disable=unused-variable # class LocationData(Base): # pylint: disable=unused-variable # class Commodity(Base): # pylint: disable=unused-variable # class CommodityData(PricedItem, Base): # pylint: disable=unused-variable # class CommodityCategory(Base): # pylint: disable=unused-variable # class Ship(Base): # pylint: disable=unused-variable # class ShipData(PricedItem, Base): # pylint: disable=unused-variable # class Cargo(Base): # pylint: disable=unused-variable # class Property(Base): # pylint: disable=unused-variable # class PropertyData(PricedItem, Base): # pylint: disable=unused-variable # class ShipPart(Base): # pylint: disable=unused-variable # class ShipPartData(PricedItem, Base): # pylint: disable=unused-variable # class EventData(Base): # pylint: disable=unused-variable # class EventCondition(Base): # pylint: disable=unused-variable # class ConditionCategory(Base): # pylint: disable=unused-variable # class Player(Base): # pylint: disable=unused-variable # class World(Base): # pylint: disable=unused-variable # SCHEMA_NAMES = ('SystemData', 'CelestialData', 'LocationData', 'Commodity', 'CommodityData', # 'CommodityCategory', 'Ship', 'ShipData', 'Cargo', 'Property', 'PropertyData', # 'ShipPart', 'ShipPartData', 'EventData', 'EventCondition', 'ConditionCategory', # 'Player', 'World',) # def init_schema(datadir): # def _init_systems(session, systems): # def _init_ships(session, ships): # def _init_property(session, properties): # def _init_parts(session, ship_parts): # def _init_events(session, events): # def init_savegame(engine, game_data): # def create_savegame(savegame, datadir): # def load_savegame(savegame, datadir): # # Path: magnate/savegame/data_def.py # BASE_SCHEMA = None # SYSTEM_SCHEMA = None # SYSTEM_SCHEMA = v.Schema(v.All(system_structure, # known_celestial)) # BASE_SCHEMA = v.Schema(v.All(base_structure, # volume_or_storage)) # def known_celestial(data): # def volume_or_storage(data): # def _define_schemas(datadir): # def load_data_definitions(datadir): . Output only the next line.
for key, value in old_types.items():
Given the following code snippet before the placeholder: <|code_start|> @pytest.fixture def clean_context(): old_engine = db.engine db.engine = None old_types = {} for key, value in base_types.__dict__.items(): if key.endswith('Type'): old_types[key] = value old_system_schema = data_def.SYSTEM_SCHEMA old_base_schema = data_def.BASE_SCHEMA yield data_def.SYSTEM_SCHEMA = old_system_schema data_def.BASE_SCHEMA = old_base_schema for key, value in old_types.items(): base_types.__dict__[key] = value db.engine = old_engine @pytest.fixture def datadir(): <|code_end|> , predict the next line using imports from the current file: import os.path import pytest from magnate.savegame import base_types, db, data_def and context including class names, function names, and sometimes code from other files: # Path: magnate/savegame/base_types.py # def type_name(value): # def _generic_types_validator(type_enum, value): # def load_base_types(datadir): # def init_base_types(datadir): # DATA_TYPES_SCHEMA = v.Schema({'version': '0.1', # 'types': {type_name: [str]}, }, # required=True) # # Path: magnate/savegame/db.py # class PricedItem: # class SystemData(Base): # pylint: disable=unused-variable # class CelestialData(Base): # pylint: disable=unused-variable # class LocationData(Base): # pylint: disable=unused-variable # class Commodity(Base): # pylint: disable=unused-variable # class CommodityData(PricedItem, Base): # pylint: disable=unused-variable # class CommodityCategory(Base): # pylint: disable=unused-variable # class Ship(Base): # pylint: disable=unused-variable # class ShipData(PricedItem, Base): # pylint: disable=unused-variable # class Cargo(Base): # pylint: disable=unused-variable # class Property(Base): # pylint: disable=unused-variable # class PropertyData(PricedItem, Base): # pylint: disable=unused-variable # class ShipPart(Base): # pylint: disable=unused-variable # class ShipPartData(PricedItem, Base): # pylint: disable=unused-variable # class EventData(Base): # pylint: disable=unused-variable # class EventCondition(Base): # pylint: disable=unused-variable # class ConditionCategory(Base): # pylint: disable=unused-variable # class Player(Base): # pylint: disable=unused-variable # class World(Base): # pylint: disable=unused-variable # SCHEMA_NAMES = ('SystemData', 'CelestialData', 'LocationData', 'Commodity', 'CommodityData', # 'CommodityCategory', 'Ship', 'ShipData', 'Cargo', 'Property', 'PropertyData', # 'ShipPart', 'ShipPartData', 'EventData', 'EventCondition', 'ConditionCategory', # 'Player', 'World',) # def init_schema(datadir): # def _init_systems(session, systems): # def _init_ships(session, ships): # def _init_property(session, properties): # def _init_parts(session, ship_parts): # def _init_events(session, events): # def init_savegame(engine, game_data): # def create_savegame(savegame, datadir): # def load_savegame(savegame, datadir): # # Path: magnate/savegame/data_def.py # BASE_SCHEMA = None # SYSTEM_SCHEMA = None # SYSTEM_SCHEMA = v.Schema(v.All(system_structure, # known_celestial)) # BASE_SCHEMA = v.Schema(v.All(base_structure, # volume_or_storage)) # def known_celestial(data): # def volume_or_storage(data): # def _define_schemas(datadir): # def load_data_definitions(datadir): . Output only the next line.
datadir = os.path.join(os.path.dirname(__file__), '../data')
Given snippet: <|code_start|> for name, value in db.__dict__.items(): if value is None and name not in ('engine', 'Base'): undefined_schema.append(name) db.init_schema(datadir) first_schema = {} for name, value in db.__dict__.items(): first_schema[name] = value # A table wasn't initialized globally yet db.CommodityCategory = None db.init_schema(datadir) # Assert nothing was added assert len(db.__dict__) == db_items # Assert that all of the schema values have changed for name in undefined_schema: assert db.__dict__[name] is not first_schema[name] def _check_fake_data_load(engine): Session = sqlalchemy.orm.sessionmaker(bind=engine) session = Session() systems = session.query(db.SystemData).all() assert len(systems) == 1 assert systems[0].name == 'Test' assert len(systems[0].celestials) == 2 <|code_end|> , continue by predicting the next line. Consider current file imports: import os.path import shutil import pytest import sqlalchemy from magnate.errors import MagnateNoSaveGame from magnate.savegame import base_types from magnate.savegame import data_def from magnate.savegame import db and context: # Path: magnate/errors.py # class MagnateNoSaveGame(MagnateSaveError): # """Raised when a save game file is missing""" # pass # # Path: magnate/savegame/base_types.py # def type_name(value): # def _generic_types_validator(type_enum, value): # def load_base_types(datadir): # def init_base_types(datadir): # DATA_TYPES_SCHEMA = v.Schema({'version': '0.1', # 'types': {type_name: [str]}, }, # required=True) # # Path: magnate/savegame/data_def.py # BASE_SCHEMA = None # SYSTEM_SCHEMA = None # SYSTEM_SCHEMA = v.Schema(v.All(system_structure, # known_celestial)) # BASE_SCHEMA = v.Schema(v.All(base_structure, # volume_or_storage)) # def known_celestial(data): # def volume_or_storage(data): # def _define_schemas(datadir): # def load_data_definitions(datadir): # # Path: magnate/savegame/db.py # class PricedItem: # class SystemData(Base): # pylint: disable=unused-variable # class CelestialData(Base): # pylint: disable=unused-variable # class LocationData(Base): # pylint: disable=unused-variable # class Commodity(Base): # pylint: disable=unused-variable # class CommodityData(PricedItem, Base): # pylint: disable=unused-variable # class CommodityCategory(Base): # pylint: disable=unused-variable # class Ship(Base): # pylint: disable=unused-variable # class ShipData(PricedItem, Base): # pylint: disable=unused-variable # class Cargo(Base): # pylint: disable=unused-variable # class Property(Base): # pylint: disable=unused-variable # class PropertyData(PricedItem, Base): # pylint: disable=unused-variable # class ShipPart(Base): # pylint: disable=unused-variable # class ShipPartData(PricedItem, Base): # pylint: disable=unused-variable # class EventData(Base): # pylint: disable=unused-variable # class EventCondition(Base): # pylint: disable=unused-variable # class ConditionCategory(Base): # pylint: disable=unused-variable # class Player(Base): # pylint: disable=unused-variable # class World(Base): # pylint: disable=unused-variable # SCHEMA_NAMES = ('SystemData', 'CelestialData', 'LocationData', 'Commodity', 'CommodityData', # 'CommodityCategory', 'Ship', 'ShipData', 'Cargo', 'Property', 'PropertyData', # 'ShipPart', 'ShipPartData', 'EventData', 'EventCondition', 'ConditionCategory', # 'Player', 'World',) # def init_schema(datadir): # def _init_systems(session, systems): # def _init_ships(session, ships): # def _init_property(session, properties): # def _init_parts(session, ship_parts): # def _init_events(session, events): # def init_savegame(engine, game_data): # def create_savegame(savegame, datadir): # def load_savegame(savegame, datadir): which might include code, classes, or functions. Output only the next line.
assert frozenset((systems[0].celestials[0].name, systems[0].celestials[1].name)) == frozenset(('Primary', 'Friesland'))
Next line prediction: <|code_start|> # A table wasn't initialized globally yet db.CommodityCategory = None db.init_schema(datadir) # Assert nothing was added assert len(db.__dict__) == db_items # Assert that all of the schema values have changed for name in undefined_schema: assert db.__dict__[name] is not first_schema[name] def _check_fake_data_load(engine): Session = sqlalchemy.orm.sessionmaker(bind=engine) session = Session() systems = session.query(db.SystemData).all() assert len(systems) == 1 assert systems[0].name == 'Test' assert len(systems[0].celestials) == 2 assert frozenset((systems[0].celestials[0].name, systems[0].celestials[1].name)) == frozenset(('Primary', 'Friesland')) assert systems[0].celestials[0].locations[0].name == 'Solar Observation Station' assert systems[0].celestials[1].locations == [] commodities = session.query(db.CommodityData).all() assert len(commodities) == 1 assert commodities[0].name == 'Drugs' ships = session.query(db.ShipData).all() assert len(ships) == 1 <|code_end|> . Use current file imports: (import os.path import shutil import pytest import sqlalchemy from magnate.errors import MagnateNoSaveGame from magnate.savegame import base_types from magnate.savegame import data_def from magnate.savegame import db) and context including class names, function names, or small code snippets from other files: # Path: magnate/errors.py # class MagnateNoSaveGame(MagnateSaveError): # """Raised when a save game file is missing""" # pass # # Path: magnate/savegame/base_types.py # def type_name(value): # def _generic_types_validator(type_enum, value): # def load_base_types(datadir): # def init_base_types(datadir): # DATA_TYPES_SCHEMA = v.Schema({'version': '0.1', # 'types': {type_name: [str]}, }, # required=True) # # Path: magnate/savegame/data_def.py # BASE_SCHEMA = None # SYSTEM_SCHEMA = None # SYSTEM_SCHEMA = v.Schema(v.All(system_structure, # known_celestial)) # BASE_SCHEMA = v.Schema(v.All(base_structure, # volume_or_storage)) # def known_celestial(data): # def volume_or_storage(data): # def _define_schemas(datadir): # def load_data_definitions(datadir): # # Path: magnate/savegame/db.py # class PricedItem: # class SystemData(Base): # pylint: disable=unused-variable # class CelestialData(Base): # pylint: disable=unused-variable # class LocationData(Base): # pylint: disable=unused-variable # class Commodity(Base): # pylint: disable=unused-variable # class CommodityData(PricedItem, Base): # pylint: disable=unused-variable # class CommodityCategory(Base): # pylint: disable=unused-variable # class Ship(Base): # pylint: disable=unused-variable # class ShipData(PricedItem, Base): # pylint: disable=unused-variable # class Cargo(Base): # pylint: disable=unused-variable # class Property(Base): # pylint: disable=unused-variable # class PropertyData(PricedItem, Base): # pylint: disable=unused-variable # class ShipPart(Base): # pylint: disable=unused-variable # class ShipPartData(PricedItem, Base): # pylint: disable=unused-variable # class EventData(Base): # pylint: disable=unused-variable # class EventCondition(Base): # pylint: disable=unused-variable # class ConditionCategory(Base): # pylint: disable=unused-variable # class Player(Base): # pylint: disable=unused-variable # class World(Base): # pylint: disable=unused-variable # SCHEMA_NAMES = ('SystemData', 'CelestialData', 'LocationData', 'Commodity', 'CommodityData', # 'CommodityCategory', 'Ship', 'ShipData', 'Cargo', 'Property', 'PropertyData', # 'ShipPart', 'ShipPartData', 'EventData', 'EventCondition', 'ConditionCategory', # 'Player', 'World',) # def init_schema(datadir): # def _init_systems(session, systems): # def _init_ships(session, ships): # def _init_property(session, properties): # def _init_parts(session, ship_parts): # def _init_events(session, events): # def init_savegame(engine, game_data): # def create_savegame(savegame, datadir): # def load_savegame(savegame, datadir): . Output only the next line.
assert ships[0].name == 'ship'
Predict the next line for this snippet: <|code_start|> def test_init_schema(datadir): db_items = len(db.__dict__) undefined_schema = [] for name, value in db.__dict__.items(): if value is None and name not in ('engine',): <|code_end|> with the help of current file imports: import os.path import shutil import pytest import sqlalchemy from magnate.errors import MagnateNoSaveGame from magnate.savegame import base_types from magnate.savegame import data_def from magnate.savegame import db and context from other files: # Path: magnate/errors.py # class MagnateNoSaveGame(MagnateSaveError): # """Raised when a save game file is missing""" # pass # # Path: magnate/savegame/base_types.py # def type_name(value): # def _generic_types_validator(type_enum, value): # def load_base_types(datadir): # def init_base_types(datadir): # DATA_TYPES_SCHEMA = v.Schema({'version': '0.1', # 'types': {type_name: [str]}, }, # required=True) # # Path: magnate/savegame/data_def.py # BASE_SCHEMA = None # SYSTEM_SCHEMA = None # SYSTEM_SCHEMA = v.Schema(v.All(system_structure, # known_celestial)) # BASE_SCHEMA = v.Schema(v.All(base_structure, # volume_or_storage)) # def known_celestial(data): # def volume_or_storage(data): # def _define_schemas(datadir): # def load_data_definitions(datadir): # # Path: magnate/savegame/db.py # class PricedItem: # class SystemData(Base): # pylint: disable=unused-variable # class CelestialData(Base): # pylint: disable=unused-variable # class LocationData(Base): # pylint: disable=unused-variable # class Commodity(Base): # pylint: disable=unused-variable # class CommodityData(PricedItem, Base): # pylint: disable=unused-variable # class CommodityCategory(Base): # pylint: disable=unused-variable # class Ship(Base): # pylint: disable=unused-variable # class ShipData(PricedItem, Base): # pylint: disable=unused-variable # class Cargo(Base): # pylint: disable=unused-variable # class Property(Base): # pylint: disable=unused-variable # class PropertyData(PricedItem, Base): # pylint: disable=unused-variable # class ShipPart(Base): # pylint: disable=unused-variable # class ShipPartData(PricedItem, Base): # pylint: disable=unused-variable # class EventData(Base): # pylint: disable=unused-variable # class EventCondition(Base): # pylint: disable=unused-variable # class ConditionCategory(Base): # pylint: disable=unused-variable # class Player(Base): # pylint: disable=unused-variable # class World(Base): # pylint: disable=unused-variable # SCHEMA_NAMES = ('SystemData', 'CelestialData', 'LocationData', 'Commodity', 'CommodityData', # 'CommodityCategory', 'Ship', 'ShipData', 'Cargo', 'Property', 'PropertyData', # 'ShipPart', 'ShipPartData', 'EventData', 'EventCondition', 'ConditionCategory', # 'Player', 'World',) # def init_schema(datadir): # def _init_systems(session, systems): # def _init_ships(session, ships): # def _init_property(session, properties): # def _init_parts(session, ship_parts): # def _init_events(session, events): # def init_savegame(engine, game_data): # def create_savegame(savegame, datadir): # def load_savegame(savegame, datadir): , which may contain function names, class names, or code. Output only the next line.
undefined_schema.append(name)
Predict the next line for this snippet: <|code_start|>state_dir: {state_dir} # Name of the User Interface plugin to use ui_plugin: urwid # Whether to use uvloop instead of the stdlib asyncio event loop use_uvloop: False # Configuration of logging output. This is given directly to twiggy.dict_cnfig() logging: version: "1.0" outputs: logfile: output: twiggy.outputs.FileOutput args: - {log_file} emitters: all: level: WARNING output_name: logfile filters: [] """.format(data_dir='/usr/share/stellarmagnate', log_file=LOG_FILE, state_dir=STATE_DIR) TESTING_CONFIG = """ data_dir: {base_dir} logging: version: "1.0" outputs: logfile: output: twiggy.outputs.FileOutput <|code_end|> with the help of current file imports: import itertools import os.path import yaml from collections.abc import MutableMapping from kitchen.iterutils import iterate from voluptuous import All, Length, Schema, MultipleInvalid from .errors import MagnateConfigError from .logging import log and context from other files: # Path: magnate/errors.py # class MagnateConfigError(MagnateError): # """Raised when processing config files""" # pass # # Path: magnate/logging.py , which may contain function names, class names, or code. Output only the next line.
args:
Here is a snippet: <|code_start|># You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Functions to read configuration files """ mlog = log.fields(mod=__name__) STATE_DIR = os.path.expanduser('~/.stellarmagnate') USER_DIR = os.path.expanduser('~/.stellarmagnate') SYSTEM_CONFIG_FILE = '/etc/stellarmagnate/magnate.cfg' USER_CONFIG_FILE = os.path.join(STATE_DIR, 'magnate.cfg') LOG_FILE = os.path.join(STATE_DIR, 'magnate.log') DEFAULT_CONFIG = """ # Directory in which the game data lives. The data is further divided into subdirectories herein: # base/ Commodity names and price ranges, ship types, locations, and such. # schema/ schema for the data files in base *deprecated*, moving to voluptuous # assets/ Images and other binary files data_dir: {data_dir}/base # Game state dir # Saves, logs, and other data that changes during operation are saved as subdirs of this <|code_end|> . Write the next line using the current file imports: import itertools import os.path import yaml from collections.abc import MutableMapping from kitchen.iterutils import iterate from voluptuous import All, Length, Schema, MultipleInvalid from .errors import MagnateConfigError from .logging import log and context from other files: # Path: magnate/errors.py # class MagnateConfigError(MagnateError): # """Raised when processing config files""" # pass # # Path: magnate/logging.py , which may include functions, classes, or code. Output only the next line.
state_dir: {state_dir}
Predict the next line after this snippet: <|code_start|>@pytest.mark.usefixtures('setup_base_types') def test_define_schemas(datadir): data_def._define_schemas(datadir) assert isinstance(data_def.BASE_SCHEMA, voluptuous.Schema) assert isinstance(data_def.SYSTEM_SCHEMA, voluptuous.Schema) GOOD_BASE_DATA = {'version': '0.1', 'ships': [ {'name': 'Ship', 'mean_price': 1, 'standard_deviation': 2, 'depreciation_rate': 3, 'storage': 4, 'weapon_mounts': 5, }, ], 'property': [ {'name': 'Warehouse', 'mean_price': 1, 'standard_deviation': 2, 'depreciation_rate': 3, 'storage': 4, }, ], 'ship_parts': [ {'name': 'Hold', 'mean_price': 1, 'standard_deviation': 2, <|code_end|> using the current file's imports: import copy import os import pytest import voluptuous import voluptuous.error from voluptuous.humanize import validate_with_humanized_errors as v_validate from magnate.savegame import base_types from magnate.savegame import data_def and any relevant context from other files: # Path: magnate/savegame/base_types.py # def type_name(value): # def _generic_types_validator(type_enum, value): # def load_base_types(datadir): # def init_base_types(datadir): # DATA_TYPES_SCHEMA = v.Schema({'version': '0.1', # 'types': {type_name: [str]}, }, # required=True) # # Path: magnate/savegame/data_def.py # BASE_SCHEMA = None # SYSTEM_SCHEMA = None # SYSTEM_SCHEMA = v.Schema(v.All(system_structure, # known_celestial)) # BASE_SCHEMA = v.Schema(v.All(base_structure, # volume_or_storage)) # def known_celestial(data): # def volume_or_storage(data): # def _define_schemas(datadir): # def load_data_definitions(datadir): . Output only the next line.
'depreciation_rate': 3,
Here is a snippet: <|code_start|> data = copy.deepcopy(GOOD_BASE_DATA) data['events'][0]['affects'] = ['food', 'illegal'] yield data data = copy.deepcopy(GOOD_BASE_DATA) data['events'][0]['affects'] = ['food', ['chemical', 'illegal']] yield data data = copy.deepcopy(GOOD_BASE_DATA) data['ship_parts'][0]['storage'] = None data['ship_parts'][0]['volume'] = 10 yield data def good_system_data(): data = copy.deepcopy(GOOD_SYSTEM_DATA) yield data data = copy.deepcopy(GOOD_SYSTEM_DATA) data['systems'][0]['commodities'][0]['categories'] = ['food', 'illegal'] yield data def bad_base_data(): data = copy.deepcopy(GOOD_BASE_DATA) data['version'] = '100.0' yield (data, "not a valid value for dictionary value @ data['version']") data = copy.deepcopy(GOOD_BASE_DATA) data['version'] = 0.1 <|code_end|> . Write the next line using the current file imports: import copy import os import pytest import voluptuous import voluptuous.error from voluptuous.humanize import validate_with_humanized_errors as v_validate from magnate.savegame import base_types from magnate.savegame import data_def and context from other files: # Path: magnate/savegame/base_types.py # def type_name(value): # def _generic_types_validator(type_enum, value): # def load_base_types(datadir): # def init_base_types(datadir): # DATA_TYPES_SCHEMA = v.Schema({'version': '0.1', # 'types': {type_name: [str]}, }, # required=True) # # Path: magnate/savegame/data_def.py # BASE_SCHEMA = None # SYSTEM_SCHEMA = None # SYSTEM_SCHEMA = v.Schema(v.All(system_structure, # known_celestial)) # BASE_SCHEMA = v.Schema(v.All(base_structure, # volume_or_storage)) # def known_celestial(data): # def volume_or_storage(data): # def _define_schemas(datadir): # def load_data_definitions(datadir): , which may include functions, classes, or code. Output only the next line.
yield (data, "not a valid value for dictionary value @ data['version']")
Here is a snippet: <|code_start|>@app.route('/login', methods=('POST', )) def login_post(): login = request.form.get('login') password = request.form.get('password') employee = view.EmployeeView.model.query.filter_by( login=login, password=password).first() if employee: session['id'] = employee.person_id session['login'] = login flash('You were logged in !', 'ok') else: flash('invalid credentials', 'error') return redirect('employees') @app.route('/logout') def logout(): session.clear() return redirect('employees') @app.route('/') @app.route('/employees/') @allow_if(Is.connected) def employees(): return view.EmployeeView.list('list_employees.html') @app.route('/companies/') @allow_if(Is.connected) <|code_end|> . Write the next line using the current file imports: from flask import flash, redirect, session, request, render_template, g from application import app from pynuts.rights import allow_if from pynuts.directives import Editable import view import document import rights as Is and context from other files: # Path: pynuts/rights.py # class allow_if(object): # pylint: disable=C0103 # """Check that the global context matches a criteria.""" # def __init__(self, auth_fun, exception=None): # self.auth_fun = auth_fun # self.exception = exception # # def __call__(self, function): # """Check the global context.""" # @wraps(function) # def check_auth(*args, **kwargs): # """Function wrapper.""" # if self.auth_fun(): # return function(*args, **kwargs) # else: # if self.exception: # raise self.exception # else: # abort(403) # # check_auth._auth_fun = self.auth_fun # return check_auth # # Path: pynuts/directives.py # class Editable(_Tag): # """ReST directive creating an HTML contenteditable tag. # # The directive's argument must look like this: # `document_type/document_id/version/part` # # You can put those optional attributes on your editable content: # # - `title` # - `id` # - `class` # # """ # option_spec = { # 'title': directives.unchanged, # 'class': directives.class_option, # 'id': directives.class_option, # 'contenteditable': directives.class_option, # } # # def run(self): # try: # super(Editable, self).run() # except NotFoundError: # self.parsed_content = docutils.core.publish_parts( # '\n'.join(self.content), writer_name='html')['body'] # for key in self.option_spec: # if key == 'title': # self.attributes[key] = self.options.get(key) # elif key == 'contenteditable': # self.attributes[key] = ' '.join(self.options.get(key, ['true'])) # else: # self.attributes[key] = ' '.join(self.options.get(key, [])) # content = '<div %s>%s</div>' % ( # ' '.join(('%s="%s"' % a) for a in self.attributes.items()), # self.parsed_content or '') # return [docutils.nodes.raw('', content, format='html')] , which may include functions, classes, or code. Output only the next line.
def companies():
Using the snippet: <|code_start|> class EmployeeView(nuts.ModelView): model = database.Employee list_column = 'fullname' table_columns = ('fullname', ) create_columns = ('login', 'password', 'name', 'firstname', 'company') read_columns = ('person_id', 'name', 'firstname', 'fullname', 'company') update_columns = ('name', 'firstname') class Form(BaseForm): person_id = IntegerField('ID') login = TextField(u'Login', validators=[Required()]) password = PasswordField(u'Password', validators=[Required()]) name = TextField(u'Surname', validators=[Required()]) firstname = TextField(u'Firstname', validators=[Required()]) <|code_end|> , determine the next line of code. You have imports: from wtforms import TextField, IntegerField, PasswordField from wtforms.ext.sqlalchemy.fields import ( QuerySelectField, QuerySelectMultipleField) from wtforms.validators import Required from pynuts.view import BaseForm from application import nuts import database and context (class names, function names, or code) available: # Path: pynuts/view.py # class BaseForm(Form): # # def handle_errors(self): # """Flash all the form errors.""" # if self.errors: # for key, errors in self.errors.items(): # flask.flash(jinja2.Markup( # u'<label for="%s">%s</label>: %s.' % ( # key, self[key].label.text, ', '.join(errors))), # 'error') . Output only the next line.
fullname = TextField(u'Employee name')
Based on the snippet: <|code_start|> class EmployeeView(nuts.ModelView): model = database.Employee list_column = 'fullname' create_columns = ('name', 'firstname') class Form(BaseForm): id = IntegerField(u'ID') name = TextField(u'Surname', validators=[Required()]) firstname = TextField(u'Firstname', validators=[Required()]) <|code_end|> , predict the immediate next line with the help of imports: from wtforms import TextField, IntegerField from wtforms.validators import Required from pynuts.view import BaseForm from application import nuts import database and context (classes, functions, sometimes code) from other files: # Path: pynuts/view.py # class BaseForm(Form): # # def handle_errors(self): # """Flash all the form errors.""" # if self.errors: # for key, errors in self.errors.items(): # flask.flash(jinja2.Markup( # u'<label for="%s">%s</label>: %s.' % ( # key, self[key].label.text, ', '.join(errors))), # 'error') . Output only the next line.
fullname = TextField(u'Fullname')
Given the code snippet: <|code_start|> if value: value = json.loads(value) except: logger.debug("Redis exception: couldn't get_cache {}".format(key)) value = None return value def del_cache(key): """Delete a cached item.""" key = Config.db.redis_prefix + key client = get_redis() if not client: return client.delete(key) def lock_cache(key, timeout=5, expire=20): """Cache level 'file locking' implementation. The `key` will be automatically suffixed with `_lock`. The `timeout` is the max amount of time to wait for a lock. The `expire` is how long a lock may exist before it's considered stale. Returns True on success, None on failure to acquire lock.""" client = get_redis() if not client: return # Take the lock. <|code_end|> , generate the next line using the imports in this file: import codecs import os import os.path import re import redis import json import time from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN from rophako.settings import Config from rophako.utils import handle_exception from rophako.log import logger and context (functions, classes, or occasionally code) from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/utils.py # def handle_exception(error): # """Send an e-mail to the site admin when an exception occurs.""" # if current_app.config.get("DEBUG"): # print(traceback.format_exc()) # raise # # import rophako.jsondb as JsonDB # # # Don't spam too many e-mails in a short time frame. # cache = JsonDB.get_cache("exception_catcher") # if cache: # last_exception = int(cache) # if int(time.time()) - last_exception < 120: # # Only one e-mail per 2 minutes, minimum # logger.error("RAPID EXCEPTIONS, DROPPING") # return # JsonDB.set_cache("exception_catcher", int(time.time())) # # username = "anonymous" # try: # if hasattr(g, "info") and "session" in g.info and "username" in g.info["session"]: # username = g.info["session"]["username"] # except: # pass # # # Get the timestamp. # timestamp = time.ctime(time.time()) # # # Exception's traceback. # error = str(error.__class__.__name__) + ": " + str(error) # stacktrace = error + "\n\n" \ # + "==== Start Traceback ====\n" \ # + traceback.format_exc() \ # + "==== End Traceback ====\n\n" \ # + "Request Information\n" \ # + "-------------------\n" \ # + "Address: " + remote_addr() + "\n" \ # + "User Agent: " + request.user_agent.string + "\n" \ # + "Referrer: " + request.referrer # # # Construct the subject and message # subject = "Internal Server Error on {} - {} - {}".format( # Config.site.site_name, # username, # timestamp, # ) # message = "{} has experienced an exception on the route: {}".format( # username, # request.path, # ) # message += "\n\n" + stacktrace # # # Send the e-mail. # send_email( # to=Config.site.notify_address, # subject=subject, # message=message, # ) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
lock = client.lock(key, timeout=expire)
Based on the snippet: <|code_start|> try: value = client.get(key) if value: value = json.loads(value) except: logger.debug("Redis exception: couldn't get_cache {}".format(key)) value = None return value def del_cache(key): """Delete a cached item.""" key = Config.db.redis_prefix + key client = get_redis() if not client: return client.delete(key) def lock_cache(key, timeout=5, expire=20): """Cache level 'file locking' implementation. The `key` will be automatically suffixed with `_lock`. The `timeout` is the max amount of time to wait for a lock. The `expire` is how long a lock may exist before it's considered stale. Returns True on success, None on failure to acquire lock.""" client = get_redis() if not client: <|code_end|> , predict the immediate next line with the help of imports: import codecs import os import os.path import re import redis import json import time from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN from rophako.settings import Config from rophako.utils import handle_exception from rophako.log import logger and context (classes, functions, sometimes code) from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/utils.py # def handle_exception(error): # """Send an e-mail to the site admin when an exception occurs.""" # if current_app.config.get("DEBUG"): # print(traceback.format_exc()) # raise # # import rophako.jsondb as JsonDB # # # Don't spam too many e-mails in a short time frame. # cache = JsonDB.get_cache("exception_catcher") # if cache: # last_exception = int(cache) # if int(time.time()) - last_exception < 120: # # Only one e-mail per 2 minutes, minimum # logger.error("RAPID EXCEPTIONS, DROPPING") # return # JsonDB.set_cache("exception_catcher", int(time.time())) # # username = "anonymous" # try: # if hasattr(g, "info") and "session" in g.info and "username" in g.info["session"]: # username = g.info["session"]["username"] # except: # pass # # # Get the timestamp. # timestamp = time.ctime(time.time()) # # # Exception's traceback. # error = str(error.__class__.__name__) + ": " + str(error) # stacktrace = error + "\n\n" \ # + "==== Start Traceback ====\n" \ # + traceback.format_exc() \ # + "==== End Traceback ====\n\n" \ # + "Request Information\n" \ # + "-------------------\n" \ # + "Address: " + remote_addr() + "\n" \ # + "User Agent: " + request.user_agent.string + "\n" \ # + "Referrer: " + request.referrer # # # Construct the subject and message # subject = "Internal Server Error on {} - {} - {}".format( # Config.site.site_name, # username, # timestamp, # ) # message = "{} has experienced an exception on the route: {}".format( # username, # request.path, # ) # message += "\n\n" + stacktrace # # # Send the e-mail. # send_email( # to=Config.site.notify_address, # subject=subject, # message=message, # ) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
return
Predict the next line after this snippet: <|code_start|> if value: value = json.loads(value) except: logger.debug("Redis exception: couldn't get_cache {}".format(key)) value = None return value def del_cache(key): """Delete a cached item.""" key = Config.db.redis_prefix + key client = get_redis() if not client: return client.delete(key) def lock_cache(key, timeout=5, expire=20): """Cache level 'file locking' implementation. The `key` will be automatically suffixed with `_lock`. The `timeout` is the max amount of time to wait for a lock. The `expire` is how long a lock may exist before it's considered stale. Returns True on success, None on failure to acquire lock.""" client = get_redis() if not client: return # Take the lock. <|code_end|> using the current file's imports: import codecs import os import os.path import re import redis import json import time from fcntl import flock, LOCK_EX, LOCK_SH, LOCK_UN from rophako.settings import Config from rophako.utils import handle_exception from rophako.log import logger and any relevant context from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/utils.py # def handle_exception(error): # """Send an e-mail to the site admin when an exception occurs.""" # if current_app.config.get("DEBUG"): # print(traceback.format_exc()) # raise # # import rophako.jsondb as JsonDB # # # Don't spam too many e-mails in a short time frame. # cache = JsonDB.get_cache("exception_catcher") # if cache: # last_exception = int(cache) # if int(time.time()) - last_exception < 120: # # Only one e-mail per 2 minutes, minimum # logger.error("RAPID EXCEPTIONS, DROPPING") # return # JsonDB.set_cache("exception_catcher", int(time.time())) # # username = "anonymous" # try: # if hasattr(g, "info") and "session" in g.info and "username" in g.info["session"]: # username = g.info["session"]["username"] # except: # pass # # # Get the timestamp. # timestamp = time.ctime(time.time()) # # # Exception's traceback. # error = str(error.__class__.__name__) + ": " + str(error) # stacktrace = error + "\n\n" \ # + "==== Start Traceback ====\n" \ # + traceback.format_exc() \ # + "==== End Traceback ====\n\n" \ # + "Request Information\n" \ # + "-------------------\n" \ # + "Address: " + remote_addr() + "\n" \ # + "User Agent: " + request.user_agent.string + "\n" \ # + "Referrer: " + request.referrer # # # Construct the subject and message # subject = "Internal Server Error on {} - {} - {}".format( # Config.site.site_name, # username, # timestamp, # ) # message = "{} has experienced an exception on the route: {}".format( # username, # request.path, # ) # message += "\n\n" + stacktrace # # # Send the e-mail. # send_email( # to=Config.site.notify_address, # subject=subject, # message=message, # ) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
lock = client.lock(key, timeout=expire)
Here is a snippet: <|code_start|> return { key: data for key, data in db.items() if data["privacy"] == "private" } def rebuild_index(): """Rebuild the index.json if it goes missing.""" index = {} entries = JsonDB.list_docs("blog/entries") for post_id in entries: db = JsonDB.get("blog/entries/{}".format(post_id)) update_index(post_id, db, index, False) JsonDB.commit("blog/index", index) return index def update_index(post_id, post, index=None, commit=True): """Update a post's meta-data in the index. This is also used for adding a new post to the index for the first time. * post_id: The ID number for the post * post: The DB object for a blog post * index: If you already have the index open, you can pass it here * commit: Write the DB after updating the index (default True)""" if index is None: index = get_index(drafts=True) index[post_id] = dict( <|code_end|> . Write the next line using the current file imports: from flask import g from rophako.settings import Config from rophako.log import logger import time import re import glob import os import sys import rophako.jsondb as JsonDB and context from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): , which may include functions, classes, or code. Output only the next line.
fid = post["fid"],
Based on the snippet: <|code_start|> db = JsonDB.get("blog/index") # Filter out only the draft posts. return { key: data for key, data in db.items() if data["privacy"] == "private" } def rebuild_index(): """Rebuild the index.json if it goes missing.""" index = {} entries = JsonDB.list_docs("blog/entries") for post_id in entries: db = JsonDB.get("blog/entries/{}".format(post_id)) update_index(post_id, db, index, False) JsonDB.commit("blog/index", index) return index def update_index(post_id, post, index=None, commit=True): """Update a post's meta-data in the index. This is also used for adding a new post to the index for the first time. * post_id: The ID number for the post * post: The DB object for a blog post * index: If you already have the index open, you can pass it here * commit: Write the DB after updating the index (default True)""" if index is None: <|code_end|> , predict the immediate next line with the help of imports: from flask import g from rophako.settings import Config from rophako.log import logger import time import re import glob import os import sys import rophako.jsondb as JsonDB and context (classes, functions, sometimes code) from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
index = get_index(drafts=True)
Based on the snippet: <|code_start|> except Exception as e: logger.error("Couldn't load JSON from emoticon file: {}".format(e)) data = {} # Cache and return it. _cache = data return data def render(message): """Render the emoticons into a message. The message should already be stripped of HTML and otherwise be 'safe' to embed on a web page. The output of this function includes `<img>` tags and these won't work otherwise.""" # Get the smileys config. smileys = load_theme() # Process all smileys. for img in sorted(smileys["map"]): for trigger in smileys["map"][img]: if trigger in message: # Substitute it. url = request.url_root.strip("/") \ .replace("http:", "") \ .replace("https:", "") sub = """<img src="{url}" class="rophako-emoticon" alt="{trigger}" title="{trigger}">""".format( url="{}/static/smileys/{}/{}".format(url, Config.emoticons.theme, img), trigger=trigger, <|code_end|> , predict the immediate next line with the help of imports: from flask import request from rophako.settings import Config from rophako.log import logger import os import codecs import json import re and context (classes, functions, sometimes code) from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
)
Based on the snippet: <|code_start|> # Give up. return {} # Read it. fh = codecs.open(settings, "r", "utf-8") text = fh.read() fh.close() try: data = json.loads(text) except Exception as e: logger.error("Couldn't load JSON from emoticon file: {}".format(e)) data = {} # Cache and return it. _cache = data return data def render(message): """Render the emoticons into a message. The message should already be stripped of HTML and otherwise be 'safe' to embed on a web page. The output of this function includes `<img>` tags and these won't work otherwise.""" # Get the smileys config. smileys = load_theme() # Process all smileys. <|code_end|> , predict the immediate next line with the help of imports: from flask import request from rophako.settings import Config from rophako.log import logger import os import codecs import json import re and context (classes, functions, sometimes code) from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
for img in sorted(smileys["map"]):
Given the code snippet: <|code_start|> # Username musn't exist. if exists(username): # The front-end shouldn't let this happen. raise Exception("Can't create username {}: already exists!".format(username)) # Crypt their password. hashedpass = hash_password(password) logger.info("Create user {} with username {}".format(uid, username)) # Create the user file. JsonDB.commit("users/by-id/{}".format(uid), dict( uid=uid, username=username, name=name, picture="", role=role, password=hashedpass, created=time.time(), )) # And their username to ID map. JsonDB.commit("users/by-name/{}".format(username), dict( uid=uid, )) return uid <|code_end|> , generate the next line using the imports in this file: import bcrypt import time import rophako.jsondb as JsonDB import rophako.model.photo as Photo from rophako.settings import Config from rophako.log import logger and context (functions, classes, or occasionally code) from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
def update_user(uid, data):
Given the following code snippet before the placeholder: <|code_start|> if photo: return photo["avatar"] return None def exists(uid=None, username=None): """Query whether a user ID or name exists.""" if uid: return JsonDB.exists("users/by-id/{}".format(uid)) elif username: return JsonDB.exists("users/by-name/{}".format(username.lower())) def hash_password(password): return bcrypt.hashpw(str(password).encode("utf-8"), bcrypt.gensalt(int(Config.security.bcrypt_iterations))).decode("utf-8") def check_auth(username, password): """Check the authentication credentials for the username and password. Returns a boolean true or false. On error, an error is logged.""" # Check if the username exists. if not exists(username=username): logger.error("User authentication failed: username {} not found!".format(username)) return False # Get the user's file. db = get_user(username=username) # Check the password. <|code_end|> , predict the next line using imports from the current file: import bcrypt import time import rophako.jsondb as JsonDB import rophako.model.photo as Photo from rophako.settings import Config from rophako.log import logger and context including class names, function names, and sometimes code from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
test = bcrypt.hashpw(str(password).encode("utf-8"), str(db["password"]).encode("utf-8")).decode("utf-8")
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import parser = argparse.ArgumentParser(description="Rophako") parser.add_argument( "--port", "-p", type=int, help="Port to listen on", default=2006, ) parser.add_argument( <|code_end|> , predict the next line using imports from the current file: import argparse from rophako.app import app from OpenSSL import SSL and context including class names, function names, and sometimes code from other files: # Path: rophako/app.py # BLUEPRINT_PATHS = [] # def before_request(): # def after_request(): # def catchall(path): # def index(): # def catch_exception(error): # def not_found(error): # def forbidden(error): . Output only the next line.
"--key", "-k",
Next line prediction: <|code_start|> """Wiki models.""" def render_page(content): """Render the Markdown content of a Wiki page, and support inter-page linking with [[double braces]]. For simple links, just use the [[Page Name]]. To have a different link text than the page name, use [[Link Text|Page Name]].""" html = render_markdown(content) # Look for [[double brackets]] links = re.findall(r'\[\[(.+?)\]\]', html) for match in links: label = page = match if "|" in match: label, page = match.split("|", 2) # Does the page exist? output = '''<a href="{url}">{label}</a>''' if not JsonDB.exists("wiki/pages/{}".format(page)): output = '''<a href="{url}" class="wiki-broken">{label}</a>''' html = html.replace("[[{}]]".format(match), output.format( url=url_for("wiki.view_page", name=name_to_url(page)), label=label, ) <|code_end|> . Use current file imports: (from flask import url_for from rophako.utils import render_markdown from rophako.log import logger import time import re import hashlib import rophako.jsondb as JsonDB) and context including class names, function names, or small code snippets from other files: # Path: rophako/utils.py # def render_markdown(body, html_escape=True, extensions=None, blacklist=None): # """Render a block of Markdown text. # # This will default to escaping literal HTML characters. Set # `html_escape=False` to trust HTML. # # * extensions should be a set() of extensions to add. # * blacklist should be a set() of extensions to blacklist.""" # # args = dict( # lazy_ol=False, # If a numbered list starts at e.g. 4, show the <ol> there # extensions=[ # "fenced_code", # GitHub style code blocks # "tables", # http://michelf.ca/projects/php-markdown/extra/#table # "smart_strong", # Handles double__underscore better. # "codehilite", # Code highlighting with Pygment! # "nl2br", # Line breaks inside a paragraph become <br> # "sane_lists", # Make lists less surprising # ], # extension_configs={ # "codehilite": { # "linenums": False, # } # } # ) # if html_escape: # args["safe_mode"] = "escape" # # # Additional extensions? # if extensions is not None: # for ext in extensions: # args["extensions"].append(ext) # if blacklist is not None: # for ext in blacklist: # args["extensions"].remove(str(ext)) # # return u'<div class="markdown">{}</div>'.format( # markdown.markdown(body, **args) # ) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import """Wiki models.""" def render_page(content): """Render the Markdown content of a Wiki page, and support inter-page linking with [[double braces]]. For simple links, just use the [[Page Name]]. To have a different link text than the page name, use [[Link Text|Page Name]].""" html = render_markdown(content) # Look for [[double brackets]] links = re.findall(r'\[\[(.+?)\]\]', html) for match in links: label = page = match if "|" in match: label, page = match.split("|", 2) # Does the page exist? output = '''<a href="{url}">{label}</a>''' if not JsonDB.exists("wiki/pages/{}".format(page)): output = '''<a href="{url}" class="wiki-broken">{label}</a>''' html = html.replace("[[{}]]".format(match), output.format( url=url_for("wiki.view_page", name=name_to_url(page)), <|code_end|> . Use current file imports: (from flask import url_for from rophako.utils import render_markdown from rophako.log import logger import time import re import hashlib import rophako.jsondb as JsonDB) and context including class names, function names, or small code snippets from other files: # Path: rophako/utils.py # def render_markdown(body, html_escape=True, extensions=None, blacklist=None): # """Render a block of Markdown text. # # This will default to escaping literal HTML characters. Set # `html_escape=False` to trust HTML. # # * extensions should be a set() of extensions to add. # * blacklist should be a set() of extensions to blacklist.""" # # args = dict( # lazy_ol=False, # If a numbered list starts at e.g. 4, show the <ol> there # extensions=[ # "fenced_code", # GitHub style code blocks # "tables", # http://michelf.ca/projects/php-markdown/extra/#table # "smart_strong", # Handles double__underscore better. # "codehilite", # Code highlighting with Pygment! # "nl2br", # Line breaks inside a paragraph become <br> # "sane_lists", # Make lists less surprising # ], # extension_configs={ # "codehilite": { # "linenums": False, # } # } # ) # if html_escape: # args["safe_mode"] = "escape" # # # Additional extensions? # if extensions is not None: # for ext in extensions: # args["extensions"].append(ext) # if blacklist is not None: # for ext in blacklist: # args["extensions"].remove(str(ext)) # # return u'<div class="markdown">{}</div>'.format( # markdown.markdown(body, **args) # ) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
label=label,
Using the snippet: <|code_start|> ) def rename_album(old_name, new_name): """Rename an existing photo album. Returns True on success, False if the new name conflicts with another album's name.""" old_name = sanitize_name(old_name) new_name = sanitize_name(new_name) index = get_index() # New name is unique? if new_name in index["albums"]: logger.error("Can't rename album: new name already exists!") return False def transfer_key(obj, old_key, new_key): # Reusable function to do a simple move on a dict key. obj[new_key] = obj[old_key] del obj[old_key] # Simple moves. transfer_key(index["albums"], old_name, new_name) transfer_key(index["covers"], old_name, new_name) transfer_key(index["photo-order"], old_name, new_name) transfer_key(index["settings"], old_name, new_name) # Update the photo -> album maps. for photo in index["map"]: <|code_end|> , determine the next line of code. You have imports: import os import time import requests import hashlib import random import rophako.jsondb as JsonDB from flask import g from PIL import Image from rophako.settings import Config from rophako.utils import sanitize_name, remote_addr from rophako.log import logger and context (class names, function names, or code) available: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/utils.py # def sanitize_name(name): # """Sanitize a name that may be used in the filesystem. # # Only allows numbers, letters, and some symbols.""" # return re.sub(r'[^A-Za-z0-9 .\-_]+', '', name) # # def remote_addr(): # """Retrieve the end user's remote IP address. If the site is configured # to honor X-Forwarded-For and this header is present, it's returned.""" # if Config.security.use_forwarded_for: # return request.access_route[0] # return request.remote_addr # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
if index["map"][photo] == old_name:
Using the snippet: <|code_start|> return dict( name=name, format=index["settings"][name]["format"], description=index["settings"][name]["description"], cover=album[cover]["thumb"], ) def rename_album(old_name, new_name): """Rename an existing photo album. Returns True on success, False if the new name conflicts with another album's name.""" old_name = sanitize_name(old_name) new_name = sanitize_name(new_name) index = get_index() # New name is unique? if new_name in index["albums"]: logger.error("Can't rename album: new name already exists!") return False def transfer_key(obj, old_key, new_key): # Reusable function to do a simple move on a dict key. obj[new_key] = obj[old_key] del obj[old_key] # Simple moves. transfer_key(index["albums"], old_name, new_name) <|code_end|> , determine the next line of code. You have imports: import os import time import requests import hashlib import random import rophako.jsondb as JsonDB from flask import g from PIL import Image from rophako.settings import Config from rophako.utils import sanitize_name, remote_addr from rophako.log import logger and context (class names, function names, or code) available: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/utils.py # def sanitize_name(name): # """Sanitize a name that may be used in the filesystem. # # Only allows numbers, letters, and some symbols.""" # return re.sub(r'[^A-Za-z0-9 .\-_]+', '', name) # # def remote_addr(): # """Retrieve the end user's remote IP address. If the site is configured # to honor X-Forwarded-For and this header is present, it's returned.""" # if Config.security.use_forwarded_for: # return request.access_route[0] # return request.remote_addr # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
transfer_key(index["covers"], old_name, new_name)
Given the following code snippet before the placeholder: <|code_start|> def rename_album(old_name, new_name): """Rename an existing photo album. Returns True on success, False if the new name conflicts with another album's name.""" old_name = sanitize_name(old_name) new_name = sanitize_name(new_name) index = get_index() # New name is unique? if new_name in index["albums"]: logger.error("Can't rename album: new name already exists!") return False def transfer_key(obj, old_key, new_key): # Reusable function to do a simple move on a dict key. obj[new_key] = obj[old_key] del obj[old_key] # Simple moves. transfer_key(index["albums"], old_name, new_name) transfer_key(index["covers"], old_name, new_name) transfer_key(index["photo-order"], old_name, new_name) transfer_key(index["settings"], old_name, new_name) # Update the photo -> album maps. for photo in index["map"]: if index["map"][photo] == old_name: <|code_end|> , predict the next line using imports from the current file: import os import time import requests import hashlib import random import rophako.jsondb as JsonDB from flask import g from PIL import Image from rophako.settings import Config from rophako.utils import sanitize_name, remote_addr from rophako.log import logger and context including class names, function names, and sometimes code from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/utils.py # def sanitize_name(name): # """Sanitize a name that may be used in the filesystem. # # Only allows numbers, letters, and some symbols.""" # return re.sub(r'[^A-Za-z0-9 .\-_]+', '', name) # # def remote_addr(): # """Retrieve the end user's remote IP address. If the site is configured # to honor X-Forwarded-For and this header is present, it's returned.""" # if Config.security.use_forwarded_for: # return request.access_route[0] # return request.remote_addr # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
index["map"][photo] = new_name
Predict the next line after this snippet: <|code_start|> index = get_index() if not name in index["albums"]: return None album = index["albums"][name] cover = index["covers"][name] return dict( name=name, format=index["settings"][name]["format"], description=index["settings"][name]["description"], cover=album[cover]["thumb"], ) def rename_album(old_name, new_name): """Rename an existing photo album. Returns True on success, False if the new name conflicts with another album's name.""" old_name = sanitize_name(old_name) new_name = sanitize_name(new_name) index = get_index() # New name is unique? if new_name in index["albums"]: logger.error("Can't rename album: new name already exists!") return False <|code_end|> using the current file's imports: import os import time import requests import hashlib import random import rophako.jsondb as JsonDB from flask import g from PIL import Image from rophako.settings import Config from rophako.utils import sanitize_name, remote_addr from rophako.log import logger and any relevant context from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/utils.py # def sanitize_name(name): # """Sanitize a name that may be used in the filesystem. # # Only allows numbers, letters, and some symbols.""" # return re.sub(r'[^A-Za-z0-9 .\-_]+', '', name) # # def remote_addr(): # """Retrieve the end user's remote IP address. If the site is configured # to honor X-Forwarded-For and this header is present, it's returned.""" # if Config.security.use_forwarded_for: # return request.access_route[0] # return request.remote_addr # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
def transfer_key(obj, old_key, new_key):
Based on the snippet: <|code_start|> # Refresh their login status from the DB. if session["login"]: if not User.exists(uid=session["uid"]): # Weird! Log them out. logout() return db = User.get_user(uid=session["uid"]) session["username"] = db["username"] session["name"] = db["name"] session["role"] = db["role"] # Copy session params into g.info. The only people who should touch the # session are the login/out pages. for key in session: g.info["session"][key] = session[key] @app.context_processor def after_request(): """Called just before render_template. Inject g.info into the template vars.""" return g.info @app.route("/<path:path>") def catchall(path): """The catch-all path handler. If it exists in the www folders, it's sent, otherwise we give the 404 error page.""" <|code_end|> , predict the immediate next line with the help of imports: from flask import (Flask, g, request, session, render_template, send_file, abort, redirect) from flask_sslify import SSLify from flask_compress import Compress from rophako.settings import Config from rophako.plugin import load_plugin from rophako.log import logger from rophako.modules.account import logout import jinja2 import os.path import datetime import sys import rophako.utils import rophako.model.emoticons as Emoticons import rophako.model.user as User and context (classes, functions, sometimes code) from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/plugin.py # def load_plugin(name, as_blueprint=True, template_path=None): # """Load a Rophako CMS plugin. # # * `name` is a Python module name, i.e. `rophako.modules.blog` # * `as_blueprint` is True if the module exports a blueprint object called # `mod` that can be attached to the Flask app. Set this value to False if # you simply need to include a Python module that isn't a blueprint. # * `template_path` is a filesystem path where the blueprint's templates # can be found. If not provided, the path is automatically determined # based on the module name, which is suitable for the built-in plugins.""" # from rophako.app import app, BLUEPRINT_PATHS # module = import_module(name) # if as_blueprint: # mod = getattr(module, "mod") # app.register_blueprint(mod) # # # Get the template path to add to the BLUEPRINT_PATHS. # if template_path is None: # module_path = name.replace(".", "/") # template_path = os.path.join(module_path, "templates") # # BLUEPRINT_PATHS.append(template_path) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
if path.endswith("/"):
Next line prediction: <|code_start|> @app.context_processor def after_request(): """Called just before render_template. Inject g.info into the template vars.""" return g.info @app.route("/<path:path>") def catchall(path): """The catch-all path handler. If it exists in the www folders, it's sent, otherwise we give the 404 error page.""" if path.endswith("/"): path = path.strip("/") # Remove trailing slashes. return redirect(path) # Search for this file. for root in [Config.site.site_root, "rophako/www"]: abspath = os.path.abspath("{}/{}".format(root, path)) if os.path.isfile(abspath): return send_file(abspath) # The exact file wasn't found, look for some extensions and index pages. suffixes = [ ".html", "/index.html", ".md", # Markdown formatted pages. "/index.md", ] for suffix in suffixes: <|code_end|> . Use current file imports: (from flask import (Flask, g, request, session, render_template, send_file, abort, redirect) from flask_sslify import SSLify from flask_compress import Compress from rophako.settings import Config from rophako.plugin import load_plugin from rophako.log import logger from rophako.modules.account import logout import jinja2 import os.path import datetime import sys import rophako.utils import rophako.model.emoticons as Emoticons import rophako.model.user as User) and context including class names, function names, or small code snippets from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/plugin.py # def load_plugin(name, as_blueprint=True, template_path=None): # """Load a Rophako CMS plugin. # # * `name` is a Python module name, i.e. `rophako.modules.blog` # * `as_blueprint` is True if the module exports a blueprint object called # `mod` that can be attached to the Flask app. Set this value to False if # you simply need to include a Python module that isn't a blueprint. # * `template_path` is a filesystem path where the blueprint's templates # can be found. If not provided, the path is automatically determined # based on the module name, which is suitable for the built-in plugins.""" # from rophako.app import app, BLUEPRINT_PATHS # module = import_module(name) # if as_blueprint: # mod = getattr(module, "mod") # app.register_blueprint(mod) # # # Get the template path to add to the BLUEPRINT_PATHS. # if template_path is None: # module_path = name.replace(".", "/") # template_path = os.path.join(module_path, "templates") # # BLUEPRINT_PATHS.append(template_path) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
if not "." in path and os.path.isfile(abspath + suffix):
Next line prediction: <|code_start|> if session["login"]: if not User.exists(uid=session["uid"]): # Weird! Log them out. logout() return db = User.get_user(uid=session["uid"]) session["username"] = db["username"] session["name"] = db["name"] session["role"] = db["role"] # Copy session params into g.info. The only people who should touch the # session are the login/out pages. for key in session: g.info["session"][key] = session[key] @app.context_processor def after_request(): """Called just before render_template. Inject g.info into the template vars.""" return g.info @app.route("/<path:path>") def catchall(path): """The catch-all path handler. If it exists in the www folders, it's sent, otherwise we give the 404 error page.""" if path.endswith("/"): path = path.strip("/") # Remove trailing slashes. <|code_end|> . Use current file imports: (from flask import (Flask, g, request, session, render_template, send_file, abort, redirect) from flask_sslify import SSLify from flask_compress import Compress from rophako.settings import Config from rophako.plugin import load_plugin from rophako.log import logger from rophako.modules.account import logout import jinja2 import os.path import datetime import sys import rophako.utils import rophako.model.emoticons as Emoticons import rophako.model.user as User) and context including class names, function names, or small code snippets from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/plugin.py # def load_plugin(name, as_blueprint=True, template_path=None): # """Load a Rophako CMS plugin. # # * `name` is a Python module name, i.e. `rophako.modules.blog` # * `as_blueprint` is True if the module exports a blueprint object called # `mod` that can be attached to the Flask app. Set this value to False if # you simply need to include a Python module that isn't a blueprint. # * `template_path` is a filesystem path where the blueprint's templates # can be found. If not provided, the path is automatically determined # based on the module name, which is suitable for the built-in plugins.""" # from rophako.app import app, BLUEPRINT_PATHS # module = import_module(name) # if as_blueprint: # mod = getattr(module, "mod") # app.register_blueprint(mod) # # # Get the template path to add to the BLUEPRINT_PATHS. # if template_path is None: # module_path = name.replace(".", "/") # template_path = os.path.join(module_path, "templates") # # BLUEPRINT_PATHS.append(template_path) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
return redirect(path)
Given the code snippet: <|code_start|> def count_comments(thread): """Count the comments on a thread.""" comments = get_comments(thread) return len(comments.keys()) def add_subscriber(thread, email): """Add a subscriber to a thread.""" if not "@" in email: return # Sanity check: only subscribe to threads that exist. if not JsonDB.exists("comments/threads/{}".format(thread)): return logger.info("Subscribe e-mail {} to thread {}".format(email, thread)) subs = get_subscribers(thread) subs[email] = int(time.time()) write_subscribers(thread, subs) def unsubscribe(thread, email): """Unsubscribe an e-mail address from a thread. If `thread` is `*`, the e-mail is unsubscribed from all threads.""" # Which threads to unsubscribe from? threads = [] if thread == "*": <|code_end|> , generate the next line using the imports in this file: from flask import url_for, session from itsdangerous import URLSafeSerializer from rophako.settings import Config from rophako.utils import send_email, render_markdown from rophako.log import logger import time import hashlib import urllib import random import sys import uuid import rophako.jsondb as JsonDB import rophako.model.user as User import rophako.model.emoticons as Emoticons and context (functions, classes, or occasionally code) from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/utils.py # def send_email(to, subject, message, header=None, footer=None, sender=None, # reply_to=None): # """Send a (markdown-formatted) e-mail out. # # This will deliver an HTML-formatted e-mail (using the ``email.inc.html`` # template) using the rendered Markdown contents of ``message`` and # ``footer``. It will also send a plain text version using the raw Markdown # formatting in case the user can't accept HTML. # # Parameters: # to ([]str): list of addresses to send the message to. # subject (str): email subject and title. # message (str): the email body, in Markdown format. # header (str): the header text for the HTML email (plain text). # footer (str): optional email footer, in Markdown format. The default # footer is defined in the ``email.inc.html`` template. # sender (str): optional sender email address. Defaults to the one # specified in the site configuration. # reply_to (str): optional Reply-To address header. # """ # if sender is None: # sender = Config.mail.sender # # if type(to) != list: # to = [to] # # # Render the Markdown bits. # if footer: # footer = render_markdown(footer) # # # Default header matches the subject. # if not header: # header = subject # # html_message = render_template("email.inc.html", # title=subject, # header=header, # message=render_markdown(message), # footer=footer, # ) # # logger.info("Send email to {}".format(to)) # if Config.mail.method == "smtp": # # Send mail with SMTP. # for email in to: # msg = MIMEMultipart("alternative") # msg.set_charset("utf-8") # # msg["Subject"] = subject # msg["From"] = sender # msg["To"] = email # if reply_to is not None: # msg["Reply-To"] = reply_to # # text = MIMEText(message, "plain", "utf-8") # msg.attach(text) # # html = MIMEText(html_message, "html", "utf-8") # msg.attach(html) # # # Send the e-mail. # try: # server = smtplib.SMTP(Config.mail.server, Config.mail.port) # server.sendmail(sender, [email], msg.as_string()) # except: # pass # # def render_markdown(body, html_escape=True, extensions=None, blacklist=None): # """Render a block of Markdown text. # # This will default to escaping literal HTML characters. Set # `html_escape=False` to trust HTML. # # * extensions should be a set() of extensions to add. # * blacklist should be a set() of extensions to blacklist.""" # # args = dict( # lazy_ol=False, # If a numbered list starts at e.g. 4, show the <ol> there # extensions=[ # "fenced_code", # GitHub style code blocks # "tables", # http://michelf.ca/projects/php-markdown/extra/#table # "smart_strong", # Handles double__underscore better. # "codehilite", # Code highlighting with Pygment! # "nl2br", # Line breaks inside a paragraph become <br> # "sane_lists", # Make lists less surprising # ], # extension_configs={ # "codehilite": { # "linenums": False, # } # } # ) # if html_escape: # args["safe_mode"] = "escape" # # # Additional extensions? # if extensions is not None: # for ext in extensions: # args["extensions"].append(ext) # if blacklist is not None: # for ext in blacklist: # args["extensions"].remove(str(ext)) # # return u'<div class="markdown">{}</div>'.format( # markdown.markdown(body, **args) # ) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
threads = JsonDB.list_docs("comments/subscribers")
Based on the snippet: <|code_start|> if not "@" in email: return # Sanity check: only subscribe to threads that exist. if not JsonDB.exists("comments/threads/{}".format(thread)): return logger.info("Subscribe e-mail {} to thread {}".format(email, thread)) subs = get_subscribers(thread) subs[email] = int(time.time()) write_subscribers(thread, subs) def unsubscribe(thread, email): """Unsubscribe an e-mail address from a thread. If `thread` is `*`, the e-mail is unsubscribed from all threads.""" # Which threads to unsubscribe from? threads = [] if thread == "*": threads = JsonDB.list_docs("comments/subscribers") else: threads = [thread] # Remove them as a subscriber. for thread in threads: if JsonDB.exists("comments/subscribers/{}".format(thread)): logger.info("Unsubscribe e-mail address {} from comment thread {}".format(email, thread)) db = get_subscribers(thread) <|code_end|> , predict the immediate next line with the help of imports: from flask import url_for, session from itsdangerous import URLSafeSerializer from rophako.settings import Config from rophako.utils import send_email, render_markdown from rophako.log import logger import time import hashlib import urllib import random import sys import uuid import rophako.jsondb as JsonDB import rophako.model.user as User import rophako.model.emoticons as Emoticons and context (classes, functions, sometimes code) from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/utils.py # def send_email(to, subject, message, header=None, footer=None, sender=None, # reply_to=None): # """Send a (markdown-formatted) e-mail out. # # This will deliver an HTML-formatted e-mail (using the ``email.inc.html`` # template) using the rendered Markdown contents of ``message`` and # ``footer``. It will also send a plain text version using the raw Markdown # formatting in case the user can't accept HTML. # # Parameters: # to ([]str): list of addresses to send the message to. # subject (str): email subject and title. # message (str): the email body, in Markdown format. # header (str): the header text for the HTML email (plain text). # footer (str): optional email footer, in Markdown format. The default # footer is defined in the ``email.inc.html`` template. # sender (str): optional sender email address. Defaults to the one # specified in the site configuration. # reply_to (str): optional Reply-To address header. # """ # if sender is None: # sender = Config.mail.sender # # if type(to) != list: # to = [to] # # # Render the Markdown bits. # if footer: # footer = render_markdown(footer) # # # Default header matches the subject. # if not header: # header = subject # # html_message = render_template("email.inc.html", # title=subject, # header=header, # message=render_markdown(message), # footer=footer, # ) # # logger.info("Send email to {}".format(to)) # if Config.mail.method == "smtp": # # Send mail with SMTP. # for email in to: # msg = MIMEMultipart("alternative") # msg.set_charset("utf-8") # # msg["Subject"] = subject # msg["From"] = sender # msg["To"] = email # if reply_to is not None: # msg["Reply-To"] = reply_to # # text = MIMEText(message, "plain", "utf-8") # msg.attach(text) # # html = MIMEText(html_message, "html", "utf-8") # msg.attach(html) # # # Send the e-mail. # try: # server = smtplib.SMTP(Config.mail.server, Config.mail.port) # server.sendmail(sender, [email], msg.as_string()) # except: # pass # # def render_markdown(body, html_escape=True, extensions=None, blacklist=None): # """Render a block of Markdown text. # # This will default to escaping literal HTML characters. Set # `html_escape=False` to trust HTML. # # * extensions should be a set() of extensions to add. # * blacklist should be a set() of extensions to blacklist.""" # # args = dict( # lazy_ol=False, # If a numbered list starts at e.g. 4, show the <ol> there # extensions=[ # "fenced_code", # GitHub style code blocks # "tables", # http://michelf.ca/projects/php-markdown/extra/#table # "smart_strong", # Handles double__underscore better. # "codehilite", # Code highlighting with Pygment! # "nl2br", # Line breaks inside a paragraph become <br> # "sane_lists", # Make lists less surprising # ], # extension_configs={ # "codehilite": { # "linenums": False, # } # } # ) # if html_escape: # args["safe_mode"] = "escape" # # # Additional extensions? # if extensions is not None: # for ext in extensions: # args["extensions"].append(ext) # if blacklist is not None: # for ext in blacklist: # args["extensions"].remove(str(ext)) # # return u'<div class="markdown">{}</div>'.format( # markdown.markdown(body, **args) # ) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
del db[email]
Here is a snippet: <|code_start|> """Count the comments on a thread.""" comments = get_comments(thread) return len(comments.keys()) def add_subscriber(thread, email): """Add a subscriber to a thread.""" if not "@" in email: return # Sanity check: only subscribe to threads that exist. if not JsonDB.exists("comments/threads/{}".format(thread)): return logger.info("Subscribe e-mail {} to thread {}".format(email, thread)) subs = get_subscribers(thread) subs[email] = int(time.time()) write_subscribers(thread, subs) def unsubscribe(thread, email): """Unsubscribe an e-mail address from a thread. If `thread` is `*`, the e-mail is unsubscribed from all threads.""" # Which threads to unsubscribe from? threads = [] if thread == "*": threads = JsonDB.list_docs("comments/subscribers") else: <|code_end|> . Write the next line using the current file imports: from flask import url_for, session from itsdangerous import URLSafeSerializer from rophako.settings import Config from rophako.utils import send_email, render_markdown from rophako.log import logger import time import hashlib import urllib import random import sys import uuid import rophako.jsondb as JsonDB import rophako.model.user as User import rophako.model.emoticons as Emoticons and context from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/utils.py # def send_email(to, subject, message, header=None, footer=None, sender=None, # reply_to=None): # """Send a (markdown-formatted) e-mail out. # # This will deliver an HTML-formatted e-mail (using the ``email.inc.html`` # template) using the rendered Markdown contents of ``message`` and # ``footer``. It will also send a plain text version using the raw Markdown # formatting in case the user can't accept HTML. # # Parameters: # to ([]str): list of addresses to send the message to. # subject (str): email subject and title. # message (str): the email body, in Markdown format. # header (str): the header text for the HTML email (plain text). # footer (str): optional email footer, in Markdown format. The default # footer is defined in the ``email.inc.html`` template. # sender (str): optional sender email address. Defaults to the one # specified in the site configuration. # reply_to (str): optional Reply-To address header. # """ # if sender is None: # sender = Config.mail.sender # # if type(to) != list: # to = [to] # # # Render the Markdown bits. # if footer: # footer = render_markdown(footer) # # # Default header matches the subject. # if not header: # header = subject # # html_message = render_template("email.inc.html", # title=subject, # header=header, # message=render_markdown(message), # footer=footer, # ) # # logger.info("Send email to {}".format(to)) # if Config.mail.method == "smtp": # # Send mail with SMTP. # for email in to: # msg = MIMEMultipart("alternative") # msg.set_charset("utf-8") # # msg["Subject"] = subject # msg["From"] = sender # msg["To"] = email # if reply_to is not None: # msg["Reply-To"] = reply_to # # text = MIMEText(message, "plain", "utf-8") # msg.attach(text) # # html = MIMEText(html_message, "html", "utf-8") # msg.attach(html) # # # Send the e-mail. # try: # server = smtplib.SMTP(Config.mail.server, Config.mail.port) # server.sendmail(sender, [email], msg.as_string()) # except: # pass # # def render_markdown(body, html_escape=True, extensions=None, blacklist=None): # """Render a block of Markdown text. # # This will default to escaping literal HTML characters. Set # `html_escape=False` to trust HTML. # # * extensions should be a set() of extensions to add. # * blacklist should be a set() of extensions to blacklist.""" # # args = dict( # lazy_ol=False, # If a numbered list starts at e.g. 4, show the <ol> there # extensions=[ # "fenced_code", # GitHub style code blocks # "tables", # http://michelf.ca/projects/php-markdown/extra/#table # "smart_strong", # Handles double__underscore better. # "codehilite", # Code highlighting with Pygment! # "nl2br", # Line breaks inside a paragraph become <br> # "sane_lists", # Make lists less surprising # ], # extension_configs={ # "codehilite": { # "linenums": False, # } # } # ) # if html_escape: # args["safe_mode"] = "escape" # # # Additional extensions? # if extensions is not None: # for ext in extensions: # args["extensions"].append(ext) # if blacklist is not None: # for ext in blacklist: # args["extensions"].remove(str(ext)) # # return u'<div class="markdown">{}</div>'.format( # markdown.markdown(body, **args) # ) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): , which may include functions, classes, or code. Output only the next line.
threads = [thread]
Given the following code snippet before the placeholder: <|code_start|> return # Sanity check: only subscribe to threads that exist. if not JsonDB.exists("comments/threads/{}".format(thread)): return logger.info("Subscribe e-mail {} to thread {}".format(email, thread)) subs = get_subscribers(thread) subs[email] = int(time.time()) write_subscribers(thread, subs) def unsubscribe(thread, email): """Unsubscribe an e-mail address from a thread. If `thread` is `*`, the e-mail is unsubscribed from all threads.""" # Which threads to unsubscribe from? threads = [] if thread == "*": threads = JsonDB.list_docs("comments/subscribers") else: threads = [thread] # Remove them as a subscriber. for thread in threads: if JsonDB.exists("comments/subscribers/{}".format(thread)): logger.info("Unsubscribe e-mail address {} from comment thread {}".format(email, thread)) db = get_subscribers(thread) del db[email] <|code_end|> , predict the next line using imports from the current file: from flask import url_for, session from itsdangerous import URLSafeSerializer from rophako.settings import Config from rophako.utils import send_email, render_markdown from rophako.log import logger import time import hashlib import urllib import random import sys import uuid import rophako.jsondb as JsonDB import rophako.model.user as User import rophako.model.emoticons as Emoticons and context including class names, function names, and sometimes code from other files: # Path: rophako/settings.py # class ConfigHandler(object): # def load_settings(self): # def print_settings(self): # def load_plugins(self): # def __getattr__(self, section): # # Path: rophako/utils.py # def send_email(to, subject, message, header=None, footer=None, sender=None, # reply_to=None): # """Send a (markdown-formatted) e-mail out. # # This will deliver an HTML-formatted e-mail (using the ``email.inc.html`` # template) using the rendered Markdown contents of ``message`` and # ``footer``. It will also send a plain text version using the raw Markdown # formatting in case the user can't accept HTML. # # Parameters: # to ([]str): list of addresses to send the message to. # subject (str): email subject and title. # message (str): the email body, in Markdown format. # header (str): the header text for the HTML email (plain text). # footer (str): optional email footer, in Markdown format. The default # footer is defined in the ``email.inc.html`` template. # sender (str): optional sender email address. Defaults to the one # specified in the site configuration. # reply_to (str): optional Reply-To address header. # """ # if sender is None: # sender = Config.mail.sender # # if type(to) != list: # to = [to] # # # Render the Markdown bits. # if footer: # footer = render_markdown(footer) # # # Default header matches the subject. # if not header: # header = subject # # html_message = render_template("email.inc.html", # title=subject, # header=header, # message=render_markdown(message), # footer=footer, # ) # # logger.info("Send email to {}".format(to)) # if Config.mail.method == "smtp": # # Send mail with SMTP. # for email in to: # msg = MIMEMultipart("alternative") # msg.set_charset("utf-8") # # msg["Subject"] = subject # msg["From"] = sender # msg["To"] = email # if reply_to is not None: # msg["Reply-To"] = reply_to # # text = MIMEText(message, "plain", "utf-8") # msg.attach(text) # # html = MIMEText(html_message, "html", "utf-8") # msg.attach(html) # # # Send the e-mail. # try: # server = smtplib.SMTP(Config.mail.server, Config.mail.port) # server.sendmail(sender, [email], msg.as_string()) # except: # pass # # def render_markdown(body, html_escape=True, extensions=None, blacklist=None): # """Render a block of Markdown text. # # This will default to escaping literal HTML characters. Set # `html_escape=False` to trust HTML. # # * extensions should be a set() of extensions to add. # * blacklist should be a set() of extensions to blacklist.""" # # args = dict( # lazy_ol=False, # If a numbered list starts at e.g. 4, show the <ol> there # extensions=[ # "fenced_code", # GitHub style code blocks # "tables", # http://michelf.ca/projects/php-markdown/extra/#table # "smart_strong", # Handles double__underscore better. # "codehilite", # Code highlighting with Pygment! # "nl2br", # Line breaks inside a paragraph become <br> # "sane_lists", # Make lists less surprising # ], # extension_configs={ # "codehilite": { # "linenums": False, # } # } # ) # if html_escape: # args["safe_mode"] = "escape" # # # Additional extensions? # if extensions is not None: # for ext in extensions: # args["extensions"].append(ext) # if blacklist is not None: # for ext in blacklist: # args["extensions"].remove(str(ext)) # # return u'<div class="markdown">{}</div>'.format( # markdown.markdown(body, **args) # ) # # Path: rophako/log.py # class LogHandler(logging.Handler): # def emit(self, record): . Output only the next line.
write_subscribers(thread, db)
Given snippet: <|code_start|>#!/usr/bin/env python3 logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) class GenotypeTestCase(unittest.TestCase): def setUp(self): self.graph = RDFGraph() self.curie_map = curie_map.get() self.genotype = Genotype(self.graph) self.cutil = CurieUtil(self.curie_map) self.test_cat_pred = self.cutil.get_uri(blv.terms['category']) self.test_cat_genotype_category = self.cutil.get_uri(blv.terms['Genotype']) self.test_cat_background_category = self.cutil.get_uri( blv.terms['PopulationOfIndividualOrganisms']) def tearDown(self): self.genotype = None def test_addGenotype(self): cutil = CurieUtil(self.curie_map) gid = 'MGI:5515892' label = \ 'Pmp22<Tr-2J>/Pmp22<+> [C57BL/6J-Pmp22<Tr-2J>/GrsrJ]' self.genotype.addGenotype(gid, label) self.assertTrue( (URIRef(cutil.get_uri(gid)), RDFS['label'], <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest import logging from rdflib.namespace import RDFS, URIRef from rdflib import Literal from dipper import curie_map from dipper.models.Genotype import Genotype from dipper.graph.RDFGraph import RDFGraph from dipper.utils.CurieUtil import CurieUtil from dipper.models.BiolinkVocabulary import BioLinkVocabulary as blv and context: # Path: dipper/curie_map.py # LOG = logging.getLogger(__name__) # def get(): # def get_base(): which might include code, classes, or functions. Output only the next line.
Literal(label)) in self.genotype.graph)
Given the code snippet: <|code_start|> (phenotyping_center, colony) = self.test_set_1[2:4] (project_name, project_fullname, pipeline_name, pipeline_stable_id, procedure_stable_id, procedure_name, parameter_stable_id, parameter_name) = self.test_set_1[11:19] (statistical_method, resource_name) = self.test_set_1[26:28] impc._add_study_provenance( phenotyping_center, colony, project_name, pipeline_name, pipeline_stable_id, procedure_stable_id, procedure_name, parameter_stable_id, parameter_name, statistical_method, resource_name) # dbg LOG.info( "Provenance graph as turtle:\n%s\n", impc.graph.serialize(format="turtle").decode("utf-8") ) triples = """ <https://monarchinitiative.org/.well-known/genid/b0b26361b8687b5ad9ef> a owl:NamedIndividual ; rdfs:label "MEFW" . <|code_end|> , generate the next line using the imports in this file: import unittest import logging import csv import gzip from dipper.sources.IMPC import IMPC from dipper.utils.CurieUtil import CurieUtil from dipper.utils.TestUtils import TestUtils from dipper import curie_map from dipper.graph.RDFGraph import RDFGraph, URIRef and context (functions, classes, or occasionally code) from other files: # Path: dipper/sources/IMPC.py # IMPC = 'ftp://ftp.ebi.ac.uk/pub/databases/impc' # # Path: dipper/curie_map.py # LOG = logging.getLogger(__name__) # def get(): # def get_base(): . Output only the next line.
<https://monarchinitiative.org/.well-known/genid/b6f14f763c8d0629360e> a OBI:0000471 ;
Continue the code snippet: <|code_start|># # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import unicode_literals try: except ImportError: SKIP_VALUES = ("", None) EXPAND__TO_DOT = True DOC_META_FIELDS = frozenset( ( "id", "routing", ) ) META_FIELDS = frozenset( ( # Elasticsearch metadata fields, except 'type' "index", <|code_end|> . Use current file imports: import collections.abc as collections_abc # only works on python 3.3+ import collections as collections_abc from copy import copy from six import add_metaclass, iteritems from six.moves import map from .exceptions import UnknownDslObject, ValidationException and context (classes, functions, or code) from other files: # Path: elasticsearch_dsl/exceptions.py # class UnknownDslObject(ElasticsearchDslException): # pass # # class ValidationException(ValueError, ElasticsearchDslException): # pass . Output only the next line.
"using",
Predict the next line for this snippet: <|code_start|># Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from __future__ import unicode_literals try: except ImportError: SKIP_VALUES = ("", None) EXPAND__TO_DOT = True DOC_META_FIELDS = frozenset( ( "id", "routing", ) ) META_FIELDS = frozenset( ( # Elasticsearch metadata fields, except 'type' "index", "using", <|code_end|> with the help of current file imports: import collections.abc as collections_abc # only works on python 3.3+ import collections as collections_abc from copy import copy from six import add_metaclass, iteritems from six.moves import map from .exceptions import UnknownDslObject, ValidationException and context from other files: # Path: elasticsearch_dsl/exceptions.py # class UnknownDslObject(ElasticsearchDslException): # pass # # class ValidationException(ValueError, ElasticsearchDslException): # pass , which may contain function names, class names, or code. Output only the next line.
"score",
Here is a snippet: <|code_start|> n = analysis.CustomNormalizer( "my_normalizer", filter=["lowercase", "asciifolding"], char_filter=["quote"] ) assert { "type": "custom", "filter": ["lowercase", "asciifolding"], "char_filter": ["quote"], } == n.get_definition() def test_tokenizer(): t = analysis.tokenizer("trigram", "nGram", min_gram=3, max_gram=3) assert t.to_dict() == "trigram" assert {"type": "nGram", "min_gram": 3, "max_gram": 3} == t.get_definition() def test_custom_analyzer_can_collect_custom_items(): trigram = analysis.tokenizer("trigram", "nGram", min_gram=3, max_gram=3) my_stop = analysis.token_filter("my_stop", "stop", stopwords=["a", "b"]) umlauts = analysis.char_filter("umlauts", "pattern_replace", mappings=["ü=>ue"]) a = analysis.analyzer( "my_analyzer", tokenizer=trigram, filter=["lowercase", my_stop], char_filter=["html_strip", umlauts], ) assert a.to_dict() == "my_analyzer" <|code_end|> . Write the next line using the current file imports: from pytest import raises from elasticsearch_dsl import analysis and context from other files: # Path: elasticsearch_dsl/analysis.py # class AnalysisBase(object): # class CustomAnalysis(object): # class CustomAnalysisDefinition(CustomAnalysis): # class BuiltinAnalysis(object): # class Analyzer(AnalysisBase, DslBase): # class BuiltinAnalyzer(BuiltinAnalysis, Analyzer): # class CustomAnalyzer(CustomAnalysisDefinition, Analyzer): # class Normalizer(AnalysisBase, DslBase): # class BuiltinNormalizer(BuiltinAnalysis, Normalizer): # class CustomNormalizer(CustomAnalysisDefinition, Normalizer): # class Tokenizer(AnalysisBase, DslBase): # class BuiltinTokenizer(BuiltinAnalysis, Tokenizer): # class CustomTokenizer(CustomAnalysis, Tokenizer): # class TokenFilter(AnalysisBase, DslBase): # class BuiltinTokenFilter(BuiltinAnalysis, TokenFilter): # class CustomTokenFilter(CustomAnalysis, TokenFilter): # class MultiplexerTokenFilter(CustomTokenFilter): # class ConditionalTokenFilter(CustomTokenFilter): # class CharFilter(AnalysisBase, DslBase): # class BuiltinCharFilter(BuiltinAnalysis, CharFilter): # class CustomCharFilter(CustomAnalysis, CharFilter): # def _type_shortcut(cls, name_or_instance, type=None, **kwargs): # def __init__(self, filter_name, builtin_type="custom", **kwargs): # def to_dict(self): # def get_definition(self): # def get_analysis_definition(self): # def __init__(self, name): # def to_dict(self): # def get_analysis_definition(self): # def simulate(self, text, using="default", explain=False, attributes=None): # def get_analysis_definition(self): # def get_definition(self): # def get_analysis_definition(self): # def get_definition(self): # def get_analysis_definition(self): , which may include functions, classes, or code. Output only the next line.
assert {
Given snippet: <|code_start|># Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. class AttrJSONSerializer(JSONSerializer): def default(self, data): if isinstance(data, AttrList): return data._l_ if hasattr(data, "to_dict"): return data.to_dict() <|code_end|> , continue by predicting the next line. Consider current file imports: from elasticsearch.serializer import JSONSerializer from .utils import AttrList and context: # Path: elasticsearch_dsl/utils.py # class AttrList(object): # def __init__(self, l, obj_wrapper=None): # # make iterables into lists # if not isinstance(l, list): # l = list(l) # self._l_ = l # self._obj_wrapper = obj_wrapper # # def __repr__(self): # return repr(self._l_) # # def __eq__(self, other): # if isinstance(other, AttrList): # return other._l_ == self._l_ # # make sure we still equal to a dict with the same data # return other == self._l_ # # def __ne__(self, other): # return not self == other # # def __getitem__(self, k): # l = self._l_[k] # if isinstance(k, slice): # return AttrList(l, obj_wrapper=self._obj_wrapper) # return _wrap(l, self._obj_wrapper) # # def __setitem__(self, k, value): # self._l_[k] = value # # def __iter__(self): # return map(lambda i: _wrap(i, self._obj_wrapper), self._l_) # # def __len__(self): # return len(self._l_) # # def __nonzero__(self): # return bool(self._l_) # # __bool__ = __nonzero__ # # def __getattr__(self, name): # return getattr(self._l_, name) # # def __getstate__(self): # return self._l_, self._obj_wrapper # # def __setstate__(self, state): # self._l_, self._obj_wrapper = state which might include code, classes, or functions. Output only the next line.
return super(AttrJSONSerializer, self).default(data)
Continue the code snippet: <|code_start|># KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. class Hit(AttrDict): def __init__(self, document): data = {} if "_source" in document: data = document["_source"] if "fields" in document: data.update(document["fields"]) super(Hit, self).__init__(data) # assign meta as attribute and not as key in self._d_ super(AttrDict, self).__setattr__("meta", HitMeta(document)) def __getstate__(self): # add self.meta since it is not in self.__dict__ return super(Hit, self).__getstate__() + (self.meta,) def __setstate__(self, state): super(AttrDict, self).__setattr__("meta", state[-1]) super(Hit, self).__setstate__(state[:-1]) def __dir__(self): # be sure to expose meta in dir(self) return super(Hit, self).__dir__() + ["meta"] <|code_end|> . Use current file imports: from ..utils import AttrDict, HitMeta and context (classes, functions, or code) from other files: # Path: elasticsearch_dsl/utils.py # class AttrDict(object): # """ # Helper class to provide attribute like access (read and write) to # dictionaries. Used to provide a convenient way to access both results and # nested dsl dicts. # """ # # def __init__(self, d): # # assign the inner dict manually to prevent __setattr__ from firing # super(AttrDict, self).__setattr__("_d_", d) # # def __contains__(self, key): # return key in self._d_ # # def __nonzero__(self): # return bool(self._d_) # # __bool__ = __nonzero__ # # def __dir__(self): # # introspection for auto-complete in IPython etc # return list(self._d_.keys()) # # def __eq__(self, other): # if isinstance(other, AttrDict): # return other._d_ == self._d_ # # make sure we still equal to a dict with the same data # return other == self._d_ # # def __ne__(self, other): # return not self == other # # def __repr__(self): # r = repr(self._d_) # if len(r) > 60: # r = r[:60] + "...}" # return r # # def __getstate__(self): # return (self._d_,) # # def __setstate__(self, state): # super(AttrDict, self).__setattr__("_d_", state[0]) # # def __getattr__(self, attr_name): # try: # return self.__getitem__(attr_name) # except KeyError: # raise AttributeError( # "{!r} object has no attribute {!r}".format( # self.__class__.__name__, attr_name # ) # ) # # def __delattr__(self, attr_name): # try: # del self._d_[attr_name] # except KeyError: # raise AttributeError( # "{!r} object has no attribute {!r}".format( # self.__class__.__name__, attr_name # ) # ) # # def __getitem__(self, key): # return _wrap(self._d_[key]) # # def __setitem__(self, key, value): # self._d_[key] = value # # def __delitem__(self, key): # del self._d_[key] # # def __setattr__(self, name, value): # if name in self._d_ or not hasattr(self.__class__, name): # self._d_[name] = value # else: # # there is an attribute on the class (could be property, ..) - don't add it as field # super(AttrDict, self).__setattr__(name, value) # # def __iter__(self): # return iter(self._d_) # # def to_dict(self): # return self._d_ # # class HitMeta(AttrDict): # def __init__(self, document, exclude=("_source", "_fields")): # d = { # k[1:] if k.startswith("_") else k: v # for (k, v) in iteritems(document) # if k not in exclude # } # if "type" in d: # # make sure we are consistent everywhere in python # d["doc_type"] = d.pop("type") # super(HitMeta, self).__init__(d) . Output only the next line.
def __repr__(self):
Next line prediction: <|code_start|># Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. class Hit(AttrDict): def __init__(self, document): data = {} if "_source" in document: data = document["_source"] if "fields" in document: <|code_end|> . Use current file imports: (from ..utils import AttrDict, HitMeta) and context including class names, function names, or small code snippets from other files: # Path: elasticsearch_dsl/utils.py # class AttrDict(object): # """ # Helper class to provide attribute like access (read and write) to # dictionaries. Used to provide a convenient way to access both results and # nested dsl dicts. # """ # # def __init__(self, d): # # assign the inner dict manually to prevent __setattr__ from firing # super(AttrDict, self).__setattr__("_d_", d) # # def __contains__(self, key): # return key in self._d_ # # def __nonzero__(self): # return bool(self._d_) # # __bool__ = __nonzero__ # # def __dir__(self): # # introspection for auto-complete in IPython etc # return list(self._d_.keys()) # # def __eq__(self, other): # if isinstance(other, AttrDict): # return other._d_ == self._d_ # # make sure we still equal to a dict with the same data # return other == self._d_ # # def __ne__(self, other): # return not self == other # # def __repr__(self): # r = repr(self._d_) # if len(r) > 60: # r = r[:60] + "...}" # return r # # def __getstate__(self): # return (self._d_,) # # def __setstate__(self, state): # super(AttrDict, self).__setattr__("_d_", state[0]) # # def __getattr__(self, attr_name): # try: # return self.__getitem__(attr_name) # except KeyError: # raise AttributeError( # "{!r} object has no attribute {!r}".format( # self.__class__.__name__, attr_name # ) # ) # # def __delattr__(self, attr_name): # try: # del self._d_[attr_name] # except KeyError: # raise AttributeError( # "{!r} object has no attribute {!r}".format( # self.__class__.__name__, attr_name # ) # ) # # def __getitem__(self, key): # return _wrap(self._d_[key]) # # def __setitem__(self, key, value): # self._d_[key] = value # # def __delitem__(self, key): # del self._d_[key] # # def __setattr__(self, name, value): # if name in self._d_ or not hasattr(self.__class__, name): # self._d_[name] = value # else: # # there is an attribute on the class (could be property, ..) - don't add it as field # super(AttrDict, self).__setattr__(name, value) # # def __iter__(self): # return iter(self._d_) # # def to_dict(self): # return self._d_ # # class HitMeta(AttrDict): # def __init__(self, document, exclude=("_source", "_fields")): # d = { # k[1:] if k.startswith("_") else k: v # for (k, v) in iteritems(document) # if k not in exclude # } # if "type" in d: # # make sure we are consistent everywhere in python # d["doc_type"] = d.pop("type") # super(HitMeta, self).__init__(d) . Output only the next line.
data.update(document["fields"])
Given the following code snippet before the placeholder: <|code_start|> write_client.indices.create( index="test-mapping", body={"settings": {"analysis": new_analysis}} ) m.field("title", "text", analyzer=analyzer) m.save("test-mapping", using=write_client) assert { "test-mapping": { "mappings": { "properties": { "name": {"type": "text", "analyzer": "my_analyzer"}, "title": {"type": "text", "analyzer": "my_analyzer"}, } } } } == write_client.indices.get_mapping(index="test-mapping") def test_mapping_gets_updated_from_es(write_client): write_client.indices.create( index="test-mapping", body={ "settings": {"number_of_shards": 1, "number_of_replicas": 0}, "mappings": { "date_detection": False, "properties": { "title": { "type": "text", "analyzer": "snowball", <|code_end|> , predict the next line using imports from the current file: from pytest import raises from elasticsearch_dsl import analysis, exceptions, mapping and context including class names, function names, and sometimes code from other files: # Path: elasticsearch_dsl/analysis.py # class AnalysisBase(object): # class CustomAnalysis(object): # class CustomAnalysisDefinition(CustomAnalysis): # class BuiltinAnalysis(object): # class Analyzer(AnalysisBase, DslBase): # class BuiltinAnalyzer(BuiltinAnalysis, Analyzer): # class CustomAnalyzer(CustomAnalysisDefinition, Analyzer): # class Normalizer(AnalysisBase, DslBase): # class BuiltinNormalizer(BuiltinAnalysis, Normalizer): # class CustomNormalizer(CustomAnalysisDefinition, Normalizer): # class Tokenizer(AnalysisBase, DslBase): # class BuiltinTokenizer(BuiltinAnalysis, Tokenizer): # class CustomTokenizer(CustomAnalysis, Tokenizer): # class TokenFilter(AnalysisBase, DslBase): # class BuiltinTokenFilter(BuiltinAnalysis, TokenFilter): # class CustomTokenFilter(CustomAnalysis, TokenFilter): # class MultiplexerTokenFilter(CustomTokenFilter): # class ConditionalTokenFilter(CustomTokenFilter): # class CharFilter(AnalysisBase, DslBase): # class BuiltinCharFilter(BuiltinAnalysis, CharFilter): # class CustomCharFilter(CustomAnalysis, CharFilter): # def _type_shortcut(cls, name_or_instance, type=None, **kwargs): # def __init__(self, filter_name, builtin_type="custom", **kwargs): # def to_dict(self): # def get_definition(self): # def get_analysis_definition(self): # def __init__(self, name): # def to_dict(self): # def get_analysis_definition(self): # def simulate(self, text, using="default", explain=False, attributes=None): # def get_analysis_definition(self): # def get_definition(self): # def get_analysis_definition(self): # def get_definition(self): # def get_analysis_definition(self): # # Path: elasticsearch_dsl/exceptions.py # class ElasticsearchDslException(Exception): # class UnknownDslObject(ElasticsearchDslException): # class ValidationException(ValueError, ElasticsearchDslException): # class IllegalOperation(ElasticsearchDslException): # # Path: elasticsearch_dsl/mapping.py # META_FIELDS = frozenset( # ( # "dynamic", # "transform", # "dynamic_date_formats", # "date_detection", # "numeric_detection", # "dynamic_templates", # "enabled", # ) # ) # class Properties(DslBase): # class Mapping(object): # def __init__(self): # def __repr__(self): # def __getitem__(self, name): # def __contains__(self, name): # def to_dict(self): # def field(self, name, *args, **kwargs): # def _collect_fields(self): # def update(self, other_object): # def __init__(self): # def __repr__(self): # def _clone(self): # def from_es(cls, index, using="default"): # def resolve_nested(self, field_path): # def resolve_field(self, field_path): # def _collect_analysis(self): # def save(self, index, using="default"): # def update_from_es(self, index, using="default"): # def _update_from_dict(self, raw): # def update(self, mapping, update_only=False): # def __contains__(self, name): # def __getitem__(self, name): # def __iter__(self): # def field(self, *args, **kwargs): # def meta(self, name, params=None, **kwargs): # def to_dict(self): . Output only the next line.
"fields": {"raw": {"type": "keyword"}},
Continue the code snippet: <|code_start|> write_client.indices.create(index="test-mapping") with raises(exceptions.IllegalOperation): m.save("test-mapping", using=write_client) write_client.cluster.health(index="test-mapping", wait_for_status="yellow") write_client.indices.close(index="test-mapping") m.save("test-mapping", using=write_client) assert { "test-mapping": { "mappings": { "properties": {"name": {"type": "text", "analyzer": "my_analyzer"}} } } } == write_client.indices.get_mapping(index="test-mapping") def test_mapping_saved_into_es_when_index_already_exists_with_analysis(write_client): m = mapping.Mapping() analyzer = analysis.analyzer("my_analyzer", tokenizer="keyword") m.field("name", "text", analyzer=analyzer) new_analysis = analyzer.get_analysis_definition() new_analysis["analyzer"]["other_analyzer"] = { "type": "custom", "tokenizer": "whitespace", } write_client.indices.create( index="test-mapping", body={"settings": {"analysis": new_analysis}} <|code_end|> . Use current file imports: from pytest import raises from elasticsearch_dsl import analysis, exceptions, mapping and context (classes, functions, or code) from other files: # Path: elasticsearch_dsl/analysis.py # class AnalysisBase(object): # class CustomAnalysis(object): # class CustomAnalysisDefinition(CustomAnalysis): # class BuiltinAnalysis(object): # class Analyzer(AnalysisBase, DslBase): # class BuiltinAnalyzer(BuiltinAnalysis, Analyzer): # class CustomAnalyzer(CustomAnalysisDefinition, Analyzer): # class Normalizer(AnalysisBase, DslBase): # class BuiltinNormalizer(BuiltinAnalysis, Normalizer): # class CustomNormalizer(CustomAnalysisDefinition, Normalizer): # class Tokenizer(AnalysisBase, DslBase): # class BuiltinTokenizer(BuiltinAnalysis, Tokenizer): # class CustomTokenizer(CustomAnalysis, Tokenizer): # class TokenFilter(AnalysisBase, DslBase): # class BuiltinTokenFilter(BuiltinAnalysis, TokenFilter): # class CustomTokenFilter(CustomAnalysis, TokenFilter): # class MultiplexerTokenFilter(CustomTokenFilter): # class ConditionalTokenFilter(CustomTokenFilter): # class CharFilter(AnalysisBase, DslBase): # class BuiltinCharFilter(BuiltinAnalysis, CharFilter): # class CustomCharFilter(CustomAnalysis, CharFilter): # def _type_shortcut(cls, name_or_instance, type=None, **kwargs): # def __init__(self, filter_name, builtin_type="custom", **kwargs): # def to_dict(self): # def get_definition(self): # def get_analysis_definition(self): # def __init__(self, name): # def to_dict(self): # def get_analysis_definition(self): # def simulate(self, text, using="default", explain=False, attributes=None): # def get_analysis_definition(self): # def get_definition(self): # def get_analysis_definition(self): # def get_definition(self): # def get_analysis_definition(self): # # Path: elasticsearch_dsl/exceptions.py # class ElasticsearchDslException(Exception): # class UnknownDslObject(ElasticsearchDslException): # class ValidationException(ValueError, ElasticsearchDslException): # class IllegalOperation(ElasticsearchDslException): # # Path: elasticsearch_dsl/mapping.py # META_FIELDS = frozenset( # ( # "dynamic", # "transform", # "dynamic_date_formats", # "date_detection", # "numeric_detection", # "dynamic_templates", # "enabled", # ) # ) # class Properties(DslBase): # class Mapping(object): # def __init__(self): # def __repr__(self): # def __getitem__(self, name): # def __contains__(self, name): # def to_dict(self): # def field(self, name, *args, **kwargs): # def _collect_fields(self): # def update(self, other_object): # def __init__(self): # def __repr__(self): # def _clone(self): # def from_es(cls, index, using="default"): # def resolve_nested(self, field_path): # def resolve_field(self, field_path): # def _collect_analysis(self): # def save(self, index, using="default"): # def update_from_es(self, index, using="default"): # def _update_from_dict(self, raw): # def update(self, mapping, update_only=False): # def __contains__(self, name): # def __getitem__(self, name): # def __iter__(self): # def field(self, *args, **kwargs): # def meta(self, name, params=None, **kwargs): # def to_dict(self): . Output only the next line.
)
Given snippet: <|code_start|># this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. def test_mapping_saved_into_es(write_client): m = mapping.Mapping() m.field( "name", "text", analyzer=analysis.analyzer("my_analyzer", tokenizer="keyword") ) m.field("tags", "keyword") m.save("test-mapping", using=write_client) assert { "test-mapping": { "mappings": { "properties": { <|code_end|> , continue by predicting the next line. Consider current file imports: from pytest import raises from elasticsearch_dsl import analysis, exceptions, mapping and context: # Path: elasticsearch_dsl/analysis.py # class AnalysisBase(object): # class CustomAnalysis(object): # class CustomAnalysisDefinition(CustomAnalysis): # class BuiltinAnalysis(object): # class Analyzer(AnalysisBase, DslBase): # class BuiltinAnalyzer(BuiltinAnalysis, Analyzer): # class CustomAnalyzer(CustomAnalysisDefinition, Analyzer): # class Normalizer(AnalysisBase, DslBase): # class BuiltinNormalizer(BuiltinAnalysis, Normalizer): # class CustomNormalizer(CustomAnalysisDefinition, Normalizer): # class Tokenizer(AnalysisBase, DslBase): # class BuiltinTokenizer(BuiltinAnalysis, Tokenizer): # class CustomTokenizer(CustomAnalysis, Tokenizer): # class TokenFilter(AnalysisBase, DslBase): # class BuiltinTokenFilter(BuiltinAnalysis, TokenFilter): # class CustomTokenFilter(CustomAnalysis, TokenFilter): # class MultiplexerTokenFilter(CustomTokenFilter): # class ConditionalTokenFilter(CustomTokenFilter): # class CharFilter(AnalysisBase, DslBase): # class BuiltinCharFilter(BuiltinAnalysis, CharFilter): # class CustomCharFilter(CustomAnalysis, CharFilter): # def _type_shortcut(cls, name_or_instance, type=None, **kwargs): # def __init__(self, filter_name, builtin_type="custom", **kwargs): # def to_dict(self): # def get_definition(self): # def get_analysis_definition(self): # def __init__(self, name): # def to_dict(self): # def get_analysis_definition(self): # def simulate(self, text, using="default", explain=False, attributes=None): # def get_analysis_definition(self): # def get_definition(self): # def get_analysis_definition(self): # def get_definition(self): # def get_analysis_definition(self): # # Path: elasticsearch_dsl/exceptions.py # class ElasticsearchDslException(Exception): # class UnknownDslObject(ElasticsearchDslException): # class ValidationException(ValueError, ElasticsearchDslException): # class IllegalOperation(ElasticsearchDslException): # # Path: elasticsearch_dsl/mapping.py # META_FIELDS = frozenset( # ( # "dynamic", # "transform", # "dynamic_date_formats", # "date_detection", # "numeric_detection", # "dynamic_templates", # "enabled", # ) # ) # class Properties(DslBase): # class Mapping(object): # def __init__(self): # def __repr__(self): # def __getitem__(self, name): # def __contains__(self, name): # def to_dict(self): # def field(self, name, *args, **kwargs): # def _collect_fields(self): # def update(self, other_object): # def __init__(self): # def __repr__(self): # def _clone(self): # def from_es(cls, index, using="default"): # def resolve_nested(self, field_path): # def resolve_field(self, field_path): # def _collect_analysis(self): # def save(self, index, using="default"): # def update_from_es(self, index, using="default"): # def _update_from_dict(self, raw): # def update(self, mapping, update_only=False): # def __contains__(self, name): # def __getitem__(self, name): # def __iter__(self): # def field(self, *args, **kwargs): # def meta(self, name, params=None, **kwargs): # def to_dict(self): which might include code, classes, or functions. Output only the next line.
"name": {"type": "text", "analyzer": "my_analyzer"},
Continue the code snippet: <|code_start|># ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. def test_count_all(data_client): s = Search(using=data_client).index("git") assert 53 == s.count() def test_count_prefetch(data_client, mocker): mocker.spy(data_client, "count") search = Search(using=data_client).index("git") search.execute() assert search.count() == 53 assert data_client.count.call_count == 0 search._response.hits.total.relation = "gte" <|code_end|> . Use current file imports: from elasticsearch_dsl.search import Q, Search and context (classes, functions, or code) from other files: # Path: elasticsearch_dsl/search.py # class QueryProxy(object): # class ProxyDescriptor(object): # class AggsProxy(AggBase, DslBase): # class Request(object): # class Search(Request): # class MultiSearch(Request): # def __init__(self, search, attr_name): # def __nonzero__(self): # def __call__(self, *args, **kwargs): # def __getattr__(self, attr_name): # def __setattr__(self, attr_name, value): # def __getstate__(self): # def __setstate__(self, state): # def __init__(self, name): # def __get__(self, instance, owner): # def __set__(self, instance, value): # def __init__(self, search): # def to_dict(self): # def __init__(self, using="default", index=None, doc_type=None, extra=None): # def __eq__(self, other): # def __copy__(self): # def params(self, **kwargs): # def index(self, *index): # def _resolve_field(self, path): # def _resolve_nested(self, hit, parent_class=None): # def _get_result(self, hit, parent_class=None): # def doc_type(self, *doc_type, **kwargs): # def using(self, client): # def extra(self, **kwargs): # def _clone(self): # def __init__(self, **kwargs): # def filter(self, *args, **kwargs): # def exclude(self, *args, **kwargs): # def __iter__(self): # def __getitem__(self, n): # def from_dict(cls, d): # def _clone(self): # def response_class(self, cls): # def update_from_dict(self, d): # def script_fields(self, **kwargs): # def source(self, fields=None, **kwargs): # def sort(self, *keys): # def highlight_options(self, **kwargs): # def highlight(self, *fields, **kwargs): # def suggest(self, name, text, **kwargs): # def to_dict(self, count=False, **kwargs): # def count(self): # def execute(self, ignore_cache=False): # def scan(self): # def delete(self): # def __init__(self, **kwargs): # def __getitem__(self, key): # def __iter__(self): # def _clone(self): # def add(self, search): # def to_dict(self): # def execute(self, ignore_cache=False, raise_on_error=True): . Output only the next line.
assert search.count() == 53
Predict the next line after this snippet: <|code_start|># Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. def test_count_all(data_client): s = Search(using=data_client).index("git") assert 53 == s.count() def test_count_prefetch(data_client, mocker): mocker.spy(data_client, "count") search = Search(using=data_client).index("git") search.execute() assert search.count() == 53 <|code_end|> using the current file's imports: from elasticsearch_dsl.search import Q, Search and any relevant context from other files: # Path: elasticsearch_dsl/search.py # class QueryProxy(object): # class ProxyDescriptor(object): # class AggsProxy(AggBase, DslBase): # class Request(object): # class Search(Request): # class MultiSearch(Request): # def __init__(self, search, attr_name): # def __nonzero__(self): # def __call__(self, *args, **kwargs): # def __getattr__(self, attr_name): # def __setattr__(self, attr_name, value): # def __getstate__(self): # def __setstate__(self, state): # def __init__(self, name): # def __get__(self, instance, owner): # def __set__(self, instance, value): # def __init__(self, search): # def to_dict(self): # def __init__(self, using="default", index=None, doc_type=None, extra=None): # def __eq__(self, other): # def __copy__(self): # def params(self, **kwargs): # def index(self, *index): # def _resolve_field(self, path): # def _resolve_nested(self, hit, parent_class=None): # def _get_result(self, hit, parent_class=None): # def doc_type(self, *doc_type, **kwargs): # def using(self, client): # def extra(self, **kwargs): # def _clone(self): # def __init__(self, **kwargs): # def filter(self, *args, **kwargs): # def exclude(self, *args, **kwargs): # def __iter__(self): # def __getitem__(self, n): # def from_dict(cls, d): # def _clone(self): # def response_class(self, cls): # def update_from_dict(self, d): # def script_fields(self, **kwargs): # def source(self, fields=None, **kwargs): # def sort(self, *keys): # def highlight_options(self, **kwargs): # def highlight(self, *fields, **kwargs): # def suggest(self, name, text, **kwargs): # def to_dict(self, count=False, **kwargs): # def count(self): # def execute(self, ignore_cache=False): # def scan(self): # def delete(self): # def __init__(self, **kwargs): # def __getitem__(self, key): # def __iter__(self): # def _clone(self): # def add(self, search): # def to_dict(self): # def execute(self, ignore_cache=False, raise_on_error=True): . Output only the next line.
assert data_client.count.call_count == 0
Next line prediction: <|code_start|># this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. __all__ = ["Range"] class Range(AttrDict): OPS = { "lt": operator.lt, "lte": operator.le, "gt": operator.gt, "gte": operator.ge, } def __init__(self, *args, **kwargs): <|code_end|> . Use current file imports: (import operator from six import iteritems, string_types from .utils import AttrDict) and context including class names, function names, or small code snippets from other files: # Path: elasticsearch_dsl/utils.py # class AttrDict(object): # """ # Helper class to provide attribute like access (read and write) to # dictionaries. Used to provide a convenient way to access both results and # nested dsl dicts. # """ # # def __init__(self, d): # # assign the inner dict manually to prevent __setattr__ from firing # super(AttrDict, self).__setattr__("_d_", d) # # def __contains__(self, key): # return key in self._d_ # # def __nonzero__(self): # return bool(self._d_) # # __bool__ = __nonzero__ # # def __dir__(self): # # introspection for auto-complete in IPython etc # return list(self._d_.keys()) # # def __eq__(self, other): # if isinstance(other, AttrDict): # return other._d_ == self._d_ # # make sure we still equal to a dict with the same data # return other == self._d_ # # def __ne__(self, other): # return not self == other # # def __repr__(self): # r = repr(self._d_) # if len(r) > 60: # r = r[:60] + "...}" # return r # # def __getstate__(self): # return (self._d_,) # # def __setstate__(self, state): # super(AttrDict, self).__setattr__("_d_", state[0]) # # def __getattr__(self, attr_name): # try: # return self.__getitem__(attr_name) # except KeyError: # raise AttributeError( # "{!r} object has no attribute {!r}".format( # self.__class__.__name__, attr_name # ) # ) # # def __delattr__(self, attr_name): # try: # del self._d_[attr_name] # except KeyError: # raise AttributeError( # "{!r} object has no attribute {!r}".format( # self.__class__.__name__, attr_name # ) # ) # # def __getitem__(self, key): # return _wrap(self._d_[key]) # # def __setitem__(self, key, value): # self._d_[key] = value # # def __delitem__(self, key): # del self._d_[key] # # def __setattr__(self, name, value): # if name in self._d_ or not hasattr(self.__class__, name): # self._d_[name] = value # else: # # there is an attribute on the class (could be property, ..) - don't add it as field # super(AttrDict, self).__setattr__(name, value) # # def __iter__(self): # return iter(self._d_) # # def to_dict(self): # return self._d_ . Output only the next line.
if args and (len(args) > 1 or kwargs or not isinstance(args[0], dict)):
Given snippet: <|code_start|>def test_bool_with_different_minimum_should_match_should_not_be_combined(): q1 = query.Q( "bool", minimum_should_match=2, should=[ query.Q("term", field="aa1"), query.Q("term", field="aa2"), query.Q("term", field="aa3"), query.Q("term", field="aa4"), ], ) q2 = query.Q( "bool", minimum_should_match=3, should=[ query.Q("term", field="bb1"), query.Q("term", field="bb2"), query.Q("term", field="bb3"), query.Q("term", field="bb4"), ], ) q3 = query.Q( "bool", minimum_should_match=4, should=[ query.Q("term", field="cc1"), query.Q("term", field="cc2"), query.Q("term", field="cc3"), query.Q("term", field="cc4"), ], <|code_end|> , continue by predicting the next line. Consider current file imports: from pytest import raises from elasticsearch_dsl import function, query and context: # Path: elasticsearch_dsl/function.py # def SF(name_or_sf, **params): # def to_dict(self): # def to_dict(self): # class ScoreFunction(DslBase): # class ScriptScore(ScoreFunction): # class BoostFactor(ScoreFunction): # class RandomScore(ScoreFunction): # class FieldValueFactor(ScoreFunction): # class Linear(ScoreFunction): # class Gauss(ScoreFunction): # class Exp(ScoreFunction): # # Path: elasticsearch_dsl/query.py # def Q(name_or_query="match_all", **params): # def __add__(self, other): # def __invert__(self): # def __or__(self, other): # def __and__(self, other): # def __add__(self, other): # def __or__(self, other): # def __invert__(self): # def __add__(self, other): # def __or__(self, other): # def __invert__(self): # def __add__(self, other): # def __or__(self, other): # def _min_should_match(self): # def __invert__(self): # def __and__(self, other): # def __init__(self, **kwargs): # class Query(DslBase): # class MatchAll(Query): # class MatchNone(Query): # class Bool(Query): # class FunctionScore(Query): # class Boosting(Query): # class ConstantScore(Query): # class DisMax(Query): # class Filtered(Query): # class Indices(Query): # class Percolate(Query): # class Nested(Query): # class HasChild(Query): # class HasParent(Query): # class TopChildren(Query): # class SpanFirst(Query): # class SpanMulti(Query): # class SpanNear(Query): # class SpanNot(Query): # class SpanOr(Query): # class FieldMaskingSpan(Query): # class SpanContaining(Query): # class SpanWithin(Query): # class CombinedFields(Query): # class Common(Query): # class Fuzzy(Query): # class FuzzyLikeThis(Query): # class FuzzyLikeThisField(Query): # class RankFeature(Query): # class DistanceFeature(Query): # class GeoBoundingBox(Query): # class GeoDistance(Query): # class GeoDistanceRange(Query): # class GeoPolygon(Query): # class GeoShape(Query): # class GeohashCell(Query): # class Ids(Query): # class Intervals(Query): # class Limit(Query): # class Match(Query): # class MatchPhrase(Query): # class MatchPhrasePrefix(Query): # class MatchBoolPrefix(Query): # class Exists(Query): # class MoreLikeThis(Query): # class MoreLikeThisField(Query): # class MultiMatch(Query): # class Prefix(Query): # class QueryString(Query): # class Range(Query): # class Regexp(Query): # class Shape(Query): # class SimpleQueryString(Query): # class SpanTerm(Query): # class Template(Query): # class Term(Query): # class Terms(Query): # class TermsSet(Query): # class Wildcard(Query): # class Script(Query): # class ScriptScore(Query): # class Type(Query): # class ParentId(Query): # class Wrapper(Query): # EMPTY_QUERY = MatchAll() which might include code, classes, or functions. Output only the next line.
)
Here is a snippet: <|code_start|> assert ~q == query.Bool(must_not=[query.Match(f=42)]) def test_inverted_query_with_must_not_become_should(): q = query.Q("bool", must_not=[query.Q("match", f=1), query.Q("match", f=2)]) assert ~q == query.Q("bool", should=[query.Q("match", f=1), query.Q("match", f=2)]) def test_inverted_query_with_must_and_must_not(): q = query.Q( "bool", must=[query.Q("match", f=3), query.Q("match", f=4)], must_not=[query.Q("match", f=1), query.Q("match", f=2)], ) print((~q).to_dict()) assert ~q == query.Q( "bool", should=[ # negation of must query.Q("bool", must_not=[query.Q("match", f=3)]), query.Q("bool", must_not=[query.Q("match", f=4)]), # negation of must_not query.Q("match", f=1), query.Q("match", f=2), ], ) <|code_end|> . Write the next line using the current file imports: from pytest import raises from elasticsearch_dsl import function, query and context from other files: # Path: elasticsearch_dsl/function.py # def SF(name_or_sf, **params): # def to_dict(self): # def to_dict(self): # class ScoreFunction(DslBase): # class ScriptScore(ScoreFunction): # class BoostFactor(ScoreFunction): # class RandomScore(ScoreFunction): # class FieldValueFactor(ScoreFunction): # class Linear(ScoreFunction): # class Gauss(ScoreFunction): # class Exp(ScoreFunction): # # Path: elasticsearch_dsl/query.py # def Q(name_or_query="match_all", **params): # def __add__(self, other): # def __invert__(self): # def __or__(self, other): # def __and__(self, other): # def __add__(self, other): # def __or__(self, other): # def __invert__(self): # def __add__(self, other): # def __or__(self, other): # def __invert__(self): # def __add__(self, other): # def __or__(self, other): # def _min_should_match(self): # def __invert__(self): # def __and__(self, other): # def __init__(self, **kwargs): # class Query(DslBase): # class MatchAll(Query): # class MatchNone(Query): # class Bool(Query): # class FunctionScore(Query): # class Boosting(Query): # class ConstantScore(Query): # class DisMax(Query): # class Filtered(Query): # class Indices(Query): # class Percolate(Query): # class Nested(Query): # class HasChild(Query): # class HasParent(Query): # class TopChildren(Query): # class SpanFirst(Query): # class SpanMulti(Query): # class SpanNear(Query): # class SpanNot(Query): # class SpanOr(Query): # class FieldMaskingSpan(Query): # class SpanContaining(Query): # class SpanWithin(Query): # class CombinedFields(Query): # class Common(Query): # class Fuzzy(Query): # class FuzzyLikeThis(Query): # class FuzzyLikeThisField(Query): # class RankFeature(Query): # class DistanceFeature(Query): # class GeoBoundingBox(Query): # class GeoDistance(Query): # class GeoDistanceRange(Query): # class GeoPolygon(Query): # class GeoShape(Query): # class GeohashCell(Query): # class Ids(Query): # class Intervals(Query): # class Limit(Query): # class Match(Query): # class MatchPhrase(Query): # class MatchPhrasePrefix(Query): # class MatchBoolPrefix(Query): # class Exists(Query): # class MoreLikeThis(Query): # class MoreLikeThisField(Query): # class MultiMatch(Query): # class Prefix(Query): # class QueryString(Query): # class Range(Query): # class Regexp(Query): # class Shape(Query): # class SimpleQueryString(Query): # class SpanTerm(Query): # class Template(Query): # class Term(Query): # class Terms(Query): # class TermsSet(Query): # class Wildcard(Query): # class Script(Query): # class ScriptScore(Query): # class Type(Query): # class ParentId(Query): # class Wrapper(Query): # EMPTY_QUERY = MatchAll() , which may include functions, classes, or code. Output only the next line.
def test_double_invert_returns_original_query():
Given the following code snippet before the placeholder: <|code_start|> self.assertEqual(token_instance['email'], self.email) def test_login_social_simple_jwt_pair_only(self): self._check_login_social_simple_jwt_only( reverse('login_social_jwt_pair'), data={'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'}, token_type='access', ) def test_login_social_simple_jwt_pair_only_provider_in_url(self): self._check_login_social_simple_jwt_only( reverse('login_social_jwt_pair', kwargs={'provider': 'facebook'}), data={'code': '3D52VoM1uiw94a1ETnGvYlCw'}, token_type='access', ) def test_login_social_simple_jwt_pair_user(self): self._check_login_social_simple_jwt_user( reverse('login_social_jwt_pair_user'), data={'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'}, token_type='access', ) def test_login_social_simple_jwt_pair_user_provider_in_url(self): self._check_login_social_simple_jwt_user( reverse('login_social_jwt_pair_user', kwargs={'provider': 'facebook'}), data={'code': '3D52VoM1uiw94a1ETnGvYlCw'}, token_type='access', ) <|code_end|> , predict the next line using imports from the current file: from django.test import override_settings from django.urls import reverse from rest_framework.test import APITestCase from rest_framework_simplejwt.authentication import JWTAuthentication from social_core.utils import parse_qs from .base import BaseFacebookAPITestCase, BaseTwitterApiTestCase and context including class names, function names, and sometimes code from other files: # Path: tests/base.py # class BaseFacebookAPITestCase(RestSocialMixin, FacebookOAuth2Test): # # def do_rest_login(self): # start_url = self.backend.start().url # self.auth_handlers(start_url) # # class BaseTwitterApiTestCase(RestSocialMixin, TwitterOAuth1Test): # # def do_rest_login(self): # self.request_token_handler() # start_url = self.backend.start().url # self.auth_handlers(start_url) . Output only the next line.
def test_login_social_simple_jwt_sliding_only(self):
Based on the snippet: <|code_start|> self._check_login_social_simple_jwt_user( reverse('login_social_jwt_pair_user'), data={'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'}, token_type='access', ) def test_login_social_simple_jwt_pair_user_provider_in_url(self): self._check_login_social_simple_jwt_user( reverse('login_social_jwt_pair_user', kwargs={'provider': 'facebook'}), data={'code': '3D52VoM1uiw94a1ETnGvYlCw'}, token_type='access', ) def test_login_social_simple_jwt_sliding_only(self): self._check_login_social_simple_jwt_only( reverse('login_social_jwt_sliding'), data={'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'}, token_type='sliding', ) def test_login_social_simple_jwt_sliding_only_provider_in_url(self): self._check_login_social_simple_jwt_only( reverse('login_social_jwt_sliding', kwargs={'provider': 'facebook'}), data={'code': '3D52VoM1uiw94a1ETnGvYlCw'}, token_type='sliding', ) def test_login_social_simple_jwt_sliding_user(self): self._check_login_social_simple_jwt_user( reverse('login_social_jwt_sliding_user'), <|code_end|> , predict the immediate next line with the help of imports: from django.test import override_settings from django.urls import reverse from rest_framework.test import APITestCase from rest_framework_simplejwt.authentication import JWTAuthentication from social_core.utils import parse_qs from .base import BaseFacebookAPITestCase, BaseTwitterApiTestCase and context (classes, functions, sometimes code) from other files: # Path: tests/base.py # class BaseFacebookAPITestCase(RestSocialMixin, FacebookOAuth2Test): # # def do_rest_login(self): # start_url = self.backend.start().url # self.auth_handlers(start_url) # # class BaseTwitterApiTestCase(RestSocialMixin, TwitterOAuth1Test): # # def do_rest_login(self): # self.request_token_handler() # start_url = self.backend.start().url # self.auth_handlers(start_url) . Output only the next line.
data={'provider': 'facebook', 'code': '3D52VoM1uiw94a1ETnGvYlCw'},
Predict the next line for this snippet: <|code_start|> class HomeJWTView(TemplateView): template_name = 'home_jwt.html' class HomeKnoxView(TemplateView): template_name = 'home_knox.html' class LogoutSessionView(APIView): def post(self, request, *args, **kwargs): logout(request) return Response(status=status.HTTP_204_NO_CONTENT) class BaseDetailView(generics.RetrieveAPIView): permission_classes = IsAuthenticated, serializer_class = UserSerializer model = get_user_model() def get_object(self, queryset=None): return self.request.user class UserSessionDetailView(BaseDetailView): authentication_classes = (SessionAuthentication, ) <|code_end|> with the help of current file imports: from django.views.generic import TemplateView from django.contrib.auth import logout, get_user_model from django.utils.decorators import method_decorator from django.views.decorators.csrf import ensure_csrf_cookie from rest_framework import generics, status from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_social_auth.serializers import UserSerializer from rest_social_auth.views import KnoxAuthMixin, SimpleJWTAuthMixin and context from other files: # Path: rest_social_auth/serializers.py # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # Path: rest_social_auth/views.py # class KnoxAuthMixin(object): # def get_authenticators(self): # try: # from knox.auth import TokenAuthentication # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # return [TokenAuthentication()] # # class SimpleJWTAuthMixin(object): # def get_authenticators(self): # try: # from rest_framework_simplejwt.authentication import JWTAuthentication # except ImportError: # warnings.warn( # 'django-rest-framework-simplejwt must be installed for JWT authentication', # ImportWarning, # ) # raise # # return [JWTAuthentication()] , which may contain function names, class names, or code. Output only the next line.
class UserTokenDetailView(BaseDetailView):
Based on the snippet: <|code_start|> class HomeTokenView(TemplateView): template_name = 'home_token.html' class HomeJWTView(TemplateView): template_name = 'home_jwt.html' class HomeKnoxView(TemplateView): template_name = 'home_knox.html' class LogoutSessionView(APIView): def post(self, request, *args, **kwargs): logout(request) return Response(status=status.HTTP_204_NO_CONTENT) class BaseDetailView(generics.RetrieveAPIView): permission_classes = IsAuthenticated, serializer_class = UserSerializer model = get_user_model() def get_object(self, queryset=None): return self.request.user <|code_end|> , predict the immediate next line with the help of imports: from django.views.generic import TemplateView from django.contrib.auth import logout, get_user_model from django.utils.decorators import method_decorator from django.views.decorators.csrf import ensure_csrf_cookie from rest_framework import generics, status from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_social_auth.serializers import UserSerializer from rest_social_auth.views import KnoxAuthMixin, SimpleJWTAuthMixin and context (classes, functions, sometimes code) from other files: # Path: rest_social_auth/serializers.py # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # Path: rest_social_auth/views.py # class KnoxAuthMixin(object): # def get_authenticators(self): # try: # from knox.auth import TokenAuthentication # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # return [TokenAuthentication()] # # class SimpleJWTAuthMixin(object): # def get_authenticators(self): # try: # from rest_framework_simplejwt.authentication import JWTAuthentication # except ImportError: # warnings.warn( # 'django-rest-framework-simplejwt must be installed for JWT authentication', # ImportWarning, # ) # raise # # return [JWTAuthentication()] . Output only the next line.
class UserSessionDetailView(BaseDetailView):
Based on the snippet: <|code_start|>class HomeSessionView(TemplateView): template_name = 'home_session.html' @method_decorator(ensure_csrf_cookie) def get(self, request, *args, **kwargs): return super(HomeSessionView, self).get(request, *args, **kwargs) class HomeTokenView(TemplateView): template_name = 'home_token.html' class HomeJWTView(TemplateView): template_name = 'home_jwt.html' class HomeKnoxView(TemplateView): template_name = 'home_knox.html' class LogoutSessionView(APIView): def post(self, request, *args, **kwargs): logout(request) return Response(status=status.HTTP_204_NO_CONTENT) class BaseDetailView(generics.RetrieveAPIView): permission_classes = IsAuthenticated, serializer_class = UserSerializer <|code_end|> , predict the immediate next line with the help of imports: from django.views.generic import TemplateView from django.contrib.auth import logout, get_user_model from django.utils.decorators import method_decorator from django.views.decorators.csrf import ensure_csrf_cookie from rest_framework import generics, status from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_social_auth.serializers import UserSerializer from rest_social_auth.views import KnoxAuthMixin, SimpleJWTAuthMixin and context (classes, functions, sometimes code) from other files: # Path: rest_social_auth/serializers.py # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # Path: rest_social_auth/views.py # class KnoxAuthMixin(object): # def get_authenticators(self): # try: # from knox.auth import TokenAuthentication # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # return [TokenAuthentication()] # # class SimpleJWTAuthMixin(object): # def get_authenticators(self): # try: # from rest_framework_simplejwt.authentication import JWTAuthentication # except ImportError: # warnings.warn( # 'django-rest-framework-simplejwt must be installed for JWT authentication', # ImportWarning, # ) # raise # # return [JWTAuthentication()] . Output only the next line.
model = get_user_model()
Next line prediction: <|code_start|> try: except ImportError: logger = logging.getLogger(__name__) REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEPTIONS', True) STRATEGY = getattr(settings, setting_name('STRATEGY'), 'rest_social_auth.strategy.DRFStrategy') <|code_end|> . Use current file imports: (import logging import warnings from urllib.parse import urljoin, urlencode, urlparse # python 3x from urllib import urlencode # python 2x from urlparse import urljoin, urlparse from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.encoding import iri_to_uri from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from social_django.utils import psa, STORAGE from social_django.views import _do_login as social_auth_login from social_core.backends.oauth import BaseOAuth1 from social_core.utils import get_strategy, parse_qs, user_is_authenticated, setting_name from social_core.exceptions import AuthException from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny from requests.exceptions import HTTPError from .serializers import ( JWTPairSerializer, JWTSlidingSerializer, KnoxSerializer, OAuth1InputSerializer, OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) from knox.auth import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication) and context including class names, function names, or small code snippets from other files: # Path: rest_social_auth/serializers.py # class JWTPairSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # refresh = serializers.SerializerMethodField() # # jwt_token_class_name = 'RefreshToken' # # def get_token(self, obj): # return str(self.get_token_instance().access_token) # # def get_refresh(self, obj): # return str(self.get_token_instance()) # # class JWTSlidingSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # # jwt_token_class_name = 'SlidingToken' # # def get_token(self, obj): # return str(self.get_token_instance()) # # class KnoxSerializer(TokenSerializer): # def get_token(self, obj): # try: # from knox.models import AuthToken # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # token_instance, token_key = AuthToken.objects.create(obj) # return token_key # # class OAuth1InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # oauth_token = serializers.CharField() # oauth_verifier = serializers.CharField() # # class OAuth2InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # code = serializers.CharField() # redirect_uri = serializers.CharField(required=False) # # class TokenSerializer(serializers.Serializer): # # token = serializers.SerializerMethodField() # # def get_token(self, obj): # token, created = Token.objects.get_or_create(user=obj) # return token.key # # class UserJWTSlidingSerializer(JWTSlidingSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserKnoxSerializer(KnoxSerializer, UserSerializer): # pass # # class UserJWTPairSerializer(JWTPairSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # class UserTokenSerializer(TokenSerializer, UserSerializer): # pass . Output only the next line.
def load_strategy(request=None):
Given the code snippet: <|code_start|> try: except ImportError: logger = logging.getLogger(__name__) REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') <|code_end|> , generate the next line using the imports in this file: import logging import warnings from urllib.parse import urljoin, urlencode, urlparse # python 3x from urllib import urlencode # python 2x from urlparse import urljoin, urlparse from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.encoding import iri_to_uri from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from social_django.utils import psa, STORAGE from social_django.views import _do_login as social_auth_login from social_core.backends.oauth import BaseOAuth1 from social_core.utils import get_strategy, parse_qs, user_is_authenticated, setting_name from social_core.exceptions import AuthException from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny from requests.exceptions import HTTPError from .serializers import ( JWTPairSerializer, JWTSlidingSerializer, KnoxSerializer, OAuth1InputSerializer, OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) from knox.auth import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication and context (functions, classes, or occasionally code) from other files: # Path: rest_social_auth/serializers.py # class JWTPairSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # refresh = serializers.SerializerMethodField() # # jwt_token_class_name = 'RefreshToken' # # def get_token(self, obj): # return str(self.get_token_instance().access_token) # # def get_refresh(self, obj): # return str(self.get_token_instance()) # # class JWTSlidingSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # # jwt_token_class_name = 'SlidingToken' # # def get_token(self, obj): # return str(self.get_token_instance()) # # class KnoxSerializer(TokenSerializer): # def get_token(self, obj): # try: # from knox.models import AuthToken # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # token_instance, token_key = AuthToken.objects.create(obj) # return token_key # # class OAuth1InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # oauth_token = serializers.CharField() # oauth_verifier = serializers.CharField() # # class OAuth2InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # code = serializers.CharField() # redirect_uri = serializers.CharField(required=False) # # class TokenSerializer(serializers.Serializer): # # token = serializers.SerializerMethodField() # # def get_token(self, obj): # token, created = Token.objects.get_or_create(user=obj) # return token.key # # class UserJWTSlidingSerializer(JWTSlidingSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserKnoxSerializer(KnoxSerializer, UserSerializer): # pass # # class UserJWTPairSerializer(JWTPairSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # class UserTokenSerializer(TokenSerializer, UserSerializer): # pass . Output only the next line.
DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True)
Next line prediction: <|code_start|> try: except ImportError: logger = logging.getLogger(__name__) <|code_end|> . Use current file imports: (import logging import warnings from urllib.parse import urljoin, urlencode, urlparse # python 3x from urllib import urlencode # python 2x from urlparse import urljoin, urlparse from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.encoding import iri_to_uri from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from social_django.utils import psa, STORAGE from social_django.views import _do_login as social_auth_login from social_core.backends.oauth import BaseOAuth1 from social_core.utils import get_strategy, parse_qs, user_is_authenticated, setting_name from social_core.exceptions import AuthException from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny from requests.exceptions import HTTPError from .serializers import ( JWTPairSerializer, JWTSlidingSerializer, KnoxSerializer, OAuth1InputSerializer, OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) from knox.auth import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication) and context including class names, function names, or small code snippets from other files: # Path: rest_social_auth/serializers.py # class JWTPairSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # refresh = serializers.SerializerMethodField() # # jwt_token_class_name = 'RefreshToken' # # def get_token(self, obj): # return str(self.get_token_instance().access_token) # # def get_refresh(self, obj): # return str(self.get_token_instance()) # # class JWTSlidingSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # # jwt_token_class_name = 'SlidingToken' # # def get_token(self, obj): # return str(self.get_token_instance()) # # class KnoxSerializer(TokenSerializer): # def get_token(self, obj): # try: # from knox.models import AuthToken # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # token_instance, token_key = AuthToken.objects.create(obj) # return token_key # # class OAuth1InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # oauth_token = serializers.CharField() # oauth_verifier = serializers.CharField() # # class OAuth2InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # code = serializers.CharField() # redirect_uri = serializers.CharField(required=False) # # class TokenSerializer(serializers.Serializer): # # token = serializers.SerializerMethodField() # # def get_token(self, obj): # token, created = Token.objects.get_or_create(user=obj) # return token.key # # class UserJWTSlidingSerializer(JWTSlidingSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserKnoxSerializer(KnoxSerializer, UserSerializer): # pass # # class UserJWTPairSerializer(JWTPairSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # class UserTokenSerializer(TokenSerializer, UserSerializer): # pass . Output only the next line.
REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/')
Predict the next line for this snippet: <|code_start|> try: except ImportError: logger = logging.getLogger(__name__) REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEPTIONS', True) STRATEGY = getattr(settings, setting_name('STRATEGY'), 'rest_social_auth.strategy.DRFStrategy') def load_strategy(request=None): return get_strategy(STRATEGY, STORAGE, request) <|code_end|> with the help of current file imports: import logging import warnings from urllib.parse import urljoin, urlencode, urlparse # python 3x from urllib import urlencode # python 2x from urlparse import urljoin, urlparse from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.encoding import iri_to_uri from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from social_django.utils import psa, STORAGE from social_django.views import _do_login as social_auth_login from social_core.backends.oauth import BaseOAuth1 from social_core.utils import get_strategy, parse_qs, user_is_authenticated, setting_name from social_core.exceptions import AuthException from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny from requests.exceptions import HTTPError from .serializers import ( JWTPairSerializer, JWTSlidingSerializer, KnoxSerializer, OAuth1InputSerializer, OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) from knox.auth import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication and context from other files: # Path: rest_social_auth/serializers.py # class JWTPairSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # refresh = serializers.SerializerMethodField() # # jwt_token_class_name = 'RefreshToken' # # def get_token(self, obj): # return str(self.get_token_instance().access_token) # # def get_refresh(self, obj): # return str(self.get_token_instance()) # # class JWTSlidingSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # # jwt_token_class_name = 'SlidingToken' # # def get_token(self, obj): # return str(self.get_token_instance()) # # class KnoxSerializer(TokenSerializer): # def get_token(self, obj): # try: # from knox.models import AuthToken # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # token_instance, token_key = AuthToken.objects.create(obj) # return token_key # # class OAuth1InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # oauth_token = serializers.CharField() # oauth_verifier = serializers.CharField() # # class OAuth2InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # code = serializers.CharField() # redirect_uri = serializers.CharField(required=False) # # class TokenSerializer(serializers.Serializer): # # token = serializers.SerializerMethodField() # # def get_token(self, obj): # token, created = Token.objects.get_or_create(user=obj) # return token.key # # class UserJWTSlidingSerializer(JWTSlidingSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserKnoxSerializer(KnoxSerializer, UserSerializer): # pass # # class UserJWTPairSerializer(JWTPairSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # class UserTokenSerializer(TokenSerializer, UserSerializer): # pass , which may contain function names, class names, or code. Output only the next line.
@psa(REDIRECT_URI, load_strategy=load_strategy)
Continue the code snippet: <|code_start|> try: except ImportError: logger = logging.getLogger(__name__) REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEPTIONS', True) STRATEGY = getattr(settings, setting_name('STRATEGY'), 'rest_social_auth.strategy.DRFStrategy') def load_strategy(request=None): return get_strategy(STRATEGY, STORAGE, request) @psa(REDIRECT_URI, load_strategy=load_strategy) def decorate_request(request, backend): <|code_end|> . Use current file imports: import logging import warnings from urllib.parse import urljoin, urlencode, urlparse # python 3x from urllib import urlencode # python 2x from urlparse import urljoin, urlparse from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.encoding import iri_to_uri from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from social_django.utils import psa, STORAGE from social_django.views import _do_login as social_auth_login from social_core.backends.oauth import BaseOAuth1 from social_core.utils import get_strategy, parse_qs, user_is_authenticated, setting_name from social_core.exceptions import AuthException from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny from requests.exceptions import HTTPError from .serializers import ( JWTPairSerializer, JWTSlidingSerializer, KnoxSerializer, OAuth1InputSerializer, OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) from knox.auth import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication and context (classes, functions, or code) from other files: # Path: rest_social_auth/serializers.py # class JWTPairSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # refresh = serializers.SerializerMethodField() # # jwt_token_class_name = 'RefreshToken' # # def get_token(self, obj): # return str(self.get_token_instance().access_token) # # def get_refresh(self, obj): # return str(self.get_token_instance()) # # class JWTSlidingSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # # jwt_token_class_name = 'SlidingToken' # # def get_token(self, obj): # return str(self.get_token_instance()) # # class KnoxSerializer(TokenSerializer): # def get_token(self, obj): # try: # from knox.models import AuthToken # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # token_instance, token_key = AuthToken.objects.create(obj) # return token_key # # class OAuth1InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # oauth_token = serializers.CharField() # oauth_verifier = serializers.CharField() # # class OAuth2InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # code = serializers.CharField() # redirect_uri = serializers.CharField(required=False) # # class TokenSerializer(serializers.Serializer): # # token = serializers.SerializerMethodField() # # def get_token(self, obj): # token, created = Token.objects.get_or_create(user=obj) # return token.key # # class UserJWTSlidingSerializer(JWTSlidingSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserKnoxSerializer(KnoxSerializer, UserSerializer): # pass # # class UserJWTPairSerializer(JWTPairSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # class UserTokenSerializer(TokenSerializer, UserSerializer): # pass . Output only the next line.
pass
Predict the next line after this snippet: <|code_start|> try: except ImportError: logger = logging.getLogger(__name__) REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') <|code_end|> using the current file's imports: import logging import warnings from urllib.parse import urljoin, urlencode, urlparse # python 3x from urllib import urlencode # python 2x from urlparse import urljoin, urlparse from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.encoding import iri_to_uri from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from social_django.utils import psa, STORAGE from social_django.views import _do_login as social_auth_login from social_core.backends.oauth import BaseOAuth1 from social_core.utils import get_strategy, parse_qs, user_is_authenticated, setting_name from social_core.exceptions import AuthException from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny from requests.exceptions import HTTPError from .serializers import ( JWTPairSerializer, JWTSlidingSerializer, KnoxSerializer, OAuth1InputSerializer, OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) from knox.auth import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication and any relevant context from other files: # Path: rest_social_auth/serializers.py # class JWTPairSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # refresh = serializers.SerializerMethodField() # # jwt_token_class_name = 'RefreshToken' # # def get_token(self, obj): # return str(self.get_token_instance().access_token) # # def get_refresh(self, obj): # return str(self.get_token_instance()) # # class JWTSlidingSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # # jwt_token_class_name = 'SlidingToken' # # def get_token(self, obj): # return str(self.get_token_instance()) # # class KnoxSerializer(TokenSerializer): # def get_token(self, obj): # try: # from knox.models import AuthToken # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # token_instance, token_key = AuthToken.objects.create(obj) # return token_key # # class OAuth1InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # oauth_token = serializers.CharField() # oauth_verifier = serializers.CharField() # # class OAuth2InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # code = serializers.CharField() # redirect_uri = serializers.CharField(required=False) # # class TokenSerializer(serializers.Serializer): # # token = serializers.SerializerMethodField() # # def get_token(self, obj): # token, created = Token.objects.get_or_create(user=obj) # return token.key # # class UserJWTSlidingSerializer(JWTSlidingSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserKnoxSerializer(KnoxSerializer, UserSerializer): # pass # # class UserJWTPairSerializer(JWTPairSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # class UserTokenSerializer(TokenSerializer, UserSerializer): # pass . Output only the next line.
DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True)
Next line prediction: <|code_start|> try: except ImportError: logger = logging.getLogger(__name__) REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEPTIONS', True) STRATEGY = getattr(settings, setting_name('STRATEGY'), 'rest_social_auth.strategy.DRFStrategy') def load_strategy(request=None): return get_strategy(STRATEGY, STORAGE, request) @psa(REDIRECT_URI, load_strategy=load_strategy) <|code_end|> . Use current file imports: (import logging import warnings from urllib.parse import urljoin, urlencode, urlparse # python 3x from urllib import urlencode # python 2x from urlparse import urljoin, urlparse from django.conf import settings from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.encoding import iri_to_uri from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from social_django.utils import psa, STORAGE from social_django.views import _do_login as social_auth_login from social_core.backends.oauth import BaseOAuth1 from social_core.utils import get_strategy, parse_qs, user_is_authenticated, setting_name from social_core.exceptions import AuthException from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import AllowAny from requests.exceptions import HTTPError from .serializers import ( JWTPairSerializer, JWTSlidingSerializer, KnoxSerializer, OAuth1InputSerializer, OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) from knox.auth import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication) and context including class names, function names, or small code snippets from other files: # Path: rest_social_auth/serializers.py # class JWTPairSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # refresh = serializers.SerializerMethodField() # # jwt_token_class_name = 'RefreshToken' # # def get_token(self, obj): # return str(self.get_token_instance().access_token) # # def get_refresh(self, obj): # return str(self.get_token_instance()) # # class JWTSlidingSerializer(JWTBaseSerializer): # token = serializers.SerializerMethodField() # # jwt_token_class_name = 'SlidingToken' # # def get_token(self, obj): # return str(self.get_token_instance()) # # class KnoxSerializer(TokenSerializer): # def get_token(self, obj): # try: # from knox.models import AuthToken # except ImportError: # warnings.warn( # 'django-rest-knox must be installed for Knox authentication', # ImportWarning, # ) # raise # # token_instance, token_key = AuthToken.objects.create(obj) # return token_key # # class OAuth1InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # oauth_token = serializers.CharField() # oauth_verifier = serializers.CharField() # # class OAuth2InputSerializer(serializers.Serializer): # # provider = serializers.CharField(required=False) # code = serializers.CharField() # redirect_uri = serializers.CharField(required=False) # # class TokenSerializer(serializers.Serializer): # # token = serializers.SerializerMethodField() # # def get_token(self, obj): # token, created = Token.objects.get_or_create(user=obj) # return token.key # # class UserJWTSlidingSerializer(JWTSlidingSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserKnoxSerializer(KnoxSerializer, UserSerializer): # pass # # class UserJWTPairSerializer(JWTPairSerializer, UserSerializer): # # def get_token_payload(self, user): # payload = dict(UserSerializer(user).data) # payload.pop('id', None) # return payload # # class UserSerializer(serializers.ModelSerializer): # # class Meta: # model = get_user_model() # # Custom user model may not have some fields from the list below, # # excluding them based on actual fields # exclude = [ # field for field in ( # 'is_staff', 'is_active', 'date_joined', 'password', 'last_login', # 'user_permissions', 'groups', 'is_superuser', # ) if field in [mfield.name for mfield in get_user_model()._meta.get_fields()] # ] # # class UserTokenSerializer(TokenSerializer, UserSerializer): # pass . Output only the next line.
def decorate_request(request, backend):