Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|> self._loaded_plugins[plugin_name] = plugin return plugin def list_plugins(self) -> Dict[str, Dict[str, Any]]: valid_classes = [ 'ArchiverPlugin', 'BasePlugin', 'ProviderPlugin', 'WorkerPlugin', 'ConnectorPlugin', 'DispatcherPlugin', 'DecoratorPlugin', ] plugins = {} for plugin in self._plugin_name_to_info.keys(): plugin_classes = [] try: with open(self._plugin_name_to_info[plugin][0]) as f: parsed_plugin = ast.parse(f.read()) classes = [n for n in parsed_plugin.body if isinstance(n, ast.ClassDef)] for c in classes: for base in c.bases: if base.id in valid_classes: # type: ignore plugin_classes.append( base.id.replace('Plugin', '') # type: ignore ) except (UnicodeDecodeError, ValueError): plugin_classes = ['UNKNOWN'] plugins[plugin] = { <|code_end|> , generate the next line using the imports in this file: import os import inspect import logging import configparser import importlib.util import stoq.helpers as helpers import ast from pkg_resources import parse_version from typing import Dict, List, Optional, Tuple, Any, Union from stoq.data_classes import Error from .exceptions import StoqException, StoqPluginNotFound from stoq.plugins import ( ArchiverPlugin, BasePlugin, ProviderPlugin, WorkerPlugin, ConnectorPlugin, DispatcherPlugin, DecoratorPlugin, ) from stoq import __version__ and context (functions, classes, or occasionally code) from other files: # Path: stoq/data_classes.py # class Error: # def __init__( # self, # error: str, # plugin_name: Optional[str] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object for errors collected from plugins # # :param error: Error message to add to results # :param plugin_name: The name of the plugin producing the error # :param payload_id: The ``payload_id`` of the ``Payload`` that the error occurred on # # >>> from stoq import Error, Payload # >>> errors: List[Error] = [] # >>> payload = Payload(b'test bytes') # >>> err = Error( # ... error='This is our error message', # ... plugin_name='test_plugin', # ... payload_id=payload.results.payload_id # ... ) # >>> errors.append(err) # # """ # self.error = error # self.plugin_name = plugin_name # self.payload_id = payload_id # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/exceptions.py # class StoqException(Exception): # pass # # class StoqPluginNotFound(Exception): # pass # # Path: stoq/plugins/base.py # class BasePlugin(ABC): # def __init__(self, config: StoqConfigParser) -> None: # self.config = config # self.plugin_name = config.get('Core', 'Name', fallback=self.__class__.__name__) # self.__author__ = config.get('Documentation', 'Author', fallback='') # self.__version__ = config.get('Documentation', 'Version', fallback='') # self.__website__ = config.get('Documentation', 'Website', fallback='') # self.__description__ = config.get('Documentation', 'Description', fallback='') # self.log = logging.getLogger(f'stoq.{self.plugin_name}') # # Path: stoq/plugins/archiver.py # class ArchiverPlugin(BasePlugin): # async def archive( # self, payload: Payload, request: Request # ) -> Optional[ArchiverResponse]: # """ # Archive payload # # :param payload: Payload object to archive # :param request: Originating Request object # # :return: ArchiverResponse object. Results are used to retrieve payload. # # >>> import asyncio # >>> from stoq import Stoq, Payload # >>> payload = Payload(b'this is going to be saved') # >>> s = Stoq() # >>> loop = asyncio.get_event_loop() # >>> archiver = s.load_plugin('filedir') # >>> loop.run_until_complete(archiver.archive(payload)) # ... {'path': '/tmp/bad.exe'} # # """ # pass # # async def get(self, task: ArchiverResponse) -> Optional[Payload]: # """ # Retrieve payload for processing # # :param task: Task to be processed to load payload. Must contain `ArchiverResponse` # results from `ArchiverPlugin.archive()` # # :return: Payload object for scanning # # >>> import asyncio # >>> from stoq import Stoq, ArchiverResponse # >>> s = Stoq() # >>> loop = asyncio.get_event_loop() # >>> archiver = s.load_plugin('filedir') # >>> task = ArchiverResponse(results={'path': '/tmp/bad.exe'}) # >>> payload = loop.run_until_complete(archiver.get(task)) # # """ # pass # # Path: stoq/plugins/connector.py # class ConnectorPlugin(BasePlugin, ABC): # @abstractmethod # async def save(self, response: StoqResponse) -> None: # pass # # Path: stoq/plugins/provider.py # class ProviderPlugin(BasePlugin, ABC): # @abstractmethod # async def ingest(self, queue: Queue) -> None: # pass # # Path: stoq/plugins/worker.py # class WorkerPlugin(BasePlugin, ABC): # def __init__(self, config: StoqConfigParser) -> None: # super().__init__(config) # self.required_workers = config.getset( # 'options', 'required_workers', fallback=set() # ) # # @abstractmethod # async def scan( # self, payload: Payload, request: Request # ) -> Optional[WorkerResponse]: # pass # # Path: stoq/plugins/dispatcher.py # class DispatcherPlugin(BasePlugin, ABC): # @abstractmethod # async def get_dispatches( # self, payload: Payload, request: Request # ) -> Optional[DispatcherResponse]: # pass # # Path: stoq/plugins/decorator.py # class DecoratorPlugin(BasePlugin, ABC): # @abstractmethod # async def decorate(self, response: StoqResponse) -> Optional[DecoratorResponse]: # pass . Output only the next line.
'classes': plugin_classes,
Next line prediction: <|code_start|> predicate=lambda mem: inspect.isclass(mem) and issubclass(mem, BasePlugin) and mem not in [ ArchiverPlugin, BasePlugin, ProviderPlugin, WorkerPlugin, ConnectorPlugin, DispatcherPlugin, DecoratorPlugin, ] and not inspect.isabstract(mem), ) if len(plugin_classes) == 0: raise StoqException( f'No valid plugin classes found in the module for {plugin_name}' ) if len(plugin_classes) > 1: raise StoqException( f'Multiple possible plugin classes found in the module for {plugin_name},' ' unable to distinguish which to use.' ) _, plugin_class = plugin_classes[0] # Plugin configuration order of precendence: # 1) plugin options provided at instantiation of `Stoq()` # 2) plugin configuration in `stoq.cfg` # 3) `plugin_name.stoq` if isinstance( self._stoq_config, helpers.StoqConfigParser <|code_end|> . Use current file imports: (import os import inspect import logging import configparser import importlib.util import stoq.helpers as helpers import ast from pkg_resources import parse_version from typing import Dict, List, Optional, Tuple, Any, Union from stoq.data_classes import Error from .exceptions import StoqException, StoqPluginNotFound from stoq.plugins import ( ArchiverPlugin, BasePlugin, ProviderPlugin, WorkerPlugin, ConnectorPlugin, DispatcherPlugin, DecoratorPlugin, ) from stoq import __version__) and context including class names, function names, or small code snippets from other files: # Path: stoq/data_classes.py # class Error: # def __init__( # self, # error: str, # plugin_name: Optional[str] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object for errors collected from plugins # # :param error: Error message to add to results # :param plugin_name: The name of the plugin producing the error # :param payload_id: The ``payload_id`` of the ``Payload`` that the error occurred on # # >>> from stoq import Error, Payload # >>> errors: List[Error] = [] # >>> payload = Payload(b'test bytes') # >>> err = Error( # ... error='This is our error message', # ... plugin_name='test_plugin', # ... payload_id=payload.results.payload_id # ... ) # >>> errors.append(err) # # """ # self.error = error # self.plugin_name = plugin_name # self.payload_id = payload_id # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/exceptions.py # class StoqException(Exception): # pass # # class StoqPluginNotFound(Exception): # pass # # Path: stoq/plugins/base.py # class BasePlugin(ABC): # def __init__(self, config: StoqConfigParser) -> None: # self.config = config # self.plugin_name = config.get('Core', 'Name', fallback=self.__class__.__name__) # self.__author__ = config.get('Documentation', 'Author', fallback='') # self.__version__ = config.get('Documentation', 'Version', fallback='') # self.__website__ = config.get('Documentation', 'Website', fallback='') # self.__description__ = config.get('Documentation', 'Description', fallback='') # self.log = logging.getLogger(f'stoq.{self.plugin_name}') # # Path: stoq/plugins/archiver.py # class ArchiverPlugin(BasePlugin): # async def archive( # self, payload: Payload, request: Request # ) -> Optional[ArchiverResponse]: # """ # Archive payload # # :param payload: Payload object to archive # :param request: Originating Request object # # :return: ArchiverResponse object. Results are used to retrieve payload. # # >>> import asyncio # >>> from stoq import Stoq, Payload # >>> payload = Payload(b'this is going to be saved') # >>> s = Stoq() # >>> loop = asyncio.get_event_loop() # >>> archiver = s.load_plugin('filedir') # >>> loop.run_until_complete(archiver.archive(payload)) # ... {'path': '/tmp/bad.exe'} # # """ # pass # # async def get(self, task: ArchiverResponse) -> Optional[Payload]: # """ # Retrieve payload for processing # # :param task: Task to be processed to load payload. Must contain `ArchiverResponse` # results from `ArchiverPlugin.archive()` # # :return: Payload object for scanning # # >>> import asyncio # >>> from stoq import Stoq, ArchiverResponse # >>> s = Stoq() # >>> loop = asyncio.get_event_loop() # >>> archiver = s.load_plugin('filedir') # >>> task = ArchiverResponse(results={'path': '/tmp/bad.exe'}) # >>> payload = loop.run_until_complete(archiver.get(task)) # # """ # pass # # Path: stoq/plugins/connector.py # class ConnectorPlugin(BasePlugin, ABC): # @abstractmethod # async def save(self, response: StoqResponse) -> None: # pass # # Path: stoq/plugins/provider.py # class ProviderPlugin(BasePlugin, ABC): # @abstractmethod # async def ingest(self, queue: Queue) -> None: # pass # # Path: stoq/plugins/worker.py # class WorkerPlugin(BasePlugin, ABC): # def __init__(self, config: StoqConfigParser) -> None: # super().__init__(config) # self.required_workers = config.getset( # 'options', 'required_workers', fallback=set() # ) # # @abstractmethod # async def scan( # self, payload: Payload, request: Request # ) -> Optional[WorkerResponse]: # pass # # Path: stoq/plugins/dispatcher.py # class DispatcherPlugin(BasePlugin, ABC): # @abstractmethod # async def get_dispatches( # self, payload: Payload, request: Request # ) -> Optional[DispatcherResponse]: # pass # # Path: stoq/plugins/decorator.py # class DecoratorPlugin(BasePlugin, ABC): # @abstractmethod # async def decorate(self, response: StoqResponse) -> Optional[DecoratorResponse]: # pass . Output only the next line.
) and self._stoq_config.has_section( # pyre-ignore[16]
Predict the next line for this snippet: <|code_start|> if parse_version(__version__) < parse_version(min_stoq_version): self.log.warning( f'Plugin {plugin_name} not compatible with this version of ' 'stoQ. Unpredictable results may occur!' ) spec = importlib.util.spec_from_file_location( plugin_config.get('Core', 'Module'), module_path ) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) # type: ignore plugin_classes = inspect.getmembers( module, predicate=lambda mem: inspect.isclass(mem) and issubclass(mem, BasePlugin) and mem not in [ ArchiverPlugin, BasePlugin, ProviderPlugin, WorkerPlugin, ConnectorPlugin, DispatcherPlugin, DecoratorPlugin, ] and not inspect.isabstract(mem), ) if len(plugin_classes) == 0: raise StoqException( f'No valid plugin classes found in the module for {plugin_name}' ) <|code_end|> with the help of current file imports: import os import inspect import logging import configparser import importlib.util import stoq.helpers as helpers import ast from pkg_resources import parse_version from typing import Dict, List, Optional, Tuple, Any, Union from stoq.data_classes import Error from .exceptions import StoqException, StoqPluginNotFound from stoq.plugins import ( ArchiverPlugin, BasePlugin, ProviderPlugin, WorkerPlugin, ConnectorPlugin, DispatcherPlugin, DecoratorPlugin, ) from stoq import __version__ and context from other files: # Path: stoq/data_classes.py # class Error: # def __init__( # self, # error: str, # plugin_name: Optional[str] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object for errors collected from plugins # # :param error: Error message to add to results # :param plugin_name: The name of the plugin producing the error # :param payload_id: The ``payload_id`` of the ``Payload`` that the error occurred on # # >>> from stoq import Error, Payload # >>> errors: List[Error] = [] # >>> payload = Payload(b'test bytes') # >>> err = Error( # ... error='This is our error message', # ... plugin_name='test_plugin', # ... payload_id=payload.results.payload_id # ... ) # >>> errors.append(err) # # """ # self.error = error # self.plugin_name = plugin_name # self.payload_id = payload_id # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/exceptions.py # class StoqException(Exception): # pass # # class StoqPluginNotFound(Exception): # pass # # Path: stoq/plugins/base.py # class BasePlugin(ABC): # def __init__(self, config: StoqConfigParser) -> None: # self.config = config # self.plugin_name = config.get('Core', 'Name', fallback=self.__class__.__name__) # self.__author__ = config.get('Documentation', 'Author', fallback='') # self.__version__ = config.get('Documentation', 'Version', fallback='') # self.__website__ = config.get('Documentation', 'Website', fallback='') # self.__description__ = config.get('Documentation', 'Description', fallback='') # self.log = logging.getLogger(f'stoq.{self.plugin_name}') # # Path: stoq/plugins/archiver.py # class ArchiverPlugin(BasePlugin): # async def archive( # self, payload: Payload, request: Request # ) -> Optional[ArchiverResponse]: # """ # Archive payload # # :param payload: Payload object to archive # :param request: Originating Request object # # :return: ArchiverResponse object. Results are used to retrieve payload. # # >>> import asyncio # >>> from stoq import Stoq, Payload # >>> payload = Payload(b'this is going to be saved') # >>> s = Stoq() # >>> loop = asyncio.get_event_loop() # >>> archiver = s.load_plugin('filedir') # >>> loop.run_until_complete(archiver.archive(payload)) # ... {'path': '/tmp/bad.exe'} # # """ # pass # # async def get(self, task: ArchiverResponse) -> Optional[Payload]: # """ # Retrieve payload for processing # # :param task: Task to be processed to load payload. Must contain `ArchiverResponse` # results from `ArchiverPlugin.archive()` # # :return: Payload object for scanning # # >>> import asyncio # >>> from stoq import Stoq, ArchiverResponse # >>> s = Stoq() # >>> loop = asyncio.get_event_loop() # >>> archiver = s.load_plugin('filedir') # >>> task = ArchiverResponse(results={'path': '/tmp/bad.exe'}) # >>> payload = loop.run_until_complete(archiver.get(task)) # # """ # pass # # Path: stoq/plugins/connector.py # class ConnectorPlugin(BasePlugin, ABC): # @abstractmethod # async def save(self, response: StoqResponse) -> None: # pass # # Path: stoq/plugins/provider.py # class ProviderPlugin(BasePlugin, ABC): # @abstractmethod # async def ingest(self, queue: Queue) -> None: # pass # # Path: stoq/plugins/worker.py # class WorkerPlugin(BasePlugin, ABC): # def __init__(self, config: StoqConfigParser) -> None: # super().__init__(config) # self.required_workers = config.getset( # 'options', 'required_workers', fallback=set() # ) # # @abstractmethod # async def scan( # self, payload: Payload, request: Request # ) -> Optional[WorkerResponse]: # pass # # Path: stoq/plugins/dispatcher.py # class DispatcherPlugin(BasePlugin, ABC): # @abstractmethod # async def get_dispatches( # self, payload: Payload, request: Request # ) -> Optional[DispatcherResponse]: # pass # # Path: stoq/plugins/decorator.py # class DecoratorPlugin(BasePlugin, ABC): # @abstractmethod # async def decorate(self, response: StoqResponse) -> Optional[DecoratorResponse]: # pass , which may contain function names, class names, or code. Output only the next line.
if len(plugin_classes) > 1:
Given snippet: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 DummyWorker2(WorkerPlugin): async def scan( self, payload: Payload, request: Request ) -> Optional[WorkerResponse]: <|code_end|> , continue by predicting the next line. Consider current file imports: from typing import Optional from stoq.data_classes import Payload, Request, WorkerResponse from stoq.plugins import WorkerPlugin and context: # Path: stoq/data_classes.py # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class WorkerResponse: # def __init__( # self, # results: Optional[Dict] = None, # extracted: Optional[List[ExtractedPayload]] = None, # errors: Optional[List[Error]] = None, # dispatch_to: Optional[List[str]] = None, # ) -> None: # """ # # Object containing response from worker plugins # # :param results: Results from worker scan # :param extracted: ``ExtractedPayload`` objects of extracted payloads from scan # :param errors: Errors that occurred # # >>> from stoq import WorkerResponse, ExtractedPayload # >>> results = {'is_bad': True, 'filetype': 'executable'} # >>> extracted_payload = [ExtractedPayload(content=data, payload_meta=extracted_meta)] # >>> response = WorkerResponse(results=results, extracted=extracted_payload) # # """ # self.results = results # self.extracted = extracted or [] # self.errors = errors or [] # self.dispatch_to = dispatch_to or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/worker.py # class WorkerPlugin(BasePlugin, ABC): # def __init__(self, config: StoqConfigParser) -> None: # super().__init__(config) # self.required_workers = config.getset( # 'options', 'required_workers', fallback=set() # ) # # @abstractmethod # async def scan( # self, payload: Payload, request: Request # ) -> Optional[WorkerResponse]: # pass which might include code, classes, or functions. Output only the next line.
pass
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 DummyWorker2(WorkerPlugin): async def scan( self, payload: Payload, request: Request ) -> Optional[WorkerResponse]: <|code_end|> with the help of current file imports: from typing import Optional from stoq.data_classes import Payload, Request, WorkerResponse from stoq.plugins import WorkerPlugin and context from other files: # Path: stoq/data_classes.py # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class WorkerResponse: # def __init__( # self, # results: Optional[Dict] = None, # extracted: Optional[List[ExtractedPayload]] = None, # errors: Optional[List[Error]] = None, # dispatch_to: Optional[List[str]] = None, # ) -> None: # """ # # Object containing response from worker plugins # # :param results: Results from worker scan # :param extracted: ``ExtractedPayload`` objects of extracted payloads from scan # :param errors: Errors that occurred # # >>> from stoq import WorkerResponse, ExtractedPayload # >>> results = {'is_bad': True, 'filetype': 'executable'} # >>> extracted_payload = [ExtractedPayload(content=data, payload_meta=extracted_meta)] # >>> response = WorkerResponse(results=results, extracted=extracted_payload) # # """ # self.results = results # self.extracted = extracted or [] # self.errors = errors or [] # self.dispatch_to = dispatch_to or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/worker.py # class WorkerPlugin(BasePlugin, ABC): # def __init__(self, config: StoqConfigParser) -> None: # super().__init__(config) # self.required_workers = config.getset( # 'options', 'required_workers', fallback=set() # ) # # @abstractmethod # async def scan( # self, payload: Payload, request: Request # ) -> Optional[WorkerResponse]: # pass , which may contain function names, class names, or code. Output only the next line.
pass
Next line prediction: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 DummyWorker2(WorkerPlugin): async def scan( self, payload: Payload, request: Request ) -> Optional[WorkerResponse]: <|code_end|> . Use current file imports: (from typing import Optional from stoq.data_classes import Payload, Request, WorkerResponse from stoq.plugins import WorkerPlugin) and context including class names, function names, or small code snippets from other files: # Path: stoq/data_classes.py # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class WorkerResponse: # def __init__( # self, # results: Optional[Dict] = None, # extracted: Optional[List[ExtractedPayload]] = None, # errors: Optional[List[Error]] = None, # dispatch_to: Optional[List[str]] = None, # ) -> None: # """ # # Object containing response from worker plugins # # :param results: Results from worker scan # :param extracted: ``ExtractedPayload`` objects of extracted payloads from scan # :param errors: Errors that occurred # # >>> from stoq import WorkerResponse, ExtractedPayload # >>> results = {'is_bad': True, 'filetype': 'executable'} # >>> extracted_payload = [ExtractedPayload(content=data, payload_meta=extracted_meta)] # >>> response = WorkerResponse(results=results, extracted=extracted_payload) # # """ # self.results = results # self.extracted = extracted or [] # self.errors = errors or [] # self.dispatch_to = dispatch_to or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/worker.py # class WorkerPlugin(BasePlugin, ABC): # def __init__(self, config: StoqConfigParser) -> None: # super().__init__(config) # self.required_workers = config.getset( # 'options', 'required_workers', fallback=set() # ) # # @abstractmethod # async def scan( # self, payload: Payload, request: Request # ) -> Optional[WorkerResponse]: # pass . Output only the next line.
pass
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 DummyWorker(WorkerPlugin): PLUGINS2_DUP_MARKER = True async def scan( self, payload: Payload, request: Request ) -> Optional[WorkerResponse]: <|code_end|> using the current file's imports: from typing import Optional from stoq.data_classes import Payload, Request, WorkerResponse from stoq.plugins import WorkerPlugin and any relevant context from other files: # Path: stoq/data_classes.py # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class WorkerResponse: # def __init__( # self, # results: Optional[Dict] = None, # extracted: Optional[List[ExtractedPayload]] = None, # errors: Optional[List[Error]] = None, # dispatch_to: Optional[List[str]] = None, # ) -> None: # """ # # Object containing response from worker plugins # # :param results: Results from worker scan # :param extracted: ``ExtractedPayload`` objects of extracted payloads from scan # :param errors: Errors that occurred # # >>> from stoq import WorkerResponse, ExtractedPayload # >>> results = {'is_bad': True, 'filetype': 'executable'} # >>> extracted_payload = [ExtractedPayload(content=data, payload_meta=extracted_meta)] # >>> response = WorkerResponse(results=results, extracted=extracted_payload) # # """ # self.results = results # self.extracted = extracted or [] # self.errors = errors or [] # self.dispatch_to = dispatch_to or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/worker.py # class WorkerPlugin(BasePlugin, ABC): # def __init__(self, config: StoqConfigParser) -> None: # super().__init__(config) # self.required_workers = config.getset( # 'options', 'required_workers', fallback=set() # ) # # @abstractmethod # async def scan( # self, payload: Payload, request: Request # ) -> Optional[WorkerResponse]: # pass . Output only the next line.
return None
Given the code snippet: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 DummyWorker(WorkerPlugin): PLUGINS2_DUP_MARKER = True async def scan( self, payload: Payload, request: Request ) -> Optional[WorkerResponse]: <|code_end|> , generate the next line using the imports in this file: from typing import Optional from stoq.data_classes import Payload, Request, WorkerResponse from stoq.plugins import WorkerPlugin and context (functions, classes, or occasionally code) from other files: # Path: stoq/data_classes.py # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class WorkerResponse: # def __init__( # self, # results: Optional[Dict] = None, # extracted: Optional[List[ExtractedPayload]] = None, # errors: Optional[List[Error]] = None, # dispatch_to: Optional[List[str]] = None, # ) -> None: # """ # # Object containing response from worker plugins # # :param results: Results from worker scan # :param extracted: ``ExtractedPayload`` objects of extracted payloads from scan # :param errors: Errors that occurred # # >>> from stoq import WorkerResponse, ExtractedPayload # >>> results = {'is_bad': True, 'filetype': 'executable'} # >>> extracted_payload = [ExtractedPayload(content=data, payload_meta=extracted_meta)] # >>> response = WorkerResponse(results=results, extracted=extracted_payload) # # """ # self.results = results # self.extracted = extracted or [] # self.errors = errors or [] # self.dispatch_to = dispatch_to or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/worker.py # class WorkerPlugin(BasePlugin, ABC): # def __init__(self, config: StoqConfigParser) -> None: # super().__init__(config) # self.required_workers = config.getset( # 'options', 'required_workers', fallback=set() # ) # # @abstractmethod # async def scan( # self, payload: Payload, request: Request # ) -> Optional[WorkerResponse]: # pass . Output only the next line.
return None
Next line prediction: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 DummyWorker(WorkerPlugin): async def scan( self, payload: Payload, request: Request ) -> Optional[WorkerResponse]: <|code_end|> . Use current file imports: (from typing import Optional from stoq.data_classes import Payload, Request, WorkerResponse from stoq.plugins import WorkerPlugin) and context including class names, function names, or small code snippets from other files: # Path: stoq/data_classes.py # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class WorkerResponse: # def __init__( # self, # results: Optional[Dict] = None, # extracted: Optional[List[ExtractedPayload]] = None, # errors: Optional[List[Error]] = None, # dispatch_to: Optional[List[str]] = None, # ) -> None: # """ # # Object containing response from worker plugins # # :param results: Results from worker scan # :param extracted: ``ExtractedPayload`` objects of extracted payloads from scan # :param errors: Errors that occurred # # >>> from stoq import WorkerResponse, ExtractedPayload # >>> results = {'is_bad': True, 'filetype': 'executable'} # >>> extracted_payload = [ExtractedPayload(content=data, payload_meta=extracted_meta)] # >>> response = WorkerResponse(results=results, extracted=extracted_payload) # # """ # self.results = results # self.extracted = extracted or [] # self.errors = errors or [] # self.dispatch_to = dispatch_to or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/worker.py # class WorkerPlugin(BasePlugin, ABC): # def __init__(self, config: StoqConfigParser) -> None: # super().__init__(config) # self.required_workers = config.getset( # 'options', 'required_workers', fallback=set() # ) # # @abstractmethod # async def scan( # self, payload: Payload, request: Request # ) -> Optional[WorkerResponse]: # pass . Output only the next line.
return None
Continue the code snippet: <|code_start|> ) -> None: if github: if plugin_path.startswith('git+http'): pass elif plugin_path.startswith('stoq:'): plugin_name = plugin_path.split(':')[1] plugin_path = f'{StoqPluginInstaller.DEFAULT_REPO}#egg={plugin_name}&subdirectory={plugin_name}' else: raise StoqException('Invalid Github repository specified.') else: plugin_path = os.path.abspath(plugin_path) if not os.path.isdir(plugin_path): raise StoqException( f'Given plugin directory does not exist: {plugin_path}' ) install_dir = os.path.abspath(install_dir) if not os.path.isdir(install_dir): raise StoqException( f'Given install directory does not exist: {install_dir}' ) StoqPluginInstaller.setup_package(plugin_path, install_dir, upgrade, github) @staticmethod def setup_package( plugin_path: str, install_dir: str, upgrade: bool, github: bool ) -> None: if github: url = ( plugin_path.split('+')[1] .split('#')[0] <|code_end|> . Use current file imports: import os import sys import logging import requests import subprocess from tempfile import NamedTemporaryFile from .exceptions import StoqException, StoqPluginException and context (classes, functions, or code) from other files: # Path: stoq/exceptions.py # class StoqException(Exception): # pass # # class StoqPluginException(Exception): # pass . Output only the next line.
.replace('.git', '')
Next line prediction: <|code_start|> .split('#')[0] .replace('.git', '') .replace('github.com', 'raw.githubusercontent.com') .replace('@', '/') ) path = plugin_path.split('subdirectory=')[1] requirements = f'{url}/{path}/requirements.txt' with NamedTemporaryFile() as temp_file: response = requests.get(requirements) if response.status_code == 200: temp_file.write(response.content) temp_file.flush() subprocess.check_call( [ sys.executable, '-m', 'pip', 'install', '--quiet', '-r', temp_file.name, ] ) elif response.status_code == 404: pass else: log.info(f'Failed to install requirements from {requirements}') else: requirements = f'{plugin_path}/requirements.txt' if os.path.isfile(requirements): <|code_end|> . Use current file imports: (import os import sys import logging import requests import subprocess from tempfile import NamedTemporaryFile from .exceptions import StoqException, StoqPluginException) and context including class names, function names, or small code snippets from other files: # Path: stoq/exceptions.py # class StoqException(Exception): # pass # # class StoqPluginException(Exception): # pass . Output only the next line.
subprocess.check_call(
Continue the code snippet: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 ExtractPayload(WorkerPlugin): EXTRACTED_PAYLOAD = None async def scan( self, payload: Payload, request: Request ) -> Optional[WorkerResponse]: if self.EXTRACTED_PAYLOAD: return WorkerResponse( extracted=[ExtractedPayload(self.EXTRACTED_PAYLOAD)] # type: ignore ) <|code_end|> . Use current file imports: import os from typing import Optional from stoq.data_classes import ExtractedPayload, Payload, Request, WorkerResponse from stoq.plugins import WorkerPlugin and context (classes, functions, or code) from other files: # Path: stoq/data_classes.py # class ExtractedPayload: # def __init__( # self, content: bytes, payload_meta: Optional[PayloadMeta] = None # ) -> None: # """ # # Object to store extracted payloads for further analysis # # :param content: Raw bytes of extracted payload # :param payload_meta: ``PayloadMeta`` object containing metadata about extracted payload # # >>> from stoq import PayloadMeta, ExtractedPayload # >>> src = '/tmp/bad.exe' # >>> data = open(src, 'rb').read() # >>> extra_data = {'source': src} # >>> extracted_meta = PayloadMeta(should_archive=True, extra_data=extra_data) # >>> extracted_payload = ExtractedPayload(content=data, payload_meta=extracted_meta) # # """ # # self.content = content # self.payload_meta: PayloadMeta = PayloadMeta() if payload_meta is None else payload_meta # # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class WorkerResponse: # def __init__( # self, # results: Optional[Dict] = None, # extracted: Optional[List[ExtractedPayload]] = None, # errors: Optional[List[Error]] = None, # dispatch_to: Optional[List[str]] = None, # ) -> None: # """ # # Object containing response from worker plugins # # :param results: Results from worker scan # :param extracted: ``ExtractedPayload`` objects of extracted payloads from scan # :param errors: Errors that occurred # # >>> from stoq import WorkerResponse, ExtractedPayload # >>> results = {'is_bad': True, 'filetype': 'executable'} # >>> extracted_payload = [ExtractedPayload(content=data, payload_meta=extracted_meta)] # >>> response = WorkerResponse(results=results, extracted=extracted_payload) # # """ # self.results = results # self.extracted = extracted or [] # self.errors = errors or [] # self.dispatch_to = dispatch_to or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/worker.py # class WorkerPlugin(BasePlugin, ABC): # def __init__(self, config: StoqConfigParser) -> None: # super().__init__(config) # self.required_workers = config.getset( # 'options', 'required_workers', fallback=set() # ) # # @abstractmethod # async def scan( # self, payload: Payload, request: Request # ) -> Optional[WorkerResponse]: # pass . Output only the next line.
else:
Given the code snippet: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 ExtractPayload(WorkerPlugin): EXTRACTED_PAYLOAD = None async def scan( self, payload: Payload, request: Request ) -> Optional[WorkerResponse]: if self.EXTRACTED_PAYLOAD: return WorkerResponse( extracted=[ExtractedPayload(self.EXTRACTED_PAYLOAD)] # type: ignore ) <|code_end|> , generate the next line using the imports in this file: import os from typing import Optional from stoq.data_classes import ExtractedPayload, Payload, Request, WorkerResponse from stoq.plugins import WorkerPlugin and context (functions, classes, or occasionally code) from other files: # Path: stoq/data_classes.py # class ExtractedPayload: # def __init__( # self, content: bytes, payload_meta: Optional[PayloadMeta] = None # ) -> None: # """ # # Object to store extracted payloads for further analysis # # :param content: Raw bytes of extracted payload # :param payload_meta: ``PayloadMeta`` object containing metadata about extracted payload # # >>> from stoq import PayloadMeta, ExtractedPayload # >>> src = '/tmp/bad.exe' # >>> data = open(src, 'rb').read() # >>> extra_data = {'source': src} # >>> extracted_meta = PayloadMeta(should_archive=True, extra_data=extra_data) # >>> extracted_payload = ExtractedPayload(content=data, payload_meta=extracted_meta) # # """ # # self.content = content # self.payload_meta: PayloadMeta = PayloadMeta() if payload_meta is None else payload_meta # # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class WorkerResponse: # def __init__( # self, # results: Optional[Dict] = None, # extracted: Optional[List[ExtractedPayload]] = None, # errors: Optional[List[Error]] = None, # dispatch_to: Optional[List[str]] = None, # ) -> None: # """ # # Object containing response from worker plugins # # :param results: Results from worker scan # :param extracted: ``ExtractedPayload`` objects of extracted payloads from scan # :param errors: Errors that occurred # # >>> from stoq import WorkerResponse, ExtractedPayload # >>> results = {'is_bad': True, 'filetype': 'executable'} # >>> extracted_payload = [ExtractedPayload(content=data, payload_meta=extracted_meta)] # >>> response = WorkerResponse(results=results, extracted=extracted_payload) # # """ # self.results = results # self.extracted = extracted or [] # self.errors = errors or [] # self.dispatch_to = dispatch_to or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/worker.py # class WorkerPlugin(BasePlugin, ABC): # def __init__(self, config: StoqConfigParser) -> None: # super().__init__(config) # self.required_workers = config.getset( # 'options', 'required_workers', fallback=set() # ) # # @abstractmethod # async def scan( # self, payload: Payload, request: Request # ) -> Optional[WorkerResponse]: # pass . Output only the next line.
else:
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 ConditionalDispatcher(DispatcherPlugin): CONDITIONAL_DISPATCH_WORKER = 'dummy_worker' WORKERS = ['simple_worker'] async def get_dispatches( self, payload: Payload, request: Request ) -> Optional[DispatcherResponse]: dr = DispatcherResponse() <|code_end|> using the current file's imports: from typing import Optional from stoq.data_classes import Payload, DispatcherResponse, Request from stoq.plugins import DispatcherPlugin and any relevant context from other files: # Path: stoq/data_classes.py # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class DispatcherResponse: # def __init__( # self, # plugin_names: Optional[List[str]] = None, # meta: Optional[Dict] = None, # errors: Optional[List[Error]] = None, # ) -> None: # """ # # Object containing response from dispatcher plugins # # :param plugins_names: Plugins to send payload to for scanning # :param meta: Metadata pertaining to dispatching results # :param errors: Errors that occurred # # >>> from stoq import DispatcherResponse # >>> plugins = ['yara', 'exif'] # >>> meta = {'hit': 'exe_file'} # >>> dispatcher = DispatcherResponse(plugin_names=plugins, meta=meta) # # """ # self.plugin_names = [] if plugin_names is None else plugin_names # self.meta = {} if meta is None else meta # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/dispatcher.py # class DispatcherPlugin(BasePlugin, ABC): # @abstractmethod # async def get_dispatches( # self, payload: Payload, request: Request # ) -> Optional[DispatcherResponse]: # pass . Output only the next line.
if any(
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 ConditionalDispatcher(DispatcherPlugin): CONDITIONAL_DISPATCH_WORKER = 'dummy_worker' WORKERS = ['simple_worker'] async def get_dispatches( self, payload: Payload, request: Request ) -> Optional[DispatcherResponse]: dr = DispatcherResponse() if any( self.CONDITIONAL_DISPATCH_WORKER in request_payload.results.plugins_run['workers'] <|code_end|> , predict the next line using imports from the current file: from typing import Optional from stoq.data_classes import Payload, DispatcherResponse, Request from stoq.plugins import DispatcherPlugin and context including class names, function names, and sometimes code from other files: # Path: stoq/data_classes.py # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class DispatcherResponse: # def __init__( # self, # plugin_names: Optional[List[str]] = None, # meta: Optional[Dict] = None, # errors: Optional[List[Error]] = None, # ) -> None: # """ # # Object containing response from dispatcher plugins # # :param plugins_names: Plugins to send payload to for scanning # :param meta: Metadata pertaining to dispatching results # :param errors: Errors that occurred # # >>> from stoq import DispatcherResponse # >>> plugins = ['yara', 'exif'] # >>> meta = {'hit': 'exe_file'} # >>> dispatcher = DispatcherResponse(plugin_names=plugins, meta=meta) # # """ # self.plugin_names = [] if plugin_names is None else plugin_names # self.meta = {} if meta is None else meta # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/dispatcher.py # class DispatcherPlugin(BasePlugin, ABC): # @abstractmethod # async def get_dispatches( # self, payload: Payload, request: Request # ) -> Optional[DispatcherResponse]: # pass . Output only the next line.
for request_payload in request.payloads
Based on the snippet: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 ConditionalDispatcher(DispatcherPlugin): CONDITIONAL_DISPATCH_WORKER = 'dummy_worker' WORKERS = ['simple_worker'] async def get_dispatches( self, payload: Payload, request: Request ) -> Optional[DispatcherResponse]: dr = DispatcherResponse() if any( self.CONDITIONAL_DISPATCH_WORKER in request_payload.results.plugins_run['workers'] <|code_end|> , predict the immediate next line with the help of imports: from typing import Optional from stoq.data_classes import Payload, DispatcherResponse, Request from stoq.plugins import DispatcherPlugin and context (classes, functions, sometimes code) from other files: # Path: stoq/data_classes.py # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class DispatcherResponse: # def __init__( # self, # plugin_names: Optional[List[str]] = None, # meta: Optional[Dict] = None, # errors: Optional[List[Error]] = None, # ) -> None: # """ # # Object containing response from dispatcher plugins # # :param plugins_names: Plugins to send payload to for scanning # :param meta: Metadata pertaining to dispatching results # :param errors: Errors that occurred # # >>> from stoq import DispatcherResponse # >>> plugins = ['yara', 'exif'] # >>> meta = {'hit': 'exe_file'} # >>> dispatcher = DispatcherResponse(plugin_names=plugins, meta=meta) # # """ # self.plugin_names = [] if plugin_names is None else plugin_names # self.meta = {} if meta is None else meta # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/dispatcher.py # class DispatcherPlugin(BasePlugin, ABC): # @abstractmethod # async def get_dispatches( # self, payload: Payload, request: Request # ) -> Optional[DispatcherResponse]: # pass . Output only the next line.
for request_payload in request.payloads
Here is a snippet: <|code_start|>#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 ConditionalDispatcher(DispatcherPlugin): CONDITIONAL_DISPATCH_WORKER = 'dummy_worker' WORKERS = ['simple_worker'] async def get_dispatches( self, payload: Payload, request: Request ) -> Optional[DispatcherResponse]: dr = DispatcherResponse() if any( self.CONDITIONAL_DISPATCH_WORKER in request_payload.results.plugins_run['workers'] for request_payload in request.payloads <|code_end|> . Write the next line using the current file imports: from typing import Optional from stoq.data_classes import Payload, DispatcherResponse, Request from stoq.plugins import DispatcherPlugin and context from other files: # Path: stoq/data_classes.py # class Payload: # def __init__( # self, # content: Union[bytes, str], # payload_meta: Optional[PayloadMeta] = None, # extracted_by: Optional[Union[str, List[str]]] = None, # extracted_from: Optional[Union[str, List[str]]] = None, # payload_id: Optional[str] = None, # ) -> None: # """ # # Object to store payload and related information # # :param content: Raw bytes to be scanned # :param payload_meta: Metadata pertaining to originating source # :param extracted_by: Name of plugin that extracted the payload # :param extracted_from: Unique payload ID the payload was extracted from # :param payload_id: Unique ID of payload # # >>> from stoq import PayloadMeta, Payload # >>> content = b'This is a raw payload' # >>> payload_meta = PayloadMeta(should_archive=True) # >>> payload = Payload(content, payload_meta=payload_meta) # # """ # self.content = content if isinstance(content, bytes) else content.encode() # self.dispatch_meta: Dict[str, Dict] = {} # self.results = PayloadResults( # payload_id=payload_id, # size=len(content), # payload_meta=payload_meta, # extracted_from=extracted_from, # extracted_by=extracted_by, # ) # # def __repr__(self): # return repr(self.__dict__) # # class DispatcherResponse: # def __init__( # self, # plugin_names: Optional[List[str]] = None, # meta: Optional[Dict] = None, # errors: Optional[List[Error]] = None, # ) -> None: # """ # # Object containing response from dispatcher plugins # # :param plugins_names: Plugins to send payload to for scanning # :param meta: Metadata pertaining to dispatching results # :param errors: Errors that occurred # # >>> from stoq import DispatcherResponse # >>> plugins = ['yara', 'exif'] # >>> meta = {'hit': 'exe_file'} # >>> dispatcher = DispatcherResponse(plugin_names=plugins, meta=meta) # # """ # self.plugin_names = [] if plugin_names is None else plugin_names # self.meta = {} if meta is None else meta # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # class Request: # def __init__( # self, # payloads: Optional[List[Payload]] = None, # request_meta: Optional[RequestMeta] = None, # errors: Optional[List[Error]] = None, # ): # """ # # Object that contains the state of a ``Stoq`` scan. This object is accessible within # all archiver, dispatcher, and worker plugins. # # :param payloads: All payloads that are being processed, to include extracted payloads # :param request_meta: Original ``RequestMeta`` object # :param errors: All errors that have been generated by plugins or ``Stoq`` # # """ # # self.payloads = payloads or [] # self.request_meta = request_meta or RequestMeta() # self.errors = errors or [] # # def __str__(self) -> str: # return helpers.dumps(self) # # def __repr__(self): # return repr(self.__dict__) # # Path: stoq/plugins/dispatcher.py # class DispatcherPlugin(BasePlugin, ABC): # @abstractmethod # async def get_dispatches( # self, payload: Payload, request: Request # ) -> Optional[DispatcherResponse]: # pass , which may include functions, classes, or code. Output only the next line.
):
Continue the code snippet: <|code_start|> class OIDCCallbackView(OIDCAuthenticationCallbackView): def login_failure(self, msg=''): if not msg: msg = ('Login failed. Please make sure that you are ' <|code_end|> . Use current file imports: import feedparser import json import logging import requests import forms import utils from django import http from django.db.models import Q from django.conf import settings from django.contrib import messages from django.contrib.auth.models import User from django.core.cache import cache from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from django.http import Http404, HttpResponse, HttpResponseBadRequest from django.shortcuts import redirect, render from django.views import generic from django.views.decorators.cache import cache_control, never_cache from django_statsd.clients import statsd from mozilla_django_oidc.views import OIDCAuthenticationCallbackView from raven.contrib.django.models import client from remo.base.decorators import PermissionMixin, permission_check from remo.base.forms import EmailMentorForm from remo.featuredrep.models import FeaturedRep from remo.profiles.forms import UserStatusForm from remo.profiles.models import UserProfile, UserStatus and context (classes, functions, or code) from other files: # Path: remo/profiles/forms.py # class UserStatusForm(happyforms.ModelForm): # """Form for displaying info regarding the availability status of a user.""" # start_date = forms.DateField(input_formats=['%d %B %Y']) # expected_date = forms.DateField(input_formats=['%d %B %Y']) # is_replaced = forms.BooleanField(widget=forms.RadioSelect( # choices=BOOLEAN_CHOICES, attrs={'id': 'id_is_replaced'}), # required=False) # # def __init__(self, *args, **kwargs): # super(UserStatusForm, self).__init__(*args, **kwargs) # query = (User.objects.filter( # groups__name='Rep', userprofile__registration_complete=True) # .exclude(id=self.instance.user.id).order_by('first_name')) # self.fields['replacement_rep'].queryset = query # # if self.instance.id: # self.fields['expected_date'].widget = forms.HiddenInput() # self.fields['start_date'].widget = forms.HiddenInput() # self.fields['start_date'].required = False # # def clean(self): # """Clean Form.""" # cdata = super(UserStatusForm, self).clean() # # if self.instance.id: # cdata['start_date'] = self.instance.start_date # return cdata # # tomorrow = get_date(days=1) # today = get_date() # # if 'start_date' in cdata: # if cdata['start_date'] < today: # msg = u'Start date cannot be in the past.' # self._errors['start_date'] = self.error_class([msg]) # # if 'expected_date' in cdata: # start_date = cdata['start_date'] # expected_date = cdata['expected_date'] # max_period = start_date + timedelta(weeks=MAX_UNAVAILABILITY_PERIOD) # # if expected_date < tomorrow: # msg = (u'Return day cannot be earlier than {0}' # .format(tomorrow.strftime('%d %B %Y'))) # self._errors['expected_date'] = self.error_class([msg]) # if expected_date < start_date: # msg = u'Return date cannot be before start date.' # self._errors['expected_date'] = self.error_class([msg]) # if expected_date > max_period: # msg = (u'The maximum period for unavailability is until {0}.' # .format(max_period.strftime('%d %B %Y'))) # sop = mark_safe(msg + (' For more information please check ' # 'the %s') % LEAVING_SOP_URL) # self._errors['expected_date'] = self.error_class([sop]) # # if ('is_replaced' in cdata # and cdata['is_replaced'] and not cdata['replacement_rep']): # msg = 'Please select a replacement Rep during your absence.' # self._errors['replacement_rep'] = self.error_class([msg]) # # return cdata # # class Meta: # model = UserStatus # fields = ['start_date', 'expected_date', 'replacement_rep'] . Output only the next line.
'an accepted Rep or a vouched Mozillian '
Predict the next line for this snippet: <|code_start|> RE_PERIOD = r'period/(?P<period>\w+)/' RE_START = r'(start/(?P<start>\d{4}\-\d{2}\-\d{2})/)?' RE_END = r'(end/(?P<end>\d{4}\-\d{2}\-\d{2})/)?' RE_SEARCH = r'(search/(?P<search>.+?)/)?' urlpatterns = [ url(r'^new/$', events_views.edit_event, name='events_new_event'), url(r'^new$', RedirectView.as_view(url='new/', permanent=True)), url(r'^$', events_views.list_events, name='events_list_events'), url(r'^' + RE_PERIOD + RE_START + RE_END + RE_SEARCH + 'ical/$', events_views.multiple_event_ical, name='multiple_event_ical'), # This url is intentionally left without a $ url(r'^', events_views.redirect_list_events, name='events_list_profiles_redirect'), <|code_end|> with the help of current file imports: from django.conf.urls import url from django.views.generic import RedirectView from remo.events import views as events_views and context from other files: # Path: remo/events/views.py # def redirect_list_events(request): # def list_events(request): # def manage_subscription(request, slug, subscribe=True): # def view_event(request, slug): # def delete_event_comment(request, slug, pk): # def edit_event(request, slug=None, clone=None): # def delete_event(request, slug): # def export_single_event_to_ical(request, slug): # def email_attendees(request, slug): # def multiple_event_ical(request, period, start=None, end=None, search=None): , which may contain function names, class names, or code. Output only the next line.
]
Based on the snippet: <|code_start|> LINE_LIMIT = 75 FOLD_SEP = u'\r\n ' COUNTRIES_NAME_TO_CODE = {} for code, name in product_details.get_regions('en').items(): name = name.lower() COUNTRIES_NAME_TO_CODE[name] = code # Yanking filters from Django. library.filter(strip_tags) library.filter(defaultfilters.timesince) library.filter(defaultfilters.truncatewords) library.filter(defaultfilters.pluralize) @library.global_function <|code_end|> , predict the immediate next line with the help of imports: import re import time import urllib import urlparse import jinja2 from datetime import datetime, timedelta from django.conf import settings from django.contrib.auth.models import User from django.contrib.staticfiles.storage import staticfiles_storage from django.core.urlresolvers import reverse from django.template import defaultfilters from django.template.loader import render_to_string from django.utils.encoding import smart_str from django.utils.html import strip_tags from markdown import markdown as python_markdown from django_jinja import library from product_details import product_details from remo.base import utils and context (classes, functions, sometimes code) from other files: # Path: remo/base/utils.py # def absolutify(url): # def get_object_or_none(model_class, **kwargs): # def get_or_create_instance(model_class, **kwargs): # def go_back_n_months(date, n=1, first_day=False): # def go_fwd_n_months(date, n=1, first_day=False): # def latest_object_or_none(model_class, field_name=None): # def month2number(month): # def number2month(month, full_name=True): # def add_permissions_to_groups(app, permissions): # def validate_datetime(data, **kwargs): # def get_date(days=0, weeks=0): # def daterange(start_date, end_date): # def get_quarter(date=None): . Output only the next line.
def thisyear():
Given snippet: <|code_start|> @app.task def send_remo_mail(subject, recipients_list, sender=None, message=None, email_template=None, data=None, <|code_end|> , continue by predicting the next line. Consider current file imports: from django import forms from django.conf import settings from django.contrib.auth.models import User from django.core.mail import EmailMessage from django.core.validators import validate_email from django.template.loader import render_to_string from remo.celery import app import requests and context: # Path: remo/celery.py # RUN_DAILY = 60 * 60 * 24 # RUN_HOURLY = 60 * 60 # class Celery(BaseCelery): # def on_configure(self): # def setup_periodic_tasks(sender, **kwargs): which might include code, classes, or functions. Output only the next line.
headers=None):
Given snippet: <|code_start|> urlpatterns = [ url(r'^$', base_views.main, name='main'), url(r'^capture-csp-violation$', base_views.capture_csp_violation, name='capture-csp-violation'), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf.urls import url from remo.base import views as base_views and context: # Path: remo/base/views.py # class OIDCCallbackView(OIDCAuthenticationCallbackView): # class BaseListView(PermissionMixin, generic.ListView): # class BaseCreateView(PermissionMixin, generic.CreateView): # class BaseUpdateView(PermissionMixin, generic.UpdateView): # class BaseDeleteView(PermissionMixin, generic.DeleteView): # def login_failure(self, msg=''): # def main(request): # def custom_404(request): # def custom_500(request): # def robots_txt(request): # def edit_settings(request): # def edit_availability(request, display_name): # def get_context_data(self, **kwargs): # def get_context_data(self, **kwargs): # def form_valid(self, form): # def get_context_data(self, **kwargs): # def form_valid(self, form): # def get(self, request, *args, **kwargs): # def post(self, request, *args, **kwargs): # def delete(self, request, *args, **kwargs): # def capture_csp_violation(request): which might include code, classes, or functions. Output only the next line.
]
Given snippet: <|code_start|> OPTIONAL_PARAMETER_REGEX = r'(?:/(?P<day>\d+)/(?P<id>\d+))?' urlpatterns = [ url(r'^(?P<year>\d+)/(?P<month>\w+)%s/$' % OPTIONAL_PARAMETER_REGEX, views.view_ng_report, name='reports_ng_view_report'), url(r'^(?P<year>\d+)/(?P<month>\w+)/(?P<day>\d+)/(?P<id>\d+)/edit/$', views.edit_ng_report, name='reports_ng_edit_report'), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf.urls import url from remo.reports import views and context: # Path: remo/reports/views.py # LIST_NG_REPORTS_DEFAULT_SORT = 'created_date_desc' # LIST_NG_REPORTS_VALID_SORTS = { # 'reporter_desc': '-user__last_name,user__first_name', # 'reporter_asc': 'user__last_name,user__first_name', # 'mentor_desc': '-mentor__last_name,mentor__first_name', # 'mentor_asc': 'mentor__last_name,mentor__first_name', # 'activity_desc': '-activity__name', # 'activity_asc': 'activity__name', # 'report_date_desc': '-report_date', # 'report_date_asc': 'report_date', # 'created_date_desc': '-created_on', # 'created_date_asc': 'created_on'} # def edit_ng_report(request, display_name='', year=None, month=None, day=None, id=None): # def view_ng_report(request, display_name, year, month, day=None, id=None): # def delete_ng_report(request, display_name, year, month, day, id): # def delete_ng_report_comment(request, display_name, year, month, day, id, comment_id): # def list_ng_reports(request, mentor=None, rep=None, functional_area_slug=None): which might include code, classes, or functions. Output only the next line.
url(r'^(?P<year>\d+)/(?P<month>\w+)/(?P<day>\d+)/(?P<id>\d+)/delete/$',
Using the snippet: <|code_start|> urlpatterns = [ url(r'^$', dashboard_views.dashboard, name='dashboard'), url(r'^emailmentees/$', dashboard_views.email_mentees, name='email_mentees'), <|code_end|> , determine the next line of code. You have imports: from django.views.generic import RedirectView from django.conf.urls import url from remo.dashboard import views as dashboard_views and context (class names, function names, or code) available: # Path: remo/dashboard/views.py # LIST_ACTION_ITEMS_DEFAULT_SORT = 'action_item_date_desc' # LIST_ACTION_ITEMS_VALID_SORTS = { # 'action_desc': '-name', # 'action_asc': 'name', # 'action_item_priority_desc': '-priority', # 'action_item_priority_asc': 'priority', # 'action_item_date_desc': '-due_date', # 'action_item_date_asc': 'due_date' # } # def dashboard_mozillians(request, user): # def dashboard(request): # def email_mentees(request): # def list_action_items(request): # def kpi(request): . Output only the next line.
url(r'^stats/$', RedirectView.as_view(url='/dashboard/kpi/', permanent=True)),
Based on the snippet: <|code_start|> INACTIVE_HIGH = timedelta(weeks=8) INACTIVE_LOW = timedelta(weeks=4) @library.filter <|code_end|> , predict the immediate next line with the help of imports: import urlparse from datetime import timedelta from django.conf import settings from django.utils import timezone from django_jinja import library from libravatar import libravatar_url from remo.base.templatetags.helpers import urlparams from remo.profiles.models import FunctionalArea, UserAvatar from remo.reports.utils import get_last_report and context (classes, functions, sometimes code) from other files: # Path: remo/base/templatetags/helpers.py # @library.filter # def urlparams(url_, hash=None, **query): # """Add a fragment and/or query paramaters to a URL. # # New query params will be appended to exising parameters, except duplicate # names, which will be replaced. # """ # url = urlparse.urlparse(url_) # fragment = hash if hash is not None else url.fragment # # # Use dict(parse_qsl) so we don't get lists of values. # q = url.query # query_dict = dict(urlparse.parse_qsl(smart_str(q))) if q else {} # query_dict.update((k, v) for k, v in query.items()) # # query_string = _urlencode([(k, v) for k, v in query_dict.items() # if v is not None]) # new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params, # query_string, fragment) # return new.geturl() # # Path: remo/reports/utils.py # def get_last_report(user): # """Return user's last report in the past.""" # today = now().date() # # try: # reports = user.ng_reports.filter(report_date__lte=today) # return reports.latest('report_date') # except NGReport.DoesNotExist: # return None . Output only the next line.
def get_avatar_url(user, size=50):
Predict the next line after this snippet: <|code_start|> INACTIVE_HIGH = timedelta(weeks=8) INACTIVE_LOW = timedelta(weeks=4) @library.filter <|code_end|> using the current file's imports: import urlparse from datetime import timedelta from django.conf import settings from django.utils import timezone from django_jinja import library from libravatar import libravatar_url from remo.base.templatetags.helpers import urlparams from remo.profiles.models import FunctionalArea, UserAvatar from remo.reports.utils import get_last_report and any relevant context from other files: # Path: remo/base/templatetags/helpers.py # @library.filter # def urlparams(url_, hash=None, **query): # """Add a fragment and/or query paramaters to a URL. # # New query params will be appended to exising parameters, except duplicate # names, which will be replaced. # """ # url = urlparse.urlparse(url_) # fragment = hash if hash is not None else url.fragment # # # Use dict(parse_qsl) so we don't get lists of values. # q = url.query # query_dict = dict(urlparse.parse_qsl(smart_str(q))) if q else {} # query_dict.update((k, v) for k, v in query.items()) # # query_string = _urlencode([(k, v) for k, v in query_dict.items() # if v is not None]) # new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params, # query_string, fragment) # return new.geturl() # # Path: remo/reports/utils.py # def get_last_report(user): # """Return user's last report in the past.""" # today = now().date() # # try: # reports = user.ng_reports.filter(report_date__lte=today) # return reports.latest('report_date') # except NGReport.DoesNotExist: # return None . Output only the next line.
def get_avatar_url(user, size=50):
Using the snippet: <|code_start|> KPI_WEEKS = 12 # Number of activities CORE = 4 ACTIVE = 1 CASUAL = 1 INACTIVE = 0 # Activities Thresholds: # The max period in which we are looking to find reports for a user # both in past and future, measured in weeks CASUAL_INACTIVE = 4 ACTIVE_CORE = 2 class UserProfileFilter(django_filters.FilterSet): groups = django_filters.CharFilter(name='groups__name') functional_areas = django_filters.CharFilter( name='userprofile__functional_areas__name') mobilising_skills = django_filters.CharFilter( name='userprofile__mobilising_skills__name') mobilising_interests = django_filters.CharFilter( name='userprofile__mobilising_interests__name') mentor = django_filters.CharFilter(name='userprofile__mentor') city = django_filters.CharFilter(name='userprofile__city') region = django_filters.CharFilter(name='userprofile__region') country = django_filters.CharFilter(name='userprofile__country') twitter = django_filters.CharFilter(name='userprofile__twitter_account') <|code_end|> , determine the next line of code. You have imports: from collections import namedtuple from datetime import datetime, timedelta from django.db.models import Count, Q from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from django.utils.timezone import now from rest_framework.views import APIView from rest_framework.response import Response from remo.profiles.api.serializers import (PeopleKPISerializer, UserProfileDetailedSerializer, UserSerializer) from remo.api.views import BaseReadOnlyModelViewset from remo.base.utils import get_quarter from remo.profiles.models import UserProfile import django_filters and context (class names, function names, or code) available: # Path: remo/profiles/api/serializers.py # class PeopleKPISerializer(BaseKPISerializer): # """Serializer for people (Reps) data.""" # inactive_week = serializers.IntegerField() # casual_week = serializers.IntegerField() # active_week = serializers.IntegerField() # core_week = serializers.IntegerField() # # class UserProfileDetailedSerializer(serializers.HyperlinkedModelSerializer): # """Detailed serializer for the UserProfile model.""" # first_name = serializers.ReadOnlyField(source='user.first_name') # last_name = serializers.ReadOnlyField(source='user.last_name') # mentor = UserSerializer() # groups = GroupSerializer(source='user.groups', many=True) # functional_areas = FunctionalAreaSerializer(many=True) # mobilising_skills = MobilisingSkillSerializer(many=True) # mobilising_interests = MobilisingInterestSerializer(many=True) # remo_url = serializers.SerializerMethodField() # date_joined_program = serializers.DateTimeField(format='%Y-%m-%d') # date_left_program = serializers.DateTimeField(format='%Y-%m-%d') # # class Meta: # model = UserProfile # # Todo add logic for mozillians_username # fields = ['first_name', 'last_name', 'display_name', # 'date_joined_program', 'date_left_program', 'city', 'region', # 'country', 'twitter_account', 'jabber_id', 'irc_name', # 'wiki_profile_url', 'irc_channels', 'linkedin_url', # 'facebook_url', 'diaspora_url', 'functional_areas', 'mobilising_skills', # 'mobilising_interests', 'bio', 'mentor', 'mozillians_profile_url', # 'timezone', 'groups', 'remo_url'] # # def get_remo_url(self, obj): # """ # Default method for fetching the profile url for the user # in ReMo portal. # """ # return absolutify(obj.get_absolute_url()) # # class UserSerializer(serializers.HyperlinkedModelSerializer): # """Serializer for the django User model.""" # display_name = serializers.ReadOnlyField(source='userprofile.display_name') # # class Meta: # model = User # fields = ['first_name', 'last_name', 'display_name', '_url'] # # Path: remo/base/utils.py # def get_quarter(date=None): # """Return the quarter for this date and datetime of Q's start.""" # if not date: # date = timezone.now() # # quarter = int(math.ceil(date.month / 3.0)) # first_month_of_quarter = 1 + 3 * (quarter - 1) # quarter_start = datetime.datetime(date.year, first_month_of_quarter, 1) # # return (quarter, quarter_start) . Output only the next line.
jabber = django_filters.CharFilter(name='userprofile__jabber_id')
Given the following code snippet before the placeholder: <|code_start|> KPI_WEEKS = 12 # Number of activities CORE = 4 ACTIVE = 1 CASUAL = 1 INACTIVE = 0 # Activities Thresholds: # The max period in which we are looking to find reports for a user # both in past and future, measured in weeks CASUAL_INACTIVE = 4 ACTIVE_CORE = 2 class UserProfileFilter(django_filters.FilterSet): groups = django_filters.CharFilter(name='groups__name') <|code_end|> , predict the next line using imports from the current file: from collections import namedtuple from datetime import datetime, timedelta from django.db.models import Count, Q from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from django.utils.timezone import now from rest_framework.views import APIView from rest_framework.response import Response from remo.profiles.api.serializers import (PeopleKPISerializer, UserProfileDetailedSerializer, UserSerializer) from remo.api.views import BaseReadOnlyModelViewset from remo.base.utils import get_quarter from remo.profiles.models import UserProfile import django_filters and context including class names, function names, and sometimes code from other files: # Path: remo/profiles/api/serializers.py # class PeopleKPISerializer(BaseKPISerializer): # """Serializer for people (Reps) data.""" # inactive_week = serializers.IntegerField() # casual_week = serializers.IntegerField() # active_week = serializers.IntegerField() # core_week = serializers.IntegerField() # # class UserProfileDetailedSerializer(serializers.HyperlinkedModelSerializer): # """Detailed serializer for the UserProfile model.""" # first_name = serializers.ReadOnlyField(source='user.first_name') # last_name = serializers.ReadOnlyField(source='user.last_name') # mentor = UserSerializer() # groups = GroupSerializer(source='user.groups', many=True) # functional_areas = FunctionalAreaSerializer(many=True) # mobilising_skills = MobilisingSkillSerializer(many=True) # mobilising_interests = MobilisingInterestSerializer(many=True) # remo_url = serializers.SerializerMethodField() # date_joined_program = serializers.DateTimeField(format='%Y-%m-%d') # date_left_program = serializers.DateTimeField(format='%Y-%m-%d') # # class Meta: # model = UserProfile # # Todo add logic for mozillians_username # fields = ['first_name', 'last_name', 'display_name', # 'date_joined_program', 'date_left_program', 'city', 'region', # 'country', 'twitter_account', 'jabber_id', 'irc_name', # 'wiki_profile_url', 'irc_channels', 'linkedin_url', # 'facebook_url', 'diaspora_url', 'functional_areas', 'mobilising_skills', # 'mobilising_interests', 'bio', 'mentor', 'mozillians_profile_url', # 'timezone', 'groups', 'remo_url'] # # def get_remo_url(self, obj): # """ # Default method for fetching the profile url for the user # in ReMo portal. # """ # return absolutify(obj.get_absolute_url()) # # class UserSerializer(serializers.HyperlinkedModelSerializer): # """Serializer for the django User model.""" # display_name = serializers.ReadOnlyField(source='userprofile.display_name') # # class Meta: # model = User # fields = ['first_name', 'last_name', 'display_name', '_url'] # # Path: remo/base/utils.py # def get_quarter(date=None): # """Return the quarter for this date and datetime of Q's start.""" # if not date: # date = timezone.now() # # quarter = int(math.ceil(date.month / 3.0)) # first_month_of_quarter = 1 + 3 * (quarter - 1) # quarter_start = datetime.datetime(date.year, first_month_of_quarter, 1) # # return (quarter, quarter_start) . Output only the next line.
functional_areas = django_filters.CharFilter(
Next line prediction: <|code_start|> KPI_WEEKS = 12 # Number of activities CORE = 4 ACTIVE = 1 CASUAL = 1 INACTIVE = 0 # Activities Thresholds: # The max period in which we are looking to find reports for a user # both in past and future, measured in weeks CASUAL_INACTIVE = 4 ACTIVE_CORE = 2 class UserProfileFilter(django_filters.FilterSet): groups = django_filters.CharFilter(name='groups__name') functional_areas = django_filters.CharFilter( name='userprofile__functional_areas__name') mobilising_skills = django_filters.CharFilter( name='userprofile__mobilising_skills__name') mobilising_interests = django_filters.CharFilter( name='userprofile__mobilising_interests__name') mentor = django_filters.CharFilter(name='userprofile__mentor') city = django_filters.CharFilter(name='userprofile__city') region = django_filters.CharFilter(name='userprofile__region') country = django_filters.CharFilter(name='userprofile__country') twitter = django_filters.CharFilter(name='userprofile__twitter_account') jabber = django_filters.CharFilter(name='userprofile__jabber_id') <|code_end|> . Use current file imports: (from collections import namedtuple from datetime import datetime, timedelta from django.db.models import Count, Q from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from django.utils.timezone import now from rest_framework.views import APIView from rest_framework.response import Response from remo.profiles.api.serializers import (PeopleKPISerializer, UserProfileDetailedSerializer, UserSerializer) from remo.api.views import BaseReadOnlyModelViewset from remo.base.utils import get_quarter from remo.profiles.models import UserProfile import django_filters) and context including class names, function names, or small code snippets from other files: # Path: remo/profiles/api/serializers.py # class PeopleKPISerializer(BaseKPISerializer): # """Serializer for people (Reps) data.""" # inactive_week = serializers.IntegerField() # casual_week = serializers.IntegerField() # active_week = serializers.IntegerField() # core_week = serializers.IntegerField() # # class UserProfileDetailedSerializer(serializers.HyperlinkedModelSerializer): # """Detailed serializer for the UserProfile model.""" # first_name = serializers.ReadOnlyField(source='user.first_name') # last_name = serializers.ReadOnlyField(source='user.last_name') # mentor = UserSerializer() # groups = GroupSerializer(source='user.groups', many=True) # functional_areas = FunctionalAreaSerializer(many=True) # mobilising_skills = MobilisingSkillSerializer(many=True) # mobilising_interests = MobilisingInterestSerializer(many=True) # remo_url = serializers.SerializerMethodField() # date_joined_program = serializers.DateTimeField(format='%Y-%m-%d') # date_left_program = serializers.DateTimeField(format='%Y-%m-%d') # # class Meta: # model = UserProfile # # Todo add logic for mozillians_username # fields = ['first_name', 'last_name', 'display_name', # 'date_joined_program', 'date_left_program', 'city', 'region', # 'country', 'twitter_account', 'jabber_id', 'irc_name', # 'wiki_profile_url', 'irc_channels', 'linkedin_url', # 'facebook_url', 'diaspora_url', 'functional_areas', 'mobilising_skills', # 'mobilising_interests', 'bio', 'mentor', 'mozillians_profile_url', # 'timezone', 'groups', 'remo_url'] # # def get_remo_url(self, obj): # """ # Default method for fetching the profile url for the user # in ReMo portal. # """ # return absolutify(obj.get_absolute_url()) # # class UserSerializer(serializers.HyperlinkedModelSerializer): # """Serializer for the django User model.""" # display_name = serializers.ReadOnlyField(source='userprofile.display_name') # # class Meta: # model = User # fields = ['first_name', 'last_name', 'display_name', '_url'] # # Path: remo/base/utils.py # def get_quarter(date=None): # """Return the quarter for this date and datetime of Q's start.""" # if not date: # date = timezone.now() # # quarter = int(math.ceil(date.month / 3.0)) # first_month_of_quarter = 1 + 3 * (quarter - 1) # quarter_start = datetime.datetime(date.year, first_month_of_quarter, 1) # # return (quarter, quarter_start) . Output only the next line.
irc_name = django_filters.CharFilter(name='userprofile__irc_name')
Given the code snippet: <|code_start|># Number of activities CORE = 4 ACTIVE = 1 CASUAL = 1 INACTIVE = 0 # Activities Thresholds: # The max period in which we are looking to find reports for a user # both in past and future, measured in weeks CASUAL_INACTIVE = 4 ACTIVE_CORE = 2 class UserProfileFilter(django_filters.FilterSet): groups = django_filters.CharFilter(name='groups__name') functional_areas = django_filters.CharFilter( name='userprofile__functional_areas__name') mobilising_skills = django_filters.CharFilter( name='userprofile__mobilising_skills__name') mobilising_interests = django_filters.CharFilter( name='userprofile__mobilising_interests__name') mentor = django_filters.CharFilter(name='userprofile__mentor') city = django_filters.CharFilter(name='userprofile__city') region = django_filters.CharFilter(name='userprofile__region') country = django_filters.CharFilter(name='userprofile__country') twitter = django_filters.CharFilter(name='userprofile__twitter_account') jabber = django_filters.CharFilter(name='userprofile__jabber_id') irc_name = django_filters.CharFilter(name='userprofile__irc_name') wiki_profile = django_filters.CharFilter( name='userprofile__wiki_profile_url') irc_channels = django_filters.CharFilter(name='userprofile__irc_channels') <|code_end|> , generate the next line using the imports in this file: from collections import namedtuple from datetime import datetime, timedelta from django.db.models import Count, Q from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from django.utils.timezone import now from rest_framework.views import APIView from rest_framework.response import Response from remo.profiles.api.serializers import (PeopleKPISerializer, UserProfileDetailedSerializer, UserSerializer) from remo.api.views import BaseReadOnlyModelViewset from remo.base.utils import get_quarter from remo.profiles.models import UserProfile import django_filters and context (functions, classes, or occasionally code) from other files: # Path: remo/profiles/api/serializers.py # class PeopleKPISerializer(BaseKPISerializer): # """Serializer for people (Reps) data.""" # inactive_week = serializers.IntegerField() # casual_week = serializers.IntegerField() # active_week = serializers.IntegerField() # core_week = serializers.IntegerField() # # class UserProfileDetailedSerializer(serializers.HyperlinkedModelSerializer): # """Detailed serializer for the UserProfile model.""" # first_name = serializers.ReadOnlyField(source='user.first_name') # last_name = serializers.ReadOnlyField(source='user.last_name') # mentor = UserSerializer() # groups = GroupSerializer(source='user.groups', many=True) # functional_areas = FunctionalAreaSerializer(many=True) # mobilising_skills = MobilisingSkillSerializer(many=True) # mobilising_interests = MobilisingInterestSerializer(many=True) # remo_url = serializers.SerializerMethodField() # date_joined_program = serializers.DateTimeField(format='%Y-%m-%d') # date_left_program = serializers.DateTimeField(format='%Y-%m-%d') # # class Meta: # model = UserProfile # # Todo add logic for mozillians_username # fields = ['first_name', 'last_name', 'display_name', # 'date_joined_program', 'date_left_program', 'city', 'region', # 'country', 'twitter_account', 'jabber_id', 'irc_name', # 'wiki_profile_url', 'irc_channels', 'linkedin_url', # 'facebook_url', 'diaspora_url', 'functional_areas', 'mobilising_skills', # 'mobilising_interests', 'bio', 'mentor', 'mozillians_profile_url', # 'timezone', 'groups', 'remo_url'] # # def get_remo_url(self, obj): # """ # Default method for fetching the profile url for the user # in ReMo portal. # """ # return absolutify(obj.get_absolute_url()) # # class UserSerializer(serializers.HyperlinkedModelSerializer): # """Serializer for the django User model.""" # display_name = serializers.ReadOnlyField(source='userprofile.display_name') # # class Meta: # model = User # fields = ['first_name', 'last_name', 'display_name', '_url'] # # Path: remo/base/utils.py # def get_quarter(date=None): # """Return the quarter for this date and datetime of Q's start.""" # if not date: # date = timezone.now() # # quarter = int(math.ceil(date.month / 3.0)) # first_month_of_quarter = 1 + 3 * (quarter - 1) # quarter_start = datetime.datetime(date.year, first_month_of_quarter, 1) # # return (quarter, quarter_start) . Output only the next line.
linkedin = django_filters.CharFilter(name='userprofile__linkedin_url')
Given snippet: <|code_start|> USERNAME_ALGO = getattr(settings, 'OIDC_USERNAME_ALGO', default_username_algo) @never_cache @user_passes_test(lambda u: u.groups.filter(Q(name='Rep') | Q(name='Admin')), login_url=settings.LOGIN_REDIRECT_URL) @permission_check(permissions=['profiles.can_edit_profiles'], filter_field='display_name', owner_field='user', <|code_end|> , continue by predicting the next line. Consider current file imports: from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.models import Group, User from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.urlresolvers import reverse from django.db.models import Q from django.http import Http404 from django.shortcuts import get_object_or_404, redirect, render from django.template.loader import render_to_string from django.utils.timezone import now from django.utils.encoding import iri_to_uri from django.utils.safestring import mark_safe from django.views.decorators.cache import cache_control, never_cache from django_statsd.clients import statsd from mozilla_django_oidc.auth import default_username_algo from product_details import product_details from remo.base.decorators import permission_check from remo.base.templatetags.helpers import urlparams from remo.events.utils import get_events_for_user from remo.profiles.models import UserProfile, UserStatus from remo.profiles.models import FunctionalArea, MobilisingInterest, MobilisingSkill from remo.voting.tasks import rotm_nomination_end_date import waffle import forms and context: # Path: remo/base/templatetags/helpers.py # @library.filter # def urlparams(url_, hash=None, **query): # """Add a fragment and/or query paramaters to a URL. # # New query params will be appended to exising parameters, except duplicate # names, which will be replaced. # """ # url = urlparse.urlparse(url_) # fragment = hash if hash is not None else url.fragment # # # Use dict(parse_qsl) so we don't get lists of values. # q = url.query # query_dict = dict(urlparse.parse_qsl(smart_str(q))) if q else {} # query_dict.update((k, v) for k, v in query.items()) # # query_string = _urlencode([(k, v) for k, v in query_dict.items() # if v is not None]) # new = urlparse.ParseResult(url.scheme, url.netloc, url.path, url.params, # query_string, fragment) # return new.geturl() # # Path: remo/voting/tasks.py # def rotm_nomination_end_date(): # return date(now().year, now().month, 10) which might include code, classes, or functions. Output only the next line.
model=UserProfile)
Here is a snippet: <|code_start|> EXTEND_VOTING_PERIOD = 48 * 3600 # 48 hours NOTIFICATION_INTERVAL = 24 * 3600 # 24 hours ROTM_VOTING_DAYS = 14 <|code_end|> . Write the next line using the current file imports: from datetime import date, datetime, timedelta from operator import or_ from django.conf import settings from django.contrib.auth.models import Group, User from django.contrib.contenttypes.models import ContentType from django.core.mail import send_mail from django.db import transaction from django.template.loader import render_to_string from django.utils.timezone import make_aware, now from remo.base.tasks import send_remo_mail from remo.base.utils import get_date, number2month from remo.celery import app from remo.dashboard.models import ActionItem from remo.voting.models import Poll from remo.voting.models import Poll from remo.voting.models import Poll from remo.voting.models import Poll, RangePoll, RangePollChoice import pytz import waffle and context from other files: # Path: remo/base/tasks.py # @app.task # def send_remo_mail(subject, recipients_list, sender=None, # message=None, email_template=None, data=None, # headers=None): # """Send email from /sender/ to /recipients_list/ with /subject/ and # /message/ as body. # # """ # # Make sure that there is either a message or a template # if not data: # data = {} # # If there is no body for the email and not a template # # to render, then do nothing. # if not message and not email_template: # return # # If there is both an email body, submitted by the user, # # and a template to render as email body, then add # # user's input to extra_content key # elif message and email_template: # data.update({'extra_content': message}) # # Make sure that there is a recipient # if not recipients_list: # return # if not headers: # headers = {} # data.update({'SITE_URL': settings.SITE_URL, # 'FROM_EMAIL': settings.FROM_EMAIL}) # # # Make sure subject is one line. # subject = subject.replace('\n', ' ') # # for recipient in recipients_list: # to = '' # if (isinstance(recipient, long) # and User.objects.filter(pk=recipient).exists()): # user = User.objects.get(pk=recipient) # to = '%s <%s>' % (user.get_full_name(), user.email) # ctx_data = {'user': user, # 'userprofile': user.userprofile} # data.update(ctx_data) # else: # try: # validate_email(recipient) # to = recipient # except forms.ValidationError: # return # # if email_template: # message = render_to_string(email_template, data) # # email_data = { # 'subject': subject, # 'body': message, # 'from_email': settings.FROM_EMAIL, # 'to': [to], # } # # if sender: # # If there is a sender, add a Reply-To header and send a copy to the sender # headers.update({'Reply-To': sender}) # email_data.update({'cc': [sender]}) # # # Add the headers to the mail data # email_data.update({'headers': headers}) # # Send the email # EmailMessage(**email_data).send() # # Path: remo/base/utils.py # def get_date(days=0, weeks=0): # """Return a date in UTC timezone, given an offset in days and or weeks. # # The calculation is based on the current date and the # offset can be either positive or negative. # """ # # return (timezone.now().date() + datetime.timedelta(days=days, weeks=weeks)) # # def number2month(month, full_name=True): # """Convert to month name to number.""" # if full_name: # format = '%B' # else: # format = '%b' # return datetime.datetime(year=2000, day=1, month=month).strftime(format) # # Path: remo/celery.py # RUN_DAILY = 60 * 60 * 24 # RUN_HOURLY = 60 * 60 # class Celery(BaseCelery): # def on_configure(self): # def setup_periodic_tasks(sender, **kwargs): , which may include functions, classes, or code. Output only the next line.
def rotm_nomination_end_date():
Predict the next line for this snippet: <|code_start|> USERNAME_ALGO = getattr(settings, 'OIDC_USERNAME_ALGO', default_username_algo) BOOLEAN_CHOICES = ((True, 'Yes'), (False, 'No')) # Max period that a user can be unavailable in weeks MAX_UNAVAILABILITY_PERIOD = 12 # SOP url for leaving the program LEAVING_SOP_URL = ('<a href="https://wiki.mozilla.org/ReMo/SOPs/Leaving" ' 'target="_blank">Leaving SOP</a>') <|code_end|> with the help of current file imports: import happyforms import re from datetime import timedelta from django import forms from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms.extras.widgets import SelectDateWidget from django.utils.safestring import mark_safe from django.utils.timezone import now from mozilla_django_oidc.auth import default_username_algo from product_details import product_details from pytz import common_timezones from remo.base.templatetags.helpers import user_is_rep from remo.base.utils import get_date from remo.profiles.models import (FunctionalArea, MobilisingInterest, MobilisingSkill, UserProfile, UserStatus) and context from other files: # Path: remo/base/templatetags/helpers.py # @library.global_function # def user_is_rep(user): # """Check if a user belongs to Rep group.""" # return (user.groups.filter(name='Rep').exists() # and user.userprofile.registration_complete) # # Path: remo/base/utils.py # def get_date(days=0, weeks=0): # """Return a date in UTC timezone, given an offset in days and or weeks. # # The calculation is based on the current date and the # offset can be either positive or negative. # """ # # return (timezone.now().date() + datetime.timedelta(days=days, weeks=weeks)) , which may contain function names, class names, or code. Output only the next line.
class InviteUserForm(happyforms.Form):
Given snippet: <|code_start|> 'getShaders', 'compare', 'consolidate', ] namedColors = OrderedDict([ ("pink", (1, 0.5, 1)), # noqa ("peach", (1, 0.5, 0.5)), # noqa ("red", (1, 0, 0)), # noqa ("darkred", (0.6, 0, 0)), # noqa ("black", (0, 0, 0)), # noqa ("lightorange", (1, 0.7, 0.1)), # noqa ("orange", (1, 0.5, 0)), # noqa ("darkorange", (0.7, 0.25, 0)), # noqa ("darkgrey", (0.25, 0.25, 0.25)), # noqa ("lightyellow", (1, 1, 0.5)), # noqa ("yellow", (1, 1, 0)), # noqa ("darkyellow", (0.8, 0.8, 0)), # noqa ("lightgrey", (0.7, 0.7, 0.7)), # noqa ("lightgreen", (0.4, 1, 0.2)), # noqa ("green", (0, 1, 0)), # noqa ("darkgreen", (0, 0.5, 0)), # noqa ("grey", (0.5, 0.5, 0.5)), # noqa ("lightblue", (0.4, 0.55, 1)), # noqa ("blue", (0, 0, 1)), # noqa <|code_end|> , continue by predicting the next line. Consider current file imports: from collections import OrderedDict from pymel.core import cmds, delete, ls, nt, sets, shadingNode from .._add import path import re and context: # Path: pdil/_add/path.py # def normalize(p): # type: (str) -> str # def compare(a, b): # type: (str, str) -> bool # def nicePath(path): # type: (str) -> str # def cleanFilepath(filepath): # type: (str) -> str # def getMayaFiles(folder): # type: (str) -> List[str] # def getTempPath(filename): which might include code, classes, or functions. Output only the next line.
("darkblue", (0, 0, 0.4)), # noqa
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import, division, print_function def mainGroup(create=True, nodes=None): main = find.mainGroup() if main: return main if create: # Draw outer arrow shape main = curve( name='main', d=True, p=[(-40, 0, 20 ), (0, 0, 60 ), (40, 0, 20 ), (40, 0, -40 ), (0, 0, -20 ), (-40, 0, -40 ), (-40, 0, 20 )] ) pdil.dagObj.lock(main, 's') main.visibility.setKeyable(False) main.visibility.set(cb=True) <|code_end|> with the help of current file imports: from pymel.core import curve, group, hide, joint, ls, objExists, parentConstraint, pointConstraint, PyNode from ._core import config from ._core import find import pdil and context from other files: # Path: pdil/tool/fossil/_core/config.py # FOSSIL_CTRL_TYPE = 'fossilCtrlType' # FOSSIL_MAIN_CONTROL = 'fossilMainControl' # JOINT_SIDE_CODE_MAP = { # 'left': _settings['joint_left'], # 'right': _settings['joint_right'], # '': '', # } # CONTROL_SIDE_CODE_MAP = { # 'left': _settings['control_left'], # 'right': _settings['control_right'], # '': '', # } # def otherSideCode(name): # def jointSideSuffix(code): # def controlSideSuffix(code): # # Path: pdil/tool/fossil/_core/find.py # def rootBone(nodes=None): # def controllers(main=None): # def mainGroup(nodePool=None, fromControl=None): # def mainGroups(): # def rootMotion(main=None): # def blueprintCards(skeletonBlueprint=None): # def order(obj): # def cardJointBuildOrder(): # def cardHierarchy(): # def gatherChildren(cards): , which may contain function names, class names, or code. Output only the next line.
tagAsMain(main)
Here is a snippet: <|code_start|>from __future__ import absolute_import, division, print_function __all__ = [ 'autoCropContent', 'identifyContent', 'disperse', 'grab', <|code_end|> . Write the next line using the current file imports: import collections import math from ..vendor.Qt import QtGui, QtWidgets from ..vendor.Qt.QtCore import QPoint and context from other files: # Path: pdil/vendor/Qt.py # QT_VERBOSE = bool(os.getenv("QT_VERBOSE")) # QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "") # QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT") # def _qInstallMessageHandler(handler): # def messageOutputHandler(*args): # def _getcpppointer(object): # def _wrapinstance(ptr, base=None): # def _translate(context, sourceText, *args): # def _loadUi(uifile, baseinstance=None): # def __init__(self, baseinstance): # def _loadCustomWidgets(self, etree): # def headerToModule(header): # def load(self, uifile, *args, **kwargs): # def createWidget(self, class_name, parent=None, name=""): # def _apply_site_config(): # def _new_module(name): # def _import_sub_module(module, name): # def _setup(module, extras): # def _reassign_misplaced_members(binding): # def _build_compatibility_members(binding, decorators=None): # def _pyside2(): # def _pyside(): # def _pyqt5(): # def _pyqt4(): # def _standardizeQFileDialog(some_function): # def wrapper(*args, **kwargs): # def _none(): # def _log(text): # def _convert(lines): # def parse(line): # def _cli(args): # def _install(): # class _UiLoader(Qt._QtUiTools.QUiLoader): , which may include functions, classes, or code. Output only the next line.
'grabTable',
Given the following code snippet before the placeholder: <|code_start|> PY_2 = sys.version_info[0] == 2 # Crass checking for python 2 try: # python 3 compatibility long except NameError: long = int # long is just an int in py3 try: except ImportError: pass #from pymel.core import optionVar, Callback, checkBox, frameLayout, menuItem __all__ = [ 'singleWindow', 'mayaMainWindow', 'deleteByName', 'convertToQt', 'getQtUIClass', 'loadUiType', 'NoUpdate', 'NoFilePrompt', 'NoAutokey', 'RedirectOutput', 'Settings', 'getGeometry', 'setGeometry', <|code_end|> , predict the next line using imports from the current file: import contextlib import importlib import logging import os import sys import xml.etree.ElementTree as xml import pysideuic import pyside2uic as pysideuic from io import StringIO from maya import OpenMayaUI from pymel.core import confirmDialog as confirmDialog_orig from ..vendor.Qt.QtGui import * from ..vendor.Qt.QtCore import * from ..vendor.Qt import QtWidgets from shiboken import wrapInstance from shiboken2 import wrapInstance from importlib import reload from pymel.core import * and context including class names, function names, and sometimes code from other files: # Path: pdil/vendor/Qt.py # QT_VERBOSE = bool(os.getenv("QT_VERBOSE")) # QT_PREFERRED_BINDING = os.getenv("QT_PREFERRED_BINDING", "") # QT_SIP_API_HINT = os.getenv("QT_SIP_API_HINT") # def _qInstallMessageHandler(handler): # def messageOutputHandler(*args): # def _getcpppointer(object): # def _wrapinstance(ptr, base=None): # def _translate(context, sourceText, *args): # def _loadUi(uifile, baseinstance=None): # def __init__(self, baseinstance): # def _loadCustomWidgets(self, etree): # def headerToModule(header): # def load(self, uifile, *args, **kwargs): # def createWidget(self, class_name, parent=None, name=""): # def _apply_site_config(): # def _new_module(name): # def _import_sub_module(module, name): # def _setup(module, extras): # def _reassign_misplaced_members(binding): # def _build_compatibility_members(binding, decorators=None): # def _pyside2(): # def _pyside(): # def _pyqt5(): # def _pyqt4(): # def _standardizeQFileDialog(some_function): # def wrapper(*args, **kwargs): # def _none(): # def _log(text): # def _convert(lines): # def parse(line): # def _cli(args): # def _install(): # class _UiLoader(Qt._QtUiTools.QUiLoader): . Output only the next line.
'autoRedistribute',
Based on the snippet: <|code_start|> CREDENTIALS = ('test', 'example.com', 'secret') GARBAGE_LEVEL = 26 class LoginMethodUpgradeTest(stubloader.StubbedTest): def testUpgrade(self): p = Portal(IRealm(self.store), [ICredentialsChecker(self.store)]) <|code_end|> , predict the immediate next line with the help of imports: from twisted.cred.portal import Portal, IRealm from twisted.cred.checkers import ICredentialsChecker from twisted.cred.credentials import UsernamePassword from axiom.test.test_userbase import IGarbage from axiom.test.historic import stubloader and context (classes, functions, sometimes code) from other files: # Path: axiom/test/test_userbase.py # class IGarbage(Interface): # pass . Output only the next line.
def loggedIn(xxx_todo_changeme):
Next line prediction: <|code_start|> def createDatabase(s): ls = LoginSystem(store=s) ls.installOn(s) acc = ls.addAccount('test', 'example.com', 'asdf') ss = acc.avatars.open() gph = GarbageProtocolHandler(store=ss, garbage=7) gph.installOn(ss) # ls.addAccount(u'test2', u'example.com', 'ghjk') if __name__ == '__main__': <|code_end|> . Use current file imports: (from axiom.userbase import LoginSystem from axiom.test.test_userbase import GarbageProtocolHandler from axiom.test.historic.stubloader import saveStub) and context including class names, function names, or small code snippets from other files: # Path: axiom/userbase.py # class LoginSystem(Item, LoginBase, SubStoreLoginMixin): # schemaVersion = 1 # typeName = 'login_system' # # loginCount = integer(default=0) # failedLogins = integer(default=0) # _txCryptContext = inmemory() # # Path: axiom/test/test_userbase.py # class GarbageProtocolHandler(Item): # schemaVersion = 1 # typeName = 'test_login_garbage' # # garbage = integer() . Output only the next line.
saveStub(createDatabase)
Given snippet: <|code_start|> def createDatabase(s): ls = LoginSystem(store=s) ls.installOn(s) <|code_end|> , continue by predicting the next line. Consider current file imports: from axiom.userbase import LoginSystem from axiom.test.test_userbase import GarbageProtocolHandler from axiom.test.historic.stubloader import saveStub and context: # Path: axiom/userbase.py # class LoginSystem(Item, LoginBase, SubStoreLoginMixin): # schemaVersion = 1 # typeName = 'login_system' # # loginCount = integer(default=0) # failedLogins = integer(default=0) # _txCryptContext = inmemory() # # Path: axiom/test/test_userbase.py # class GarbageProtocolHandler(Item): # schemaVersion = 1 # typeName = 'test_login_garbage' # # garbage = integer() which might include code, classes, or functions. Output only the next line.
acc = ls.addAccount('test', 'example.com', 'asdf')
Using the snippet: <|code_start|>class C(object): __slots__ = ['a', 'b', 'c', 'initialized'] class D: def activate(self): self.initialized = 1 self.test = 2 self.a = 3 self.b = 4 self.c = 5 class E(object): pass class X(B, A, C, D, E): pass class Y(Bsub): blah = SetOnce() class ClassWithDefault: x = 1 class DefaultTest(SchemaMachine, ClassWithDefault): x = Attribute() class Decoy(ClassWithDefault): pass <|code_end|> , determine the next line of code. You have imports: from twisted.trial import unittest from axiom.slotmachine import SetOnce, Attribute, SlotMachine, SchemaMachine and context (class names, function names, or code) available: # Path: axiom/slotmachine.py # class SetOnce(Attribute): # # def __init__(self, doc='', default=_RAISE): # Attribute.__init__(self) # if default is _RAISE: # self.default = () # else: # self.default = (default,) # # def requiredSlots(self, modname, classname, attrname): # self.name = attrname # t = self.trueattr = ('_' + self.name) # yield t # # def __set__(self, iself, value): # if not hasattr(iself, self.trueattr): # setattr(iself, self.trueattr, value) # else: # raise AttributeError('{}.{} may only be set once'.format( # type(iself).__name__, self.name)) # # def __get__(self, iself, type=None): # if type is not None and iself is None: # return self # return getattr(iself, self.trueattr, *self.default) # # class Attribute(object): # def __init__(self, doc=''): # self.doc = doc # # def requiredSlots(self, modname, classname, attrname): # self.name = attrname # yield attrname # # def __get__(self, oself, type=None): # assert oself is None, "{}: should be masked".format(self.name) # return self # # class SlotMachine(six.with_metaclass(_SlotMetaMachine, _Strict)): # pass # # class SchemaMachine(six.with_metaclass(SchemaMetaMachine, _Strict)): # pass . Output only the next line.
class DecoyDefault(Decoy, DefaultTest):
Given the following code snippet before the placeholder: <|code_start|> class A(SlotMachine): slots = ['a', 'initialized'] class B(SchemaMachine): test = Attribute() initialized = SetOnce() other = SetOnce(default=None) nondescriptor = 'readable' method = lambda self: self class Bsub(B): pass class C(object): <|code_end|> , predict the next line using imports from the current file: from twisted.trial import unittest from axiom.slotmachine import SetOnce, Attribute, SlotMachine, SchemaMachine and context including class names, function names, and sometimes code from other files: # Path: axiom/slotmachine.py # class SetOnce(Attribute): # # def __init__(self, doc='', default=_RAISE): # Attribute.__init__(self) # if default is _RAISE: # self.default = () # else: # self.default = (default,) # # def requiredSlots(self, modname, classname, attrname): # self.name = attrname # t = self.trueattr = ('_' + self.name) # yield t # # def __set__(self, iself, value): # if not hasattr(iself, self.trueattr): # setattr(iself, self.trueattr, value) # else: # raise AttributeError('{}.{} may only be set once'.format( # type(iself).__name__, self.name)) # # def __get__(self, iself, type=None): # if type is not None and iself is None: # return self # return getattr(iself, self.trueattr, *self.default) # # class Attribute(object): # def __init__(self, doc=''): # self.doc = doc # # def requiredSlots(self, modname, classname, attrname): # self.name = attrname # yield attrname # # def __get__(self, oself, type=None): # assert oself is None, "{}: should be masked".format(self.name) # return self # # class SlotMachine(six.with_metaclass(_SlotMetaMachine, _Strict)): # pass # # class SchemaMachine(six.with_metaclass(SchemaMetaMachine, _Strict)): # pass . Output only the next line.
__slots__ = ['a', 'b',
Continue the code snippet: <|code_start|> class A(SlotMachine): slots = ['a', 'initialized'] class B(SchemaMachine): test = Attribute() initialized = SetOnce() other = SetOnce(default=None) nondescriptor = 'readable' method = lambda self: self class Bsub(B): pass class C(object): __slots__ = ['a', 'b', 'c', 'initialized'] class D: def activate(self): self.initialized = 1 self.test = 2 <|code_end|> . Use current file imports: from twisted.trial import unittest from axiom.slotmachine import SetOnce, Attribute, SlotMachine, SchemaMachine and context (classes, functions, or code) from other files: # Path: axiom/slotmachine.py # class SetOnce(Attribute): # # def __init__(self, doc='', default=_RAISE): # Attribute.__init__(self) # if default is _RAISE: # self.default = () # else: # self.default = (default,) # # def requiredSlots(self, modname, classname, attrname): # self.name = attrname # t = self.trueattr = ('_' + self.name) # yield t # # def __set__(self, iself, value): # if not hasattr(iself, self.trueattr): # setattr(iself, self.trueattr, value) # else: # raise AttributeError('{}.{} may only be set once'.format( # type(iself).__name__, self.name)) # # def __get__(self, iself, type=None): # if type is not None and iself is None: # return self # return getattr(iself, self.trueattr, *self.default) # # class Attribute(object): # def __init__(self, doc=''): # self.doc = doc # # def requiredSlots(self, modname, classname, attrname): # self.name = attrname # yield attrname # # def __get__(self, oself, type=None): # assert oself is None, "{}: should be masked".format(self.name) # return self # # class SlotMachine(six.with_metaclass(_SlotMetaMachine, _Strict)): # pass # # class SchemaMachine(six.with_metaclass(SchemaMetaMachine, _Strict)): # pass . Output only the next line.
self.a = 3
Given the code snippet: <|code_start|> initialized = SetOnce() other = SetOnce(default=None) nondescriptor = 'readable' method = lambda self: self class Bsub(B): pass class C(object): __slots__ = ['a', 'b', 'c', 'initialized'] class D: def activate(self): self.initialized = 1 self.test = 2 self.a = 3 self.b = 4 self.c = 5 class E(object): pass class X(B, A, C, D, E): pass class Y(Bsub): blah = SetOnce() class ClassWithDefault: <|code_end|> , generate the next line using the imports in this file: from twisted.trial import unittest from axiom.slotmachine import SetOnce, Attribute, SlotMachine, SchemaMachine and context (functions, classes, or occasionally code) from other files: # Path: axiom/slotmachine.py # class SetOnce(Attribute): # # def __init__(self, doc='', default=_RAISE): # Attribute.__init__(self) # if default is _RAISE: # self.default = () # else: # self.default = (default,) # # def requiredSlots(self, modname, classname, attrname): # self.name = attrname # t = self.trueattr = ('_' + self.name) # yield t # # def __set__(self, iself, value): # if not hasattr(iself, self.trueattr): # setattr(iself, self.trueattr, value) # else: # raise AttributeError('{}.{} may only be set once'.format( # type(iself).__name__, self.name)) # # def __get__(self, iself, type=None): # if type is not None and iself is None: # return self # return getattr(iself, self.trueattr, *self.default) # # class Attribute(object): # def __init__(self, doc=''): # self.doc = doc # # def requiredSlots(self, modname, classname, attrname): # self.name = attrname # yield attrname # # def __get__(self, oself, type=None): # assert oself is None, "{}: should be masked".format(self.name) # return self # # class SlotMachine(six.with_metaclass(_SlotMetaMachine, _Strict)): # pass # # class SchemaMachine(six.with_metaclass(SchemaMetaMachine, _Strict)): # pass . Output only the next line.
x = 1
Given snippet: <|code_start|> SECRET = 'asdf' SECRET2 = 'ghjk' class AccountUpgradeTest(stubloader.StubbedTest): def testUpgrade(self): p = Portal(IRealm(self.store), <|code_end|> , continue by predicting the next line. Consider current file imports: from twisted.cred.portal import Portal, IRealm from twisted.cred.checkers import ICredentialsChecker from twisted.cred.credentials import UsernamePassword from axiom.test.test_userbase import IGarbage from axiom.test.historic import stubloader and context: # Path: axiom/test/test_userbase.py # class IGarbage(Interface): # pass which might include code, classes, or functions. Output only the next line.
[ICredentialsChecker(self.store)])
Using the snippet: <|code_start|> def createDatabase(s): ls = LoginSystem(store=s) installOn(ls, s) <|code_end|> , determine the next line of code. You have imports: from axiom.userbase import LoginSystem from axiom.dependency import installOn from axiom.test.historic.stubloader import saveStub from axiom.test.test_userbase import GarbageProtocolHandler and context (class names, function names, or code) available: # Path: axiom/userbase.py # class LoginSystem(Item, LoginBase, SubStoreLoginMixin): # schemaVersion = 1 # typeName = 'login_system' # # loginCount = integer(default=0) # failedLogins = integer(default=0) # _txCryptContext = inmemory() # # Path: axiom/dependency.py # def installOn(self, target): # """ # Install this object on the target along with any powerup # interfaces it declares. Also track that the object now depends on # the target, and the object was explicitly installed (and therefore # should not be uninstalled by subsequent uninstallation operations # unless it is explicitly removed). # """ # _installOn(self, target, True) # # Path: axiom/test/test_userbase.py # class GarbageProtocolHandler(Item): # schemaVersion = 1 # typeName = 'test_login_garbage' # # garbage = integer() . Output only the next line.
acc = ls.addAccount(u'test', u'example.com', u'asdf')
Here is a snippet: <|code_start|> def createDatabase(s): ls = LoginSystem(store=s) installOn(ls, s) acc = ls.addAccount(u'test', u'example.com', u'asdf') ss = acc.avatars.open() gph = GarbageProtocolHandler(store=ss, garbage=7) installOn(gph, ss) if __name__ == '__main__': <|code_end|> . Write the next line using the current file imports: from axiom.userbase import LoginSystem from axiom.dependency import installOn from axiom.test.historic.stubloader import saveStub from axiom.test.test_userbase import GarbageProtocolHandler and context from other files: # Path: axiom/userbase.py # class LoginSystem(Item, LoginBase, SubStoreLoginMixin): # schemaVersion = 1 # typeName = 'login_system' # # loginCount = integer(default=0) # failedLogins = integer(default=0) # _txCryptContext = inmemory() # # Path: axiom/dependency.py # def installOn(self, target): # """ # Install this object on the target along with any powerup # interfaces it declares. Also track that the object now depends on # the target, and the object was explicitly installed (and therefore # should not be uninstalled by subsequent uninstallation operations # unless it is explicitly removed). # """ # _installOn(self, target, True) # # Path: axiom/test/test_userbase.py # class GarbageProtocolHandler(Item): # schemaVersion = 1 # typeName = 'test_login_garbage' # # garbage = integer() , which may include functions, classes, or code. Output only the next line.
saveStub(createDatabase, 0x1240846306fcda3289550cdf9515b2c7111d2bac)
Given the following code snippet before the placeholder: <|code_start|> def createDatabase(s): ls = LoginSystem(store=s) installOn(ls, s) acc = ls.addAccount(u'test', u'example.com', u'asdf') ss = acc.avatars.open() gph = GarbageProtocolHandler(store=ss, garbage=7) installOn(gph, ss) if __name__ == '__main__': <|code_end|> , predict the next line using imports from the current file: from axiom.userbase import LoginSystem from axiom.dependency import installOn from axiom.test.historic.stubloader import saveStub from axiom.test.test_userbase import GarbageProtocolHandler and context including class names, function names, and sometimes code from other files: # Path: axiom/userbase.py # class LoginSystem(Item, LoginBase, SubStoreLoginMixin): # schemaVersion = 1 # typeName = 'login_system' # # loginCount = integer(default=0) # failedLogins = integer(default=0) # _txCryptContext = inmemory() # # Path: axiom/dependency.py # def installOn(self, target): # """ # Install this object on the target along with any powerup # interfaces it declares. Also track that the object now depends on # the target, and the object was explicitly installed (and therefore # should not be uninstalled by subsequent uninstallation operations # unless it is explicitly removed). # """ # _installOn(self, target, True) # # Path: axiom/test/test_userbase.py # class GarbageProtocolHandler(Item): # schemaVersion = 1 # typeName = 'test_login_garbage' # # garbage = integer() . Output only the next line.
saveStub(createDatabase, 0x1240846306fcda3289550cdf9515b2c7111d2bac)
Given snippet: <|code_start|># -*- test-case-name: axiom.test.test_attributes,axiom.test.test_reference -*- hotfix.require('twisted', 'filepath_copyTo') _NEEDS_FETCH = object() # token indicating that a value was not found __metaclass__ = type <|code_end|> , continue by predicting the next line. Consider current file imports: import os import six from six.moves import map from decimal import Decimal from epsilon import hotfix from zope.interface import implementer from twisted.python import filepath from twisted.python.deprecate import deprecated from twisted.python.components import registerAdapter from twisted.python.versions import Version from epsilon.extime import Time from axiom.slotmachine import Attribute as inmemory from axiom.errors import NoCrossStoreReferences, BrokenReference from axiom.iaxiom import IComparison, IOrdering, IColumn, IQuery from twisted.python.reflect import namedAny and context: # Path: axiom/slotmachine.py # class Attribute(object): # def __init__(self, doc=''): # self.doc = doc # # def requiredSlots(self, modname, classname, attrname): # self.name = attrname # yield attrname # # def __get__(self, oself, type=None): # assert oself is None, "{}: should be masked".format(self.name) # return self # # Path: axiom/errors.py # class NoCrossStoreReferences(AttributeError): # """ # References are not allowed between items within different Stores. # """ # # class BrokenReference(DataIntegrityError): # """ # A reference to a nonexistent item was detected when this should be # impossible. # """ # # Path: axiom/iaxiom.py # class IComparison(Interface): # """ # An object that represents an in-database comparison. A predicate that may # apply to certain items in a store. Passed as an argument to # attributes.AND, .OR, and Store.query(...) # """ # def getInvolvedTables(): # """ # Return a sequence of L{Item} subclasses which are referenced by this # comparison. A class may appear at most once. # """ # # # def getQuery(store): # """ # Return an SQL string with ?-style bind parameter syntax thingies. # """ # # # def getArgs(store): # """ # Return a sequence of arguments suitable for use to satisfy the bind # parameters in the result of L{getQuery}. # """ # # class IOrdering(Interface): # """ # An object suitable for passing to the 'sort' argument of a query method. # """ # def orderColumns(): # """ # Return a list of two-tuples of IColumn providers and either C{'ASC'} or # C{'DESC'} defining this ordering. # """ # # class IColumn(Interface): # """ # An object that represents a column in the database. # """ # def getShortColumnName(store): # """ # @rtype: C{str} # @return: Just the name of this column. # """ # # # def getColumnName(store): # """ # @rtype: C{str} # # @return: The fully qualified name of this object as a column within the # database, eg, C{"main_database.some_table.[this_column]"}. # """ # # def fullyQualifiedName(): # """ # @rtype: C{str} # # @return: The fully qualfied name of this object as an attribute in # Python code, eg, C{myproject.mymodule.MyClass.myAttribute}. If this # attribute is represented by an actual Python code object, it will be a # dot-separated sequence of Python identifiers; otherwise, it will # contain invalid identifier characters other than '.'. # """ # # def __get__(row): # """ # @param row: an item that has this column. # @type row: L{axiom.item.Item} # # @return: The value of the column described by this object, for the given # row. # # @rtype: depends on the underlying type of the column. # """ # # class IQuery(Interface): # """ # An object that represents a query that can be performed against a database. # """ # # limit = Attribute( # """ # An integer representing the maximum number of rows to be returned from # this query, or None, if the query is unlimited. # """) # # store = Attribute( # """ # The Axiom store that this query will return results from. # """) # # def __iter__(): # """ # Retrieve an iterator for the results of this query. # # The query is performed whenever this is called. # """ # # # def count(): # """ # Return the number of results in this query. # # NOTE: In most cases, this will have to load all of the rows in this # query. It is therefore very slow and should generally be considered # discouraged. Call with caution! # """ # # # def cloneQuery(limit): # """ # Create a similar-but-not-identical copy of this query with certain # attributes changed. # # (Currently this only supports the manipulation of the "limit" # parameter, but it is the intent that with a richer query-introspection # interface, this signature could be expanded to support many different # attributes.) # # @param limit: an integer, representing the maximum number of rows that # this query should return. # # @return: an L{IQuery} provider with the new limit. # """ which might include code, classes, or functions. Output only the next line.
class _ComparisonOperatorMuxer:
Here is a snippet: <|code_start|> class ProcessorUpgradeTest(StubbedTest): def setUp(self): # Ick, we need to catch the run event of DummyProcessor, and I can't # think of another way to do it. self.dummyRun = DummyProcessor.run self.calledBack = Deferred() def dummyRun(calledOn): self.calledBack.callback(calledOn) DummyProcessor.run = dummyRun return StubbedTest.setUp(self) def tearDown(self): # Okay this is a pretty irrelevant method on a pretty irrelevant class, # but we'll fix it anyway. DummyProcessor.run = self.dummyRun return StubbedTest.tearDown(self) <|code_end|> . Write the next line using the current file imports: from twisted.internet.defer import Deferred from axiom.test.historic.stubloader import StubbedTest from axiom.test.historic.stub_processor1to2 import DummyProcessor and context from other files: # Path: axiom/test/historic/stub_processor1to2.py # class Dummy(Item): # def createDatabase(s): , which may include functions, classes, or code. Output only the next line.
def test_pollingRemoval(self):
Continue the code snippet: <|code_start|>from __future__ import print_function def main(storePath, itemID): assert 'axiom.test.itemtest' not in sys.modules, "Test is invalid." st = store.Store(filepath.FilePath(storePath)) <|code_end|> . Use current file imports: import sys from axiom import store from twisted.python import filepath and context (classes, functions, or code) from other files: # Path: axiom/store.py # IN_MEMORY_DATABASE = ':memory:' # STORE_SELF_ID = -1 # _NEEDS_DEFAULT = object() # token for lookup failure # T = mostRecent # T = self.getOldVersionOf(typename, version) # class NoEmptyItems(Exception): # class AtomicFile(io.FileIO, object): # class SchedulingService(Service): # class BaseQuery: # class _FakeItemForFilter: # class ItemQuery(BaseQuery): # class MultipleItemQuery(BaseQuery): # class _DistinctQuery(object): # class _MultipleItemDistinctQuery(_DistinctQuery): # class AttributeQuery(BaseQuery): # class Store(Empowered): # class FakeItem: # def _mkdirIfNotExists(dirname): # def __init__(self, tempname, destpath): # def close(self): # def abort(self): # def __init__(self): # def startService(self): # def stopService(self): # def storeServiceSpecialCase(st, pups): # def _typeIsTotallyUnknown(typename, version): # def __init__(self, store, tableClass, # comparison=None, limit=None, # offset=None, sort=None): # def cloneQuery(self, limit=_noItem, sort=_noItem): # def __repr__(self): # def explain(self): # def _involvedTables(self): # def _computeFromClause(self, tables): # def _sqlAndArgs(self, verb, subject): # def _runQuery(self, verb, subject): # def locateCallSite(self): # def _selectStuff(self, verb='SELECT'): # def _massageData(self, row): # def distinct(self): # def __iter__(self): # def __init__(self, store): # def _isColumnUnique(col): # def __init__(self, *a, **k): # def paginate(self, pagesize=20): # def _AND(a, b): # def _massageData(self, row): # def getColumn(self, attributeName, raw=False): # def count(self): # def deleteFromStore(self): # def itemsToDelete(attr): # def __init__(self, *a, **k): # def _involvedTables(self): # def _massageData(self, row): # def count(self): # def distinct(self): # def __init__(self, query): # def cloneQuery(self, limit=_noItem, sort=_noItem): # def __iter__(self): # def count(self): # def count(self): # def __init__(self, # store, # tableClass, # comparison=None, limit=None, # offset=None, sort=None, # attribute=None, # raw=False): # def _massageData(self, row): # def count(self): # def sum(self): # def average(self): # def max(self, default=_noDefault): # def min(self, default=_noDefault): # def _functionOnTarget(self, which, default): # def _storeBatchServiceSpecialCase(*args, **kwargs): # def _schedulerServiceSpecialCase(empowered, pups): # def _diffSchema(diskSchema, memorySchema): # def _currentlyValidAsReferentFor(self, store): # def __init__(self, dbdir=None, filesdir=None, debug=False, parent=None, # idInParent=None, journalMode=None): # def logUpgradeFailure(aFailure): # def _attachChild(self, child): # def attachToParent(self): # def _initSchema(self): # def _startup(self): # def _loadExistingIndexes(self): # def _initdb(self, dbfname): # def __repr__(self): # def findOrCreate(self, userItemClass, __ifnew=None, **attrs): # def newFilePath(self, *path): # def newTemporaryFilePath(self, *path): # def newFile(self, *path): # def newDirectory(self, *path): # def _loadTypeSchema(self): # def _checkTypeSchemaConsistency(self, actualType, onDiskSchema): # def _prepareOldVersionOf(self, typename, version, persistedSchema): # def whenFullyUpgraded(self): # def getOldVersionOf(self, typename, version): # def findUnique(self, tableClass, comparison=None, default=_noItem): # def findFirst(self, tableClass, comparison=None, # offset=None, sort=None, default=None): # def query(self, tableClass, comparison=None, # limit=None, offset=None, sort=None): # def sum(self, summableAttribute, *a, **k): # def count(self, *a, **k): # def batchInsert(self, itemType, itemAttributes, dataRows): # def _loadedItem(self, itemClass, storeID, attrs): # def changed(self, item): # def checkpoint(self): # def transact(self, f, *a, **k): # def _begin(self): # def _setupTxnState(self): # def _commit(self): # def _postCommitHook(self): # def _rollback(self): # def revert(self): # def _inMemoryRollback(self): # def _cleanupTxnState(self): # def close(self, _report=True): # def avgms(self, l): # def _indexNameOf(self, tableClass, attrname): # def _tableNameOnlyFor(self, typename, version): # def _tableNameFor(self, typename, version): # def getTableName(self, tableClass): # def getShortColumnName(self, attribute): # def getColumnName(self, attribute): # def getTypeID(self, tableClass): # def _justCreateTable(self, tableClass): # def _maybeCreateTable(self, tableClass, key): # def _createIndexesFor(self, tableClass, extantIndexes): # def getItemByID(self, storeID, default=_noItem, autoUpgrade=True): # def querySchemaSQL(self, sql, args=()): # def querySQL(self, sql, args=()): # def _queryandfetch(self, sql, args): # def createSQL(self, sql, args=()): # def _execSQL(self, sql, args): # def executeSchemaSQL(self, sql, args=()): # def executeSQL(self, sql, args=()): # def timeinto(l, f, *a, **k): . Output only the next line.
item = st.getItemByID(itemID)
Predict the next line after this snippet: <|code_start|> return iter(self._models) def _sample(self, model, burn=False): """ Resample the hyperparameters with burnin if requested.""" if burn: model = sample(model, self._burn, False, self._rng)[-1] return sample(model, self._n, False, self._rng) def add_data(self, X, Y): # add the data nprev = self._ndata model = self._models.pop() model.add_data(X, Y) self._ndata += len(X) self._models = self._sample(model, burn=(self._ndata > 2*nprev)) def get_loglike(self): return np.mean([m.get_loglike() for m in self._models]) def sample(self, X, size=None, latent=True, rng=None): rng = rstate(rng) model = self._models[rng.randint(self._n)] return model.sample(X, size, latent, rng) def predict(self, X, grad=False): # pylint: disable=arguments-differ parts = [np.array(a) for a in zip(*[_.predict(X, grad) for _ in self._models])] mu_, s2_ = parts[:2] <|code_end|> using the current file's imports: import numpy as np from ._core import Model from ..learning import sample from ..utils.misc import rstate and any relevant context from other files: # Path: reggie/models/_core.py # class Model(object): # """ # Interface for probabilistic models of latent functions. This interface # includes the ability to add input/output data, evaluate the log-likelihood # of this data, make predictions and sample in both the latent and # observed space, evaluate tail probabilities, expectations, and entropy. # """ # def copy(self): # """ # Copy the model; this is just a convenience wrapper around deepcopy. # """ # return copy.deepcopy(self) # # def add_data(self, X, Y): # """ # Add input/output data `X` and `Y` to the model. # """ # raise NotImplementedError # # def get_loglike(self): # """ # Return the log-likelihood of the observed data. # """ # raise NotImplementedError # # def sample(self, X, size=None, latent=True, rng=None): # """ # Return a sample of the model at input locations `X`. # # If `size` is not given this will return an n-vector where n is the # length of `X`; otherwise it will return an array of shape `(size, n)`. # If `latent` is true the samples will be in the latent space, otherwise # they will be sampled in the output space. # """ # raise NotImplementedError # # def predict(self, X): # """ # Return mean and variance predictions `(mu, s2)` at inputs `X`. # """ # raise NotImplementedError # # def get_tail(self, f, X): # """ # Compute the probability that the latent function at inputs `X` exceeds # the target value `f`. # """ # raise NotImplementedError # # def get_improvement(self, f, X): # """ # Compute the expected improvement in value at inputs `X` over the target # value `f`. # """ # raise NotImplementedError # # def get_entropy(self, X): # """ # Compute the predictive entropy evaluated at inputs `X`. # """ # raise NotImplementedError # # Path: reggie/learning/sampling.py # def sample(model, n, raw=False, rng=None): # rng = rstate(rng) # models = [] # for _ in xrange(n): # model = slice_sample(model, rng=rng) # models.append(model) # if raw: # models = np.array([m.params.get_value() for m in models]) # return models # # Path: reggie/utils/misc.py # def rstate(rng=None): # """ # Return a RandomState object. This is just a simple wrapper such that if rng # is already an instance of RandomState it will be passed through, otherwise # it will create a RandomState object using rng as its seed. # """ # if not isinstance(rng, np.random.RandomState): # rng = np.random.RandomState(rng) # return rng . Output only the next line.
mu = np.mean(mu_, axis=0)
Predict the next line after this snippet: <|code_start|> class MCMC(Model): """ Model which implements MCMC to produce a posterior over parameterized models. """ def __init__(self, model, n=100, burn=100, rng=None): self._n = n self._ndata = 0 self._burn = burn self._rng = rstate(rng) self._models = self._sample(model.copy(), burn=True) def __iter__(self): return iter(self._models) def _sample(self, model, burn=False): """ Resample the hyperparameters with burnin if requested.""" if burn: model = sample(model, self._burn, False, self._rng)[-1] return sample(model, self._n, False, self._rng) def add_data(self, X, Y): # add the data nprev = self._ndata model = self._models.pop() model.add_data(X, Y) self._ndata += len(X) <|code_end|> using the current file's imports: import numpy as np from ._core import Model from ..learning import sample from ..utils.misc import rstate and any relevant context from other files: # Path: reggie/models/_core.py # class Model(object): # """ # Interface for probabilistic models of latent functions. This interface # includes the ability to add input/output data, evaluate the log-likelihood # of this data, make predictions and sample in both the latent and # observed space, evaluate tail probabilities, expectations, and entropy. # """ # def copy(self): # """ # Copy the model; this is just a convenience wrapper around deepcopy. # """ # return copy.deepcopy(self) # # def add_data(self, X, Y): # """ # Add input/output data `X` and `Y` to the model. # """ # raise NotImplementedError # # def get_loglike(self): # """ # Return the log-likelihood of the observed data. # """ # raise NotImplementedError # # def sample(self, X, size=None, latent=True, rng=None): # """ # Return a sample of the model at input locations `X`. # # If `size` is not given this will return an n-vector where n is the # length of `X`; otherwise it will return an array of shape `(size, n)`. # If `latent` is true the samples will be in the latent space, otherwise # they will be sampled in the output space. # """ # raise NotImplementedError # # def predict(self, X): # """ # Return mean and variance predictions `(mu, s2)` at inputs `X`. # """ # raise NotImplementedError # # def get_tail(self, f, X): # """ # Compute the probability that the latent function at inputs `X` exceeds # the target value `f`. # """ # raise NotImplementedError # # def get_improvement(self, f, X): # """ # Compute the expected improvement in value at inputs `X` over the target # value `f`. # """ # raise NotImplementedError # # def get_entropy(self, X): # """ # Compute the predictive entropy evaluated at inputs `X`. # """ # raise NotImplementedError # # Path: reggie/learning/sampling.py # def sample(model, n, raw=False, rng=None): # rng = rstate(rng) # models = [] # for _ in xrange(n): # model = slice_sample(model, rng=rng) # models.append(model) # if raw: # models = np.array([m.params.get_value() for m in models]) # return models # # Path: reggie/utils/misc.py # def rstate(rng=None): # """ # Return a RandomState object. This is just a simple wrapper such that if rng # is already an instance of RandomState it will be passed through, otherwise # it will create a RandomState object using rng as its seed. # """ # if not isinstance(rng, np.random.RandomState): # rng = np.random.RandomState(rng) # return rng . Output only the next line.
self._models = self._sample(model, burn=(self._ndata > 2*nprev))
Based on the snippet: <|code_start|> def sample(self, X, size=None, latent=True, rng=None): rng = rstate(rng) model = self._models[rng.randint(self._n)] return model.sample(X, size, latent, rng) def predict(self, X, grad=False): # pylint: disable=arguments-differ parts = [np.array(a) for a in zip(*[_.predict(X, grad) for _ in self._models])] mu_, s2_ = parts[:2] mu = np.mean(mu_, axis=0) s2 = np.mean(s2_ + (mu_ - mu)**2, axis=0) if not grad: return mu, s2 dmu_, ds2_ = parts[2:] dmu = np.mean(dmu_, axis=0) Dmu = dmu_ - dmu ds2 = np.mean(ds2_ + 2*mu_[:, :, None] * Dmu - 2*mu[None, :, None] * Dmu, axis=0) return mu, s2, dmu, ds2 def get_tail(self, f, X, grad=False): parts = [m.get_tail(f, X, grad) for m in self._models] return _integrate(parts, grad) def get_improvement(self, f, X, grad=False): <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from ._core import Model from ..learning import sample from ..utils.misc import rstate and context (classes, functions, sometimes code) from other files: # Path: reggie/models/_core.py # class Model(object): # """ # Interface for probabilistic models of latent functions. This interface # includes the ability to add input/output data, evaluate the log-likelihood # of this data, make predictions and sample in both the latent and # observed space, evaluate tail probabilities, expectations, and entropy. # """ # def copy(self): # """ # Copy the model; this is just a convenience wrapper around deepcopy. # """ # return copy.deepcopy(self) # # def add_data(self, X, Y): # """ # Add input/output data `X` and `Y` to the model. # """ # raise NotImplementedError # # def get_loglike(self): # """ # Return the log-likelihood of the observed data. # """ # raise NotImplementedError # # def sample(self, X, size=None, latent=True, rng=None): # """ # Return a sample of the model at input locations `X`. # # If `size` is not given this will return an n-vector where n is the # length of `X`; otherwise it will return an array of shape `(size, n)`. # If `latent` is true the samples will be in the latent space, otherwise # they will be sampled in the output space. # """ # raise NotImplementedError # # def predict(self, X): # """ # Return mean and variance predictions `(mu, s2)` at inputs `X`. # """ # raise NotImplementedError # # def get_tail(self, f, X): # """ # Compute the probability that the latent function at inputs `X` exceeds # the target value `f`. # """ # raise NotImplementedError # # def get_improvement(self, f, X): # """ # Compute the expected improvement in value at inputs `X` over the target # value `f`. # """ # raise NotImplementedError # # def get_entropy(self, X): # """ # Compute the predictive entropy evaluated at inputs `X`. # """ # raise NotImplementedError # # Path: reggie/learning/sampling.py # def sample(model, n, raw=False, rng=None): # rng = rstate(rng) # models = [] # for _ in xrange(n): # model = slice_sample(model, rng=rng) # models.append(model) # if raw: # models = np.array([m.params.get_value() for m in models]) # return models # # Path: reggie/utils/misc.py # def rstate(rng=None): # """ # Return a RandomState object. This is just a simple wrapper such that if rng # is already an instance of RandomState it will be passed through, otherwise # it will create a RandomState object using rng as its seed. # """ # if not isinstance(rng, np.random.RandomState): # rng = np.random.RandomState(rng) # return rng . Output only the next line.
parts = [m.get_improvement(f, X, grad) for m in self._models]
Predict the next line after this snippet: <|code_start|> s = np.tile(s, (size, 1)) return rng.normal(m, s) def get_logprior(self, theta, grad=False): logp = np.sum( - 0.5 * np.log(2 * np.pi * self._s2) - 0.5 * np.square(theta - self._mu) / self._s2) if grad: dlogp = -(theta - self._mu) / self._s2 return logp, dlogp else: return logp class Horseshoe(Prior): """Horseshoe prior where each parameter value is independently distributed with scale parameter scale[i].""" bounds = (EPSILON, np.inf) def __init__(self, scale=1.): self._scale = np.array(scale, copy=True, ndmin=1) self.ndim = len(self._scale) def __repr__(self): return pretty.repr_args(self, self._scale.squeeze()) def get_logprior(self, theta, grad=False): theta2_inv = (self._scale / theta)**2 <|code_end|> using the current file's imports: import numpy as np from ..utils.misc import rstate, repr_args from .domains import EPSILON and any relevant context from other files: # Path: reggie/utils/misc.py # def rstate(rng=None): # """ # Return a RandomState object. This is just a simple wrapper such that if rng # is already an instance of RandomState it will be passed through, otherwise # it will create a RandomState object using rng as its seed. # """ # if not isinstance(rng, np.random.RandomState): # rng = np.random.RandomState(rng) # return rng # # def repr_args(obj, *args, **kwargs): # """ # Return a repr string for an object with args and kwargs. # """ # typename = type(obj).__name__ # args = ['{:s}'.format(str(val)) for val in args] # kwargs = ['{:s}={:s}'.format(name, str(val)) # for name, val in kwargs.items()] # return '{:s}({:s})'.format(typename, ', '.join(args + kwargs)) # # Path: reggie/core/domains.py # EPSILON = np.finfo(np.float64).resolution . Output only the next line.
inner = np.log1p(theta2_inv)
Based on the snippet: <|code_start|> m = np.tile(m, (size, 1)) s = np.tile(s, (size, 1)) return rng.normal(m, s) def get_logprior(self, theta, grad=False): logp = np.sum( - 0.5 * np.log(2 * np.pi * self._s2) - 0.5 * np.square(theta - self._mu) / self._s2) if grad: dlogp = -(theta - self._mu) / self._s2 return logp, dlogp else: return logp class Horseshoe(Prior): """Horseshoe prior where each parameter value is independently distributed with scale parameter scale[i].""" bounds = (EPSILON, np.inf) def __init__(self, scale=1.): self._scale = np.array(scale, copy=True, ndmin=1) self.ndim = len(self._scale) def __repr__(self): return pretty.repr_args(self, self._scale.squeeze()) def get_logprior(self, theta, grad=False): <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from ..utils.misc import rstate, repr_args from .domains import EPSILON and context (classes, functions, sometimes code) from other files: # Path: reggie/utils/misc.py # def rstate(rng=None): # """ # Return a RandomState object. This is just a simple wrapper such that if rng # is already an instance of RandomState it will be passed through, otherwise # it will create a RandomState object using rng as its seed. # """ # if not isinstance(rng, np.random.RandomState): # rng = np.random.RandomState(rng) # return rng # # def repr_args(obj, *args, **kwargs): # """ # Return a repr string for an object with args and kwargs. # """ # typename = type(obj).__name__ # args = ['{:s}'.format(str(val)) for val in args] # kwargs = ['{:s}={:s}'.format(name, str(val)) # for name, val in kwargs.items()] # return '{:s}({:s})'.format(typename, ', '.join(args + kwargs)) # # Path: reggie/core/domains.py # EPSILON = np.finfo(np.float64).resolution . Output only the next line.
theta2_inv = (self._scale / theta)**2
Continue the code snippet: <|code_start|> class Horseshoe(Prior): """Horseshoe prior where each parameter value is independently distributed with scale parameter scale[i].""" bounds = (EPSILON, np.inf) def __init__(self, scale=1.): self._scale = np.array(scale, copy=True, ndmin=1) self.ndim = len(self._scale) def __repr__(self): return pretty.repr_args(self, self._scale.squeeze()) def get_logprior(self, theta, grad=False): theta2_inv = (self._scale / theta)**2 inner = np.log1p(theta2_inv) logp = np.sum(np.log(inner)) if grad: dlogp = theta2_inv / (1 + theta2_inv) dlogp /= inner dlogp *= -2 / theta return logp, dlogp else: return logp # get a dictionary mapping a string to each prior <|code_end|> . Use current file imports: import numpy as np from ..utils.misc import rstate, repr_args from .domains import EPSILON and context (classes, functions, or code) from other files: # Path: reggie/utils/misc.py # def rstate(rng=None): # """ # Return a RandomState object. This is just a simple wrapper such that if rng # is already an instance of RandomState it will be passed through, otherwise # it will create a RandomState object using rng as its seed. # """ # if not isinstance(rng, np.random.RandomState): # rng = np.random.RandomState(rng) # return rng # # def repr_args(obj, *args, **kwargs): # """ # Return a repr string for an object with args and kwargs. # """ # typename = type(obj).__name__ # args = ['{:s}'.format(str(val)) for val in args] # kwargs = ['{:s}={:s}'.format(name, str(val)) # for name, val in kwargs.items()] # return '{:s}({:s})'.format(typename, ', '.join(args + kwargs)) # # Path: reggie/core/domains.py # EPSILON = np.finfo(np.float64).resolution . Output only the next line.
PRIORS = dict()
Based on the snippet: <|code_start|> class TestLogBehaviorClass: def setup(self): self.logger = logging.getLogger("charset_normalizer") self.logger.handlers.clear() self.logger.addHandler(logging.NullHandler()) self.logger.level = logging.WARNING def test_explain_true_behavior(self, caplog): test_sequence = b'This is a test sequence of bytes that should be sufficient' from_bytes(test_sequence, steps=1, chunk_size=50, explain=True) assert explain_handler not in self.logger.handlers for record in caplog.records: assert record.levelname in ["Level 5", "DEBUG"] def test_explain_false_handler_set_behavior(self, caplog): test_sequence = b'This is a test sequence of bytes that should be sufficient' set_logging_handler(level=TRACE, format_string="%(message)s") from_bytes(test_sequence, steps=1, chunk_size=50, explain=False) assert any(isinstance(hdl, logging.StreamHandler) for hdl in self.logger.handlers) for record in caplog.records: assert record.levelname in ["Level 5", "DEBUG"] assert "Encoding detection: ascii is most likely the one." in caplog.text def test_set_stream_handler(self, caplog): <|code_end|> , predict the immediate next line with the help of imports: import pytest import logging from charset_normalizer.utils import set_logging_handler from charset_normalizer.api import from_bytes, explain_handler from charset_normalizer.constant import TRACE and context (classes, functions, sometimes code) from other files: # Path: charset_normalizer/api.py # def from_bytes( # sequences: bytes, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.2, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # explain: bool = False, # ) -> CharsetMatches: # def from_fp( # fp: BinaryIO, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.20, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # explain: bool = False, # ) -> CharsetMatches: # def from_path( # path: PathLike, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.20, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # explain: bool = False, # ) -> CharsetMatches: # def normalize( # path: PathLike, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.20, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # ) -> CharsetMatch: # # Path: charset_normalizer/constant.py # TRACE = 5 # type: int . Output only the next line.
set_logging_handler(
Here is a snippet: <|code_start|> self.logger.handlers.clear() self.logger.addHandler(logging.NullHandler()) self.logger.level = logging.WARNING def test_explain_true_behavior(self, caplog): test_sequence = b'This is a test sequence of bytes that should be sufficient' from_bytes(test_sequence, steps=1, chunk_size=50, explain=True) assert explain_handler not in self.logger.handlers for record in caplog.records: assert record.levelname in ["Level 5", "DEBUG"] def test_explain_false_handler_set_behavior(self, caplog): test_sequence = b'This is a test sequence of bytes that should be sufficient' set_logging_handler(level=TRACE, format_string="%(message)s") from_bytes(test_sequence, steps=1, chunk_size=50, explain=False) assert any(isinstance(hdl, logging.StreamHandler) for hdl in self.logger.handlers) for record in caplog.records: assert record.levelname in ["Level 5", "DEBUG"] assert "Encoding detection: ascii is most likely the one." in caplog.text def test_set_stream_handler(self, caplog): set_logging_handler( "charset_normalizer", level=logging.DEBUG ) self.logger.debug("log content should log with default format") for record in caplog.records: assert record.levelname in ["Level 5", "DEBUG"] assert "log content should log with default format" in caplog.text def test_set_stream_handler_format(self, caplog): <|code_end|> . Write the next line using the current file imports: import pytest import logging from charset_normalizer.utils import set_logging_handler from charset_normalizer.api import from_bytes, explain_handler from charset_normalizer.constant import TRACE and context from other files: # Path: charset_normalizer/api.py # def from_bytes( # sequences: bytes, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.2, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # explain: bool = False, # ) -> CharsetMatches: # def from_fp( # fp: BinaryIO, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.20, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # explain: bool = False, # ) -> CharsetMatches: # def from_path( # path: PathLike, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.20, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # explain: bool = False, # ) -> CharsetMatches: # def normalize( # path: PathLike, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.20, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # ) -> CharsetMatch: # # Path: charset_normalizer/constant.py # TRACE = 5 # type: int , which may include functions, classes, or code. Output only the next line.
set_logging_handler(
Continue the code snippet: <|code_start|> class TestLogBehaviorClass: def setup(self): self.logger = logging.getLogger("charset_normalizer") <|code_end|> . Use current file imports: import pytest import logging from charset_normalizer.utils import set_logging_handler from charset_normalizer.api import from_bytes, explain_handler from charset_normalizer.constant import TRACE and context (classes, functions, or code) from other files: # Path: charset_normalizer/api.py # def from_bytes( # sequences: bytes, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.2, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # explain: bool = False, # ) -> CharsetMatches: # def from_fp( # fp: BinaryIO, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.20, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # explain: bool = False, # ) -> CharsetMatches: # def from_path( # path: PathLike, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.20, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # explain: bool = False, # ) -> CharsetMatches: # def normalize( # path: PathLike, # steps: int = 5, # chunk_size: int = 512, # threshold: float = 0.20, # cp_isolation: List[str] = None, # cp_exclusion: List[str] = None, # preemptive_behaviour: bool = True, # ) -> CharsetMatch: # # Path: charset_normalizer/constant.py # TRACE = 5 # type: int . Output only the next line.
self.logger.handlers.clear()
Predict the next line after this snippet: <|code_start|> try: except ImportError: # pragma: no cover PathLike = str # type: ignore # Will most likely be controversial # logging.addLevelName(TRACE, "TRACE") logger = logging.getLogger("charset_normalizer") explain_handler = logging.StreamHandler() explain_handler.setFormatter( logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") ) def from_bytes( <|code_end|> using the current file's imports: import logging from os.path import basename, splitext from typing import BinaryIO, List, Optional, Set from os import PathLike from .cd import ( coherence_ratio, encoding_languages, mb_encoding_languages, merge_coherence_ratios, ) from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACE from .md import mess_ratio from .models import CharsetMatch, CharsetMatches from .utils import ( any_specified_encoding, iana_name, identify_sig_or_bom, is_cp_similar, is_multi_byte_encoding, should_strip_sig_or_bom, ) and any relevant context from other files: # Path: charset_normalizer/constant.py # IANA_SUPPORTED = sorted( # filter( # lambda x: x.endswith("_codec") is False # and x not in {"rot_13", "tactis", "mbcs"}, # list(set(aliases.values())), # ) # ) # type: List[str] # # TOO_BIG_SEQUENCE = int(10e6) # type: int # # TOO_SMALL_SEQUENCE = 32 # type: int # # TRACE = 5 # type: int # # Path: charset_normalizer/md.py # @lru_cache(maxsize=2048) # def mess_ratio( # decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False # ) -> float: # """ # Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. # """ # # detectors = [ # md_class() for md_class in MessDetectorPlugin.__subclasses__() # ] # type: List[MessDetectorPlugin] # # length = len(decoded_sequence) + 1 # type: int # # mean_mess_ratio = 0.0 # type: float # # if length < 512: # intermediary_mean_mess_ratio_calc = 32 # type: int # elif length <= 1024: # intermediary_mean_mess_ratio_calc = 64 # else: # intermediary_mean_mess_ratio_calc = 128 # # for character, index in zip(decoded_sequence + "\n", range(length)): # for detector in detectors: # if detector.eligible(character): # detector.feed(character) # # if ( # index > 0 and index % intermediary_mean_mess_ratio_calc == 0 # ) or index == length - 1: # mean_mess_ratio = sum(dt.ratio for dt in detectors) # # if mean_mess_ratio >= maximum_threshold: # break # # if debug: # for dt in detectors: # pragma: nocover # print(dt.__class__, dt.ratio) # # return round(mean_mess_ratio, 3) . Output only the next line.
sequences: bytes,
Predict the next line for this snippet: <|code_start|> try: except ImportError: # pragma: no cover PathLike = str # type: ignore # Will most likely be controversial # logging.addLevelName(TRACE, "TRACE") <|code_end|> with the help of current file imports: import logging from os.path import basename, splitext from typing import BinaryIO, List, Optional, Set from os import PathLike from .cd import ( coherence_ratio, encoding_languages, mb_encoding_languages, merge_coherence_ratios, ) from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACE from .md import mess_ratio from .models import CharsetMatch, CharsetMatches from .utils import ( any_specified_encoding, iana_name, identify_sig_or_bom, is_cp_similar, is_multi_byte_encoding, should_strip_sig_or_bom, ) and context from other files: # Path: charset_normalizer/constant.py # IANA_SUPPORTED = sorted( # filter( # lambda x: x.endswith("_codec") is False # and x not in {"rot_13", "tactis", "mbcs"}, # list(set(aliases.values())), # ) # ) # type: List[str] # # TOO_BIG_SEQUENCE = int(10e6) # type: int # # TOO_SMALL_SEQUENCE = 32 # type: int # # TRACE = 5 # type: int # # Path: charset_normalizer/md.py # @lru_cache(maxsize=2048) # def mess_ratio( # decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False # ) -> float: # """ # Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. # """ # # detectors = [ # md_class() for md_class in MessDetectorPlugin.__subclasses__() # ] # type: List[MessDetectorPlugin] # # length = len(decoded_sequence) + 1 # type: int # # mean_mess_ratio = 0.0 # type: float # # if length < 512: # intermediary_mean_mess_ratio_calc = 32 # type: int # elif length <= 1024: # intermediary_mean_mess_ratio_calc = 64 # else: # intermediary_mean_mess_ratio_calc = 128 # # for character, index in zip(decoded_sequence + "\n", range(length)): # for detector in detectors: # if detector.eligible(character): # detector.feed(character) # # if ( # index > 0 and index % intermediary_mean_mess_ratio_calc == 0 # ) or index == length - 1: # mean_mess_ratio = sum(dt.ratio for dt in detectors) # # if mean_mess_ratio >= maximum_threshold: # break # # if debug: # for dt in detectors: # pragma: nocover # print(dt.__class__, dt.ratio) # # return round(mean_mess_ratio, 3) , which may contain function names, class names, or code. Output only the next line.
logger = logging.getLogger("charset_normalizer")
Here is a snippet: <|code_start|> try: except ImportError: # pragma: no cover PathLike = str # type: ignore # Will most likely be controversial # logging.addLevelName(TRACE, "TRACE") logger = logging.getLogger("charset_normalizer") explain_handler = logging.StreamHandler() explain_handler.setFormatter( logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") ) def from_bytes( sequences: bytes, steps: int = 5, <|code_end|> . Write the next line using the current file imports: import logging from os.path import basename, splitext from typing import BinaryIO, List, Optional, Set from os import PathLike from .cd import ( coherence_ratio, encoding_languages, mb_encoding_languages, merge_coherence_ratios, ) from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACE from .md import mess_ratio from .models import CharsetMatch, CharsetMatches from .utils import ( any_specified_encoding, iana_name, identify_sig_or_bom, is_cp_similar, is_multi_byte_encoding, should_strip_sig_or_bom, ) and context from other files: # Path: charset_normalizer/constant.py # IANA_SUPPORTED = sorted( # filter( # lambda x: x.endswith("_codec") is False # and x not in {"rot_13", "tactis", "mbcs"}, # list(set(aliases.values())), # ) # ) # type: List[str] # # TOO_BIG_SEQUENCE = int(10e6) # type: int # # TOO_SMALL_SEQUENCE = 32 # type: int # # TRACE = 5 # type: int # # Path: charset_normalizer/md.py # @lru_cache(maxsize=2048) # def mess_ratio( # decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False # ) -> float: # """ # Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. # """ # # detectors = [ # md_class() for md_class in MessDetectorPlugin.__subclasses__() # ] # type: List[MessDetectorPlugin] # # length = len(decoded_sequence) + 1 # type: int # # mean_mess_ratio = 0.0 # type: float # # if length < 512: # intermediary_mean_mess_ratio_calc = 32 # type: int # elif length <= 1024: # intermediary_mean_mess_ratio_calc = 64 # else: # intermediary_mean_mess_ratio_calc = 128 # # for character, index in zip(decoded_sequence + "\n", range(length)): # for detector in detectors: # if detector.eligible(character): # detector.feed(character) # # if ( # index > 0 and index % intermediary_mean_mess_ratio_calc == 0 # ) or index == length - 1: # mean_mess_ratio = sum(dt.ratio for dt in detectors) # # if mean_mess_ratio >= maximum_threshold: # break # # if debug: # for dt in detectors: # pragma: nocover # print(dt.__class__, dt.ratio) # # return round(mean_mess_ratio, 3) , which may include functions, classes, or code. Output only the next line.
chunk_size: int = 512,
Given the following code snippet before the placeholder: <|code_start|> try: except ImportError: # pragma: no cover PathLike = str # type: ignore # Will most likely be controversial # logging.addLevelName(TRACE, "TRACE") logger = logging.getLogger("charset_normalizer") explain_handler = logging.StreamHandler() explain_handler.setFormatter( logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") ) def from_bytes( sequences: bytes, steps: int = 5, chunk_size: int = 512, threshold: float = 0.2, cp_isolation: List[str] = None, cp_exclusion: List[str] = None, <|code_end|> , predict the next line using imports from the current file: import logging from os.path import basename, splitext from typing import BinaryIO, List, Optional, Set from os import PathLike from .cd import ( coherence_ratio, encoding_languages, mb_encoding_languages, merge_coherence_ratios, ) from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACE from .md import mess_ratio from .models import CharsetMatch, CharsetMatches from .utils import ( any_specified_encoding, iana_name, identify_sig_or_bom, is_cp_similar, is_multi_byte_encoding, should_strip_sig_or_bom, ) and context including class names, function names, and sometimes code from other files: # Path: charset_normalizer/constant.py # IANA_SUPPORTED = sorted( # filter( # lambda x: x.endswith("_codec") is False # and x not in {"rot_13", "tactis", "mbcs"}, # list(set(aliases.values())), # ) # ) # type: List[str] # # TOO_BIG_SEQUENCE = int(10e6) # type: int # # TOO_SMALL_SEQUENCE = 32 # type: int # # TRACE = 5 # type: int # # Path: charset_normalizer/md.py # @lru_cache(maxsize=2048) # def mess_ratio( # decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False # ) -> float: # """ # Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. # """ # # detectors = [ # md_class() for md_class in MessDetectorPlugin.__subclasses__() # ] # type: List[MessDetectorPlugin] # # length = len(decoded_sequence) + 1 # type: int # # mean_mess_ratio = 0.0 # type: float # # if length < 512: # intermediary_mean_mess_ratio_calc = 32 # type: int # elif length <= 1024: # intermediary_mean_mess_ratio_calc = 64 # else: # intermediary_mean_mess_ratio_calc = 128 # # for character, index in zip(decoded_sequence + "\n", range(length)): # for detector in detectors: # if detector.eligible(character): # detector.feed(character) # # if ( # index > 0 and index % intermediary_mean_mess_ratio_calc == 0 # ) or index == length - 1: # mean_mess_ratio = sum(dt.ratio for dt in detectors) # # if mean_mess_ratio >= maximum_threshold: # break # # if debug: # for dt in detectors: # pragma: nocover # print(dt.__class__, dt.ratio) # # return round(mean_mess_ratio, 3) . Output only the next line.
preemptive_behaviour: bool = True,
Continue the code snippet: <|code_start|> @pytest.mark.parametrize( "content, min_expected_ratio, max_expected_ratio", [ <|code_end|> . Use current file imports: import pytest from charset_normalizer.md import mess_ratio and context (classes, functions, or code) from other files: # Path: charset_normalizer/md.py # @lru_cache(maxsize=2048) # def mess_ratio( # decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False # ) -> float: # """ # Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. # """ # # detectors = [ # md_class() for md_class in MessDetectorPlugin.__subclasses__() # ] # type: List[MessDetectorPlugin] # # length = len(decoded_sequence) + 1 # type: int # # mean_mess_ratio = 0.0 # type: float # # if length < 512: # intermediary_mean_mess_ratio_calc = 32 # type: int # elif length <= 1024: # intermediary_mean_mess_ratio_calc = 64 # else: # intermediary_mean_mess_ratio_calc = 128 # # for character, index in zip(decoded_sequence + "\n", range(length)): # for detector in detectors: # if detector.eligible(character): # detector.feed(character) # # if ( # index > 0 and index % intermediary_mean_mess_ratio_calc == 0 # ) or index == length - 1: # mean_mess_ratio = sum(dt.ratio for dt in detectors) # # if mean_mess_ratio >= maximum_threshold: # break # # if debug: # for dt in detectors: # pragma: nocover # print(dt.__class__, dt.ratio) # # return round(mean_mess_ratio, 3) . Output only the next line.
('典肇乎庚辰年十二月廿一,及己丑年二月十九,收各方語言二百五十,合逾七百萬目;二十大卷佔八成,單英文卷亦過二百萬。悉文乃天下有志共筆而成;有意助之,幾網路、隨纂作,大典茁焉。', 0., 0.),
Continue the code snippet: <|code_start|># Copyright (C) 2010-2015 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. try: HAVE_VOLATILITY = True rootlogger = logging.getLogger() # re-use the rootlogger level (so if we want to debug, it works for volatility) logging.getLogger("volatility.obj").setLevel(rootlogger.level) logging.getLogger("volatility.utils").setLevel(rootlogger.level) except ImportError: HAVE_VOLATILITY = False <|code_end|> . Use current file imports: import os import logging import volatility.conf as conf import volatility.registry as registry import volatility.commands as commands import volatility.utils as utils import volatility.plugins.malware.devicetree as devicetree import volatility.plugins.malware.apihooks as apihooks import volatility.plugins.getsids as sidm import volatility.plugins.privileges as privm import volatility.plugins.taskmods as taskmods import volatility.win32.tasks as tasks import volatility.obj as obj import volatility.exceptions as exc import volatility.plugins.filescan as filescan from lib.cuckoo.common.abstracts import Processing from lib.cuckoo.common.config import Config from lib.cuckoo.common.constants import CUCKOO_ROOT and context (classes, functions, or code) from other files: # Path: lib/cuckoo/common/abstracts.py # class Processing(object): # """Base abstract class for processing module.""" # order = 1 # enabled = True # # def __init__(self): # self.analysis_path = "" # self.logs_path = "" # self.task = None # self.options = None # # def set_options(self, options): # """Set report options. # @param options: report options dict. # """ # self.options = options # # def set_task(self, task): # """Add task information. # @param task: task dictionary. # """ # self.task = task # # def set_path(self, analysis_path): # """Set paths. # @param analysis_path: analysis folder path. # """ # self.analysis_path = analysis_path # self.log_path = os.path.join(self.analysis_path, "analysis.log") # self.file_path = os.path.realpath(os.path.join(self.analysis_path, # "binary")) # self.dropped_path = os.path.join(self.analysis_path, "files") # self.logs_path = os.path.join(self.analysis_path, "logs") # self.shots_path = os.path.join(self.analysis_path, "shots") # self.pcap_path = os.path.join(self.analysis_path, "dump.pcap") # self.pmemory_path = os.path.join(self.analysis_path, "memory") # self.memory_path = os.path.join(self.analysis_path, "memory.dmp") # # def run(self): # """Start processing. # @raise NotImplementedError: this method is abstract. # """ # raise NotImplementedError # # Path: lib/cuckoo/common/config.py # class Config: # """Configuration file parser.""" # # def __init__(self, file_name="cuckoo", cfg=None): # """ # @param file_name: file name without extension. # @param cfg: configuration file path. # """ # config = ConfigParser.ConfigParser() # # if cfg: # config.read(cfg) # else: # config.read(os.path.join(CUCKOO_ROOT, "conf", "%s.conf" % file_name)) # # for section in config.sections(): # setattr(self, section, Dictionary()) # for name, raw_value in config.items(section): # try: # # Ugly fix to avoid '0' and '1' to be parsed as a # # boolean value. # # We raise an exception to goto fail^w parse it # # as integer. # if config.get(section, name) in ["0", "1"]: # raise ValueError # # value = config.getboolean(section, name) # except ValueError: # try: # value = config.getint(section, name) # except ValueError: # value = config.get(section, name) # # setattr(getattr(self, section), name, value) # # def get(self, section): # """Get option. # @param section: section to fetch. # @raise CuckooOperationalError: if section not found. # @return: option value. # """ # try: # return getattr(self, section) # except AttributeError as e: # raise CuckooOperationalError("Option %s is not found in " # "configuration, error: %s" % # (section, e)) . Output only the next line.
log = logging.getLogger(__name__)
Given the code snippet: <|code_start|>) ROOT_URLCONF = 'web.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'web.wsgi.application' TEMPLATE_DIRS = ( "templates", ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', #'django.contrib.sites', #'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', 'analysis', 'compare', ) LOGIN_REDIRECT_URL = "/" # Fix to avoid migration warning in django 1.7 about test runner (1_6.W001). # In future it could be removed: https://code.djangoproject.com/ticket/23469 <|code_end|> , generate the next line using the imports in this file: import sys import os from lib.cuckoo.common.config import Config from secret_key import * from django.utils.crypto import get_random_string from secret_key import * from local_settings import * and context (functions, classes, or occasionally code) from other files: # Path: lib/cuckoo/common/config.py # class Config: # """Configuration file parser.""" # # def __init__(self, file_name="cuckoo", cfg=None): # """ # @param file_name: file name without extension. # @param cfg: configuration file path. # """ # config = ConfigParser.ConfigParser() # # if cfg: # config.read(cfg) # else: # config.read(os.path.join(CUCKOO_ROOT, "conf", "%s.conf" % file_name)) # # for section in config.sections(): # setattr(self, section, Dictionary()) # for name, raw_value in config.items(section): # try: # # Ugly fix to avoid '0' and '1' to be parsed as a # # boolean value. # # We raise an exception to goto fail^w parse it # # as integer. # if config.get(section, name) in ["0", "1"]: # raise ValueError # # value = config.getboolean(section, name) # except ValueError: # try: # value = config.getint(section, name) # except ValueError: # value = config.get(section, name) # # setattr(getattr(self, section), name, value) # # def get(self, section): # """Get option. # @param section: section to fetch. # @raise CuckooOperationalError: if section not found. # @return: option value. # """ # try: # return getattr(self, section) # except AttributeError as e: # raise CuckooOperationalError("Option %s is not found in " # "configuration, error: %s" % # (section, e)) . Output only the next line.
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
Continue the code snippet: <|code_start|># Copyright (C) 2010-2015 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. log = logging.getLogger(__name__) BUFSIZE = 16 * 1024 EXTENSIONS = { <|code_end|> . Use current file imports: import os import socket import select import logging import datetime import SocketServer from threading import Event, Thread from lib.cuckoo.common.config import Config from lib.cuckoo.common.constants import CUCKOO_ROOT from lib.cuckoo.common.exceptions import CuckooOperationalError from lib.cuckoo.common.exceptions import CuckooCriticalError from lib.cuckoo.common.exceptions import CuckooResultError from lib.cuckoo.common.netlog import NetlogParser, BsonParser from lib.cuckoo.common.utils import create_folder, Singleton, logtime and context (classes, functions, or code) from other files: # Path: lib/cuckoo/common/config.py # class Config: # """Configuration file parser.""" # # def __init__(self, file_name="cuckoo", cfg=None): # """ # @param file_name: file name without extension. # @param cfg: configuration file path. # """ # config = ConfigParser.ConfigParser() # # if cfg: # config.read(cfg) # else: # config.read(os.path.join(CUCKOO_ROOT, "conf", "%s.conf" % file_name)) # # for section in config.sections(): # setattr(self, section, Dictionary()) # for name, raw_value in config.items(section): # try: # # Ugly fix to avoid '0' and '1' to be parsed as a # # boolean value. # # We raise an exception to goto fail^w parse it # # as integer. # if config.get(section, name) in ["0", "1"]: # raise ValueError # # value = config.getboolean(section, name) # except ValueError: # try: # value = config.getint(section, name) # except ValueError: # value = config.get(section, name) # # setattr(getattr(self, section), name, value) # # def get(self, section): # """Get option. # @param section: section to fetch. # @raise CuckooOperationalError: if section not found. # @return: option value. # """ # try: # return getattr(self, section) # except AttributeError as e: # raise CuckooOperationalError("Option %s is not found in " # "configuration, error: %s" % # (section, e)) # # Path: lib/cuckoo/common/utils.py # def create_folder(root=".", folder=None): # """Create directory. # @param root: root path. # @param folder: folder name to be created. # @raise CuckooOperationalError: if fails to create folder. # """ # folder_path = os.path.join(root, folder) # if folder and not os.path.isdir(folder_path): # try: # os.makedirs(folder_path) # except OSError: # raise CuckooOperationalError("Unable to create folder: %s" % # folder_path) # # class Singleton(type): # """Singleton. # @see: http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python # """ # _instances = {} # # def __call__(cls, *args, **kwargs): # if cls not in cls._instances: # cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) # return cls._instances[cls] # # def logtime(dt): # """Formats time like a logger does, for the csv output # (e.g. "2013-01-25 13:21:44,590") # @param dt: datetime object # @return: time string # """ # t = time.strftime("%Y-%m-%d %H:%M:%S", dt.timetuple()) # s = "%s,%03d" % (t, dt.microsecond/1000) # return s . Output only the next line.
NetlogParser: ".raw",
Next line prediction: <|code_start|># Copyright (C) 2010-2015 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. log = logging.getLogger(__name__) BUFSIZE = 16 * 1024 EXTENSIONS = { <|code_end|> . Use current file imports: (import os import socket import select import logging import datetime import SocketServer from threading import Event, Thread from lib.cuckoo.common.config import Config from lib.cuckoo.common.constants import CUCKOO_ROOT from lib.cuckoo.common.exceptions import CuckooOperationalError from lib.cuckoo.common.exceptions import CuckooCriticalError from lib.cuckoo.common.exceptions import CuckooResultError from lib.cuckoo.common.netlog import NetlogParser, BsonParser from lib.cuckoo.common.utils import create_folder, Singleton, logtime) and context including class names, function names, or small code snippets from other files: # Path: lib/cuckoo/common/config.py # class Config: # """Configuration file parser.""" # # def __init__(self, file_name="cuckoo", cfg=None): # """ # @param file_name: file name without extension. # @param cfg: configuration file path. # """ # config = ConfigParser.ConfigParser() # # if cfg: # config.read(cfg) # else: # config.read(os.path.join(CUCKOO_ROOT, "conf", "%s.conf" % file_name)) # # for section in config.sections(): # setattr(self, section, Dictionary()) # for name, raw_value in config.items(section): # try: # # Ugly fix to avoid '0' and '1' to be parsed as a # # boolean value. # # We raise an exception to goto fail^w parse it # # as integer. # if config.get(section, name) in ["0", "1"]: # raise ValueError # # value = config.getboolean(section, name) # except ValueError: # try: # value = config.getint(section, name) # except ValueError: # value = config.get(section, name) # # setattr(getattr(self, section), name, value) # # def get(self, section): # """Get option. # @param section: section to fetch. # @raise CuckooOperationalError: if section not found. # @return: option value. # """ # try: # return getattr(self, section) # except AttributeError as e: # raise CuckooOperationalError("Option %s is not found in " # "configuration, error: %s" % # (section, e)) # # Path: lib/cuckoo/common/utils.py # def create_folder(root=".", folder=None): # """Create directory. # @param root: root path. # @param folder: folder name to be created. # @raise CuckooOperationalError: if fails to create folder. # """ # folder_path = os.path.join(root, folder) # if folder and not os.path.isdir(folder_path): # try: # os.makedirs(folder_path) # except OSError: # raise CuckooOperationalError("Unable to create folder: %s" % # folder_path) # # class Singleton(type): # """Singleton. # @see: http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python # """ # _instances = {} # # def __call__(cls, *args, **kwargs): # if cls not in cls._instances: # cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) # return cls._instances[cls] # # def logtime(dt): # """Formats time like a logger does, for the csv output # (e.g. "2013-01-25 13:21:44,590") # @param dt: datetime object # @return: time string # """ # t = time.strftime("%Y-%m-%d %H:%M:%S", dt.timetuple()) # s = "%s,%03d" % (t, dt.microsecond/1000) # return s . Output only the next line.
NetlogParser: ".raw",
Using the snippet: <|code_start|> # Try via chardet. if not result and HAVE_CHARDET: result = chardet_enc(s) # If not possible to convert the input string, try again with # a replace strategy. if not result: result = unicode(s, errors="replace") return result def cleanup_value(v): """Cleanup utility function, strips some unwanted parts from values.""" v = str(v) if v.startswith("\\??\\"): v = v[4:] return v def sanitize_filename(x): """Kind of awful but necessary sanitizing of filenames to get rid of unicode problems.""" out = "" for c in x: if c in string.letters + string.digits + " _-.": out += c else: out += "_" return out <|code_end|> , determine the next line of code. You have imports: import os import time import shutil import ntpath import string import tempfile import xmlrpclib import inspect import threading import multiprocessing import chardet from datetime import datetime from lib.cuckoo.common.exceptions import CuckooOperationalError from lib.cuckoo.common.config import Config and context (class names, function names, or code) available: # Path: lib/cuckoo/common/config.py # class Config: # """Configuration file parser.""" # # def __init__(self, file_name="cuckoo", cfg=None): # """ # @param file_name: file name without extension. # @param cfg: configuration file path. # """ # config = ConfigParser.ConfigParser() # # if cfg: # config.read(cfg) # else: # config.read(os.path.join(CUCKOO_ROOT, "conf", "%s.conf" % file_name)) # # for section in config.sections(): # setattr(self, section, Dictionary()) # for name, raw_value in config.items(section): # try: # # Ugly fix to avoid '0' and '1' to be parsed as a # # boolean value. # # We raise an exception to goto fail^w parse it # # as integer. # if config.get(section, name) in ["0", "1"]: # raise ValueError # # value = config.getboolean(section, name) # except ValueError: # try: # value = config.getint(section, name) # except ValueError: # value = config.get(section, name) # # setattr(getattr(self, section), name, value) # # def get(self, section): # """Get option. # @param section: section to fetch. # @raise CuckooOperationalError: if section not found. # @return: option value. # """ # try: # return getattr(self, section) # except AttributeError as e: # raise CuckooOperationalError("Option %s is not found in " # "configuration, error: %s" % # (section, e)) . Output only the next line.
def classlock(f):
Here is a snippet: <|code_start|> if sys.version_info >= (3, 8): # pragma: no cover else: # pragma: no cover _PortalFactoryType = typing.Callable[ [], typing.ContextManager[anyio.abc.BlockingPortal] ] # Annotations for `Session.request()` Cookies = typing.Union[ typing.MutableMapping[str, str], requests.cookies.RequestsCookieJar ] Params = typing.Union[bytes, typing.MutableMapping[str, str]] DataType = typing.Union[bytes, typing.MutableMapping[str, str], typing.IO] <|code_end|> . Write the next line using the current file imports: import asyncio import contextlib import http import inspect import io import json import math import queue import sys import types import typing import anyio.abc import requests from concurrent.futures import Future from urllib.parse import unquote, urljoin, urlsplit from anyio.streams.stapled import StapledObjectStream from starlette.types import Message, Receive, Scope, Send from starlette.websockets import WebSocketDisconnect from typing import TypedDict from typing_extensions import TypedDict and context from other files: # Path: starlette/types.py # # Path: starlette/websockets.py # class WebSocketDisconnect(Exception): # def __init__(self, code: int = 1000, reason: str = None) -> None: # self.code = code # self.reason = reason or "" , which may include functions, classes, or code. Output only the next line.
TimeOut = typing.Union[float, typing.Tuple[float, float]]
Continue the code snippet: <|code_start|> if sys.version_info >= (3, 8): # pragma: no cover else: # pragma: no cover _PortalFactoryType = typing.Callable[ [], typing.ContextManager[anyio.abc.BlockingPortal] ] # Annotations for `Session.request()` Cookies = typing.Union[ typing.MutableMapping[str, str], requests.cookies.RequestsCookieJar ] Params = typing.Union[bytes, typing.MutableMapping[str, str]] DataType = typing.Union[bytes, typing.MutableMapping[str, str], typing.IO] <|code_end|> . Use current file imports: import asyncio import contextlib import http import inspect import io import json import math import queue import sys import types import typing import anyio.abc import requests from concurrent.futures import Future from urllib.parse import unquote, urljoin, urlsplit from anyio.streams.stapled import StapledObjectStream from starlette.types import Message, Receive, Scope, Send from starlette.websockets import WebSocketDisconnect from typing import TypedDict from typing_extensions import TypedDict and context (classes, functions, or code) from other files: # Path: starlette/types.py # # Path: starlette/websockets.py # class WebSocketDisconnect(Exception): # def __init__(self, code: int = 1000, reason: str = None) -> None: # self.code = code # self.reason = reason or "" . Output only the next line.
TimeOut = typing.Union[float, typing.Tuple[float, float]]
Using the snippet: <|code_start|>if sys.version_info >= (3, 8): # pragma: no cover else: # pragma: no cover _PortalFactoryType = typing.Callable[ [], typing.ContextManager[anyio.abc.BlockingPortal] ] # Annotations for `Session.request()` Cookies = typing.Union[ typing.MutableMapping[str, str], requests.cookies.RequestsCookieJar ] Params = typing.Union[bytes, typing.MutableMapping[str, str]] DataType = typing.Union[bytes, typing.MutableMapping[str, str], typing.IO] TimeOut = typing.Union[float, typing.Tuple[float, float]] FileType = typing.MutableMapping[str, typing.IO] AuthType = typing.Union[ typing.Tuple[str, str], requests.auth.AuthBase, typing.Callable[[requests.PreparedRequest], requests.PreparedRequest], ] ASGIInstance = typing.Callable[[Receive, Send], typing.Awaitable[None]] ASGI2App = typing.Callable[[Scope], ASGIInstance] ASGI3App = typing.Callable[[Scope, Receive, Send], typing.Awaitable[None]] class _HeaderDict(requests.packages.urllib3._collections.HTTPHeaderDict): <|code_end|> , determine the next line of code. You have imports: import asyncio import contextlib import http import inspect import io import json import math import queue import sys import types import typing import anyio.abc import requests from concurrent.futures import Future from urllib.parse import unquote, urljoin, urlsplit from anyio.streams.stapled import StapledObjectStream from starlette.types import Message, Receive, Scope, Send from starlette.websockets import WebSocketDisconnect from typing import TypedDict from typing_extensions import TypedDict and context (class names, function names, or code) available: # Path: starlette/types.py # # Path: starlette/websockets.py # class WebSocketDisconnect(Exception): # def __init__(self, code: int = 1000, reason: str = None) -> None: # self.code = code # self.reason = reason or "" . Output only the next line.
def get_all(self, key: str, default: str) -> str:
Here is a snippet: <|code_start|> if sys.version_info >= (3, 8): # pragma: no cover else: # pragma: no cover _PortalFactoryType = typing.Callable[ [], typing.ContextManager[anyio.abc.BlockingPortal] ] # Annotations for `Session.request()` Cookies = typing.Union[ typing.MutableMapping[str, str], requests.cookies.RequestsCookieJar ] <|code_end|> . Write the next line using the current file imports: import asyncio import contextlib import http import inspect import io import json import math import queue import sys import types import typing import anyio.abc import requests from concurrent.futures import Future from urllib.parse import unquote, urljoin, urlsplit from anyio.streams.stapled import StapledObjectStream from starlette.types import Message, Receive, Scope, Send from starlette.websockets import WebSocketDisconnect from typing import TypedDict from typing_extensions import TypedDict and context from other files: # Path: starlette/types.py # # Path: starlette/websockets.py # class WebSocketDisconnect(Exception): # def __init__(self, code: int = 1000, reason: str = None) -> None: # self.code = code # self.reason = reason or "" , which may include functions, classes, or code. Output only the next line.
Params = typing.Union[bytes, typing.MutableMapping[str, str]]
Using the snippet: <|code_start|> if sys.version_info >= (3, 8): # pragma: no cover else: # pragma: no cover _PortalFactoryType = typing.Callable[ [], typing.ContextManager[anyio.abc.BlockingPortal] ] # Annotations for `Session.request()` Cookies = typing.Union[ typing.MutableMapping[str, str], requests.cookies.RequestsCookieJar ] Params = typing.Union[bytes, typing.MutableMapping[str, str]] DataType = typing.Union[bytes, typing.MutableMapping[str, str], typing.IO] TimeOut = typing.Union[float, typing.Tuple[float, float]] FileType = typing.MutableMapping[str, typing.IO] AuthType = typing.Union[ <|code_end|> , determine the next line of code. You have imports: import asyncio import contextlib import http import inspect import io import json import math import queue import sys import types import typing import anyio.abc import requests from concurrent.futures import Future from urllib.parse import unquote, urljoin, urlsplit from anyio.streams.stapled import StapledObjectStream from starlette.types import Message, Receive, Scope, Send from starlette.websockets import WebSocketDisconnect from typing import TypedDict from typing_extensions import TypedDict and context (class names, function names, or code) available: # Path: starlette/types.py # # Path: starlette/websockets.py # class WebSocketDisconnect(Exception): # def __init__(self, code: int = 1000, reason: str = None) -> None: # self.code = code # self.reason = reason or "" . Output only the next line.
typing.Tuple[str, str],
Based on the snippet: <|code_start|> class HTTPSRedirectMiddleware: def __init__(self, app: ASGIApp) -> None: self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: <|code_end|> , predict the immediate next line with the help of imports: from starlette.datastructures import URL from starlette.responses import RedirectResponse from starlette.types import ASGIApp, Receive, Scope, Send and context (classes, functions, sometimes code) from other files: # Path: starlette/datastructures.py # class URL: # def __init__( # self, # url: str = "", # scope: typing.Optional[Scope] = None, # **components: typing.Any, # ) -> None: # if scope is not None: # assert not url, 'Cannot set both "url" and "scope".' # assert not components, 'Cannot set both "scope" and "**components".' # scheme = scope.get("scheme", "http") # server = scope.get("server", None) # path = scope.get("root_path", "") + scope["path"] # query_string = scope.get("query_string", b"") # # host_header = None # for key, value in scope["headers"]: # if key == b"host": # host_header = value.decode("latin-1") # break # # if host_header is not None: # url = f"{scheme}://{host_header}{path}" # elif server is None: # url = path # else: # host, port = server # default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme] # if port == default_port: # url = f"{scheme}://{host}{path}" # else: # url = f"{scheme}://{host}:{port}{path}" # # if query_string: # url += "?" + query_string.decode() # elif components: # assert not url, 'Cannot set both "url" and "**components".' # url = URL("").replace(**components).components.geturl() # # self._url = url # # @property # def components(self) -> SplitResult: # if not hasattr(self, "_components"): # self._components = urlsplit(self._url) # return self._components # # @property # def scheme(self) -> str: # return self.components.scheme # # @property # def netloc(self) -> str: # return self.components.netloc # # @property # def path(self) -> str: # return self.components.path # # @property # def query(self) -> str: # return self.components.query # # @property # def fragment(self) -> str: # return self.components.fragment # # @property # def username(self) -> typing.Union[None, str]: # return self.components.username # # @property # def password(self) -> typing.Union[None, str]: # return self.components.password # # @property # def hostname(self) -> typing.Union[None, str]: # return self.components.hostname # # @property # def port(self) -> typing.Optional[int]: # return self.components.port # # @property # def is_secure(self) -> bool: # return self.scheme in ("https", "wss") # # def replace(self, **kwargs: typing.Any) -> "URL": # if ( # "username" in kwargs # or "password" in kwargs # or "hostname" in kwargs # or "port" in kwargs # ): # hostname = kwargs.pop("hostname", self.hostname) # port = kwargs.pop("port", self.port) # username = kwargs.pop("username", self.username) # password = kwargs.pop("password", self.password) # # netloc = hostname # if port is not None: # netloc += f":{port}" # if username is not None: # userpass = username # if password is not None: # userpass += f":{password}" # netloc = f"{userpass}@{netloc}" # # kwargs["netloc"] = netloc # # components = self.components._replace(**kwargs) # return self.__class__(components.geturl()) # # def include_query_params(self, **kwargs: typing.Any) -> "URL": # params = MultiDict(parse_qsl(self.query, keep_blank_values=True)) # params.update({str(key): str(value) for key, value in kwargs.items()}) # query = urlencode(params.multi_items()) # return self.replace(query=query) # # def replace_query_params(self, **kwargs: typing.Any) -> "URL": # query = urlencode([(str(key), str(value)) for key, value in kwargs.items()]) # return self.replace(query=query) # # def remove_query_params( # self, keys: typing.Union[str, typing.Sequence[str]] # ) -> "URL": # if isinstance(keys, str): # keys = [keys] # params = MultiDict(parse_qsl(self.query, keep_blank_values=True)) # for key in keys: # params.pop(key, None) # query = urlencode(params.multi_items()) # return self.replace(query=query) # # def __eq__(self, other: typing.Any) -> bool: # return str(self) == str(other) # # def __str__(self) -> str: # return self._url # # def __repr__(self) -> str: # url = str(self) # if self.password: # url = str(self.replace(password="********")) # return f"{self.__class__.__name__}({repr(url)})" # # Path: starlette/responses.py # class RedirectResponse(Response): # def __init__( # self, # url: typing.Union[str, URL], # status_code: int = 307, # headers: typing.Mapping[str, str] = None, # background: BackgroundTask = None, # ) -> None: # super().__init__( # content=b"", status_code=status_code, headers=headers, background=background # ) # self.headers["location"] = quote(str(url), safe=":/%#?=@[]!$&'()*+,;") # # Path: starlette/types.py . Output only the next line.
if scope["type"] in ("http", "websocket") and scope["scheme"] in ("http", "ws"):
Here is a snippet: <|code_start|> class HTTPSRedirectMiddleware: def __init__(self, app: ASGIApp) -> None: self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if scope["type"] in ("http", "websocket") and scope["scheme"] in ("http", "ws"): url = URL(scope=scope) <|code_end|> . Write the next line using the current file imports: from starlette.datastructures import URL from starlette.responses import RedirectResponse from starlette.types import ASGIApp, Receive, Scope, Send and context from other files: # Path: starlette/datastructures.py # class URL: # def __init__( # self, # url: str = "", # scope: typing.Optional[Scope] = None, # **components: typing.Any, # ) -> None: # if scope is not None: # assert not url, 'Cannot set both "url" and "scope".' # assert not components, 'Cannot set both "scope" and "**components".' # scheme = scope.get("scheme", "http") # server = scope.get("server", None) # path = scope.get("root_path", "") + scope["path"] # query_string = scope.get("query_string", b"") # # host_header = None # for key, value in scope["headers"]: # if key == b"host": # host_header = value.decode("latin-1") # break # # if host_header is not None: # url = f"{scheme}://{host_header}{path}" # elif server is None: # url = path # else: # host, port = server # default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme] # if port == default_port: # url = f"{scheme}://{host}{path}" # else: # url = f"{scheme}://{host}:{port}{path}" # # if query_string: # url += "?" + query_string.decode() # elif components: # assert not url, 'Cannot set both "url" and "**components".' # url = URL("").replace(**components).components.geturl() # # self._url = url # # @property # def components(self) -> SplitResult: # if not hasattr(self, "_components"): # self._components = urlsplit(self._url) # return self._components # # @property # def scheme(self) -> str: # return self.components.scheme # # @property # def netloc(self) -> str: # return self.components.netloc # # @property # def path(self) -> str: # return self.components.path # # @property # def query(self) -> str: # return self.components.query # # @property # def fragment(self) -> str: # return self.components.fragment # # @property # def username(self) -> typing.Union[None, str]: # return self.components.username # # @property # def password(self) -> typing.Union[None, str]: # return self.components.password # # @property # def hostname(self) -> typing.Union[None, str]: # return self.components.hostname # # @property # def port(self) -> typing.Optional[int]: # return self.components.port # # @property # def is_secure(self) -> bool: # return self.scheme in ("https", "wss") # # def replace(self, **kwargs: typing.Any) -> "URL": # if ( # "username" in kwargs # or "password" in kwargs # or "hostname" in kwargs # or "port" in kwargs # ): # hostname = kwargs.pop("hostname", self.hostname) # port = kwargs.pop("port", self.port) # username = kwargs.pop("username", self.username) # password = kwargs.pop("password", self.password) # # netloc = hostname # if port is not None: # netloc += f":{port}" # if username is not None: # userpass = username # if password is not None: # userpass += f":{password}" # netloc = f"{userpass}@{netloc}" # # kwargs["netloc"] = netloc # # components = self.components._replace(**kwargs) # return self.__class__(components.geturl()) # # def include_query_params(self, **kwargs: typing.Any) -> "URL": # params = MultiDict(parse_qsl(self.query, keep_blank_values=True)) # params.update({str(key): str(value) for key, value in kwargs.items()}) # query = urlencode(params.multi_items()) # return self.replace(query=query) # # def replace_query_params(self, **kwargs: typing.Any) -> "URL": # query = urlencode([(str(key), str(value)) for key, value in kwargs.items()]) # return self.replace(query=query) # # def remove_query_params( # self, keys: typing.Union[str, typing.Sequence[str]] # ) -> "URL": # if isinstance(keys, str): # keys = [keys] # params = MultiDict(parse_qsl(self.query, keep_blank_values=True)) # for key in keys: # params.pop(key, None) # query = urlencode(params.multi_items()) # return self.replace(query=query) # # def __eq__(self, other: typing.Any) -> bool: # return str(self) == str(other) # # def __str__(self) -> str: # return self._url # # def __repr__(self) -> str: # url = str(self) # if self.password: # url = str(self.replace(password="********")) # return f"{self.__class__.__name__}({repr(url)})" # # Path: starlette/responses.py # class RedirectResponse(Response): # def __init__( # self, # url: typing.Union[str, URL], # status_code: int = 307, # headers: typing.Mapping[str, str] = None, # background: BackgroundTask = None, # ) -> None: # super().__init__( # content=b"", status_code=status_code, headers=headers, background=background # ) # self.headers["location"] = quote(str(url), safe=":/%#?=@[]!$&'()*+,;") # # Path: starlette/types.py , which may include functions, classes, or code. Output only the next line.
redirect_scheme = {"http": "https", "ws": "wss"}[url.scheme]
Predict the next line for this snippet: <|code_start|> try: # @contextfunction renamed to @pass_context in Jinja 3.0, to be removed in 3.1 if hasattr(jinja2, "pass_context"): pass_context = jinja2.pass_context else: # pragma: nocover pass_context = jinja2.contextfunction except ImportError: # pragma: nocover jinja2 = None # type: ignore class _TemplateResponse(Response): media_type = "text/html" def __init__( self, template: typing.Any, context: dict, <|code_end|> with the help of current file imports: import typing import jinja2 from os import PathLike from starlette.background import BackgroundTask from starlette.responses import Response from starlette.types import Receive, Scope, Send and context from other files: # Path: starlette/background.py # class BackgroundTask: # def __init__( # self, func: typing.Callable[P, typing.Any], *args: P.args, **kwargs: P.kwargs # ) -> None: # self.func = func # self.args = args # self.kwargs = kwargs # self.is_async = asyncio.iscoroutinefunction(func) # # async def __call__(self) -> None: # if self.is_async: # await self.func(*self.args, **self.kwargs) # else: # await run_in_threadpool(self.func, *self.args, **self.kwargs) # # Path: starlette/responses.py # class Response: # media_type = None # charset = "utf-8" # # def __init__( # self, # content: typing.Any = None, # status_code: int = 200, # headers: typing.Mapping[str, str] = None, # media_type: str = None, # background: BackgroundTask = None, # ) -> None: # self.status_code = status_code # if media_type is not None: # self.media_type = media_type # self.background = background # self.body = self.render(content) # self.init_headers(headers) # # def render(self, content: typing.Any) -> bytes: # if content is None: # return b"" # if isinstance(content, bytes): # return content # return content.encode(self.charset) # # def init_headers(self, headers: typing.Mapping[str, str] = None) -> None: # if headers is None: # raw_headers: typing.List[typing.Tuple[bytes, bytes]] = [] # populate_content_length = True # populate_content_type = True # else: # raw_headers = [ # (k.lower().encode("latin-1"), v.encode("latin-1")) # for k, v in headers.items() # ] # keys = [h[0] for h in raw_headers] # populate_content_length = b"content-length" not in keys # populate_content_type = b"content-type" not in keys # # body = getattr(self, "body", None) # if ( # body is not None # and populate_content_length # and not (self.status_code < 200 or self.status_code in (204, 304)) # ): # content_length = str(len(body)) # raw_headers.append((b"content-length", content_length.encode("latin-1"))) # # content_type = self.media_type # if content_type is not None and populate_content_type: # if content_type.startswith("text/"): # content_type += "; charset=" + self.charset # raw_headers.append((b"content-type", content_type.encode("latin-1"))) # # self.raw_headers = raw_headers # # @property # def headers(self) -> MutableHeaders: # if not hasattr(self, "_headers"): # self._headers = MutableHeaders(raw=self.raw_headers) # return self._headers # # def set_cookie( # self, # key: str, # value: str = "", # max_age: int = None, # expires: int = None, # path: str = "/", # domain: str = None, # secure: bool = False, # httponly: bool = False, # samesite: str = "lax", # ) -> None: # cookie: http.cookies.BaseCookie = http.cookies.SimpleCookie() # cookie[key] = value # if max_age is not None: # cookie[key]["max-age"] = max_age # if expires is not None: # cookie[key]["expires"] = expires # if path is not None: # cookie[key]["path"] = path # if domain is not None: # cookie[key]["domain"] = domain # if secure: # cookie[key]["secure"] = True # if httponly: # cookie[key]["httponly"] = True # if samesite is not None: # assert samesite.lower() in [ # "strict", # "lax", # "none", # ], "samesite must be either 'strict', 'lax' or 'none'" # cookie[key]["samesite"] = samesite # cookie_val = cookie.output(header="").strip() # self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1"))) # # def delete_cookie( # self, # key: str, # path: str = "/", # domain: str = None, # secure: bool = False, # httponly: bool = False, # samesite: str = "lax", # ) -> None: # self.set_cookie( # key, # max_age=0, # expires=0, # path=path, # domain=domain, # secure=secure, # httponly=httponly, # samesite=samesite, # ) # # async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: # await send( # { # "type": "http.response.start", # "status": self.status_code, # "headers": self.raw_headers, # } # ) # await send({"type": "http.response.body", "body": self.body}) # # if self.background is not None: # await self.background() # # Path: starlette/types.py , which may contain function names, class names, or code. Output only the next line.
status_code: int = 200,
Predict the next line after this snippet: <|code_start|> warnings.warn( "starlette.middleware.wsgi is deprecated and will be removed in a future release. " "Please refer to https://github.com/abersheeran/a2wsgi as a replacement.", DeprecationWarning, <|code_end|> using the current file's imports: import io import math import sys import typing import warnings import anyio from starlette.types import Receive, Scope, Send and any relevant context from other files: # Path: starlette/types.py . Output only the next line.
)
Given the following code snippet before the placeholder: <|code_start|> if sys.version_info >= (3, 10): # pragma: no cover else: # pragma: no cover P = ParamSpec("P") <|code_end|> , predict the next line using imports from the current file: import asyncio import sys import typing from typing import ParamSpec from typing_extensions import ParamSpec from starlette.concurrency import run_in_threadpool and context including class names, function names, and sometimes code from other files: # Path: starlette/concurrency.py # async def run_in_threadpool( # func: typing.Callable[P, T], *args: P.args, **kwargs: P.kwargs # ) -> T: # if kwargs: # pragma: no cover # # run_sync doesn't accept 'kwargs', so bind them in here # func = functools.partial(func, **kwargs) # return await anyio.to_thread.run_sync(func, *args) . Output only the next line.
class BackgroundTask:
Based on the snippet: <|code_start|> class Address(typing.NamedTuple): host: str port: int class URL: def __init__( self, url: str = "", scope: typing.Optional[Scope] = None, **components: typing.Any, ) -> None: if scope is not None: <|code_end|> , predict the immediate next line with the help of imports: import tempfile import typing from collections.abc import Sequence from shlex import shlex from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit from starlette.concurrency import run_in_threadpool from starlette.types import Scope and context (classes, functions, sometimes code) from other files: # Path: starlette/concurrency.py # async def run_in_threadpool( # func: typing.Callable[P, T], *args: P.args, **kwargs: P.kwargs # ) -> T: # if kwargs: # pragma: no cover # # run_sync doesn't accept 'kwargs', so bind them in here # func = functools.partial(func, **kwargs) # return await anyio.to_thread.run_sync(func, *args) # # Path: starlette/types.py . Output only the next line.
assert not url, 'Cannot set both "url" and "scope".'
Here is a snippet: <|code_start|> self._url = url @property def components(self) -> SplitResult: if not hasattr(self, "_components"): self._components = urlsplit(self._url) return self._components @property def scheme(self) -> str: return self.components.scheme @property def netloc(self) -> str: return self.components.netloc @property def path(self) -> str: return self.components.path @property def query(self) -> str: return self.components.query @property def fragment(self) -> str: return self.components.fragment @property def username(self) -> typing.Union[None, str]: <|code_end|> . Write the next line using the current file imports: import tempfile import typing from collections.abc import Sequence from shlex import shlex from urllib.parse import SplitResult, parse_qsl, urlencode, urlsplit from starlette.concurrency import run_in_threadpool from starlette.types import Scope and context from other files: # Path: starlette/concurrency.py # async def run_in_threadpool( # func: typing.Callable[P, T], *args: P.args, **kwargs: P.kwargs # ) -> T: # if kwargs: # pragma: no cover # # run_sync doesn't accept 'kwargs', so bind them in here # func = functools.partial(func, **kwargs) # return await anyio.to_thread.run_sync(func, *args) # # Path: starlette/types.py , which may include functions, classes, or code. Output only the next line.
return self.components.username
Given snippet: <|code_start|> app = WSGIMiddleware(hello_world) client = test_client_factory(app) response = client.get("/") assert response.status_code == 200 assert response.text == "Hello World!\n" def test_wsgi_post(test_client_factory): app = WSGIMiddleware(echo_body) client = test_client_factory(app) response = client.post("/", json={"example": 123}) assert response.status_code == 200 assert response.text == '{"example": 123}' def test_wsgi_exception(test_client_factory): # Note that we're testing the WSGI app directly here. # The HTTP protocol implementations would catch this error and return 500. app = WSGIMiddleware(raise_exception) client = test_client_factory(app) with pytest.raises(RuntimeError): client.get("/") def test_wsgi_exc_info(test_client_factory): # Note that we're testing the WSGI app directly here. # The HTTP protocol implementations would catch this error and return 500. app = WSGIMiddleware(return_exc_info) client = test_client_factory(app) with pytest.raises(RuntimeError): <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import pytest from starlette.middleware.wsgi import WSGIMiddleware, build_environ and context: # Path: starlette/middleware/wsgi.py # class WSGIMiddleware: # def __init__(self, app: typing.Callable) -> None: # self.app = app # # async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: # assert scope["type"] == "http" # responder = WSGIResponder(self.app, scope) # await responder(receive, send) # # def build_environ(scope: Scope, body: bytes) -> dict: # """ # Builds a scope and request body into a WSGI environ object. # """ # environ = { # "REQUEST_METHOD": scope["method"], # "SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"), # "PATH_INFO": scope["path"].encode("utf8").decode("latin1"), # "QUERY_STRING": scope["query_string"].decode("ascii"), # "SERVER_PROTOCOL": f"HTTP/{scope['http_version']}", # "wsgi.version": (1, 0), # "wsgi.url_scheme": scope.get("scheme", "http"), # "wsgi.input": io.BytesIO(body), # "wsgi.errors": sys.stdout, # "wsgi.multithread": True, # "wsgi.multiprocess": True, # "wsgi.run_once": False, # } # # # Get server name and port - required in WSGI, not in ASGI # server = scope.get("server") or ("localhost", 80) # environ["SERVER_NAME"] = server[0] # environ["SERVER_PORT"] = server[1] # # # Get client IP address # if scope.get("client"): # environ["REMOTE_ADDR"] = scope["client"][0] # # # Go through headers and make them into environ entries # for name, value in scope.get("headers", []): # name = name.decode("latin1") # if name == "content-length": # corrected_name = "CONTENT_LENGTH" # elif name == "content-type": # corrected_name = "CONTENT_TYPE" # else: # corrected_name = f"HTTP_{name}".upper().replace("-", "_") # # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in # # case # value = value.decode("latin1") # if corrected_name in environ: # value = environ[corrected_name] + "," + value # environ[corrected_name] = value # return environ which might include code, classes, or functions. Output only the next line.
response = client.get("/")
Based on the snippet: <|code_start|> headers = [ ("Content-Type", "text/plain; charset=utf-8"), ("Content-Length", str(len(output))), ] start_response(status, headers) return [output] def raise_exception(environ, start_response): raise RuntimeError("Something went wrong") def return_exc_info(environ, start_response): try: raise RuntimeError("Something went wrong") except RuntimeError: status = "500 Internal Server Error" output = b"Internal Server Error" headers = [ ("Content-Type", "text/plain; charset=utf-8"), ("Content-Length", str(len(output))), ] start_response(status, headers, exc_info=sys.exc_info()) return [output] def test_wsgi_get(test_client_factory): app = WSGIMiddleware(hello_world) client = test_client_factory(app) response = client.get("/") <|code_end|> , predict the immediate next line with the help of imports: import sys import pytest from starlette.middleware.wsgi import WSGIMiddleware, build_environ and context (classes, functions, sometimes code) from other files: # Path: starlette/middleware/wsgi.py # class WSGIMiddleware: # def __init__(self, app: typing.Callable) -> None: # self.app = app # # async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: # assert scope["type"] == "http" # responder = WSGIResponder(self.app, scope) # await responder(receive, send) # # def build_environ(scope: Scope, body: bytes) -> dict: # """ # Builds a scope and request body into a WSGI environ object. # """ # environ = { # "REQUEST_METHOD": scope["method"], # "SCRIPT_NAME": scope.get("root_path", "").encode("utf8").decode("latin1"), # "PATH_INFO": scope["path"].encode("utf8").decode("latin1"), # "QUERY_STRING": scope["query_string"].decode("ascii"), # "SERVER_PROTOCOL": f"HTTP/{scope['http_version']}", # "wsgi.version": (1, 0), # "wsgi.url_scheme": scope.get("scheme", "http"), # "wsgi.input": io.BytesIO(body), # "wsgi.errors": sys.stdout, # "wsgi.multithread": True, # "wsgi.multiprocess": True, # "wsgi.run_once": False, # } # # # Get server name and port - required in WSGI, not in ASGI # server = scope.get("server") or ("localhost", 80) # environ["SERVER_NAME"] = server[0] # environ["SERVER_PORT"] = server[1] # # # Get client IP address # if scope.get("client"): # environ["REMOTE_ADDR"] = scope["client"][0] # # # Go through headers and make them into environ entries # for name, value in scope.get("headers", []): # name = name.decode("latin1") # if name == "content-length": # corrected_name = "CONTENT_LENGTH" # elif name == "content-type": # corrected_name = "CONTENT_TYPE" # else: # corrected_name = f"HTTP_{name}".upper().replace("-", "_") # # HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in # # case # value = value.decode("latin1") # if corrected_name in environ: # value = environ[corrected_name] + "," + value # environ[corrected_name] = value # return environ . Output only the next line.
assert response.status_code == 200
Predict the next line after this snippet: <|code_start|> class WebSocketState(enum.Enum): CONNECTING = 0 CONNECTED = 1 DISCONNECTED = 2 class WebSocketDisconnect(Exception): def __init__(self, code: int = 1000, reason: str = None) -> None: <|code_end|> using the current file's imports: import enum import json import typing from starlette.requests import HTTPConnection from starlette.types import Message, Receive, Scope, Send and any relevant context from other files: # Path: starlette/requests.py # class HTTPConnection(Mapping): # """ # A base class for incoming HTTP connections, that is used to provide # any functionality that is common to both `Request` and `WebSocket`. # """ # # def __init__(self, scope: Scope, receive: Receive = None) -> None: # assert scope["type"] in ("http", "websocket") # self.scope = scope # # def __getitem__(self, key: str) -> typing.Any: # return self.scope[key] # # def __iter__(self) -> typing.Iterator[str]: # return iter(self.scope) # # def __len__(self) -> int: # return len(self.scope) # # # Don't use the `abc.Mapping.__eq__` implementation. # # Connection instances should never be considered equal # # unless `self is other`. # __eq__ = object.__eq__ # __hash__ = object.__hash__ # # @property # def app(self) -> typing.Any: # return self.scope["app"] # # @property # def url(self) -> URL: # if not hasattr(self, "_url"): # self._url = URL(scope=self.scope) # return self._url # # @property # def base_url(self) -> URL: # if not hasattr(self, "_base_url"): # base_url_scope = dict(self.scope) # base_url_scope["path"] = "/" # base_url_scope["query_string"] = b"" # base_url_scope["root_path"] = base_url_scope.get( # "app_root_path", base_url_scope.get("root_path", "") # ) # self._base_url = URL(scope=base_url_scope) # return self._base_url # # @property # def headers(self) -> Headers: # if not hasattr(self, "_headers"): # self._headers = Headers(scope=self.scope) # return self._headers # # @property # def query_params(self) -> QueryParams: # if not hasattr(self, "_query_params"): # self._query_params = QueryParams(self.scope["query_string"]) # return self._query_params # # @property # def path_params(self) -> typing.Dict[str, typing.Any]: # return self.scope.get("path_params", {}) # # @property # def cookies(self) -> typing.Dict[str, str]: # if not hasattr(self, "_cookies"): # cookies: typing.Dict[str, str] = {} # cookie_header = self.headers.get("cookie") # # if cookie_header: # cookies = cookie_parser(cookie_header) # self._cookies = cookies # return self._cookies # # @property # def client(self) -> typing.Optional[Address]: # # client is a 2 item tuple of (host, port), None or missing # host_port = self.scope.get("client") # if host_port is not None: # return Address(*host_port) # return None # # @property # def session(self) -> dict: # assert ( # "session" in self.scope # ), "SessionMiddleware must be installed to access request.session" # return self.scope["session"] # # @property # def auth(self) -> typing.Any: # assert ( # "auth" in self.scope # ), "AuthenticationMiddleware must be installed to access request.auth" # return self.scope["auth"] # # @property # def user(self) -> typing.Any: # assert ( # "user" in self.scope # ), "AuthenticationMiddleware must be installed to access request.user" # return self.scope["user"] # # @property # def state(self) -> State: # if not hasattr(self, "_state"): # # Ensure 'state' has an empty dict if it's not already populated. # self.scope.setdefault("state", {}) # # Create a state instance with a reference to the dict in which it should # # store info # self._state = State(self.scope["state"]) # return self._state # # def url_for(self, name: str, **path_params: typing.Any) -> str: # router: Router = self.scope["router"] # url_path = router.url_path_for(name, **path_params) # return url_path.make_absolute_url(base_url=self.base_url) # # Path: starlette/types.py . Output only the next line.
self.code = code
Given the code snippet: <|code_start|> class WebSocketState(enum.Enum): CONNECTING = 0 CONNECTED = 1 <|code_end|> , generate the next line using the imports in this file: import enum import json import typing from starlette.requests import HTTPConnection from starlette.types import Message, Receive, Scope, Send and context (functions, classes, or occasionally code) from other files: # Path: starlette/requests.py # class HTTPConnection(Mapping): # """ # A base class for incoming HTTP connections, that is used to provide # any functionality that is common to both `Request` and `WebSocket`. # """ # # def __init__(self, scope: Scope, receive: Receive = None) -> None: # assert scope["type"] in ("http", "websocket") # self.scope = scope # # def __getitem__(self, key: str) -> typing.Any: # return self.scope[key] # # def __iter__(self) -> typing.Iterator[str]: # return iter(self.scope) # # def __len__(self) -> int: # return len(self.scope) # # # Don't use the `abc.Mapping.__eq__` implementation. # # Connection instances should never be considered equal # # unless `self is other`. # __eq__ = object.__eq__ # __hash__ = object.__hash__ # # @property # def app(self) -> typing.Any: # return self.scope["app"] # # @property # def url(self) -> URL: # if not hasattr(self, "_url"): # self._url = URL(scope=self.scope) # return self._url # # @property # def base_url(self) -> URL: # if not hasattr(self, "_base_url"): # base_url_scope = dict(self.scope) # base_url_scope["path"] = "/" # base_url_scope["query_string"] = b"" # base_url_scope["root_path"] = base_url_scope.get( # "app_root_path", base_url_scope.get("root_path", "") # ) # self._base_url = URL(scope=base_url_scope) # return self._base_url # # @property # def headers(self) -> Headers: # if not hasattr(self, "_headers"): # self._headers = Headers(scope=self.scope) # return self._headers # # @property # def query_params(self) -> QueryParams: # if not hasattr(self, "_query_params"): # self._query_params = QueryParams(self.scope["query_string"]) # return self._query_params # # @property # def path_params(self) -> typing.Dict[str, typing.Any]: # return self.scope.get("path_params", {}) # # @property # def cookies(self) -> typing.Dict[str, str]: # if not hasattr(self, "_cookies"): # cookies: typing.Dict[str, str] = {} # cookie_header = self.headers.get("cookie") # # if cookie_header: # cookies = cookie_parser(cookie_header) # self._cookies = cookies # return self._cookies # # @property # def client(self) -> typing.Optional[Address]: # # client is a 2 item tuple of (host, port), None or missing # host_port = self.scope.get("client") # if host_port is not None: # return Address(*host_port) # return None # # @property # def session(self) -> dict: # assert ( # "session" in self.scope # ), "SessionMiddleware must be installed to access request.session" # return self.scope["session"] # # @property # def auth(self) -> typing.Any: # assert ( # "auth" in self.scope # ), "AuthenticationMiddleware must be installed to access request.auth" # return self.scope["auth"] # # @property # def user(self) -> typing.Any: # assert ( # "user" in self.scope # ), "AuthenticationMiddleware must be installed to access request.user" # return self.scope["user"] # # @property # def state(self) -> State: # if not hasattr(self, "_state"): # # Ensure 'state' has an empty dict if it's not already populated. # self.scope.setdefault("state", {}) # # Create a state instance with a reference to the dict in which it should # # store info # self._state = State(self.scope["state"]) # return self._state # # def url_for(self, name: str, **path_params: typing.Any) -> str: # router: Router = self.scope["router"] # url_path = router.url_path_for(name, **path_params) # return url_path.make_absolute_url(base_url=self.base_url) # # Path: starlette/types.py . Output only the next line.
DISCONNECTED = 2
Continue the code snippet: <|code_start|> class WebSocketState(enum.Enum): CONNECTING = 0 CONNECTED = 1 DISCONNECTED = 2 class WebSocketDisconnect(Exception): def __init__(self, code: int = 1000, reason: str = None) -> None: self.code = code self.reason = reason or "" class WebSocket(HTTPConnection): def __init__(self, scope: Scope, receive: Receive, send: Send) -> None: super().__init__(scope) assert scope["type"] == "websocket" self._receive = receive self._send = send <|code_end|> . Use current file imports: import enum import json import typing from starlette.requests import HTTPConnection from starlette.types import Message, Receive, Scope, Send and context (classes, functions, or code) from other files: # Path: starlette/requests.py # class HTTPConnection(Mapping): # """ # A base class for incoming HTTP connections, that is used to provide # any functionality that is common to both `Request` and `WebSocket`. # """ # # def __init__(self, scope: Scope, receive: Receive = None) -> None: # assert scope["type"] in ("http", "websocket") # self.scope = scope # # def __getitem__(self, key: str) -> typing.Any: # return self.scope[key] # # def __iter__(self) -> typing.Iterator[str]: # return iter(self.scope) # # def __len__(self) -> int: # return len(self.scope) # # # Don't use the `abc.Mapping.__eq__` implementation. # # Connection instances should never be considered equal # # unless `self is other`. # __eq__ = object.__eq__ # __hash__ = object.__hash__ # # @property # def app(self) -> typing.Any: # return self.scope["app"] # # @property # def url(self) -> URL: # if not hasattr(self, "_url"): # self._url = URL(scope=self.scope) # return self._url # # @property # def base_url(self) -> URL: # if not hasattr(self, "_base_url"): # base_url_scope = dict(self.scope) # base_url_scope["path"] = "/" # base_url_scope["query_string"] = b"" # base_url_scope["root_path"] = base_url_scope.get( # "app_root_path", base_url_scope.get("root_path", "") # ) # self._base_url = URL(scope=base_url_scope) # return self._base_url # # @property # def headers(self) -> Headers: # if not hasattr(self, "_headers"): # self._headers = Headers(scope=self.scope) # return self._headers # # @property # def query_params(self) -> QueryParams: # if not hasattr(self, "_query_params"): # self._query_params = QueryParams(self.scope["query_string"]) # return self._query_params # # @property # def path_params(self) -> typing.Dict[str, typing.Any]: # return self.scope.get("path_params", {}) # # @property # def cookies(self) -> typing.Dict[str, str]: # if not hasattr(self, "_cookies"): # cookies: typing.Dict[str, str] = {} # cookie_header = self.headers.get("cookie") # # if cookie_header: # cookies = cookie_parser(cookie_header) # self._cookies = cookies # return self._cookies # # @property # def client(self) -> typing.Optional[Address]: # # client is a 2 item tuple of (host, port), None or missing # host_port = self.scope.get("client") # if host_port is not None: # return Address(*host_port) # return None # # @property # def session(self) -> dict: # assert ( # "session" in self.scope # ), "SessionMiddleware must be installed to access request.session" # return self.scope["session"] # # @property # def auth(self) -> typing.Any: # assert ( # "auth" in self.scope # ), "AuthenticationMiddleware must be installed to access request.auth" # return self.scope["auth"] # # @property # def user(self) -> typing.Any: # assert ( # "user" in self.scope # ), "AuthenticationMiddleware must be installed to access request.user" # return self.scope["user"] # # @property # def state(self) -> State: # if not hasattr(self, "_state"): # # Ensure 'state' has an empty dict if it's not already populated. # self.scope.setdefault("state", {}) # # Create a state instance with a reference to the dict in which it should # # store info # self._state = State(self.scope["state"]) # return self._state # # def url_for(self, name: str, **path_params: typing.Any) -> str: # router: Router = self.scope["router"] # url_path = router.url_path_for(name, **path_params) # return url_path.make_absolute_url(base_url=self.base_url) # # Path: starlette/types.py . Output only the next line.
self.client_state = WebSocketState.CONNECTING
Here is a snippet: <|code_start|> class WebSocketState(enum.Enum): CONNECTING = 0 CONNECTED = 1 DISCONNECTED = 2 class WebSocketDisconnect(Exception): <|code_end|> . Write the next line using the current file imports: import enum import json import typing from starlette.requests import HTTPConnection from starlette.types import Message, Receive, Scope, Send and context from other files: # Path: starlette/requests.py # class HTTPConnection(Mapping): # """ # A base class for incoming HTTP connections, that is used to provide # any functionality that is common to both `Request` and `WebSocket`. # """ # # def __init__(self, scope: Scope, receive: Receive = None) -> None: # assert scope["type"] in ("http", "websocket") # self.scope = scope # # def __getitem__(self, key: str) -> typing.Any: # return self.scope[key] # # def __iter__(self) -> typing.Iterator[str]: # return iter(self.scope) # # def __len__(self) -> int: # return len(self.scope) # # # Don't use the `abc.Mapping.__eq__` implementation. # # Connection instances should never be considered equal # # unless `self is other`. # __eq__ = object.__eq__ # __hash__ = object.__hash__ # # @property # def app(self) -> typing.Any: # return self.scope["app"] # # @property # def url(self) -> URL: # if not hasattr(self, "_url"): # self._url = URL(scope=self.scope) # return self._url # # @property # def base_url(self) -> URL: # if not hasattr(self, "_base_url"): # base_url_scope = dict(self.scope) # base_url_scope["path"] = "/" # base_url_scope["query_string"] = b"" # base_url_scope["root_path"] = base_url_scope.get( # "app_root_path", base_url_scope.get("root_path", "") # ) # self._base_url = URL(scope=base_url_scope) # return self._base_url # # @property # def headers(self) -> Headers: # if not hasattr(self, "_headers"): # self._headers = Headers(scope=self.scope) # return self._headers # # @property # def query_params(self) -> QueryParams: # if not hasattr(self, "_query_params"): # self._query_params = QueryParams(self.scope["query_string"]) # return self._query_params # # @property # def path_params(self) -> typing.Dict[str, typing.Any]: # return self.scope.get("path_params", {}) # # @property # def cookies(self) -> typing.Dict[str, str]: # if not hasattr(self, "_cookies"): # cookies: typing.Dict[str, str] = {} # cookie_header = self.headers.get("cookie") # # if cookie_header: # cookies = cookie_parser(cookie_header) # self._cookies = cookies # return self._cookies # # @property # def client(self) -> typing.Optional[Address]: # # client is a 2 item tuple of (host, port), None or missing # host_port = self.scope.get("client") # if host_port is not None: # return Address(*host_port) # return None # # @property # def session(self) -> dict: # assert ( # "session" in self.scope # ), "SessionMiddleware must be installed to access request.session" # return self.scope["session"] # # @property # def auth(self) -> typing.Any: # assert ( # "auth" in self.scope # ), "AuthenticationMiddleware must be installed to access request.auth" # return self.scope["auth"] # # @property # def user(self) -> typing.Any: # assert ( # "user" in self.scope # ), "AuthenticationMiddleware must be installed to access request.user" # return self.scope["user"] # # @property # def state(self) -> State: # if not hasattr(self, "_state"): # # Ensure 'state' has an empty dict if it's not already populated. # self.scope.setdefault("state", {}) # # Create a state instance with a reference to the dict in which it should # # store info # self._state = State(self.scope["state"]) # return self._state # # def url_for(self, name: str, **path_params: typing.Any) -> str: # router: Router = self.scope["router"] # url_path = router.url_path_for(name, **path_params) # return url_path.make_absolute_url(base_url=self.base_url) # # Path: starlette/types.py , which may include functions, classes, or code. Output only the next line.
def __init__(self, code: int = 1000, reason: str = None) -> None:
Based on the snippet: <|code_start|> class WebSocketState(enum.Enum): CONNECTING = 0 CONNECTED = 1 DISCONNECTED = 2 class WebSocketDisconnect(Exception): def __init__(self, code: int = 1000, reason: str = None) -> None: self.code = code <|code_end|> , predict the immediate next line with the help of imports: import enum import json import typing from starlette.requests import HTTPConnection from starlette.types import Message, Receive, Scope, Send and context (classes, functions, sometimes code) from other files: # Path: starlette/requests.py # class HTTPConnection(Mapping): # """ # A base class for incoming HTTP connections, that is used to provide # any functionality that is common to both `Request` and `WebSocket`. # """ # # def __init__(self, scope: Scope, receive: Receive = None) -> None: # assert scope["type"] in ("http", "websocket") # self.scope = scope # # def __getitem__(self, key: str) -> typing.Any: # return self.scope[key] # # def __iter__(self) -> typing.Iterator[str]: # return iter(self.scope) # # def __len__(self) -> int: # return len(self.scope) # # # Don't use the `abc.Mapping.__eq__` implementation. # # Connection instances should never be considered equal # # unless `self is other`. # __eq__ = object.__eq__ # __hash__ = object.__hash__ # # @property # def app(self) -> typing.Any: # return self.scope["app"] # # @property # def url(self) -> URL: # if not hasattr(self, "_url"): # self._url = URL(scope=self.scope) # return self._url # # @property # def base_url(self) -> URL: # if not hasattr(self, "_base_url"): # base_url_scope = dict(self.scope) # base_url_scope["path"] = "/" # base_url_scope["query_string"] = b"" # base_url_scope["root_path"] = base_url_scope.get( # "app_root_path", base_url_scope.get("root_path", "") # ) # self._base_url = URL(scope=base_url_scope) # return self._base_url # # @property # def headers(self) -> Headers: # if not hasattr(self, "_headers"): # self._headers = Headers(scope=self.scope) # return self._headers # # @property # def query_params(self) -> QueryParams: # if not hasattr(self, "_query_params"): # self._query_params = QueryParams(self.scope["query_string"]) # return self._query_params # # @property # def path_params(self) -> typing.Dict[str, typing.Any]: # return self.scope.get("path_params", {}) # # @property # def cookies(self) -> typing.Dict[str, str]: # if not hasattr(self, "_cookies"): # cookies: typing.Dict[str, str] = {} # cookie_header = self.headers.get("cookie") # # if cookie_header: # cookies = cookie_parser(cookie_header) # self._cookies = cookies # return self._cookies # # @property # def client(self) -> typing.Optional[Address]: # # client is a 2 item tuple of (host, port), None or missing # host_port = self.scope.get("client") # if host_port is not None: # return Address(*host_port) # return None # # @property # def session(self) -> dict: # assert ( # "session" in self.scope # ), "SessionMiddleware must be installed to access request.session" # return self.scope["session"] # # @property # def auth(self) -> typing.Any: # assert ( # "auth" in self.scope # ), "AuthenticationMiddleware must be installed to access request.auth" # return self.scope["auth"] # # @property # def user(self) -> typing.Any: # assert ( # "user" in self.scope # ), "AuthenticationMiddleware must be installed to access request.user" # return self.scope["user"] # # @property # def state(self) -> State: # if not hasattr(self, "_state"): # # Ensure 'state' has an empty dict if it's not already populated. # self.scope.setdefault("state", {}) # # Create a state instance with a reference to the dict in which it should # # store info # self._state = State(self.scope["state"]) # return self._state # # def url_for(self, name: str, **path_params: typing.Any) -> str: # router: Router = self.scope["router"] # url_path = router.url_path_for(name, **path_params) # return url_path.make_absolute_url(base_url=self.base_url) # # Path: starlette/types.py . Output only the next line.
self.reason = reason or ""
Given the code snippet: <|code_start|> result = cursor.fetchall() return result @staticmethod def updateHistory(clauseSentence,**update): entry = update sentence = '' for key in entry.keys(): sentence += ","+key + " = \'" + str(entry[key])+ "\' " sentence = sentence.split(',', 1)[1] conn = sqlite3.connect('XulDebugTool.db') conn.execute("update "+DBManager.TABLE_HISTORY+" set " + sentence + " where 1 = 1 " + clauseSentence ) conn.commit() conn.close() @staticmethod def updateFavorites(clauseSentence,**update): entry = update sentence = '' for key in entry.keys(): sentence += ","+key + " = \'" + str(entry[key])+ "\' " sentence = sentence.split(',', 1)[1] conn = sqlite3.connect('XulDebugTool.db') conn.execute("update "+DBManager.TABLE_FAVORITES+" set " + sentence + " where 1 = 1 " + clauseSentence ) conn.commit() conn.close() @staticmethod def deleteHistory(sentence = ''): conn = sqlite3.connect('XulDebugTool.db') <|code_end|> , generate the next line using the imports in this file: import sqlite3 from PyQt5.QtCore import QObject from XulDebugTool.ui.widget.model.database.DBManager import DBManager and context (functions, classes, or occasionally code) from other files: # Path: XulDebugTool/ui/widget/model/database/DBManager.py # class DBManager(object): # TABLE_DEVICE = "device" # TABLE_LOGIN = "login" # TABLE_CONFIGURATION = 'configuration' # TABLE_FAVORITES = 'favorites' # TABLE_HISTORY = 'history_query' # # @staticmethod # def createTable(): # conn = sqlite3.connect('XulDebugTool.db') # cursor = conn.cursor() # cursor.execute('create table if not exists '+DBManager.TABLE_DEVICE+' (name varchar(50) primary key)') # cursor.execute('create table if not exists '+DBManager.TABLE_LOGIN+' (name varchar(50) primary key)') # cursor.execute('create table if not exists '+DBManager.TABLE_HISTORY+'(id integer primary key autoincrement, name nvarchar(50) null,url nvarchar(512) null,date TIMESTAMP null,favorite binary(1) default 0)') # cursor.execute('create table if not exists '+DBManager.TABLE_FAVORITES+' (id integer primary key autoincrement, name nvarchar(50) null,url nvarchar(512) null,date TIMESTAMP null,history_id integer not null,UNIQUE(history_id),FOREIGN KEY (history_id) REFERENCES history_query(id))') # cursor.execute('create table if not exists ' + DBManager.TABLE_CONFIGURATION + ' (id integer primary key autoincrement,config_key nvarchar(100) not null unique ,config_value nvarchar(512) null )') # cursor.close() # conn.close() . Output only the next line.
if sentence != '' and sentence != None:
Continue the code snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- class BaseDialog(QDialog): def __init__(self, title): super().__init__() self.title = title def initWindow(self): self.setWindowTitle(self.title) self.setWindowIcon(IconTool.buildQIcon('icon.png')) self.resize(500, 300) <|code_end|> . Use current file imports: from PyQt5.QtWidgets import QDesktopWidget, QDialog from XulDebugTool.utils.IconTool import IconTool and context (classes, functions, or code) from other files: # Path: XulDebugTool/utils/IconTool.py # class IconTool(object): # def __init__(self): # super().__init__() # # def buildQIcon(iconName): # return QIcon(os.path.join('..', 'resources', 'images', iconName)) # # def buildQPixmap(pixmapName): # return QPixmap(os.path.join('..', 'resources', 'images', pixmapName)) . Output only the next line.
self.center()
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- class ConfigHelper(object): LOGCATPATH = "" #以下是配置信息所对应的key KEY_LOGCATPATH = 'logcatPath' @staticmethod <|code_end|> with the help of current file imports: import os from XulDebugTool.ui.widget.model.database.ConfigurationDB import ConfigurationDB and context from other files: # Path: XulDebugTool/ui/widget/model/database/ConfigurationDB.py # class ConfigurationDB(QObject): # # @staticmethod # def saveConfiguration(key ,value): # if key == None or len(str(key))<1: # return # conn = sqlite3.connect('XulDebugTool.db') # cursor = conn.execute("select count(*) from "+DBManager.TABLE_CONFIGURATION+" where config_key = '"+str(key)+"'"); # for row in cursor: # count = row[0] # if count > 0: # conn.execute("update "+DBManager.TABLE_CONFIGURATION+" set config_value = '"+str(value)+"' where config_key = '"+str(key)+"'") # else: # conn.execute("insert into "+DBManager.TABLE_CONFIGURATION+" (config_key,config_value) values('"+str(key)+"','"+str(value)+"')") # conn.commit() # conn.close() # # @staticmethod # def getConfiguration(key): # if key == None or len(str(key))<1: # return # conn = sqlite3.connect('XulDebugTool.db') # cursor = conn.execute("select * from " + DBManager.TABLE_CONFIGURATION + " where config_key = '" + str(key)+"'"); # result = '' # for row in cursor: # result = row[2] # cursor.close() # conn.close() # return result , which may contain function names, class names, or code. Output only the next line.
def initLogConfigPath():
Using the snippet: <|code_start|> else: try: url = XulDebugServerHelper.HOST + XulDebugServerHelper.__REQUEST_FOCUS + '/' + id http = urllib3.PoolManager() STCLogger().i("focusChooseItemUrl = " + url) r = http.request('GET', url) except Exception as e: STCLogger().e(e) return return r @staticmethod def getAllSelector(): if XulDebugServerHelper.HOST == '': raise ValueError('Host is empty!') else: try: url = XulDebugServerHelper.HOST + XulDebugServerHelper.__GET_SELECTOR http = urllib3.PoolManager() STCLogger().i("getAllSelector = " + url) r = http.request('GET', url) except Exception as e: STCLogger().e(e) return return r @staticmethod def getPageSelector(pageId): return XulDebugServerHelper.getLayout(pageId, False, False, False, True) <|code_end|> , determine the next line of code. You have imports: from urllib.parse import quote from XulDebugTool.logcatapi.Logcat import STCLogger import urllib3 and context (class names, function names, or code) available: # Path: XulDebugTool/logcatapi/Logcat.py # class STCLogger(): # DEBUG = "debug" # INFO = "info" # WARNING = "warning" # ERROR = "error" # CRITICAL = "critical" # def __init__(self): # # self.loggername = "STCLogger" # #当前日志模式 # self.setLogLevel(self.INFO) # # #logging.basicConfig(level=logging.DEBUG) # self.logger = logging.getLogger(self.loggername) # # self.logger.setLevel(logging.DEBUG) # # # create a file handler # self.handler = logging.FileHandler(ConfigHelper.LOGCATPATH, "a", encoding="UTF-8") # self.handler.setLevel(logging.DEBUG) # # # create a logging format # self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # self.handler.setFormatter(self.formatter) # # # add the handlers to the logger # self.logger.addHandler(self.handler) # # def removeHandler(self): # self.logger.removeHandler(self.handler) # return # # def e(self, *args): # self.logger.error(args) # self.filterLog(self.ERROR,args) # self.removeHandler() # return # # # def w(self, *args): # self.logger.warning(args) # self.filterLog(self.WARNING, args) # self.removeHandler() # return # # def i(self, *args): # self.logger.info(args) # self.filterLog(self.INFO, args) # self.removeHandler() # return # # def d(self, *args): # self.logger.debug(args) # self.filterLog(self.DEBUG, args) # self.removeHandler() # return # # def c(self, *args): # self.logger.critical(args) # self.filterLog(self.CRITICAL, args) # self.removeHandler() # return # # # # def filterLog(self,mode, args): # preLevel = self.getCurLogLevel(mode) # if preLevel >= self.level: # ConsoleController.windowPrintInfo(self.loggername, mode, args) # else: # return # # def setLogLevel(self,level): # if level is self.DEBUG: # self.level = 0 # elif level is self.INFO: # self.level = 1 # elif level is self.WARNING: # self.level = 2 # elif level is self.ERROR: # self.level = 3 # elif level is self.CRITICAL: # self.level = 4 # # def getCurLogLevel(self,level): # if level is self.DEBUG: # return 0 # elif level is self.INFO: # return 1 # elif level is self.WARNING: # return 2 # elif level is self.ERROR: # return 3 # elif level is self.CRITICAL: # return 4 . Output only the next line.
@staticmethod
Using the snippet: <|code_start|> def index(self, row, column, parent=None, *args, **kwargs): parentItem = self.getItem(parent) childItem = parentItem.child(row) if childItem is not None: return self.createIndex(row, column, childItem) else: return QModelIndex() def parent(self, index): item = self.getItem(index) parentItem = item.parent if parentItem == self.rootItem: return QModelIndex() else: return self.createIndex(parentItem.row(), 0, parentItem) def addProperty(self, p): properties = vars(p) self.beginInsertRows(QModelIndex(), self.rowCount(self.rootItem), self.rowCount(self.rootItem)) for k, v in properties.items(): self.items.append(Property(k, p, self.rootItem)) self.endInsertRows() def clear(self): self.rootItem = Property('Root', None, self) <|code_end|> , determine the next line of code. You have imports: from PyQt5.QtCore import QAbstractItemModel, Qt, QModelIndex from PyQt5.QtGui import QColor, QPixmap, QIcon from XulDebugTool.ui.widget.model.Property import Property and context (class names, function names, or code) available: # Path: XulDebugTool/ui/widget/model/Property.py # class Property(object): # def __init__(self, key, obj=None, parent=None): # self.key = key # if obj is not None: # self.ref = weakref.ref(obj) # self.parent = parent # self.children = [] # # if parent is not None and isinstance(parent, Property): # parent.addChild(self) # # def isValid(self): # return False # # def addChild(self, child): # self.children.append(child) # # def getKey(self): # return self.key # # def getValue(self): # return getattr(self.ref(), self.key) # # def setValue(self, value): # setattr(self.ref(), self.key, value) # # def childCount(self): # return len(self.children) # # def child(self, row=None): # if row is not None: # return self.children[row] # else: # return self.children # # def parent(self): # return self.parent # # def row(self): # if self.parent is not None and isinstance(self.parent, Property): # return self.parent.child().index(self) # else: # return 0 # # def createEditor(self, parent, option, index): # raise NotImplementedError # # def setEditorData(self, editor, data): # raise NotImplementedError # # def editorData(self, editor): # raise NotImplementedError . Output only the next line.
self.items = []
Predict the next line for this snippet: <|code_start|> script.setSourceCode(f.read()) script.setInjectionPoint(QWebEngineScript.DocumentReady) script.setName(name) script.setWorldId(QWebEngineScript.MainWorld) page.scripts().insert(script) @staticmethod def findNodeById(id, xml): root = etree.fromstring(xml) # print(etree.tostring(root, pretty_print=True).decode('utf-8')) try: list = root.xpath("//*[@id=%s]" % id) except Exception as e: STCLogger().e(e) return list[0] @staticmethod def setWindowWidth(width): Utils.windowWidth = width @staticmethod def setWindowHeight(height): Utils.windowHeight = height Utils.itemHeight = int(Utils.windowHeight / 36.0) @staticmethod def getWindowWidth(): return Utils.windowWidth @staticmethod <|code_end|> with the help of current file imports: import json import sqlite3 import xmltodict from PyQt5.QtWebEngineWidgets import QWebEngineScript from lxml import etree from XulDebugTool.logcatapi.Logcat import STCLogger and context from other files: # Path: XulDebugTool/logcatapi/Logcat.py # class STCLogger(): # DEBUG = "debug" # INFO = "info" # WARNING = "warning" # ERROR = "error" # CRITICAL = "critical" # def __init__(self): # # self.loggername = "STCLogger" # #当前日志模式 # self.setLogLevel(self.INFO) # # #logging.basicConfig(level=logging.DEBUG) # self.logger = logging.getLogger(self.loggername) # # self.logger.setLevel(logging.DEBUG) # # # create a file handler # self.handler = logging.FileHandler(ConfigHelper.LOGCATPATH, "a", encoding="UTF-8") # self.handler.setLevel(logging.DEBUG) # # # create a logging format # self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # self.handler.setFormatter(self.formatter) # # # add the handlers to the logger # self.logger.addHandler(self.handler) # # def removeHandler(self): # self.logger.removeHandler(self.handler) # return # # def e(self, *args): # self.logger.error(args) # self.filterLog(self.ERROR,args) # self.removeHandler() # return # # # def w(self, *args): # self.logger.warning(args) # self.filterLog(self.WARNING, args) # self.removeHandler() # return # # def i(self, *args): # self.logger.info(args) # self.filterLog(self.INFO, args) # self.removeHandler() # return # # def d(self, *args): # self.logger.debug(args) # self.filterLog(self.DEBUG, args) # self.removeHandler() # return # # def c(self, *args): # self.logger.critical(args) # self.filterLog(self.CRITICAL, args) # self.removeHandler() # return # # # # def filterLog(self,mode, args): # preLevel = self.getCurLogLevel(mode) # if preLevel >= self.level: # ConsoleController.windowPrintInfo(self.loggername, mode, args) # else: # return # # def setLogLevel(self,level): # if level is self.DEBUG: # self.level = 0 # elif level is self.INFO: # self.level = 1 # elif level is self.WARNING: # self.level = 2 # elif level is self.ERROR: # self.level = 3 # elif level is self.CRITICAL: # self.level = 4 # # def getCurLogLevel(self,level): # if level is self.DEBUG: # return 0 # elif level is self.INFO: # return 1 # elif level is self.WARNING: # return 2 # elif level is self.ERROR: # return 3 # elif level is self.CRITICAL: # return 4 , which may contain function names, class names, or code. Output only the next line.
def getWindowHeight():
Given snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/8 11:17 # @Author : Mrlsm -- starcor class SettingWindow(BaseWindow): def __init__(self): super().__init__() self.qObject = QObject() self.initUI() self.show() def initUI(self): self.resize(1000, 650) self.initLayout() super().initWindow() def initLayout(self): self.menuList = QListWidget() self.infoList = QListWidget() self.infoLabel = QLabel() self.bottomBtn = QWidget() self.infoSplitter = QSplitter(Qt.Vertical) self.infoSplitter.addWidget(self.infoLabel) <|code_end|> , continue by predicting the next line. Consider current file imports: from PyQt5.QtCore import * from PyQt5.QtWidgets import * from XulDebugTool.ui.BaseWindow import BaseWindow and context: # Path: XulDebugTool/ui/BaseWindow.py # class BaseWindow(QMainWindow): # def __init__(self): # super().__init__() # self.title = 'XulDebugTool' # # def initWindow(self): # self.setWindowTitle(self.title) # self.setWindowIcon(IconTool.buildQIcon('icon.png')) # self.center() # # # 设置窗口居中 # def center(self): # qr = self.frameGeometry() # cp = QDesktopWidget().availableGeometry().center() # qr.moveCenter(cp) # self.move(qr.topLeft()) which might include code, classes, or functions. Output only the next line.
self.infoSplitter.addWidget(self.infoList)
Next line prediction: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- class ConsoleWindow(QMainWindow): global textEdit def __init__(self, parent=None): super(ConsoleWindow, self).__init__(parent) self.isConUrl = False # 上 self.searchButton = QLineEdit() self.searchButton.setPlaceholderText("搜索") self.searchButton.setMaximumWidth(300) self.searchButton.setMaximumHeight(32) self.searchButton.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Minimum) <|code_end|> . Use current file imports: (import sys from PyQt5.QtCore import Qt from PyQt5.QtGui import QIcon, QTextCursor from PyQt5.QtWidgets import QMainWindow, QAction, \ QSplitter, QApplication, QWidget, QHBoxLayout, QComboBox, QPushButton, \ QLineEdit, QSizePolicy, QVBoxLayout, QTextBrowser from XulDebugTool.utils.ConsoleStreamEmittor import ConsoleEmittor from XulDebugTool.utils.IconTool import IconTool) and context including class names, function names, or small code snippets from other files: # Path: XulDebugTool/utils/ConsoleStreamEmittor.py # class ConsoleEmittor(QObject): # textWritten = pyqtSignal(str) # # def write(self, text): # self.textWritten.emit(str(text)) # # Path: XulDebugTool/utils/IconTool.py # class IconTool(object): # def __init__(self): # super().__init__() # # def buildQIcon(iconName): # return QIcon(os.path.join('..', 'resources', 'images', iconName)) # # def buildQPixmap(pixmapName): # return QPixmap(os.path.join('..', 'resources', 'images', pixmapName)) . Output only the next line.
self.combo = QComboBox(self);
Predict the next line after this snippet: <|code_start|>#!/usr/bin/python # -*- coding: utf-8 -*- class ConsoleWindow(QMainWindow): global textEdit def __init__(self, parent=None): super(ConsoleWindow, self).__init__(parent) self.isConUrl = False # 上 self.searchButton = QLineEdit() self.searchButton.setPlaceholderText("搜索") self.searchButton.setMaximumWidth(300) self.searchButton.setMaximumHeight(32) self.searchButton.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Minimum) self.combo = QComboBox(self); self.combo.insertItem(0, 'Error'); self.combo.insertItem(1, 'Debug'); self.combo.insertItem(2, 'Verbose'); self.combo.insertItem(3, 'Warning'); <|code_end|> using the current file's imports: import sys from PyQt5.QtCore import Qt from PyQt5.QtGui import QIcon, QTextCursor from PyQt5.QtWidgets import QMainWindow, QAction, \ QSplitter, QApplication, QWidget, QHBoxLayout, QComboBox, QPushButton, \ QLineEdit, QSizePolicy, QVBoxLayout, QTextBrowser from XulDebugTool.utils.ConsoleStreamEmittor import ConsoleEmittor from XulDebugTool.utils.IconTool import IconTool and any relevant context from other files: # Path: XulDebugTool/utils/ConsoleStreamEmittor.py # class ConsoleEmittor(QObject): # textWritten = pyqtSignal(str) # # def write(self, text): # self.textWritten.emit(str(text)) # # Path: XulDebugTool/utils/IconTool.py # class IconTool(object): # def __init__(self): # super().__init__() # # def buildQIcon(iconName): # return QIcon(os.path.join('..', 'resources', 'images', iconName)) # # def buildQPixmap(pixmapName): # return QPixmap(os.path.join('..', 'resources', 'images', pixmapName)) . Output only the next line.
self.combo.setCurrentIndex(0)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- class ConfigurationDB(QObject): @staticmethod def saveConfiguration(key ,value): if key == None or len(str(key))<1: <|code_end|> , generate the next line using the imports in this file: import sqlite3 from PyQt5.QtCore import QObject from XulDebugTool.ui.widget.model.database.DBManager import DBManager and context (functions, classes, or occasionally code) from other files: # Path: XulDebugTool/ui/widget/model/database/DBManager.py # class DBManager(object): # TABLE_DEVICE = "device" # TABLE_LOGIN = "login" # TABLE_CONFIGURATION = 'configuration' # TABLE_FAVORITES = 'favorites' # TABLE_HISTORY = 'history_query' # # @staticmethod # def createTable(): # conn = sqlite3.connect('XulDebugTool.db') # cursor = conn.cursor() # cursor.execute('create table if not exists '+DBManager.TABLE_DEVICE+' (name varchar(50) primary key)') # cursor.execute('create table if not exists '+DBManager.TABLE_LOGIN+' (name varchar(50) primary key)') # cursor.execute('create table if not exists '+DBManager.TABLE_HISTORY+'(id integer primary key autoincrement, name nvarchar(50) null,url nvarchar(512) null,date TIMESTAMP null,favorite binary(1) default 0)') # cursor.execute('create table if not exists '+DBManager.TABLE_FAVORITES+' (id integer primary key autoincrement, name nvarchar(50) null,url nvarchar(512) null,date TIMESTAMP null,history_id integer not null,UNIQUE(history_id),FOREIGN KEY (history_id) REFERENCES history_query(id))') # cursor.execute('create table if not exists ' + DBManager.TABLE_CONFIGURATION + ' (id integer primary key autoincrement,config_key nvarchar(100) not null unique ,config_value nvarchar(512) null )') # cursor.close() # conn.close() . Output only the next line.
return
Given the following code snippet before the placeholder: <|code_start|> self.initWindowTitle() self.initAboutTitle() self.initProduction() self.initGitAddress() self.initCompanyAddress() self.initVersionNumber() def initVersionNumber(self): self.versionNumber = QtWidgets.QLabel(self) self.versionNumber.setGeometry(QtCore.QRect(50, 230, 300, 21)) self.versionNumber.setObjectName("label_4") self.versionNumber.setText("版本号:Release version v1.2") #版本号应该写到版本配置文件里面去,从哪里读取 def initCompanyAddress(self): self.company = QtWidgets.QPushButton(self) self.company.setGeometry(50, 195, 300, 23) self.company.setStyleSheet("QPushButton{background: transparent; color: blue}") self.company.setObjectName("pushButton") self.company.clicked.connect(self.openCompanyUrl) self.company.setText("https://www.starcor.com/ch/index.html") def initGitAddress(self): self.gitAddress = QtWidgets.QPushButton(self) self.gitAddress.setGeometry(QtCore.QRect(50, 160, 300, 50)) self.gitAddress.setStyleSheet("QPushButton{background: transparent; color: blue; text-align: left}") self.gitAddress.setLayoutDirection(Qt.LayoutDirectionAuto) self.gitAddress.setObjectName("label_3") self.gitAddress.clicked.connect(self.openGitUrl) self.gitAddress.setText("https://github.com/starcor-company/XulDebugTool") <|code_end|> , predict the next line using imports from the current file: import webbrowser from PyQt5 import QtWidgets, QtCore from PyQt5.QtCore import Qt from PyQt5.QtGui import QFont from PyQt5.QtWidgets import QLabel from XulDebugTool.ui.BaseWindow import BaseWindow and context including class names, function names, and sometimes code from other files: # Path: XulDebugTool/ui/BaseWindow.py # class BaseWindow(QMainWindow): # def __init__(self): # super().__init__() # self.title = 'XulDebugTool' # # def initWindow(self): # self.setWindowTitle(self.title) # self.setWindowIcon(IconTool.buildQIcon('icon.png')) # self.center() # # # 设置窗口居中 # def center(self): # qr = self.frameGeometry() # cp = QDesktopWidget().availableGeometry().center() # qr.moveCenter(cp) # self.move(qr.topLeft()) . Output only the next line.
def initProduction(self):