Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Here is a snippet: <|code_start|> deadline=120.0, ), default_timeout=120.0, client_info=client_info, ), self.bind_device_to_gateway: gapic_v1.method.wrap_method( self.bind_device_to_gateway, default_timeout=120.0, client_info=client_info, ), self.unbind_device_from_gateway: gapic_v1.method.wrap_method( self.unbind_device_from_gateway, default_timeout=120.0, client_info=client_info, ), } def close(self): """Closes resources associated with the transport. .. warning:: Only call this method if the transport is NOT shared with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property def create_device_registry( self, ) -> Callable[ <|code_end|> . Write the next line using the current file imports: import abc import pkg_resources import google.auth # type: ignore import google.api_core from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.iot_v1.types import device_manager from google.cloud.iot_v1.types import resources from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore and context from other files: # Path: google/cloud/iot_v1/types/device_manager.py # class CreateDeviceRegistryRequest(proto.Message): # class GetDeviceRegistryRequest(proto.Message): # class DeleteDeviceRegistryRequest(proto.Message): # class UpdateDeviceRegistryRequest(proto.Message): # class ListDeviceRegistriesRequest(proto.Message): # class ListDeviceRegistriesResponse(proto.Message): # class CreateDeviceRequest(proto.Message): # class GetDeviceRequest(proto.Message): # class UpdateDeviceRequest(proto.Message): # class DeleteDeviceRequest(proto.Message): # class ListDevicesRequest(proto.Message): # class GatewayListOptions(proto.Message): # class ListDevicesResponse(proto.Message): # class ModifyCloudToDeviceConfigRequest(proto.Message): # class ListDeviceConfigVersionsRequest(proto.Message): # class ListDeviceConfigVersionsResponse(proto.Message): # class ListDeviceStatesRequest(proto.Message): # class ListDeviceStatesResponse(proto.Message): # class SendCommandToDeviceRequest(proto.Message): # class SendCommandToDeviceResponse(proto.Message): # class BindDeviceToGatewayRequest(proto.Message): # class BindDeviceToGatewayResponse(proto.Message): # class UnbindDeviceFromGatewayRequest(proto.Message): # class UnbindDeviceFromGatewayResponse(proto.Message): # def raw_page(self): # def raw_page(self): # # Path: google/cloud/iot_v1/types/resources.py # class MqttState(proto.Enum): # class HttpState(proto.Enum): # class LogLevel(proto.Enum): # class GatewayType(proto.Enum): # class GatewayAuthMethod(proto.Enum): # class PublicKeyCertificateFormat(proto.Enum): # class PublicKeyFormat(proto.Enum): # class Device(proto.Message): # class GatewayConfig(proto.Message): # class DeviceRegistry(proto.Message): # class MqttConfig(proto.Message): # class HttpConfig(proto.Message): # class EventNotificationConfig(proto.Message): # class StateNotificationConfig(proto.Message): # class RegistryCredential(proto.Message): # class X509CertificateDetails(proto.Message): # class PublicKeyCertificate(proto.Message): # class DeviceCredential(proto.Message): # class PublicKeyCredential(proto.Message): # class DeviceConfig(proto.Message): # class DeviceState(proto.Message): # MQTT_STATE_UNSPECIFIED = 0 # MQTT_ENABLED = 1 # MQTT_DISABLED = 2 # HTTP_STATE_UNSPECIFIED = 0 # HTTP_ENABLED = 1 # HTTP_DISABLED = 2 # LOG_LEVEL_UNSPECIFIED = 0 # NONE = 10 # ERROR = 20 # INFO = 30 # DEBUG = 40 # GATEWAY_TYPE_UNSPECIFIED = 0 # GATEWAY = 1 # NON_GATEWAY = 2 # GATEWAY_AUTH_METHOD_UNSPECIFIED = 0 # ASSOCIATION_ONLY = 1 # DEVICE_AUTH_TOKEN_ONLY = 2 # ASSOCIATION_AND_DEVICE_AUTH_TOKEN = 3 # UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT = 0 # X509_CERTIFICATE_PEM = 1 # UNSPECIFIED_PUBLIC_KEY_FORMAT = 0 # RSA_PEM = 3 # RSA_X509_PEM = 1 # ES256_PEM = 2 # ES256_X509_PEM = 4 , which may include functions, classes, or code. Output only the next line.
[device_manager.CreateDeviceRegistryRequest],
Given the following code snippet before the placeholder: <|code_start|> ), default_timeout=120.0, client_info=client_info, ), self.bind_device_to_gateway: gapic_v1.method.wrap_method( self.bind_device_to_gateway, default_timeout=120.0, client_info=client_info, ), self.unbind_device_from_gateway: gapic_v1.method.wrap_method( self.unbind_device_from_gateway, default_timeout=120.0, client_info=client_info, ), } def close(self): """Closes resources associated with the transport. .. warning:: Only call this method if the transport is NOT shared with other clients - this may cause errors in other clients! """ raise NotImplementedError() @property def create_device_registry( self, ) -> Callable[ [device_manager.CreateDeviceRegistryRequest], <|code_end|> , predict the next line using imports from the current file: import abc import pkg_resources import google.auth # type: ignore import google.api_core from typing import Awaitable, Callable, Dict, Optional, Sequence, Union from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.iot_v1.types import device_manager from google.cloud.iot_v1.types import resources from google.iam.v1 import iam_policy_pb2 # type: ignore from google.iam.v1 import policy_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore and context including class names, function names, and sometimes code from other files: # Path: google/cloud/iot_v1/types/device_manager.py # class CreateDeviceRegistryRequest(proto.Message): # class GetDeviceRegistryRequest(proto.Message): # class DeleteDeviceRegistryRequest(proto.Message): # class UpdateDeviceRegistryRequest(proto.Message): # class ListDeviceRegistriesRequest(proto.Message): # class ListDeviceRegistriesResponse(proto.Message): # class CreateDeviceRequest(proto.Message): # class GetDeviceRequest(proto.Message): # class UpdateDeviceRequest(proto.Message): # class DeleteDeviceRequest(proto.Message): # class ListDevicesRequest(proto.Message): # class GatewayListOptions(proto.Message): # class ListDevicesResponse(proto.Message): # class ModifyCloudToDeviceConfigRequest(proto.Message): # class ListDeviceConfigVersionsRequest(proto.Message): # class ListDeviceConfigVersionsResponse(proto.Message): # class ListDeviceStatesRequest(proto.Message): # class ListDeviceStatesResponse(proto.Message): # class SendCommandToDeviceRequest(proto.Message): # class SendCommandToDeviceResponse(proto.Message): # class BindDeviceToGatewayRequest(proto.Message): # class BindDeviceToGatewayResponse(proto.Message): # class UnbindDeviceFromGatewayRequest(proto.Message): # class UnbindDeviceFromGatewayResponse(proto.Message): # def raw_page(self): # def raw_page(self): # # Path: google/cloud/iot_v1/types/resources.py # class MqttState(proto.Enum): # class HttpState(proto.Enum): # class LogLevel(proto.Enum): # class GatewayType(proto.Enum): # class GatewayAuthMethod(proto.Enum): # class PublicKeyCertificateFormat(proto.Enum): # class PublicKeyFormat(proto.Enum): # class Device(proto.Message): # class GatewayConfig(proto.Message): # class DeviceRegistry(proto.Message): # class MqttConfig(proto.Message): # class HttpConfig(proto.Message): # class EventNotificationConfig(proto.Message): # class StateNotificationConfig(proto.Message): # class RegistryCredential(proto.Message): # class X509CertificateDetails(proto.Message): # class PublicKeyCertificate(proto.Message): # class DeviceCredential(proto.Message): # class PublicKeyCredential(proto.Message): # class DeviceConfig(proto.Message): # class DeviceState(proto.Message): # MQTT_STATE_UNSPECIFIED = 0 # MQTT_ENABLED = 1 # MQTT_DISABLED = 2 # HTTP_STATE_UNSPECIFIED = 0 # HTTP_ENABLED = 1 # HTTP_DISABLED = 2 # LOG_LEVEL_UNSPECIFIED = 0 # NONE = 10 # ERROR = 20 # INFO = 30 # DEBUG = 40 # GATEWAY_TYPE_UNSPECIFIED = 0 # GATEWAY = 1 # NON_GATEWAY = 2 # GATEWAY_AUTH_METHOD_UNSPECIFIED = 0 # ASSOCIATION_ONLY = 1 # DEVICE_AUTH_TOKEN_ONLY = 2 # ASSOCIATION_AND_DEVICE_AUTH_TOKEN = 3 # UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT = 0 # X509_CERTIFICATE_PEM = 1 # UNSPECIFIED_PUBLIC_KEY_FORMAT = 0 # RSA_PEM = 3 # RSA_X509_PEM = 1 # ES256_PEM = 2 # ES256_X509_PEM = 4 . Output only the next line.
Union[resources.DeviceRegistry, Awaitable[resources.DeviceRegistry]],
Here is a snippet: <|code_start|> "ListDeviceConfigVersionsRequest", "ListDeviceConfigVersionsResponse", "ListDeviceStatesRequest", "ListDeviceStatesResponse", "SendCommandToDeviceRequest", "SendCommandToDeviceResponse", "BindDeviceToGatewayRequest", "BindDeviceToGatewayResponse", "UnbindDeviceFromGatewayRequest", "UnbindDeviceFromGatewayResponse", }, ) class CreateDeviceRegistryRequest(proto.Message): r"""Request for ``CreateDeviceRegistry``. Attributes: parent (str): Required. The project and cloud region where this device registry must be created. For example, ``projects/example-project/locations/us-central1``. device_registry (google.cloud.iot_v1.types.DeviceRegistry): Required. The device registry. The field ``name`` must be empty. The server will generate that field from the device registry ``id`` provided and the ``parent`` field. """ parent = proto.Field(proto.STRING, number=1,) device_registry = proto.Field( <|code_end|> . Write the next line using the current file imports: import proto # type: ignore from google.cloud.iot_v1.types import resources from google.protobuf import field_mask_pb2 # type: ignore and context from other files: # Path: google/cloud/iot_v1/types/resources.py # class MqttState(proto.Enum): # class HttpState(proto.Enum): # class LogLevel(proto.Enum): # class GatewayType(proto.Enum): # class GatewayAuthMethod(proto.Enum): # class PublicKeyCertificateFormat(proto.Enum): # class PublicKeyFormat(proto.Enum): # class Device(proto.Message): # class GatewayConfig(proto.Message): # class DeviceRegistry(proto.Message): # class MqttConfig(proto.Message): # class HttpConfig(proto.Message): # class EventNotificationConfig(proto.Message): # class StateNotificationConfig(proto.Message): # class RegistryCredential(proto.Message): # class X509CertificateDetails(proto.Message): # class PublicKeyCertificate(proto.Message): # class DeviceCredential(proto.Message): # class PublicKeyCredential(proto.Message): # class DeviceConfig(proto.Message): # class DeviceState(proto.Message): # MQTT_STATE_UNSPECIFIED = 0 # MQTT_ENABLED = 1 # MQTT_DISABLED = 2 # HTTP_STATE_UNSPECIFIED = 0 # HTTP_ENABLED = 1 # HTTP_DISABLED = 2 # LOG_LEVEL_UNSPECIFIED = 0 # NONE = 10 # ERROR = 20 # INFO = 30 # DEBUG = 40 # GATEWAY_TYPE_UNSPECIFIED = 0 # GATEWAY = 1 # NON_GATEWAY = 2 # GATEWAY_AUTH_METHOD_UNSPECIFIED = 0 # ASSOCIATION_ONLY = 1 # DEVICE_AUTH_TOKEN_ONLY = 2 # ASSOCIATION_AND_DEVICE_AUTH_TOKEN = 3 # UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT = 0 # X509_CERTIFICATE_PEM = 1 # UNSPECIFIED_PUBLIC_KEY_FORMAT = 0 # RSA_PEM = 3 # RSA_X509_PEM = 1 # ES256_PEM = 2 # ES256_X509_PEM = 4 , which may include functions, classes, or code. Output only the next line.
proto.MESSAGE, number=2, message=resources.DeviceRegistry,
Next line prediction: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # class ListDeviceRegistriesPager: """A pager for iterating through ``list_device_registries`` requests. This class thinly wraps an initial :class:`google.cloud.iot_v1.types.ListDeviceRegistriesResponse` object, and provides an ``__iter__`` method to iterate through its ``device_registries`` field. If there are more pages, the ``__iter__`` method will make additional ``ListDeviceRegistries`` requests and continue to iterate through the ``device_registries`` field on the corresponding responses. All the usual :class:`google.cloud.iot_v1.types.ListDeviceRegistriesResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__( self, <|code_end|> . Use current file imports: (from typing import ( Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, ) from google.cloud.iot_v1.types import device_manager from google.cloud.iot_v1.types import resources) and context including class names, function names, or small code snippets from other files: # Path: google/cloud/iot_v1/types/device_manager.py # class CreateDeviceRegistryRequest(proto.Message): # class GetDeviceRegistryRequest(proto.Message): # class DeleteDeviceRegistryRequest(proto.Message): # class UpdateDeviceRegistryRequest(proto.Message): # class ListDeviceRegistriesRequest(proto.Message): # class ListDeviceRegistriesResponse(proto.Message): # class CreateDeviceRequest(proto.Message): # class GetDeviceRequest(proto.Message): # class UpdateDeviceRequest(proto.Message): # class DeleteDeviceRequest(proto.Message): # class ListDevicesRequest(proto.Message): # class GatewayListOptions(proto.Message): # class ListDevicesResponse(proto.Message): # class ModifyCloudToDeviceConfigRequest(proto.Message): # class ListDeviceConfigVersionsRequest(proto.Message): # class ListDeviceConfigVersionsResponse(proto.Message): # class ListDeviceStatesRequest(proto.Message): # class ListDeviceStatesResponse(proto.Message): # class SendCommandToDeviceRequest(proto.Message): # class SendCommandToDeviceResponse(proto.Message): # class BindDeviceToGatewayRequest(proto.Message): # class BindDeviceToGatewayResponse(proto.Message): # class UnbindDeviceFromGatewayRequest(proto.Message): # class UnbindDeviceFromGatewayResponse(proto.Message): # def raw_page(self): # def raw_page(self): # # Path: google/cloud/iot_v1/types/resources.py # class MqttState(proto.Enum): # class HttpState(proto.Enum): # class LogLevel(proto.Enum): # class GatewayType(proto.Enum): # class GatewayAuthMethod(proto.Enum): # class PublicKeyCertificateFormat(proto.Enum): # class PublicKeyFormat(proto.Enum): # class Device(proto.Message): # class GatewayConfig(proto.Message): # class DeviceRegistry(proto.Message): # class MqttConfig(proto.Message): # class HttpConfig(proto.Message): # class EventNotificationConfig(proto.Message): # class StateNotificationConfig(proto.Message): # class RegistryCredential(proto.Message): # class X509CertificateDetails(proto.Message): # class PublicKeyCertificate(proto.Message): # class DeviceCredential(proto.Message): # class PublicKeyCredential(proto.Message): # class DeviceConfig(proto.Message): # class DeviceState(proto.Message): # MQTT_STATE_UNSPECIFIED = 0 # MQTT_ENABLED = 1 # MQTT_DISABLED = 2 # HTTP_STATE_UNSPECIFIED = 0 # HTTP_ENABLED = 1 # HTTP_DISABLED = 2 # LOG_LEVEL_UNSPECIFIED = 0 # NONE = 10 # ERROR = 20 # INFO = 30 # DEBUG = 40 # GATEWAY_TYPE_UNSPECIFIED = 0 # GATEWAY = 1 # NON_GATEWAY = 2 # GATEWAY_AUTH_METHOD_UNSPECIFIED = 0 # ASSOCIATION_ONLY = 1 # DEVICE_AUTH_TOKEN_ONLY = 2 # ASSOCIATION_AND_DEVICE_AUTH_TOKEN = 3 # UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT = 0 # X509_CERTIFICATE_PEM = 1 # UNSPECIFIED_PUBLIC_KEY_FORMAT = 0 # RSA_PEM = 3 # RSA_X509_PEM = 1 # ES256_PEM = 2 # ES256_X509_PEM = 4 . Output only the next line.
method: Callable[..., device_manager.ListDeviceRegistriesResponse],
Using the snippet: <|code_start|> metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.iot_v1.types.ListDeviceRegistriesRequest): The initial request object. response (google.cloud.iot_v1.types.ListDeviceRegistriesResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = device_manager.ListDeviceRegistriesRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property def pages(self) -> Iterator[device_manager.ListDeviceRegistriesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = self._method(self._request, metadata=self._metadata) yield self._response <|code_end|> , determine the next line of code. You have imports: from typing import ( Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, ) from google.cloud.iot_v1.types import device_manager from google.cloud.iot_v1.types import resources and context (class names, function names, or code) available: # Path: google/cloud/iot_v1/types/device_manager.py # class CreateDeviceRegistryRequest(proto.Message): # class GetDeviceRegistryRequest(proto.Message): # class DeleteDeviceRegistryRequest(proto.Message): # class UpdateDeviceRegistryRequest(proto.Message): # class ListDeviceRegistriesRequest(proto.Message): # class ListDeviceRegistriesResponse(proto.Message): # class CreateDeviceRequest(proto.Message): # class GetDeviceRequest(proto.Message): # class UpdateDeviceRequest(proto.Message): # class DeleteDeviceRequest(proto.Message): # class ListDevicesRequest(proto.Message): # class GatewayListOptions(proto.Message): # class ListDevicesResponse(proto.Message): # class ModifyCloudToDeviceConfigRequest(proto.Message): # class ListDeviceConfigVersionsRequest(proto.Message): # class ListDeviceConfigVersionsResponse(proto.Message): # class ListDeviceStatesRequest(proto.Message): # class ListDeviceStatesResponse(proto.Message): # class SendCommandToDeviceRequest(proto.Message): # class SendCommandToDeviceResponse(proto.Message): # class BindDeviceToGatewayRequest(proto.Message): # class BindDeviceToGatewayResponse(proto.Message): # class UnbindDeviceFromGatewayRequest(proto.Message): # class UnbindDeviceFromGatewayResponse(proto.Message): # def raw_page(self): # def raw_page(self): # # Path: google/cloud/iot_v1/types/resources.py # class MqttState(proto.Enum): # class HttpState(proto.Enum): # class LogLevel(proto.Enum): # class GatewayType(proto.Enum): # class GatewayAuthMethod(proto.Enum): # class PublicKeyCertificateFormat(proto.Enum): # class PublicKeyFormat(proto.Enum): # class Device(proto.Message): # class GatewayConfig(proto.Message): # class DeviceRegistry(proto.Message): # class MqttConfig(proto.Message): # class HttpConfig(proto.Message): # class EventNotificationConfig(proto.Message): # class StateNotificationConfig(proto.Message): # class RegistryCredential(proto.Message): # class X509CertificateDetails(proto.Message): # class PublicKeyCertificate(proto.Message): # class DeviceCredential(proto.Message): # class PublicKeyCredential(proto.Message): # class DeviceConfig(proto.Message): # class DeviceState(proto.Message): # MQTT_STATE_UNSPECIFIED = 0 # MQTT_ENABLED = 1 # MQTT_DISABLED = 2 # HTTP_STATE_UNSPECIFIED = 0 # HTTP_ENABLED = 1 # HTTP_DISABLED = 2 # LOG_LEVEL_UNSPECIFIED = 0 # NONE = 10 # ERROR = 20 # INFO = 30 # DEBUG = 40 # GATEWAY_TYPE_UNSPECIFIED = 0 # GATEWAY = 1 # NON_GATEWAY = 2 # GATEWAY_AUTH_METHOD_UNSPECIFIED = 0 # ASSOCIATION_ONLY = 1 # DEVICE_AUTH_TOKEN_ONLY = 2 # ASSOCIATION_AND_DEVICE_AUTH_TOKEN = 3 # UNSPECIFIED_PUBLIC_KEY_CERTIFICATE_FORMAT = 0 # X509_CERTIFICATE_PEM = 1 # UNSPECIFIED_PUBLIC_KEY_FORMAT = 0 # RSA_PEM = 3 # RSA_X509_PEM = 1 # ES256_PEM = 2 # ES256_X509_PEM = 4 . Output only the next line.
def __iter__(self) -> Iterator[resources.DeviceRegistry]:
Predict the next line after this snippet: <|code_start|> ``record.myfield = val``). This is opposite to ``__get__()`` which needs to handle both class and instance access. """ raise AttributeError() def __set_name__(self, owner, name): """Inject the class attribute name into the field. This ensures that a field has access to the attribute name used on the class. In the following example, the attribute name ``schema`` would be set in the ``ConstantField`` object instance. .. code-block:: python class MyRecord(Record, SystemFieldsMixin): schema = ConstantField(...) """ self._attr_name = name def post_init(self, record, data, model=None, field_data=None): """Core implementation of post_init to support argument loading.""" if field_data is not None: self.__set__(record, field_data) def get_dictkey(self, instance): """Helper to use a lookup key to get a nested object. Assume the key have been set in ``self.key`` """ try: <|code_end|> using the current file's imports: import inspect import warnings from ..dictutils import dict_lookup, parse_lookup_key from ..extensions import ExtensionMixin, RecordExtension, RecordMeta and any relevant context from other files: # Path: invenio_records/dictutils.py # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # def parse_lookup_key(lookup_key): # """Parse a lookup key.""" # if not lookup_key: # raise KeyError("No lookup key specified") # # # Parse the list of keys # if isinstance(lookup_key, str): # keys = lookup_key.split('.') # elif isinstance(lookup_key, list): # keys = lookup_key # else: # raise TypeError('lookup must be string or list') # # return keys # # Path: invenio_records/extensions.py # class ExtensionMixin: # """Defines the methods needed by an extension.""" # # def pre_init(self, record, data, model=None, **kwargs): # """Called when a new record instance is initialized. # # Called when a new record is instantiated (i.e. during all # ``Record({...})``). This means it's also called when e.g. a record # is created via ``Record.create()``. # # :param data: The dict passed to the record's constructor. # :param model: The model class used for initialization. # """ # # def post_init(self, record, data, model=None, **kwargs): # """Called after a record is initialized.""" # # def pre_dump(self, record, data, dumper=None): # """Called before a record is dumped.""" # # def post_dump(self, record, data, dumper=None): # """Called after a record is dumped.""" # # def pre_load(self, data, loader=None): # """Called before a record is loaded.""" # # def post_load(self, record, data, loader=None): # """Called after a record is loaded.""" # # def pre_create(self, record): # """Called before a record is created.""" # # def post_create(self, record): # """Called after a record is created.""" # # def pre_commit(self, record): # """Called before a record is committed.""" # # def pre_delete(self, record, force=False): # """Called before a record is deleted.""" # # def post_delete(self, record, force=False): # """Called after a record is deleted.""" # # def pre_revert(self, record, revision): # """Called before a record is reverted.""" # # def post_revert(self, new_record, revision): # """Called after a record is reverted.""" # # class RecordExtension(ExtensionMixin): # """Base class for a record extensions.""" # # class RecordMeta(type): # """Metaclass responsible for initializing the extension registry.""" # # def __new__(mcs, name, bases, attrs): # """Create a new record class.""" # # Initialise an "_extensions" attribute on each class, to ensure each # # class have a separate extensions registry. # if '_extensions' not in attrs: # attrs['_extensions'] = [] # # # Construct the class. # return super().__new__(mcs, name, bases, attrs) . Output only the next line.
return dict_lookup(instance, self.key)
Continue the code snippet: <|code_start|> """Inject the class attribute name into the field. This ensures that a field has access to the attribute name used on the class. In the following example, the attribute name ``schema`` would be set in the ``ConstantField`` object instance. .. code-block:: python class MyRecord(Record, SystemFieldsMixin): schema = ConstantField(...) """ self._attr_name = name def post_init(self, record, data, model=None, field_data=None): """Core implementation of post_init to support argument loading.""" if field_data is not None: self.__set__(record, field_data) def get_dictkey(self, instance): """Helper to use a lookup key to get a nested object. Assume the key have been set in ``self.key`` """ try: return dict_lookup(instance, self.key) except KeyError: return None def set_dictkey(self, instance, value, create_if_missing=False): """Helper to set value using a lookup key on a nested object.""" <|code_end|> . Use current file imports: import inspect import warnings from ..dictutils import dict_lookup, parse_lookup_key from ..extensions import ExtensionMixin, RecordExtension, RecordMeta and context (classes, functions, or code) from other files: # Path: invenio_records/dictutils.py # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # def parse_lookup_key(lookup_key): # """Parse a lookup key.""" # if not lookup_key: # raise KeyError("No lookup key specified") # # # Parse the list of keys # if isinstance(lookup_key, str): # keys = lookup_key.split('.') # elif isinstance(lookup_key, list): # keys = lookup_key # else: # raise TypeError('lookup must be string or list') # # return keys # # Path: invenio_records/extensions.py # class ExtensionMixin: # """Defines the methods needed by an extension.""" # # def pre_init(self, record, data, model=None, **kwargs): # """Called when a new record instance is initialized. # # Called when a new record is instantiated (i.e. during all # ``Record({...})``). This means it's also called when e.g. a record # is created via ``Record.create()``. # # :param data: The dict passed to the record's constructor. # :param model: The model class used for initialization. # """ # # def post_init(self, record, data, model=None, **kwargs): # """Called after a record is initialized.""" # # def pre_dump(self, record, data, dumper=None): # """Called before a record is dumped.""" # # def post_dump(self, record, data, dumper=None): # """Called after a record is dumped.""" # # def pre_load(self, data, loader=None): # """Called before a record is loaded.""" # # def post_load(self, record, data, loader=None): # """Called after a record is loaded.""" # # def pre_create(self, record): # """Called before a record is created.""" # # def post_create(self, record): # """Called after a record is created.""" # # def pre_commit(self, record): # """Called before a record is committed.""" # # def pre_delete(self, record, force=False): # """Called before a record is deleted.""" # # def post_delete(self, record, force=False): # """Called after a record is deleted.""" # # def pre_revert(self, record, revision): # """Called before a record is reverted.""" # # def post_revert(self, new_record, revision): # """Called after a record is reverted.""" # # class RecordExtension(ExtensionMixin): # """Base class for a record extensions.""" # # class RecordMeta(type): # """Metaclass responsible for initializing the extension registry.""" # # def __new__(mcs, name, bases, attrs): # """Create a new record class.""" # # Initialise an "_extensions" attribute on each class, to ensure each # # class have a separate extensions registry. # if '_extensions' not in attrs: # attrs['_extensions'] = [] # # # Construct the class. # return super().__new__(mcs, name, bases, attrs) . Output only the next line.
keys = parse_lookup_key(self.key)
Continue the code snippet: <|code_start|> return fields class SystemFieldContext: """Base class for a system field context. A system field context is created once you access a field's attribute on a class. As the system field may be defined on a super class, this context allows us to know from which class the field was accessed. Normally you should subclass this class, and implement methods the methods on it that requires you to know the record class. """ def __init__(self, field, record_cls): """Initialise the field context.""" self._field = field self._record_cls = record_cls @property def field(self): """Access the field to prevent it from being overwritten.""" return self._field @property def record_cls(self): """Record class to prevent it from being overwritten.""" return self._record_cls <|code_end|> . Use current file imports: import inspect import warnings from ..dictutils import dict_lookup, parse_lookup_key from ..extensions import ExtensionMixin, RecordExtension, RecordMeta and context (classes, functions, or code) from other files: # Path: invenio_records/dictutils.py # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # def parse_lookup_key(lookup_key): # """Parse a lookup key.""" # if not lookup_key: # raise KeyError("No lookup key specified") # # # Parse the list of keys # if isinstance(lookup_key, str): # keys = lookup_key.split('.') # elif isinstance(lookup_key, list): # keys = lookup_key # else: # raise TypeError('lookup must be string or list') # # return keys # # Path: invenio_records/extensions.py # class ExtensionMixin: # """Defines the methods needed by an extension.""" # # def pre_init(self, record, data, model=None, **kwargs): # """Called when a new record instance is initialized. # # Called when a new record is instantiated (i.e. during all # ``Record({...})``). This means it's also called when e.g. a record # is created via ``Record.create()``. # # :param data: The dict passed to the record's constructor. # :param model: The model class used for initialization. # """ # # def post_init(self, record, data, model=None, **kwargs): # """Called after a record is initialized.""" # # def pre_dump(self, record, data, dumper=None): # """Called before a record is dumped.""" # # def post_dump(self, record, data, dumper=None): # """Called after a record is dumped.""" # # def pre_load(self, data, loader=None): # """Called before a record is loaded.""" # # def post_load(self, record, data, loader=None): # """Called after a record is loaded.""" # # def pre_create(self, record): # """Called before a record is created.""" # # def post_create(self, record): # """Called after a record is created.""" # # def pre_commit(self, record): # """Called before a record is committed.""" # # def pre_delete(self, record, force=False): # """Called before a record is deleted.""" # # def post_delete(self, record, force=False): # """Called after a record is deleted.""" # # def pre_revert(self, record, revision): # """Called before a record is reverted.""" # # def post_revert(self, new_record, revision): # """Called after a record is reverted.""" # # class RecordExtension(ExtensionMixin): # """Base class for a record extensions.""" # # class RecordMeta(type): # """Metaclass responsible for initializing the extension registry.""" # # def __new__(mcs, name, bases, attrs): # """Create a new record class.""" # # Initialise an "_extensions" attribute on each class, to ensure each # # class have a separate extensions registry. # if '_extensions' not in attrs: # attrs['_extensions'] = [] # # # Construct the class. # return super().__new__(mcs, name, bases, attrs) . Output only the next line.
class SystemField(ExtensionMixin):
Predict the next line after this snippet: <|code_start|> else: if not isinstance(parent[k], dict): raise KeyError( "Expected a dict at subkey '{}'. " "Found '{}'.".format( k, parent[k].__class__.__name__) ) parent = parent[k] if not isinstance(parent, dict): raise KeyError( "Expected a dict at subkey '{}'. Found '{}'.".format( keys[-2], parent.__class__.__name__) ) parent[keys[-1]] = value def _set_cache(self, instance, obj): """Set an object on the instance's cache.""" if not hasattr(instance, '_obj_cache'): instance._obj_cache = {} instance._obj_cache[self.attr_name] = obj def _get_cache(self, instance): """Get the object from the instance's cache.""" return getattr(instance, '_obj_cache', {}).get(self.attr_name) <|code_end|> using the current file's imports: import inspect import warnings from ..dictutils import dict_lookup, parse_lookup_key from ..extensions import ExtensionMixin, RecordExtension, RecordMeta and any relevant context from other files: # Path: invenio_records/dictutils.py # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # def parse_lookup_key(lookup_key): # """Parse a lookup key.""" # if not lookup_key: # raise KeyError("No lookup key specified") # # # Parse the list of keys # if isinstance(lookup_key, str): # keys = lookup_key.split('.') # elif isinstance(lookup_key, list): # keys = lookup_key # else: # raise TypeError('lookup must be string or list') # # return keys # # Path: invenio_records/extensions.py # class ExtensionMixin: # """Defines the methods needed by an extension.""" # # def pre_init(self, record, data, model=None, **kwargs): # """Called when a new record instance is initialized. # # Called when a new record is instantiated (i.e. during all # ``Record({...})``). This means it's also called when e.g. a record # is created via ``Record.create()``. # # :param data: The dict passed to the record's constructor. # :param model: The model class used for initialization. # """ # # def post_init(self, record, data, model=None, **kwargs): # """Called after a record is initialized.""" # # def pre_dump(self, record, data, dumper=None): # """Called before a record is dumped.""" # # def post_dump(self, record, data, dumper=None): # """Called after a record is dumped.""" # # def pre_load(self, data, loader=None): # """Called before a record is loaded.""" # # def post_load(self, record, data, loader=None): # """Called after a record is loaded.""" # # def pre_create(self, record): # """Called before a record is created.""" # # def post_create(self, record): # """Called after a record is created.""" # # def pre_commit(self, record): # """Called before a record is committed.""" # # def pre_delete(self, record, force=False): # """Called before a record is deleted.""" # # def post_delete(self, record, force=False): # """Called after a record is deleted.""" # # def pre_revert(self, record, revision): # """Called before a record is reverted.""" # # def post_revert(self, new_record, revision): # """Called after a record is reverted.""" # # class RecordExtension(ExtensionMixin): # """Base class for a record extensions.""" # # class RecordMeta(type): # """Metaclass responsible for initializing the extension registry.""" # # def __new__(mcs, name, bases, attrs): # """Create a new record class.""" # # Initialise an "_extensions" attribute on each class, to ensure each # # class have a separate extensions registry. # if '_extensions' not in attrs: # attrs['_extensions'] = [] # # # Construct the class. # return super().__new__(mcs, name, bases, attrs) . Output only the next line.
class SystemFieldsExt(RecordExtension):
Continue the code snippet: <|code_start|> def pre_create(self, *args, **kwargs): """Called after a record is created.""" self._run('pre_create', *args, **kwargs) def post_create(self, *args, **kwargs): """Called after a record is created.""" self._run('post_create', *args, **kwargs) def pre_commit(self, *args, **kwargs): """Called before a record is committed.""" self._run('pre_commit', *args, **kwargs) def pre_delete(self, *args, **kwargs): """Called before a record is deleted.""" self._run('pre_delete', *args, **kwargs) def post_delete(self, *args, **kwargs): """Called after a record is deleted.""" self._run('post_delete', *args, **kwargs) def pre_revert(self, *args, **kwargs): """Called before a record is reverted.""" self._run('pre_revert', *args, **kwargs) def post_revert(self, *args, **kwargs): """Called after a record is reverted.""" self._run('post_revert', *args, **kwargs) <|code_end|> . Use current file imports: import inspect import warnings from ..dictutils import dict_lookup, parse_lookup_key from ..extensions import ExtensionMixin, RecordExtension, RecordMeta and context (classes, functions, or code) from other files: # Path: invenio_records/dictutils.py # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # def parse_lookup_key(lookup_key): # """Parse a lookup key.""" # if not lookup_key: # raise KeyError("No lookup key specified") # # # Parse the list of keys # if isinstance(lookup_key, str): # keys = lookup_key.split('.') # elif isinstance(lookup_key, list): # keys = lookup_key # else: # raise TypeError('lookup must be string or list') # # return keys # # Path: invenio_records/extensions.py # class ExtensionMixin: # """Defines the methods needed by an extension.""" # # def pre_init(self, record, data, model=None, **kwargs): # """Called when a new record instance is initialized. # # Called when a new record is instantiated (i.e. during all # ``Record({...})``). This means it's also called when e.g. a record # is created via ``Record.create()``. # # :param data: The dict passed to the record's constructor. # :param model: The model class used for initialization. # """ # # def post_init(self, record, data, model=None, **kwargs): # """Called after a record is initialized.""" # # def pre_dump(self, record, data, dumper=None): # """Called before a record is dumped.""" # # def post_dump(self, record, data, dumper=None): # """Called after a record is dumped.""" # # def pre_load(self, data, loader=None): # """Called before a record is loaded.""" # # def post_load(self, record, data, loader=None): # """Called after a record is loaded.""" # # def pre_create(self, record): # """Called before a record is created.""" # # def post_create(self, record): # """Called after a record is created.""" # # def pre_commit(self, record): # """Called before a record is committed.""" # # def pre_delete(self, record, force=False): # """Called before a record is deleted.""" # # def post_delete(self, record, force=False): # """Called after a record is deleted.""" # # def pre_revert(self, record, revision): # """Called before a record is reverted.""" # # def post_revert(self, new_record, revision): # """Called after a record is reverted.""" # # class RecordExtension(ExtensionMixin): # """Base class for a record extensions.""" # # class RecordMeta(type): # """Metaclass responsible for initializing the extension registry.""" # # def __new__(mcs, name, bases, attrs): # """Create a new record class.""" # # Initialise an "_extensions" attribute on each class, to ensure each # # class have a separate extensions registry. # if '_extensions' not in attrs: # attrs['_extensions'] = [] # # # Construct the class. # return super().__new__(mcs, name, bases, attrs) . Output only the next line.
class SystemFieldsMeta(RecordMeta):
Given the following code snippet before the placeholder: <|code_start|># Copyright (C) 2020 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Relations dumper. Dumper used to dump/load relations to/from an ElasticSearch body. """ class RelationDumperExt(ElasticsearchDumperExt): """Dumper for a relations field.""" def __init__(self, key, fields=None): """Initialize the dumper.""" self.key = key self.fields = fields def dump(self, record, data): """Dump relations.""" relations = getattr(record, self.key) relations.dereference(fields=self.fields) relation_fields = self.fields or relations for rel_field_name in relation_fields: rel_field = getattr(relations, rel_field_name) try: dict_set( data, rel_field.key, <|code_end|> , predict the next line using imports from the current file: from ..dictutils import dict_lookup, dict_set from .elasticsearch import ElasticsearchDumperExt and context including class names, function names, and sometimes code from other files: # Path: invenio_records/dictutils.py # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # def dict_set(source, key, value): # """Set a value into a dict via a dot-notated key. # # This also creates missing key "paths". # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a'] = value`` # - ``'a.b'`` - Equivalent to ``source['a']['b'] = value`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0] = value`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to set the value in. # :param key: A string using dot notation, or a list of keys. # :param value: The value to be set. # """ # keys = parse_lookup_key(key) # parent = source # for key in keys[:-1]: # if isinstance(key, int): # parent = parent[key] # else: # parent = parent.setdefault(key, {}) # parent[keys[-1]] = value # # Path: invenio_records/dumpers/elasticsearch.py # class ElasticsearchDumperExt: # """Interface for Elasticsearch dumper extensions.""" # # def dump(self, record, data): # """Dump the data.""" # # def load(self, data, record_cls): # """Load the data. # # Reverse the changes made by the dump method. # """ . Output only the next line.
dict_lookup(record, rel_field.key)
Using the snippet: <|code_start|># # This file is part of Invenio. # Copyright (C) 2020 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Relations dumper. Dumper used to dump/load relations to/from an ElasticSearch body. """ class RelationDumperExt(ElasticsearchDumperExt): """Dumper for a relations field.""" def __init__(self, key, fields=None): """Initialize the dumper.""" self.key = key self.fields = fields def dump(self, record, data): """Dump relations.""" relations = getattr(record, self.key) relations.dereference(fields=self.fields) relation_fields = self.fields or relations for rel_field_name in relation_fields: rel_field = getattr(relations, rel_field_name) try: <|code_end|> , determine the next line of code. You have imports: from ..dictutils import dict_lookup, dict_set from .elasticsearch import ElasticsearchDumperExt and context (class names, function names, or code) available: # Path: invenio_records/dictutils.py # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # def dict_set(source, key, value): # """Set a value into a dict via a dot-notated key. # # This also creates missing key "paths". # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a'] = value`` # - ``'a.b'`` - Equivalent to ``source['a']['b'] = value`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0] = value`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to set the value in. # :param key: A string using dot notation, or a list of keys. # :param value: The value to be set. # """ # keys = parse_lookup_key(key) # parent = source # for key in keys[:-1]: # if isinstance(key, int): # parent = parent[key] # else: # parent = parent.setdefault(key, {}) # parent[keys[-1]] = value # # Path: invenio_records/dumpers/elasticsearch.py # class ElasticsearchDumperExt: # """Interface for Elasticsearch dumper extensions.""" # # def dump(self, record, data): # """Dump the data.""" # # def load(self, data, record_cls): # """Load the data. # # Reverse the changes made by the dump method. # """ . Output only the next line.
dict_set(
Predict the next line for this snippet: <|code_start|> dump_type): """Helper method to load model fields from dump. :param record_cls: The record class being used for loading. :param model_field_name: The name of the SQLAlchemy model field on the record's model. :param dump: The dictionary of the dump. :param dump_key: The key to use in the dump. :param dump_type: The data type used for deserialization. """ # Retrieve the value val = dump.pop(dump_key) # Return None values immediately. if val is None: return val # Determine dump data type if not provided if dump_type is None: sa_field = getattr(record_cls.model_cls, model_field_name) dump_type = self._sa_type(record_cls.model_cls, model_field_name) # Deserialize the value return self._deserialize(val, dump_type) @staticmethod def _iter_modelfields(record_cls): """Internal helper method to extract all model fields.""" for attr_name in dir(record_cls): systemfield = getattr(record_cls, attr_name) <|code_end|> with the help of current file imports: from copy import deepcopy from datetime import date, datetime from uuid import UUID from sqlalchemy.sql.sqltypes import JSON, Boolean, DateTime, Integer, String, \ Text from sqlalchemy.sql.type_api import Variant from sqlalchemy_utils.types.uuid import UUIDType from ..systemfields.model import ModelField from .base import Dumper import arrow import pytz and context from other files: # Path: invenio_records/systemfields/model.py # class ModelField(SystemField): # """Model field for providing get and set access on a model field.""" # # def __init__(self, model_field_name=None, dump=True, dump_key=None, # dump_type=None): # """Initialize the field. # # :param model_field_name: Name of field on the database model. # :param dump: Set to false to not dump the field. # :param dump_key: The dictionary key to use in dumps. # :param dump_type: The data type used to determine how to serialize the # model field. # """ # self._model_field_name = model_field_name # self.dump = dump # self._dump_key = dump_key # self._dump_type = dump_type # # # # # Helpers # # # @property # def model_field_name(self): # """The name of the SQLAlchemy field on the model. # # Defaults to the attribute name used on the class. # """ # return self._model_field_name or self.attr_name # # @property # def dump_key(self): # """The dictionary key to use in dump output. # # Note, it's up to the dumper to choose if it respects this name. # The name defaults to the model field name. # """ # return self._dump_key or self.model_field_name # # @property # def dump_type(self): # """The data type used to determine how to serialize the model field. # # Defaults to none, meaning the dumper will determine how to dump it. # """ # return self._dump_type # # def _set(self, model, value): # """Internal method to set value on the model's field.""" # setattr(model, self.model_field_name, value) # # # # # Data descriptor # # # def __get__(self, record, owner=None): # """Accessing the attribute.""" # # Class access # if record is None: # return self # # Instance access # try: # return getattr(record.model, self.model_field_name) # except AttributeError: # return None # # def __set__(self, instance, value): # """Accessing the attribute.""" # self._set(instance.model, value) # # # # # Record extension # # # def post_init(self, record, data, model=None, field_data=None): # """Initialise the model field.""" # if field_data is not None: # self._set(model, field_data) # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() , which may contain function names, class names, or code. Output only the next line.
if isinstance(systemfield, ModelField):
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2020 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Elasticsearch source dumper. Dumper used to dump/load an the body of an Elasticsearch document. """ class ElasticsearchDumperExt: """Interface for Elasticsearch dumper extensions.""" def dump(self, record, data): """Dump the data.""" def load(self, data, record_cls): """Load the data. Reverse the changes made by the dump method. """ <|code_end|> , predict the immediate next line with the help of imports: from copy import deepcopy from datetime import date, datetime from uuid import UUID from sqlalchemy.sql.sqltypes import JSON, Boolean, DateTime, Integer, String, \ Text from sqlalchemy.sql.type_api import Variant from sqlalchemy_utils.types.uuid import UUIDType from ..systemfields.model import ModelField from .base import Dumper import arrow import pytz and context (classes, functions, sometimes code) from other files: # Path: invenio_records/systemfields/model.py # class ModelField(SystemField): # """Model field for providing get and set access on a model field.""" # # def __init__(self, model_field_name=None, dump=True, dump_key=None, # dump_type=None): # """Initialize the field. # # :param model_field_name: Name of field on the database model. # :param dump: Set to false to not dump the field. # :param dump_key: The dictionary key to use in dumps. # :param dump_type: The data type used to determine how to serialize the # model field. # """ # self._model_field_name = model_field_name # self.dump = dump # self._dump_key = dump_key # self._dump_type = dump_type # # # # # Helpers # # # @property # def model_field_name(self): # """The name of the SQLAlchemy field on the model. # # Defaults to the attribute name used on the class. # """ # return self._model_field_name or self.attr_name # # @property # def dump_key(self): # """The dictionary key to use in dump output. # # Note, it's up to the dumper to choose if it respects this name. # The name defaults to the model field name. # """ # return self._dump_key or self.model_field_name # # @property # def dump_type(self): # """The data type used to determine how to serialize the model field. # # Defaults to none, meaning the dumper will determine how to dump it. # """ # return self._dump_type # # def _set(self, model, value): # """Internal method to set value on the model's field.""" # setattr(model, self.model_field_name, value) # # # # # Data descriptor # # # def __get__(self, record, owner=None): # """Accessing the attribute.""" # # Class access # if record is None: # return self # # Instance access # try: # return getattr(record.model, self.model_field_name) # except AttributeError: # return None # # def __set__(self, instance, value): # """Accessing the attribute.""" # self._set(instance.model, value) # # # # # Record extension # # # def post_init(self, record, data, model=None, field_data=None): # """Initialise the model field.""" # if field_data is not None: # self._set(model, field_data) # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() . Output only the next line.
class ElasticsearchDumper(Dumper):
Given snippet: <|code_start|> def _validate(self, format_checker=None, validator=None, use_model=False): """Implementation of the JSONSchema validation.""" # Use the encoder to transform Python dictionary into JSON document # prior to validation unless we explicitly ask to use the already # encoded JSON in the model. if use_model: json = self.model.json else: json = self.model_cls.encode(dict(self)) if '$schema' in self and self['$schema'] is not None: # Validate (an error will raise an exception) _records_state.validate( json, self['$schema'], # Use defaults of class if not specified by user. format_checker=format_checker or self.format_checker, cls=validator or self.validator ) # Return encoded data, so we don't have to double encode. return json def replace_refs(self): """Replace the ``$ref`` keys within the JSON.""" if self.enable_jsonref: return _records_state.replace_refs(self) else: return self <|code_end|> , continue by predicting the next line. Consider current file imports: import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update and context: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py which might include code, classes, or functions. Output only the next line.
def clear_none(self, key=None):
Here is a snippet: <|code_start|> if use_model: json = self.model.json else: json = self.model_cls.encode(dict(self)) if '$schema' in self and self['$schema'] is not None: # Validate (an error will raise an exception) _records_state.validate( json, self['$schema'], # Use defaults of class if not specified by user. format_checker=format_checker or self.format_checker, cls=validator or self.validator ) # Return encoded data, so we don't have to double encode. return json def replace_refs(self): """Replace the ``$ref`` keys within the JSON.""" if self.enable_jsonref: return _records_state.replace_refs(self) else: return self def clear_none(self, key=None): """Helper method to clear None, empty dict and list values. Modifications are done in place. """ <|code_end|> . Write the next line using the current file imports: import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update and context from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py , which may include functions, classes, or code. Output only the next line.
clear_none(dict_lookup(self, key) if key else self)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2020 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Record API.""" _records_state = LocalProxy(lambda: current_app.extensions['invenio-records']) class RecordBase(dict): """Base class for Record and RecordRevision to share common features.""" model_cls = RecordMetadata """SQLAlchemy model class defining which table stores the records.""" format_checker = None """Class-level attribute to specify a default JSONSchema format checker.""" validator = None """Class-level attribute to specify a JSONSchema validator class.""" <|code_end|> , generate the next line using the imports in this file: import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update and context (functions, classes, or occasionally code) from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py . Output only the next line.
dumper = Dumper()
Continue the code snippet: <|code_start|> data = apply_patch(dict(self), patch) return self.__class__(data, model=self.model) def commit(self, format_checker=None, validator=None, **kwargs): r"""Store changes of the current record instance in the database. #. Send a signal :data:`invenio_records.signals.before_record_update` with the current record to be committed as parameter. #. Validate the current record data. #. Commit the current record in the database. #. Send a signal :data:`invenio_records.signals.after_record_update` with the committed record as parameter. :Keyword Arguments: * **format_checker** -- An instance of the class :class:`jsonschema.FormatChecker`, which contains validation rules for formats. See :func:`~invenio_records.api.RecordBase.validate` for more details. * **validator** -- A :class:`jsonschema.IValidator` class that will be used to validate the record. See :func:`~invenio_records.api.RecordBase.validate` for more details. :returns: The :class:`Record` instance. """ if self.model is None or self.model.is_deleted: <|code_end|> . Use current file imports: import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update and context (classes, functions, or code) from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py . Output only the next line.
raise MissingModelError()
Continue the code snippet: <|code_start|> #. Delete or soft-delete the current record. #. Send a signal :data:`invenio_records.signals.after_record_delete` with the current deleted record as parameter. :param force: if ``True``, completely deletes the current record from the database, otherwise soft-deletes it. :returns: The deleted :class:`Record` instance. """ if self.model is None: raise MissingModelError() with db.session.begin_nested(): if self.send_signals: before_record_delete.send( current_app._get_current_object(), record=self ) # Run pre delete extensions for e in self._extensions: e.pre_delete(self, force=force) if force: db.session.delete(self.model) else: self.model.is_deleted = True db.session.merge(self.model) if self.send_signals: <|code_end|> . Use current file imports: import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update and context (classes, functions, or code) from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py . Output only the next line.
after_record_delete.send(
Next line prediction: <|code_start|> format_checker = kwargs.pop('format_checker', None) validator = kwargs.pop('validator', None) # Create the record and the model record = cls( data, model=cls.model_cls(id=id_, data=data), **kwargs ) if cls.send_signals: before_record_insert.send( current_app._get_current_object(), record=record ) # Run pre create extensions for e in cls._extensions: e.pre_create(record) # Validate also encodes the data record._validate( format_checker=format_checker, validator=validator, use_model=True # use model (already encoded) and didn't change ) db.session.add(record.model) if cls.send_signals: <|code_end|> . Use current file imports: (import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update) and context including class names, function names, or small code snippets from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py . Output only the next line.
after_record_insert.send(
Based on the snippet: <|code_start|> :returns: The :class:`Record` instance corresponding to the revision id """ if self.model is None: raise MissingModelError() revision = self.revisions[revision_id] with db.session.begin_nested(): if self.send_signals: # TODO: arguments to this signal does not make sense. # Ought to be both record and revision. before_record_revert.send( current_app._get_current_object(), record=self ) for e in self._extensions: e.pre_revert(self, revision) # Here we explicitly set the json column in order to not # encode/decode the json data via the ``data`` property. self.model.json = revision.model.json flag_modified(self.model, 'json') db.session.merge(self.model) if self.send_signals: # TODO: arguments to this signal does not make sense. # Ought to be the class being returned just below and should # include the revision. <|code_end|> , predict the immediate next line with the help of imports: import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update and context (classes, functions, sometimes code) from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py . Output only the next line.
after_record_revert.send(
Next line prediction: <|code_start|> :func:`~invenio_records.api.RecordBase.validate` for more details. :returns: The :class:`Record` instance. """ if self.model is None or self.model.is_deleted: raise MissingModelError() with db.session.begin_nested(): if self.send_signals: before_record_update.send( current_app._get_current_object(), record=self ) # Run pre commit extensions for e in self._extensions: e.pre_commit(self, **kwargs) # Validate also encodes the data json = self._validate( format_checker=format_checker, validator=validator) # Thus, we pass the encoded JSON directly to the model to avoid # double encoding. self.model.json = json flag_modified(self.model, 'json') db.session.merge(self.model) if self.send_signals: <|code_end|> . Use current file imports: (import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update) and context including class names, function names, or small code snippets from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py . Output only the next line.
after_record_update.send(
Given the code snippet: <|code_start|> ) return self def delete(self, force=False): """Delete a record. If `force` is ``False``, the record is soft-deleted: record data will be deleted but the record identifier and the history of the record will be kept. This ensures that the same record identifier cannot be used twice, and that you can still retrieve its history. If `force` is ``True``, then the record is completely deleted from the database. #. Send a signal :data:`invenio_records.signals.before_record_delete` with the current record as parameter. #. Delete or soft-delete the current record. #. Send a signal :data:`invenio_records.signals.after_record_delete` with the current deleted record as parameter. :param force: if ``True``, completely deletes the current record from the database, otherwise soft-deletes it. :returns: The deleted :class:`Record` instance. """ if self.model is None: raise MissingModelError() with db.session.begin_nested(): if self.send_signals: <|code_end|> , generate the next line using the imports in this file: import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update and context (functions, classes, or occasionally code) from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py . Output only the next line.
before_record_delete.send(
Based on the snippet: <|code_start|> :Keyword Arguments: * **format_checker** -- An instance of the class :class:`jsonschema.FormatChecker`, which contains validation rules for formats. See :func:`~invenio_records.api.RecordBase.validate` for more details. * **validator** -- A :class:`jsonschema.IValidator` class that will be used to validate the record. See :func:`~invenio_records.api.RecordBase.validate` for more details. :param data: Dict with the record metadata. :param id_: Specify a UUID to use for the new record, instead of automatically generated. :returns: A new :class:`Record` instance. """ with db.session.begin_nested(): # For backward compatibility we pop them here. format_checker = kwargs.pop('format_checker', None) validator = kwargs.pop('validator', None) # Create the record and the model record = cls( data, model=cls.model_cls(id=id_, data=data), **kwargs ) if cls.send_signals: <|code_end|> , predict the immediate next line with the help of imports: import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update and context (classes, functions, sometimes code) from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py . Output only the next line.
before_record_insert.send(
Predict the next line after this snippet: <|code_start|> if self.model is None: raise MissingModelError() self.model.is_deleted = False return self def revert(self, revision_id): """Revert the record to a specific revision. #. Send a signal :data:`invenio_records.signals.before_record_revert` with the current record as parameter. #. Revert the record to the revision id passed as parameter. #. Send a signal :data:`invenio_records.signals.after_record_revert` with the reverted record as parameter. :param revision_id: Specify the record revision id :returns: The :class:`Record` instance corresponding to the revision id """ if self.model is None: raise MissingModelError() revision = self.revisions[revision_id] with db.session.begin_nested(): if self.send_signals: # TODO: arguments to this signal does not make sense. # Ought to be both record and revision. <|code_end|> using the current file's imports: import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update and any relevant context from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py . Output only the next line.
before_record_revert.send(
Given the code snippet: <|code_start|> r"""Store changes of the current record instance in the database. #. Send a signal :data:`invenio_records.signals.before_record_update` with the current record to be committed as parameter. #. Validate the current record data. #. Commit the current record in the database. #. Send a signal :data:`invenio_records.signals.after_record_update` with the committed record as parameter. :Keyword Arguments: * **format_checker** -- An instance of the class :class:`jsonschema.FormatChecker`, which contains validation rules for formats. See :func:`~invenio_records.api.RecordBase.validate` for more details. * **validator** -- A :class:`jsonschema.IValidator` class that will be used to validate the record. See :func:`~invenio_records.api.RecordBase.validate` for more details. :returns: The :class:`Record` instance. """ if self.model is None or self.model.is_deleted: raise MissingModelError() with db.session.begin_nested(): if self.send_signals: <|code_end|> , generate the next line using the imports in this file: import inspect import warnings from copy import deepcopy from flask import current_app from invenio_db import db from jsonpatch import apply_patch from sqlalchemy.orm.attributes import flag_modified from sqlalchemy.orm.exc import NoResultFound from sqlalchemy_continuum.utils import parent_class from werkzeug.local import LocalProxy from .dictutils import clear_none, dict_lookup from .dumpers import Dumper from .errors import MissingModelError from .models import RecordMetadata from .signals import after_record_delete, after_record_insert, \ after_record_revert, after_record_update, before_record_delete, \ before_record_insert, before_record_revert, before_record_update and context (functions, classes, or occasionally code) from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # Path: invenio_records/dumpers/base.py # class Dumper: # """Interface for dumpers.""" # # def dump(self, record, data): # """Dump a record that can be used a source document for Elasticsearch. # # The job of this method is to create a Python dictionary from the record # provided in the argument. # # If you overwrite this method without calling super, then you should # ensure that you make a deep copy of the record dictionary, to avoid # that changes to the dump affects the record. # # :param record: The record to dump. # :param data: The initial dump data passed in by ``record.dumps()``. # """ # data.update(deepcopy(dict(record))) # return data # # def load(self, data, record_cls): # """Load a record from the source document of an Elasticsearch hit. # # The job of this method, is to create a record of type ``record_cls`` # based on the input ``data``. # # :param data: A Python dictionary representing the data to load. # :param records_cls: The record class to be constructed. # :returns: A instance of ``record_cls``. # """ # raise NotImplementedError() # # Path: invenio_records/errors.py # class MissingModelError(RecordsError): # """Error raised when a record has no model.""" # # Path: invenio_records/models.py # class RecordMetadata(db.Model, RecordMetadataBase): # """Represent a record metadata.""" # # __tablename__ = 'records_metadata' # # # Enables SQLAlchemy-Continuum versioning # __versioned__ = {} # # Path: invenio_records/signals.py . Output only the next line.
before_record_update.send(
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2020 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Test of dictionary utilities.""" def test_clear_none(): """Test clearning of the dictionary.""" d = { 'a': None, 'b': { 'c': None }, 'd': ['1', None, []], 'e': [{'a': None, 'b': []}], } <|code_end|> , predict the next line using imports from the current file: from copy import deepcopy from invenio_records.dictutils import clear_none, dict_lookup import pytest and context including class names, function names, and sometimes code from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value . Output only the next line.
clear_none(d)
Next line prediction: <|code_start|> 'c': None }, 'd': ['1', None, []], 'e': [{'a': None, 'b': []}], } clear_none(d) # Modifications are done in place, so gotta test after the function call. assert d == {'d': ['1']} d = { 'a': None, 'b': [ {'a': '1', 'b': None}, ], } clear_none(d) # Modifications are done in place, so gotta test after the function call. assert d == {'b': [{'a': '1'}]} def test_dict_lookup(): """Test lookup by a key.""" d = { 'a': 1, 'b': { 'c': None }, 'd': ['1', '2'], } <|code_end|> . Use current file imports: (from copy import deepcopy from invenio_records.dictutils import clear_none, dict_lookup import pytest) and context including class names, function names, or small code snippets from other files: # Path: invenio_records/dictutils.py # def clear_none(d): # """Clear None values and empty dicts from a dict.""" # del_keys = [] # for k, v in d.items(): # if v is None: # del_keys.append(k) # elif isinstance(v, dict): # clear_none(v) # if v == {}: # del_keys.append(k) # elif isinstance(v, list): # clear_none_list(v) # if v == []: # del_keys.append(k) # # # Delete the keys (cannot be done during the dict iteration) # for k in del_keys: # del d[k] # # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value . Output only the next line.
assert dict_lookup(d, 'a') == d['a']
Using the snippet: <|code_start|># -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2020-2021 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Relations system field.""" class RelationResult: """Relation access result.""" def __init__(self, field, record): """Initialize the relation result.""" self.field = field self.record = record def _lookup_id(self): <|code_end|> , determine the next line of code. You have imports: from ...dictutils import dict_lookup, dict_set, parse_lookup_key from .errors import InvalidCheckValue, InvalidRelationValue and context (class names, function names, or code) available: # Path: invenio_records/dictutils.py # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # def dict_set(source, key, value): # """Set a value into a dict via a dot-notated key. # # This also creates missing key "paths". # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a'] = value`` # - ``'a.b'`` - Equivalent to ``source['a']['b'] = value`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0] = value`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to set the value in. # :param key: A string using dot notation, or a list of keys. # :param value: The value to be set. # """ # keys = parse_lookup_key(key) # parent = source # for key in keys[:-1]: # if isinstance(key, int): # parent = parent[key] # else: # parent = parent.setdefault(key, {}) # parent[keys[-1]] = value # # def parse_lookup_key(lookup_key): # """Parse a lookup key.""" # if not lookup_key: # raise KeyError("No lookup key specified") # # # Parse the list of keys # if isinstance(lookup_key, str): # keys = lookup_key.split('.') # elif isinstance(lookup_key, list): # keys = lookup_key # else: # raise TypeError('lookup must be string or list') # # return keys # # Path: invenio_records/systemfields/relations/errors.py # class InvalidCheckValue(RelationError): # """Invalid check value.""" # # class InvalidRelationValue(RelationError): # """Invalid relation value.""" . Output only the next line.
return dict_lookup(self.record, self.value_key)
Predict the next line after this snippet: <|code_start|> return self._dereference_one(data, attrs or self.attrs) except KeyError: return None def clean(self, attrs=None): """Clean the dereferenced attributes inside the record.""" try: data = self._lookup_data() return self._clean_one(data, attrs or self.attrs) except KeyError: return None def _dereference_one(self, data, attrs): """Dereference a single object into a dict.""" # Don't dereference if already referenced. if '@v' in data: return # Get related record obj = self.resolve(data[self.field._value_key_suffix]) # Inject selected key/values from related record into # the current record. if attrs is None: data.update({ k: v for k, v in obj.items() }) else: new_obj = {} for a in attrs: if dict_lookup(obj, a): <|code_end|> using the current file's imports: from ...dictutils import dict_lookup, dict_set, parse_lookup_key from .errors import InvalidCheckValue, InvalidRelationValue and any relevant context from other files: # Path: invenio_records/dictutils.py # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # def dict_set(source, key, value): # """Set a value into a dict via a dot-notated key. # # This also creates missing key "paths". # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a'] = value`` # - ``'a.b'`` - Equivalent to ``source['a']['b'] = value`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0] = value`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to set the value in. # :param key: A string using dot notation, or a list of keys. # :param value: The value to be set. # """ # keys = parse_lookup_key(key) # parent = source # for key in keys[:-1]: # if isinstance(key, int): # parent = parent[key] # else: # parent = parent.setdefault(key, {}) # parent[keys[-1]] = value # # def parse_lookup_key(lookup_key): # """Parse a lookup key.""" # if not lookup_key: # raise KeyError("No lookup key specified") # # # Parse the list of keys # if isinstance(lookup_key, str): # keys = lookup_key.split('.') # elif isinstance(lookup_key, list): # keys = lookup_key # else: # raise TypeError('lookup must be string or list') # # return keys # # Path: invenio_records/systemfields/relations/errors.py # class InvalidCheckValue(RelationError): # """Invalid check value.""" # # class InvalidRelationValue(RelationError): # """Invalid relation value.""" . Output only the next line.
dict_set(new_obj, a, dict_lookup(obj, a))
Continue the code snippet: <|code_start|> """Relation access result.""" def __init__(self, field, record): """Initialize the relation result.""" self.field = field self.record = record def _lookup_id(self): return dict_lookup(self.record, self.value_key) def _lookup_data(self): return dict_lookup(self.record, self.key) def __call__(self, force=True): """Resolve the relation.""" try: val = self._lookup_id() obj = self.resolve(val) return obj except KeyError: return None def __getattr__(self, name): """Proxy attribute access to field.""" return getattr(self.field, name) def _value_check(self, value_to_check, object): """Checks if the value is present in the object.""" for key, value in value_to_check.items(): if key not in object: <|code_end|> . Use current file imports: from ...dictutils import dict_lookup, dict_set, parse_lookup_key from .errors import InvalidCheckValue, InvalidRelationValue and context (classes, functions, or code) from other files: # Path: invenio_records/dictutils.py # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # def dict_set(source, key, value): # """Set a value into a dict via a dot-notated key. # # This also creates missing key "paths". # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a'] = value`` # - ``'a.b'`` - Equivalent to ``source['a']['b'] = value`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0] = value`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to set the value in. # :param key: A string using dot notation, or a list of keys. # :param value: The value to be set. # """ # keys = parse_lookup_key(key) # parent = source # for key in keys[:-1]: # if isinstance(key, int): # parent = parent[key] # else: # parent = parent.setdefault(key, {}) # parent[keys[-1]] = value # # def parse_lookup_key(lookup_key): # """Parse a lookup key.""" # if not lookup_key: # raise KeyError("No lookup key specified") # # # Parse the list of keys # if isinstance(lookup_key, str): # keys = lookup_key.split('.') # elif isinstance(lookup_key, list): # keys = lookup_key # else: # raise TypeError('lookup must be string or list') # # return keys # # Path: invenio_records/systemfields/relations/errors.py # class InvalidCheckValue(RelationError): # """Invalid check value.""" # # class InvalidRelationValue(RelationError): # """Invalid relation value.""" . Output only the next line.
raise InvalidCheckValue(f'Invalid key {key}.')
Here is a snippet: <|code_start|> for key, value in value_to_check.items(): if key not in object: raise InvalidCheckValue(f'Invalid key {key}.') if isinstance(value, dict): self._value_check(value, object[key]) else: if not isinstance(value, list): raise InvalidCheckValue( f"Invalid value_check value: {value}; it must be " "a list" ) elif isinstance(object[key], list): value_exist = set(object[key]).intersection(set(value)) if not value_exist: raise InvalidCheckValue( f"Failed cross checking value_check value " f"{value} with record value {object[key]}." ) else: if object[key] not in value: raise InvalidCheckValue( f"Failed cross checking value_check value " f"{value} with record value {object[key]}." ) def validate(self): """Validate the field.""" try: val = self._lookup_id() if not self.exists(val): <|code_end|> . Write the next line using the current file imports: from ...dictutils import dict_lookup, dict_set, parse_lookup_key from .errors import InvalidCheckValue, InvalidRelationValue and context from other files: # Path: invenio_records/dictutils.py # def dict_lookup(source, lookup_key, parent=False): # """Make a lookup into a dict based on a dot notation. # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a']`` # - ``'a.b'`` - Equivalent to ``source['a']['b']`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0]`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to perform the lookup in. # :param parent: If parent argument is True, returns the parent node of # matched object. # :param lookup_key: A string using dot notation, or a list of keys. # """ # # Copied from dictdiffer (CERN contributed part) and slightly modified. # keys = parse_lookup_key(lookup_key) # # if parent: # keys = keys[:-1] # # # Lookup the key # value = source # for key in keys: # try: # if isinstance(value, list): # key = int(key) # value = value[key] # except (TypeError, IndexError, ValueError) as exc: # raise KeyError(lookup_key) from exc # return value # # def dict_set(source, key, value): # """Set a value into a dict via a dot-notated key. # # This also creates missing key "paths". # # Examples of the supported dot notation: # # - ``'a'`` - Equivalent to ``source['a'] = value`` # - ``'a.b'`` - Equivalent to ``source['a']['b'] = value`` # - ``'a.b.0'`` - Equivalent to ``source['a']['b'][0] = value`` (for lists) # # List notation is also supported: # # - `['a']`` # - ``['a','b']`` # - ``['a','b', 0]`` # # :param source: The dictionary object to set the value in. # :param key: A string using dot notation, or a list of keys. # :param value: The value to be set. # """ # keys = parse_lookup_key(key) # parent = source # for key in keys[:-1]: # if isinstance(key, int): # parent = parent[key] # else: # parent = parent.setdefault(key, {}) # parent[keys[-1]] = value # # def parse_lookup_key(lookup_key): # """Parse a lookup key.""" # if not lookup_key: # raise KeyError("No lookup key specified") # # # Parse the list of keys # if isinstance(lookup_key, str): # keys = lookup_key.split('.') # elif isinstance(lookup_key, list): # keys = lookup_key # else: # raise TypeError('lookup must be string or list') # # return keys # # Path: invenio_records/systemfields/relations/errors.py # class InvalidCheckValue(RelationError): # """Invalid check value.""" # # class InvalidRelationValue(RelationError): # """Invalid relation value.""" , which may include functions, classes, or code. Output only the next line.
raise InvalidRelationValue(f'Invalid value {val}.')
Based on the snippet: <|code_start|>translation_x_loss = [] translation_y_loss = [] scale_loss = [] valid_loss = [] valid_translation_x_loss = [] valid_translation_y_loss = [] valid_scale_loss = [] learning_rate = [0.0001, 0.001, 0.01] # let's train the model using SGD + momentum (how original). sgd = SGD(lr=learning_rate[-1], decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='mean_squared_error', optimizer=sgd) # load validation data from the h5py file (heavy lifting here) x_valid, y_valid = loader.get_valid() best_valid = np.inf for e in range(nb_epoch): print("epoch %d" % e) loss_list = [] time_list = [] time_start = time() for i in range(loader.n_iter_train): time_start_batch = time() X_batch, Y_batch = loader.next_train_batch() loss_list.append(model.train_on_batch(X_batch, Y_batch)) # calculate some time information time_list.append(time() - time_start_batch) eta = (loader.n_iter_train - i) * np.array(time_list).mean() <|code_end|> , predict the immediate next line with the help of imports: import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches from keras.optimizers import SGD from models.DataLoader import DataLoader from keras.models import load_model from scripts.progress_bar import printProgress from time import time, localtime and context (classes, functions, sometimes code) from other files: # Path: scripts/progress_bar.py # def printProgress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100): # """ # Call in a loop to create terminal progress bar # @params: # iteration - Required : current iteration (Int) # total - Required : total iterations (Int) # prefix - Optional : prefix string (Str) # suffix - Optional : suffix string (Str) # decimals - Optional : positive number of decimals in percent complete (Int) # barLength - Optional : character length of bar (Int) # """ # formatStr = "{0:." + str(decimals) + "f}" # percent = formatStr.format(100 * (iteration / float(total))) # filledLength = int(round(barLength * iteration / float(total))) # bar = '#' * filledLength + '-' * (barLength - filledLength) # sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)), # if iteration == total: # sys.stdout.write('\n') # sys.stdout.flush() . Output only the next line.
printProgress(i, loader.n_iter_train-1, prefix='Progress:', suffix='batch error: %0.5f, ETA: %0.2f sec.'%(np.array(loss_list).mean(), eta), barLength=50)
Predict the next line for this snippet: <|code_start|> nb_epoch = 200 early_stopping = True early_stopping_count = 0 early_stopping_wait = 3 train_loss = [] valid_loss = [] learning_rate = [0.0001, 0.001, 0.01] # let's train the model using SGD + momentum (how original). sgd = SGD(lr=learning_rate[-1], decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='mean_squared_error', optimizer=sgd) # load validation data from the h5py file (heavy lifting here) x_valid, y_valid = loader.get_valid() best_valid = np.inf for e in range(nb_epoch): print("epoch %d" % e) loss_list = [] time_list = [] time_start = time() for i in range(loader.n_iter_train): time_start_batch = time() X_batch, Y_batch = loader.next_train_batch() loss_list.append(model.train_on_batch(X_batch, Y_batch)) # calculate some time information time_list.append(time() - time_start_batch) eta = (loader.n_iter_train - i) * np.array(time_list).mean() <|code_end|> with the help of current file imports: import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches from keras.optimizers import SGD from models.CNN_CIFAR import cnn_cifar_batchnormalisation, cnn_cifar_small, cnn_cifar_nodropout, \ cnn_cifar_small_batchnormalisation from models.DataLoader import DataLoader from scripts.progress_bar import printProgress from time import time, localtime and context from other files: # Path: scripts/progress_bar.py # def printProgress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100): # """ # Call in a loop to create terminal progress bar # @params: # iteration - Required : current iteration (Int) # total - Required : total iterations (Int) # prefix - Optional : prefix string (Str) # suffix - Optional : suffix string (Str) # decimals - Optional : positive number of decimals in percent complete (Int) # barLength - Optional : character length of bar (Int) # """ # formatStr = "{0:." + str(decimals) + "f}" # percent = formatStr.format(100 * (iteration / float(total))) # filledLength = int(round(barLength * iteration / float(total))) # bar = '#' * filledLength + '-' * (barLength - filledLength) # sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)), # if iteration == total: # sys.stdout.write('\n') # sys.stdout.flush() , which may contain function names, class names, or code. Output only the next line.
printProgress(i, loader.n_iter_train-1, prefix='Progress:', suffix='batch error: %0.5f, ETA: %0.2f sec.'%(np.array(loss_list).mean(), eta), barLength=50)
Here is a snippet: <|code_start|> string = configFile.read() j = json.loads(string) seq = Sequence(**j) seq.path = os.path.join(os.path.abspath(seq.path), '') return seq def save_seq_result(RESULT_SRC, result): tracker = result.tracker seqName = result.seqName evalType = result.evalType src = RESULT_SRC.format(evalType) + tracker if not os.path.exists(src): os.makedirs(src) try: string = json.dumps(result, default=lambda o : o.__dict__) except: print map(type, result[0].__dict__.values()) sys.exit() fileName = src + '/{0}.json'.format(seqName) resultFile = open(fileName, 'wb') resultFile.write(string) resultFile.close() def load_seq_result(result_src): resultFile = open(result_src) string = resultFile.read() jsonList = json.loads(string) if type(jsonList) is list: <|code_end|> . Write the next line using the current file imports: import os import sys import json import scipy.io as sio from model import Sequence from scripts.model.result import Result and context from other files: # Path: scripts/model/result.py # class Result: # # tracker : trakcer name # # seqName : Sequence name # # startFrame : start frame number # # endFrame : end frame number # # res : results # # resType : result type # # fps # # def __init__(self, tracker, seqName, startFrame=0, endFrame=0, # resType='rect', evalType='OPE', res=[], fps=0, shiftType=None, tmplsize=None): # self.tracker = tracker # self.seqName = seqName # self.startFrame = startFrame # self.endFrame = endFrame # self.resType = resType # self.evalType = evalType # self.res = res # self.fps = fps # self.shiftType = shiftType # self.tmplsize = tmplsize # # self.__dict__ = OrderedDict([ # ('tracker', self.tracker), # ('seqName', self.seqName), # ('startFrame', self.startFrame), # ('endFrame', self.endFrame), # ('evalType', self.evalType), # ('fps', self.fps), # ('shiftType', self.shiftType), # ('resType', self.resType), # ('tmplsize', self.tmplsize), # ('res', self.res)]) # # def refresh_dict(self): # self.__dict__ = OrderedDict([ # ('tracker', self.tracker), # ('seqName', self.seqName), # ('startFrame', self.startFrame), # ('endFrame', self.endFrame), # ('evalType', self.evalType), # ('fps', self.fps), # ('shiftType', self.shiftType), # ('resType', self.resType), # ('tmplsize', self.tmplsize), # ('res', self.res)]) , which may include functions, classes, or code. Output only the next line.
return [Result(**j) for j in jsonList]
Given snippet: <|code_start|> # model.compile(loss='categorical_crossentropy', optimizer='rmsprop', # loss_weights=[1., 1., 1.]) # load validation data from the h5py file (heavy lifting here) x_valid, translation_x_class_valid, translation_y_class_valid, y_scale_class_valid =\ loader.get_valid_class() best_valid = np.inf for e in range(nb_epoch): print("epoch %d" % e) loss_list = [] time_list = [] time_start = time() for i in range(loader.n_iter_train): time_start_batch = time() X_batch, translation_x_class, translation_y_class, y_scale_class = \ loader.next_train_batch_with_scale_buckets() l1, l2, l3, l4 = model.train_on_batch({'main_input': X_batch}, {'translation_x_class': translation_x_class, 'translation_y_class': translation_y_class, 'y_scale_class': y_scale_class}) loss_list.append(l1) translation_x_loss.append(l2) translation_y_loss.append(l3) scale_loss.append(l4) # calculate some time information time_list.append(time() - time_start_batch) eta = (loader.n_iter_train - i) * np.array(time_list).mean() <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches from keras.optimizers import SGD from models.CNN_CIFAR import cnn_cifar_small_batchnormalisation_class_scale from models.DataLoader import DataLoader from keras.models import load_model from scripts.progress_bar import printProgress from time import time, localtime and context: # Path: scripts/progress_bar.py # def printProgress (iteration, total, prefix = '', suffix = '', decimals = 1, barLength = 100): # """ # Call in a loop to create terminal progress bar # @params: # iteration - Required : current iteration (Int) # total - Required : total iterations (Int) # prefix - Optional : prefix string (Str) # suffix - Optional : suffix string (Str) # decimals - Optional : positive number of decimals in percent complete (Int) # barLength - Optional : character length of bar (Int) # """ # formatStr = "{0:." + str(decimals) + "f}" # percent = formatStr.format(100 * (iteration / float(total))) # filledLength = int(round(barLength * iteration / float(total))) # bar = '#' * filledLength + '-' * (barLength - filledLength) # sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percent, '%', suffix)), # if iteration == total: # sys.stdout.write('\n') # sys.stdout.flush() which might include code, classes, or functions. Output only the next line.
printProgress(i, loader.n_iter_train-1, prefix='Progress:',
Here is a snippet: <|code_start|># the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # class RoutesEditorView(QtWidgets.QTableView): """Table view with specific options for editing routes in the editor """ def __init__(self, parent): """Constructor for the RoutesEditorView class""" super().__init__(parent) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setVerticalStretch(1) self.setSizePolicy(sizePolicy) self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) <|code_end|> . Write the next line using the current file imports: from Qt import QtCore, QtGui, QtWidgets, Qt from ts2.editor import delegates and context from other files: # Path: Qt.py # # Path: ts2/editor/delegates.py # class ServicesDelegate(QtWidgets.QStyledItemDelegate): # class TrainTypesDelegate(QtWidgets.QStyledItemDelegate): # class PlacesDelegate(QtWidgets.QStyledItemDelegate): # class PropertyValuesDelegate(QtWidgets.QStyledItemDelegate): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): , which may include functions, classes, or code. Output only the next line.
routeSelected = QtCore.pyqtSignal(str)
Given snippet: <|code_start|> trainSelected = QtCore.pyqtSignal(int) trainsUnselected = QtCore.pyqtSignal() def selectionChanged(self, selected, deselected): """Called when the user changes the selection. Emits the trainSelected signal""" super().selectionChanged(selected, deselected) if selected.indexes(): index = selected.indexes()[0] if index.isValid(): self.trainSelected.emit(self.model().index(index.row(), 0).data()) def setModel(self, model): """Sets model and also setup cols""" super().setModel(model) self.resizeColumnsToContents() class TrainsGraphicsView(QtWidgets.QGraphicsView): """Graphics view with specific options for editing train positions in the editor """ def __init__(self, parent): """Constructor for the TrainsGraphicsView class""" super().__init__(parent) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setVerticalStretch(1) self.setInteractive(True) <|code_end|> , continue by predicting the next line. Consider current file imports: from Qt import QtCore, QtGui, QtWidgets, Qt from ts2.editor import delegates and context: # Path: Qt.py # # Path: ts2/editor/delegates.py # class ServicesDelegate(QtWidgets.QStyledItemDelegate): # class TrainTypesDelegate(QtWidgets.QStyledItemDelegate): # class PlacesDelegate(QtWidgets.QStyledItemDelegate): # class PropertyValuesDelegate(QtWidgets.QStyledItemDelegate): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): which might include code, classes, or functions. Output only the next line.
self.setRenderHint(QtGui.QPainter.Antialiasing, False)
Next line prediction: <|code_start|> def selectionChanged(self, selected, deselected): """Called when the user changes the selection. Emits the trainSelected signal""" super().selectionChanged(selected, deselected) if selected.indexes(): index = selected.indexes()[0] if index.isValid(): self.trainSelected.emit(self.model().index(index.row(), 0).data()) def setModel(self, model): """Sets model and also setup cols""" super().setModel(model) self.resizeColumnsToContents() class TrainsGraphicsView(QtWidgets.QGraphicsView): """Graphics view with specific options for editing train positions in the editor """ def __init__(self, parent): """Constructor for the TrainsGraphicsView class""" super().__init__(parent) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setVerticalStretch(1) self.setInteractive(True) self.setRenderHint(QtGui.QPainter.Antialiasing, False) self.setDragMode(QtWidgets.QGraphicsView.ScrollHandDrag) self.setAcceptDrops(True) <|code_end|> . Use current file imports: (from Qt import QtCore, QtGui, QtWidgets, Qt from ts2.editor import delegates) and context including class names, function names, or small code snippets from other files: # Path: Qt.py # # Path: ts2/editor/delegates.py # class ServicesDelegate(QtWidgets.QStyledItemDelegate): # class TrainTypesDelegate(QtWidgets.QStyledItemDelegate): # class PlacesDelegate(QtWidgets.QStyledItemDelegate): # class PropertyValuesDelegate(QtWidgets.QStyledItemDelegate): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): . Output only the next line.
self.setBackgroundBrush(QtGui.QBrush(Qt.black))
Predict the next line after this snippet: <|code_start|> """ def __init__(self, parent): """Constructor for the TrainTypesEditorView class""" super().__init__(parent) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setVerticalStretch(1) self.setSizePolicy(sizePolicy) self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) def setModel(self, model): """Sets model and also setup cols""" super().setModel(model) self.resizeColumnsToContents() class PropertiesView(QtWidgets.QTableView): """Table view with specific options for editing track items properties in the editor """ def __init__(self, parent): """Constructor for the PropertiesView class""" super().__init__(parent) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setVerticalStretch(1) self.setSizePolicy(sizePolicy) self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows) self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection) <|code_end|> using the current file's imports: from Qt import QtCore, QtGui, QtWidgets, Qt from ts2.editor import delegates and any relevant context from other files: # Path: Qt.py # # Path: ts2/editor/delegates.py # class ServicesDelegate(QtWidgets.QStyledItemDelegate): # class TrainTypesDelegate(QtWidgets.QStyledItemDelegate): # class PlacesDelegate(QtWidgets.QStyledItemDelegate): # class PropertyValuesDelegate(QtWidgets.QStyledItemDelegate): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): # def createEditor(self, parent, option, index): # def setEditorData(self, editor, index): # def setModelData(self, editor, model, index): # def updateEditorGeometry(self, editor, option, index): . Output only the next line.
self.setItemDelegateForColumn(1, delegates.PropertyValuesDelegate(self))
Here is a snippet: <|code_start|> """Editor Trains""" class FormatException(Exception): """File format exception.""" def __init__(self, arg): """Constructor of the FormatException class.""" super().__init__(arg) class MissingDependencyException(Exception): """Exception raised when a dependency is missing (e.g. TSL file).""" def __init__(self, arg): """Constructor of the MissingDependencyException class.""" super().__init__(arg) def cumsum(lis): """Cumulated sum of a list :param: the list to cumulatively sum. :return: an iterator with each item being the cumulated sum of all the items of the original list up to this index. """ summ = 0 for x in lis: summ += x yield summ <|code_end|> . Write the next line using the current file imports: import random import simplejson import ts2.xobjects.xsettings from Qt import QtCore and context from other files: # Path: Qt.py , which may include functions, classes, or code. Output only the next line.
class DurationProba(QtCore.QObject):
Predict the next line after this snippet: <|code_start|> hlayout.addWidget(titleLabel) hlayout.addWidget(titleText) hlayout.addStretch() descriptionLabel = QtWidgets.QLabel(self) descriptionLabel.setText("<u>" + self.tr("Description:") + "</u>") descriptionText = QtWidgets.QTextEdit(self) descriptionText.setReadOnly(True) descriptionText.setText(simulation.option("description")) optionsLabel = QtWidgets.QLabel(self) optionsLabel.setText("<u>" + self.tr("Options:") + "</u>") tibOptionCB = QtWidgets.QCheckBox(self) tibOptionCB.stateChanged.connect(self.changeTIB) tibOptionCB.setChecked( int(simulation.option("trackCircuitBased")) != 0) optionLayout = QtWidgets.QFormLayout() optionLayout.addRow(self.tr("Play simulation with track circuits"), tibOptionCB) buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok) layout = QtWidgets.QVBoxLayout() layout.addLayout(hlayout) layout.addWidget(descriptionLabel) layout.addWidget(descriptionText) layout.addWidget(optionsLabel) layout.addLayout(optionLayout) layout.addWidget(buttonBox) self.setLayout(layout) buttonBox.accepted.connect(self.accept) <|code_end|> using the current file's imports: import sys import traceback import ts2 from Qt import QtCore, QtWidgets, Qt from ts2.gui import servicelistview from ts2.utils import settings and any relevant context from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
@QtCore.pyqtSlot(int)
Predict the next line after this snippet: <|code_start|> descriptionLabel = QtWidgets.QLabel(self) descriptionLabel.setText("<u>" + self.tr("Description:") + "</u>") descriptionText = QtWidgets.QTextEdit(self) descriptionText.setReadOnly(True) descriptionText.setText(simulation.option("description")) optionsLabel = QtWidgets.QLabel(self) optionsLabel.setText("<u>" + self.tr("Options:") + "</u>") tibOptionCB = QtWidgets.QCheckBox(self) tibOptionCB.stateChanged.connect(self.changeTIB) tibOptionCB.setChecked( int(simulation.option("trackCircuitBased")) != 0) optionLayout = QtWidgets.QFormLayout() optionLayout.addRow(self.tr("Play simulation with track circuits"), tibOptionCB) buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok) layout = QtWidgets.QVBoxLayout() layout.addLayout(hlayout) layout.addWidget(descriptionLabel) layout.addWidget(descriptionText) layout.addWidget(optionsLabel) layout.addLayout(optionLayout) layout.addWidget(buttonBox) self.setLayout(layout) buttonBox.accepted.connect(self.accept) @QtCore.pyqtSlot(int) def changeTIB(self, checkState): """Changes the trackItemBased Option.""" <|code_end|> using the current file's imports: import sys import traceback import ts2 from Qt import QtCore, QtWidgets, Qt from ts2.gui import servicelistview from ts2.utils import settings and any relevant context from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
if checkState == Qt.Checked:
Continue the code snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # translate = QtWidgets.qApp.translate class ExceptionDialog: """A Dialog box for displaying exception information """ @staticmethod def popupException(parent, exception=None): """Displays a dialog with all the information about the exception and the traceback.""" title = translate("ExceptionDialog", "Error") message = "" if exception is not None: message = str(exception) + "\n\n" message += message.join(traceback.format_tb(sys.exc_info()[2])) else: message += message.join(traceback.format_exc()) <|code_end|> . Use current file imports: import sys import traceback import ts2 from Qt import QtCore, QtWidgets, Qt from ts2.gui import servicelistview from ts2.utils import settings and context (classes, functions, or code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
if settings.debug:
Given the following code snippet before the placeholder: <|code_start|> }, { "__type__": "SignalState", "aspectName": "UK_DANGER", "conditions": {} } ] } } }""" class SignalItem(abstract.TrackItem): """Logical item for signals. - This class holds the logic of a signal defined by its :class:`~ts2.scenery.signals.signalitem.SignalType`. - A signal is the item from and to which routes are created. """ SIGNAL_GRAPHIC_ITEM = 0 BERTH_GRAPHIC_ITEM = 1 SIGNAL_NUMBER_ITEM = 2 def __init__(self, parameters): """ :param dict parameters: """ self._reverse = False self._signalType = None <|code_end|> , predict the next line using imports from the current file: import collections import copy import os import simplejson as json from Qt import QtCore, QtGui, QtWidgets, Qt from ts2 import utils from ts2.scenery import abstract, helper, enditem from . import signalaspect and context including class names, function names, and sometimes code from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/enditem.py # BIG = 1000000000 # class EndItem(abstract.TrackItem): # def __init__(self, parameters): # def initialize(self, simulation): # def for_json(self): # def _getEnd(self): # def getFollowingItem(self, precedingItem, direction=-1): # def graphicsBoundingRect(self, itemId): # def graphicsPaint(self, p, options, itemId, widget=0): . Output only the next line.
self._berthOrigin = QtCore.QPointF()
Given the code snippet: <|code_start|> if self._trainId is not None: return self.simulation.trains[int(self._trainId)].serviceCode else: return "" # ## Methods ######################################################### def getNextSignal(self): """Helper function that returns the next signal of SignalItem. If a route starts from this signal, the next signal is the end signal of this route. Otherwise, it is the next signal found on the line.""" if self.nextActiveRoute is not None: return self.nextActiveRoute.endSignal cur = self.getFollowingItem(self.previousItem) prev = self while cur: if isinstance(cur, SignalItem): if prev == cur.previousItem: return cur elif isinstance(cur, enditem.EndItem): return None oldPrev = prev prev = cur cur = cur.getFollowingItem(oldPrev) return None def setBerthRect(self): """Sets the berth graphics item boundingRect.""" <|code_end|> , generate the next line using the imports in this file: import collections import copy import os import simplejson as json from Qt import QtCore, QtGui, QtWidgets, Qt from ts2 import utils from ts2.scenery import abstract, helper, enditem from . import signalaspect and context (functions, classes, or occasionally code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/enditem.py # BIG = 1000000000 # class EndItem(abstract.TrackItem): # def __init__(self, parameters): # def initialize(self, simulation): # def for_json(self): # def _getEnd(self): # def getFollowingItem(self, precedingItem, direction=-1): # def graphicsBoundingRect(self, itemId): # def graphicsPaint(self, p, options, itemId, widget=0): . Output only the next line.
font = QtGui.QFont("Courier New")
Here is a snippet: <|code_start|> class SignalItem(abstract.TrackItem): """Logical item for signals. - This class holds the logic of a signal defined by its :class:`~ts2.scenery.signals.signalitem.SignalType`. - A signal is the item from and to which routes are created. """ SIGNAL_GRAPHIC_ITEM = 0 BERTH_GRAPHIC_ITEM = 1 SIGNAL_NUMBER_ITEM = 2 def __init__(self, parameters): """ :param dict parameters: """ self._reverse = False self._signalType = None self._berthOrigin = QtCore.QPointF() self._berthRect = None super().__init__(parameters) self.setBerthRect() self._activeAspect = signalLibrary.signalAspects.get(parameters.get("activeAspect")) self._previousActiveRoute = None self._nextActiveRoute = None self._trainId = None self.defaultZValue = 50 sgi = helper.TrackGraphicsItem(self, SignalItem.SIGNAL_GRAPHIC_ITEM) sgi.setPos(self.origin) <|code_end|> . Write the next line using the current file imports: import collections import copy import os import simplejson as json from Qt import QtCore, QtGui, QtWidgets, Qt from ts2 import utils from ts2.scenery import abstract, helper, enditem from . import signalaspect and context from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/enditem.py # BIG = 1000000000 # class EndItem(abstract.TrackItem): # def __init__(self, parameters): # def initialize(self, simulation): # def for_json(self): # def _getEnd(self): # def getFollowingItem(self, precedingItem, direction=-1): # def graphicsBoundingRect(self, itemId): # def graphicsPaint(self, p, options, itemId, widget=0): , which may include functions, classes, or code. Output only the next line.
sgi.setCursor(Qt.PointingHandCursor)
Using the snippet: <|code_start|> "states": [ { "__type__": "SignalState", "aspectName": "UK_CLEAR", "conditions": { "NEXT_ROUTE_ACTIVE": [], "TRAIN_NOT_PRESENT_ON_NEXT_ROUTE": [], "NEXT_SIGNAL_ASPECTS": ["UK_CLEAR", "UK_CAUTION"] } }, { "__type__": "SignalState", "aspectName": "UK_CAUTION", "conditions": { "NEXT_ROUTE_ACTIVE": [], "TRAIN_NOT_PRESENT_ON_NEXT_ROUTE": [], "NEXT_SIGNAL_ASPECTS": ["UK_DANGER", "BUFFER"] } }, { "__type__": "SignalState", "aspectName": "UK_DANGER", "conditions": {} } ] } } }""" <|code_end|> , determine the next line of code. You have imports: import collections import copy import os import simplejson as json from Qt import QtCore, QtGui, QtWidgets, Qt from ts2 import utils from ts2.scenery import abstract, helper, enditem from . import signalaspect and context (class names, function names, or code) available: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/enditem.py # BIG = 1000000000 # class EndItem(abstract.TrackItem): # def __init__(self, parameters): # def initialize(self, simulation): # def for_json(self): # def _getEnd(self): # def getFollowingItem(self, precedingItem, direction=-1): # def graphicsBoundingRect(self, itemId): # def graphicsPaint(self, p, options, itemId, widget=0): . Output only the next line.
class SignalItem(abstract.TrackItem):
Here is a snippet: <|code_start|>}""" class SignalItem(abstract.TrackItem): """Logical item for signals. - This class holds the logic of a signal defined by its :class:`~ts2.scenery.signals.signalitem.SignalType`. - A signal is the item from and to which routes are created. """ SIGNAL_GRAPHIC_ITEM = 0 BERTH_GRAPHIC_ITEM = 1 SIGNAL_NUMBER_ITEM = 2 def __init__(self, parameters): """ :param dict parameters: """ self._reverse = False self._signalType = None self._berthOrigin = QtCore.QPointF() self._berthRect = None super().__init__(parameters) self.setBerthRect() self._activeAspect = signalLibrary.signalAspects.get(parameters.get("activeAspect")) self._previousActiveRoute = None self._nextActiveRoute = None self._trainId = None self.defaultZValue = 50 <|code_end|> . Write the next line using the current file imports: import collections import copy import os import simplejson as json from Qt import QtCore, QtGui, QtWidgets, Qt from ts2 import utils from ts2.scenery import abstract, helper, enditem from . import signalaspect and context from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/enditem.py # BIG = 1000000000 # class EndItem(abstract.TrackItem): # def __init__(self, parameters): # def initialize(self, simulation): # def for_json(self): # def _getEnd(self): # def getFollowingItem(self, precedingItem, direction=-1): # def graphicsBoundingRect(self, itemId): # def graphicsPaint(self, p, options, itemId, widget=0): , which may include functions, classes, or code. Output only the next line.
sgi = helper.TrackGraphicsItem(self, SignalItem.SIGNAL_GRAPHIC_ITEM)
Based on the snippet: <|code_start|> """Returns the current aspect of the signal.""" return self._activeAspect activeAspect = property(_getActiveAspect) @property def trainServiceCode(self): """Returns the trainServiceCode of this signal. This is for display only.""" if self._trainId is not None: return self.simulation.trains[int(self._trainId)].serviceCode else: return "" # ## Methods ######################################################### def getNextSignal(self): """Helper function that returns the next signal of SignalItem. If a route starts from this signal, the next signal is the end signal of this route. Otherwise, it is the next signal found on the line.""" if self.nextActiveRoute is not None: return self.nextActiveRoute.endSignal cur = self.getFollowingItem(self.previousItem) prev = self while cur: if isinstance(cur, SignalItem): if prev == cur.previousItem: return cur <|code_end|> , predict the immediate next line with the help of imports: import collections import copy import os import simplejson as json from Qt import QtCore, QtGui, QtWidgets, Qt from ts2 import utils from ts2.scenery import abstract, helper, enditem from . import signalaspect and context (classes, functions, sometimes code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/enditem.py # BIG = 1000000000 # class EndItem(abstract.TrackItem): # def __init__(self, parameters): # def initialize(self, simulation): # def for_json(self): # def _getEnd(self): # def getFollowingItem(self, precedingItem, direction=-1): # def graphicsBoundingRect(self, itemId): # def graphicsPaint(self, p, options, itemId, widget=0): . Output only the next line.
elif isinstance(cur, enditem.EndItem):
Predict the next line for this snippet: <|code_start|># 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # class ServiceInfoModel(QtCore.QAbstractTableModel): """Model for displaying a single service information in a view """ def __init__(self, simulation): """Constructor for the ServiceInfoModel class""" super().__init__() self._service = None self.simulation = simulation def rowCount(self, parent=None, *args, **kwargs): """Returns the number of rows of the model, corresponding to the number of serviceLines of this service.""" if self._service is not None: return len(self._service.lines) else: return 0 def columnCount(self, parent=None, *args, **kwargs): """Returns the number of columns of the model""" if self._service is not None: return 4 else: return 0 <|code_end|> with the help of current file imports: from Qt import QtCore, Qt from ts2 import utils and context from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): , which may contain function names, class names, or code. Output only the next line.
def data(self, index, role=Qt.DisplayRole):
Here is a snippet: <|code_start|> def for_json(self): """Dumps this service line to JSON.""" return { "__type__": "ServiceLine", "placeCode": self.placeCode, "scheduledArrivalTime": self.scheduledArrivalTimeStr, "scheduledDepartureTime": self.scheduledDepartureTimeStr, "trackCode": self.trackCode, "mustStop": bool(self.mustStop) } @property def service(self): """Returns the service this ServiceLine belongs to""" return self._service @property def place(self): """Returns the place of this ServiceLine""" return self.service.simulation.place(self._placeCode) @property def placeCode(self): """Returns the place code of this ServiceLine""" return self._placeCode @placeCode.setter def placeCode(self, value): """Setter function for the placeCode property""" <|code_end|> . Write the next line using the current file imports: from Qt import QtCore, Qt from ts2 import utils and context from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): , which may include functions, classes, or code. Output only the next line.
if self.simulation.context == utils.Context.EDITOR_SERVICES:
Given the code snippet: <|code_start|>\x1a\x7c\xdf\x07\x00\x28\x8a\x22\xc5\x12\x73\xcb\xaf\xa1\x54\x81\ \x5c\x2e\x27\x19\xb3\x6d\x1b\xe3\xf1\x38\x5d\x56\x47\xe4\xf3\xf9\ \xb3\x15\x78\x26\x22\xf2\x7d\x9f\x14\x45\xb9\xf8\x8f\x28\x63\x8c\ \x66\xb3\xd9\xc9\x0a\x70\x03\x55\x1e\xec\xf5\x7a\xa9\x77\x43\x51\ \xa3\xdd\x6e\x87\xef\xcc\x9f\xb3\x55\x20\x22\x1a\x8d\x46\xa4\x69\ \x1a\x65\x32\x99\x0f\x09\x17\x8b\x45\xb2\x2c\x8b\x0e\x87\x03\xbf\ \x74\xf4\x1e\x31\xa8\xc2\xdb\x87\xba\xee\x3c\xff\xdf\xa0\x06\x26\ \xbc\x2b\x88\x7b\x51\xe2\xef\x2f\x59\xdd\xee\x33\xe1\x08\x65\x00\ \x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ " qt_resource_name = b"\ \x00\x07\ \x0b\x65\x57\xa7\ \x00\x74\ \x00\x73\x00\x32\x00\x2e\x00\x70\x00\x6e\x00\x67\ \x00\x07\ \x09\x01\x57\x87\ \x00\x62\ \x00\x69\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ " qt_resource_struct = b"\ \x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x01\ \x00\x00\x00\x14\x00\x00\x00\x00\x00\x01\x00\x00\x01\xad\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\ " def qInitResources(): <|code_end|> , generate the next line using the imports in this file: from Qt import QtCore and context (functions, classes, or occasionally code) from other files: # Path: Qt.py . Output only the next line.
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name,
Given the code snippet: <|code_start|> class TrackPropertiesModel(QtCore.QAbstractTableModel): """This class is a model for accessing TrackItem properties in the editor """ def __init__(self, trackItems): """Constructor for the TrackPropertiesModel class""" super().__init__() self.trackItems = trackItems self.simulation = trackItems[0].simulation self.multiType = False tiType = type(self.trackItems[0]) for ti in self.trackItems: if type(ti) != tiType: self.multiType = True break def rowCount(self, parent=None, *args): """Returns the number of rows of the model, corresponding to the number of properties.""" if self.multiType: return len(self.trackItems[0].multiProperties) else: return len(self.trackItems[0].properties) def columnCount(self, parent=None, *args): """Returns the number of columns of the model, i.e. 2, one for the property name, and one for the property value.""" return 2 <|code_end|> , generate the next line using the imports in this file: from Qt import QtCore, QtWidgets, Qt and context (functions, classes, or occasionally code) from other files: # Path: Qt.py . Output only the next line.
def data(self, index, role=Qt.DisplayRole):
Using the snippet: <|code_start|> return [(0, -5), (5, -5), (5, 0), (5, 5), (0, 5), (-5, 5), (-5, 0), (-5, -5)] class PointsItem(abstract.TrackItem): """A ``PointsItem`` is a three-way junction. The three ends and called: - common end - normal end - reverse end .. code-block:: bash ____________ reverse / common ___________/______________normal - Trains can go from common end to normal or reverse ends depending on the state of the points. - They cannot go from normal end to reverse end. - Usually, the normal end is aligned with the common end and the reverse end is sideways, but this is not mandatory. """ def __init__(self, parameters): """ :param dict paramaters: """ <|code_end|> , determine the next line of code. You have imports: from Qt import QtCore, QtWidgets, Qt from ts2 import utils from ts2.scenery import helper, abstract and context (class names, function names, or code) available: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): . Output only the next line.
self._commonEnd = QtCore.QPointF()
Given the code snippet: <|code_start|> .. code-block:: bash ____________ reverse / common ___________/______________normal - Trains can go from common end to normal or reverse ends depending on the state of the points. - They cannot go from normal end to reverse end. - Usually, the normal end is aligned with the common end and the reverse end is sideways, but this is not mandatory. """ def __init__(self, parameters): """ :param dict paramaters: """ self._commonEnd = QtCore.QPointF() self._normalEnd = QtCore.QPointF() self._reverseEnd = QtCore.QPointF() self._center = QtCore.QPointF() self._pairedTiId = "" super().__init__(parameters) self._pointsReversed = False self._reverseItem = None self.defaultZValue = 60 pgi = helper.TrackGraphicsItem(self) pgi.setPos(self._center) pgi.setZValue(self.defaultZValue) <|code_end|> , generate the next line using the imports in this file: from Qt import QtCore, QtWidgets, Qt from ts2 import utils from ts2.scenery import helper, abstract and context (functions, classes, or occasionally code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): . Output only the next line.
pgi.setCursor(Qt.PointingHandCursor)
Given the code snippet: <|code_start|> reverseTiId = self.reverseItem.tiId else: reverseTiId = None jsonData.update({ "x": self._center.x(), "y": self._center.y(), "xf": self._commonEnd.x(), "yf": self._commonEnd.y(), "xn": self._normalEnd.x(), "yn": self._normalEnd.y(), "xr": self._reverseEnd.x(), "yr": self._reverseEnd.y(), "pairedTiId": self._pairedTiId, "reverseTiId": reverseTiId }) return jsonData # ## Properties ##################################################### # Ends in scene coordinates def _getOrigin(self): """ :return: the origin point of the PointsItem, which is actually the **common end** in the scene coordinates :rtype: ``QPointF`` """ return self.center + self.commonEnd def _setOrigin(self, pos): """Setter function for the origin property""" <|code_end|> , generate the next line using the imports in this file: from Qt import QtCore, QtWidgets, Qt from ts2 import utils from ts2.scenery import helper, abstract and context (functions, classes, or occasionally code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): . Output only the next line.
if self.simulation.context == utils.Context.EDITOR_SCENERY:
Next line prediction: <|code_start|> - common end - normal end - reverse end .. code-block:: bash ____________ reverse / common ___________/______________normal - Trains can go from common end to normal or reverse ends depending on the state of the points. - They cannot go from normal end to reverse end. - Usually, the normal end is aligned with the common end and the reverse end is sideways, but this is not mandatory. """ def __init__(self, parameters): """ :param dict paramaters: """ self._commonEnd = QtCore.QPointF() self._normalEnd = QtCore.QPointF() self._reverseEnd = QtCore.QPointF() self._center = QtCore.QPointF() self._pairedTiId = "" super().__init__(parameters) self._pointsReversed = False self._reverseItem = None self.defaultZValue = 60 <|code_end|> . Use current file imports: (from Qt import QtCore, QtWidgets, Qt from ts2 import utils from ts2.scenery import helper, abstract) and context including class names, function names, or small code snippets from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): . Output only the next line.
pgi = helper.TrackGraphicsItem(self)
Given the code snippet: <|code_start|> translate = QtWidgets.qApp.translate def getEndNames(): """ :return: a list of point end names TODO """ return [ translate("PointsItem", "N"), translate("PointsItem", "NE"), translate("PointsItem", "E"), translate("PointsItem", "SE"), translate("PointsItem", "S"), translate("PointsItem", "SW"), translate("PointsItem", "W"), translate("PointsItem", "NW") ] def getEndValues(): """ :return: a list of values TODO """ return [(0, -5), (5, -5), (5, 0), (5, 5), (0, 5), (-5, 5), (-5, 0), (-5, -5)] <|code_end|> , generate the next line using the imports in this file: from Qt import QtCore, QtWidgets, Qt from ts2 import utils from ts2.scenery import helper, abstract and context (functions, classes, or occasionally code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): . Output only the next line.
class PointsItem(abstract.TrackItem):
Given the code snippet: <|code_start|> } def addMessage(self, msgText, msgType=Message.SIMULATION_MSG): """Adds a message to the logger.""" row = len(self._messages) - 1 if msgType == Message.SIMULATION_MSG: msgText = \ self.simulation.currentTime.toString("HH:mm - ") + msgText msgData = { 'msgType': msgType, 'msgText': msgText } self.beginInsertRows(QtCore.QModelIndex(), row, row) self._messages.insert(row, Message(msgData)) self.endInsertRows() def rowCount(self, parent=None, *args, **kwargs): """Returns the number of rows of the model, corresponding to the number of messages in the logger.""" return len(self._messages) def columnCount(self, parent=None, *args, **kwargs): """Returns the number of columns of the model""" return 1 def data(self, index, role=Qt.DisplayRole): """Returns the data at the given index""" if role == Qt.DisplayRole: return str(self._messages[index.row()]) elif role == Qt.FontRole: <|code_end|> , generate the next line using the imports in this file: from Qt import QtCore, QtGui, Qt from ts2 import utils and context (functions, classes, or occasionally code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
return QtGui.QFont("Courier new")
Given the following code snippet before the placeholder: <|code_start|> if self.simulation.context == utils.Context.GAME: messages = self._messages return { "__type__": "MessageLogger", "messages": messages } def addMessage(self, msgText, msgType=Message.SIMULATION_MSG): """Adds a message to the logger.""" row = len(self._messages) - 1 if msgType == Message.SIMULATION_MSG: msgText = \ self.simulation.currentTime.toString("HH:mm - ") + msgText msgData = { 'msgType': msgType, 'msgText': msgText } self.beginInsertRows(QtCore.QModelIndex(), row, row) self._messages.insert(row, Message(msgData)) self.endInsertRows() def rowCount(self, parent=None, *args, **kwargs): """Returns the number of rows of the model, corresponding to the number of messages in the logger.""" return len(self._messages) def columnCount(self, parent=None, *args, **kwargs): """Returns the number of columns of the model""" return 1 <|code_end|> , predict the next line using imports from the current file: from Qt import QtCore, QtGui, Qt from ts2 import utils and context including class names, function names, and sometimes code from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
def data(self, index, role=Qt.DisplayRole):
Continue the code snippet: <|code_start|> return self.msgText def for_json(self): """Dumps this message to JSON.""" return { "__type__": "Message", "msgType": self.msgType, "msgText": self.msgText } class MessageLogger(QtCore.QAbstractTableModel): """A MessageLogger holds all messages that has been emitted to it and format them so that it can be used directly as a model for views.""" def __init__(self, parameters): """Constructor for the MessageLogger class.""" super().__init__() self._messages = parameters.get('messages', []) + [Message( {'msgType': Message.SIMULATION_MSG, 'msgText': " "} )] self.simulation = None def initialize(self, simulation): """Initializes the message logger once everything is loaded.""" self.simulation = simulation def for_json(self): """Dumps the messages to JSON.""" messages = [] <|code_end|> . Use current file imports: from Qt import QtCore, QtGui, Qt from ts2 import utils and context (classes, functions, or code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
if self.simulation.context == utils.Context.GAME:
Given the code snippet: <|code_start|># This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # class TrainListView(QtWidgets.QTreeView): """ TODO Document TrainListView class""" def __init__(self, parent): super().__init__(parent) self.simulation = None self.setItemsExpandable(False) self.setRootIsDecorated(False) self.setHeaderHidden(False) self.setSortingEnabled(True) <|code_end|> , generate the next line using the imports in this file: from Qt import QtCore, QtWidgets from ts2 import simulation and context (functions, classes, or occasionally code) from other files: # Path: Qt.py # # Path: ts2/simulation.py # BUILTIN_OPTIONS = { # "title": "", # "description": "", # "clientToken": "client-secret", # "version": __FILE_FORMAT__, # "timeFactor": 5, # "currentTime": "06:00:00", # "warningSpeed": 8.3, # "currentScore": 0, # "defaultMaxSpeed": 44.44, # "defaultMinimumStopTime": [(45, 75, 70), (75, 90, 30)], # "defaultDelayAtEntry": [(-60, 0, 50), (0, 60, 50)], # "trackCircuitBased": False, # "defaultSignalVisibility": 100, # "wrongPlatformPenalty": 5, # "wrongDestinationPenalty": 100, # "latePenalty": 1 # } # def json_hook(dct): # def load(simulationWindow, jsonStream): # def onTrackItemChanged(sim, msg): # def onRouteActivated(sim, msg): # def onRouteDeactivated(sim, msg): # def onClockChanged(sim, msg): # def onTrainChanged(sim, msg): # def onMessageReceived(sim, msg): # def onOptionsChanged(sim, msg): # def onStateChanged(sim, msg): # def __init__(self, options, trackItems, routes, trainTypes, services, # trns, messageLogger, signalLibrary): # def loadMessageLogger(self, messageLogger): # def loadRoutes(self, routes): # def loadTrackItems(self, trackItems): # def loadTrainTypes(self, trainTypes): # def loadServices(self, services): # def loadTrains(self, trns): # def initialize(self, simulationWindow): # def for_json(self): # def saveGame(self, fileName): # def scene(self): # def messageLogger(self): # def scorer(self): # def context(self): # def option(self, key): # def setOption(self, key, value): # def startTime(self): # def currentTime(self): # def serviceListModel(self): # def selectedServiceModel(self): # def trainListModel(self): # def selectedTrainModel(self): # def routes(self): # def trainTypes(self): # def trains(self): # def addTrain(self, train): # def trackItems(self): # def trackItem(self, tiId): # def place(self, placeCode, raise_if_not_found=True): # def places(self): # def service(self, serviceCode): # def services(self): # def registerGraphicsItem(self, graphicItem): # def updateContext(self, tabNum): # def activateRoute(self, siId, persistent=False, force=False): # def desactivateRoute(self, siId): # def onPause(self, paused): # def pause(self, paused=True): # def onIsStarted(msg): # def setTimeFactor(self, timeFactor): # def timeFactorSet(msg): # def timerOut(self): # def onOptionsChanged(self, msg): # def updateSelection(self): # def updatePlaces(self): # def findRoutes(self, si1, si2): # def createTrackItemsLinks(self): # def checkTrackItemsLinks(self): # def distanceBetween(p1, p2): # def getLineItem(self, placeCode, trackCode): # class Simulation(QtCore.QObject): . Output only the next line.
trainSelected = QtCore.pyqtSignal(str)
Given the code snippet: <|code_start|># # Copyright (C) 2008-2015 by Nicolas Piganeau # npi@m4x.org # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # class TrainListView(QtWidgets.QTreeView): """ TODO Document TrainListView class""" def __init__(self, parent): super().__init__(parent) <|code_end|> , generate the next line using the imports in this file: from Qt import QtCore, QtWidgets from ts2 import simulation and context (functions, classes, or occasionally code) from other files: # Path: Qt.py # # Path: ts2/simulation.py # BUILTIN_OPTIONS = { # "title": "", # "description": "", # "clientToken": "client-secret", # "version": __FILE_FORMAT__, # "timeFactor": 5, # "currentTime": "06:00:00", # "warningSpeed": 8.3, # "currentScore": 0, # "defaultMaxSpeed": 44.44, # "defaultMinimumStopTime": [(45, 75, 70), (75, 90, 30)], # "defaultDelayAtEntry": [(-60, 0, 50), (0, 60, 50)], # "trackCircuitBased": False, # "defaultSignalVisibility": 100, # "wrongPlatformPenalty": 5, # "wrongDestinationPenalty": 100, # "latePenalty": 1 # } # def json_hook(dct): # def load(simulationWindow, jsonStream): # def onTrackItemChanged(sim, msg): # def onRouteActivated(sim, msg): # def onRouteDeactivated(sim, msg): # def onClockChanged(sim, msg): # def onTrainChanged(sim, msg): # def onMessageReceived(sim, msg): # def onOptionsChanged(sim, msg): # def onStateChanged(sim, msg): # def __init__(self, options, trackItems, routes, trainTypes, services, # trns, messageLogger, signalLibrary): # def loadMessageLogger(self, messageLogger): # def loadRoutes(self, routes): # def loadTrackItems(self, trackItems): # def loadTrainTypes(self, trainTypes): # def loadServices(self, services): # def loadTrains(self, trns): # def initialize(self, simulationWindow): # def for_json(self): # def saveGame(self, fileName): # def scene(self): # def messageLogger(self): # def scorer(self): # def context(self): # def option(self, key): # def setOption(self, key, value): # def startTime(self): # def currentTime(self): # def serviceListModel(self): # def selectedServiceModel(self): # def trainListModel(self): # def selectedTrainModel(self): # def routes(self): # def trainTypes(self): # def trains(self): # def addTrain(self, train): # def trackItems(self): # def trackItem(self, tiId): # def place(self, placeCode, raise_if_not_found=True): # def places(self): # def service(self, serviceCode): # def services(self): # def registerGraphicsItem(self, graphicItem): # def updateContext(self, tabNum): # def activateRoute(self, siId, persistent=False, force=False): # def desactivateRoute(self, siId): # def onPause(self, paused): # def pause(self, paused=True): # def onIsStarted(msg): # def setTimeFactor(self, timeFactor): # def timeFactorSet(msg): # def timerOut(self): # def onOptionsChanged(self, msg): # def updateSelection(self): # def updatePlaces(self): # def findRoutes(self, si1, si2): # def createTrackItemsLinks(self): # def checkTrackItemsLinks(self): # def distanceBetween(p1, p2): # def getLineItem(self, placeCode, trackCode): # class Simulation(QtCore.QObject): . Output only the next line.
self.simulation = None
Predict the next line after this snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # translate = QtWidgets.qApp.translate def qPointFStrizer(attr): """Returns a function giving the str representation of attr, the latter being a QPointF property.""" def getter(self): return "(%i, %i)" % (getattr(self, attr).x(), getattr(self, attr).y()) return getter def qPointFDestrizer(attr): """Returns a function which updates a QPointF property from a string representation of a QPointF.""" def setter(self, value): if self.simulation.context == utils.Context.EDITOR_SCENERY: x, y = eval(value.strip('()')) <|code_end|> using the current file's imports: from Qt import QtCore, QtGui, QtWidgets, Qt from ts2 import utils from ts2.scenery import helper and any relevant context from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): . Output only the next line.
setattr(self, attr, QtCore.QPointF(x, y))
Based on the snippet: <|code_start|> if ti is None or self.tiId != ti.tiId: return True else: return False def __updateGraphics(self): for gi in self._gi.values(): gi.update() def removeAllGraphicsItems(self): """Removes all the graphics items associated with this TrackItem from the scene.""" for gi in self._gi.values(): self.simulation.scene.removeItem(gi) @QtCore.pyqtSlot() def updateGraphics(self): self.__updateGraphics() def updateTrain(self): """Updates the graphics item for train only""" self.updateGraphics() # ## Graphics Methods ################################################# def getPen(self): """ :return: the standard pen for drawing trackItems :rtype: ``QPen`` """ <|code_end|> , predict the immediate next line with the help of imports: from Qt import QtCore, QtGui, QtWidgets, Qt from ts2 import utils from ts2.scenery import helper and context (classes, functions, sometimes code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): . Output only the next line.
pen = QtGui.QPen()
Given the following code snippet before the placeholder: <|code_start|> else: return False def __updateGraphics(self): for gi in self._gi.values(): gi.update() def removeAllGraphicsItems(self): """Removes all the graphics items associated with this TrackItem from the scene.""" for gi in self._gi.values(): self.simulation.scene.removeItem(gi) @QtCore.pyqtSlot() def updateGraphics(self): self.__updateGraphics() def updateTrain(self): """Updates the graphics item for train only""" self.updateGraphics() # ## Graphics Methods ################################################# def getPen(self): """ :return: the standard pen for drawing trackItems :rtype: ``QPen`` """ pen = QtGui.QPen() pen.setWidth(3) <|code_end|> , predict the next line using imports from the current file: from Qt import QtCore, QtGui, QtWidgets, Qt from ts2 import utils from ts2.scenery import helper and context including class names, function names, and sometimes code from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): . Output only the next line.
pen.setJoinStyle(Qt.RoundJoin)
Given the following code snippet before the placeholder: <|code_start|># # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # translate = QtWidgets.qApp.translate def qPointFStrizer(attr): """Returns a function giving the str representation of attr, the latter being a QPointF property.""" def getter(self): return "(%i, %i)" % (getattr(self, attr).x(), getattr(self, attr).y()) return getter def qPointFDestrizer(attr): """Returns a function which updates a QPointF property from a string representation of a QPointF.""" def setter(self, value): <|code_end|> , predict the next line using imports from the current file: from Qt import QtCore, QtGui, QtWidgets, Qt from ts2 import utils from ts2.scenery import helper and context including class names, function names, and sometimes code from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): . Output only the next line.
if self.simulation.context == utils.Context.EDITOR_SCENERY:
Using the snippet: <|code_start|> ) self.properties = self.getProperties() self.multiProperties = self.getMultiProperties() for gi in self._gi.values(): simulation.registerGraphicsItem(gi) self.updateGraphics() def updateData(self, msg): if "activeRoute" in msg: if msg["activeRoute"]: self.activeRoute = self.simulation.routes[msg["activeRoute"]] else: self.activeRoute = None if "activeRoutePreviousItem" in msg: if msg["activeRoutePreviousItem"]: self.activeRoutePreviousItem = self.simulation.trackItems[msg["activeRoutePreviousItem"]] else: self.activeRoutePreviousItem = None if "trainEndsFW" in msg: self._trainHeads = [v for v in msg["trainEndsFW"].values()] if "trainEndsBK" in msg: self._trainTails = [v for v in msg["trainEndsBK"].values()] self.updateGraphics() trainEntersItem = QtCore.pyqtSignal() trainLeavesItem = QtCore.pyqtSignal() @staticmethod def getProperties(): return [ <|code_end|> , determine the next line of code. You have imports: from Qt import QtCore, QtGui, QtWidgets, Qt from ts2 import utils from ts2.scenery import helper and context (class names, function names, or code) available: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): . Output only the next line.
helper.TIProperty("tiTypeStr",
Given the code snippet: <|code_start|># # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # class ServicesDelegate(QtWidgets.QStyledItemDelegate): """ServicesDelegate is a delegate that provides a combo box for selecting a Service. """ def createEditor(self, parent, option, index): """Creates the editor, i.e. a combo box for selecting a service.""" simulation = index.model().sourceModel().simulation comboBox = QtWidgets.QComboBox(parent) comboBox.setModel(simulation.servicesModel) comboBox.setModelColumn(0) return comboBox def setEditorData(self, editor, index): """Sets the values from the model in the combo box""" simulation = index.model().sourceModel().simulation <|code_end|> , generate the next line using the imports in this file: from Qt import QtWidgets, Qt and context (functions, classes, or occasionally code) from other files: # Path: Qt.py . Output only the next line.
serviceCode = index.model().data(index, Qt.EditRole)
Using the snippet: <|code_start|> """ def __init__(self, parameters): """ :param dict paramaters: """ super().__init__(parameters) self._realLength = BIG egi = helper.TrackGraphicsItem(self) egi.setPos(self.origin) self._gi[0] = egi def initialize(self, simulation): """Initialize the item after all items are loaded.""" super().initialize(simulation) if self.simulation.context in utils.Context.EDITORS: self._gi[0].setCursor(Qt.PointingHandCursor) def for_json(self): """Dumps this end item to JSON.""" jsonData = super().for_json() jsonData.update({ "nextTiId": None }) return jsonData def _getEnd(self): """ :return: a point far away of the scene :rtype: ``QPointF`` """ <|code_end|> , determine the next line of code. You have imports: from Qt import QtCore, Qt from ts2.scenery import abstract, helper from ts2 import utils and context (class names, function names, or code) available: # Path: Qt.py # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
return QtCore.QPointF(-BIG, -BIG)
Next line prediction: <|code_start|> BIG = 1000000000 class EndItem(abstract.TrackItem): """End items are invisible items to which the free ends of other trackitems must be connected to prevent the simulation from crashing. End items are defined by: - their titype which is “E” - and their position (x, y) - They are single point items """ def __init__(self, parameters): """ :param dict paramaters: """ super().__init__(parameters) self._realLength = BIG egi = helper.TrackGraphicsItem(self) egi.setPos(self.origin) self._gi[0] = egi def initialize(self, simulation): """Initialize the item after all items are loaded.""" super().initialize(simulation) if self.simulation.context in utils.Context.EDITORS: <|code_end|> . Use current file imports: (from Qt import QtCore, Qt from ts2.scenery import abstract, helper from ts2 import utils) and context including class names, function names, or small code snippets from other files: # Path: Qt.py # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
self._gi[0].setCursor(Qt.PointingHandCursor)
Here is a snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # BIG = 1000000000 class EndItem(abstract.TrackItem): """End items are invisible items to which the free ends of other trackitems must be connected to prevent the simulation from crashing. End items are defined by: - their titype which is “E” - and their position (x, y) - They are single point items """ def __init__(self, parameters): """ :param dict paramaters: """ super().__init__(parameters) self._realLength = BIG <|code_end|> . Write the next line using the current file imports: from Qt import QtCore, Qt from ts2.scenery import abstract, helper from ts2 import utils and context from other files: # Path: Qt.py # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): , which may include functions, classes, or code. Output only the next line.
egi = helper.TrackGraphicsItem(self)
Using the snippet: <|code_start|># BIG = 1000000000 class EndItem(abstract.TrackItem): """End items are invisible items to which the free ends of other trackitems must be connected to prevent the simulation from crashing. End items are defined by: - their titype which is “E” - and their position (x, y) - They are single point items """ def __init__(self, parameters): """ :param dict paramaters: """ super().__init__(parameters) self._realLength = BIG egi = helper.TrackGraphicsItem(self) egi.setPos(self.origin) self._gi[0] = egi def initialize(self, simulation): """Initialize the item after all items are loaded.""" super().initialize(simulation) <|code_end|> , determine the next line of code. You have imports: from Qt import QtCore, Qt from ts2.scenery import abstract, helper from ts2 import utils and context (class names, function names, or code) available: # Path: Qt.py # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
if self.simulation.context in utils.Context.EDITORS:
Predict the next line after this snippet: <|code_start|> self.setValue("recent", ts2.utils.to_json(lst)) return lst def getEditorRecent(self): """List of recent files :rtype: lst of str's """ s = self.value("editorRecent") if not s: return [] return ts2.utils.from_json(s) def addEditorRecent(self, filePath): """Add a recent file""" lst = self.getEditorRecent() if filePath in lst: # already in so remove, so move to front lst.remove(filePath) # insert at front lst.insert(0, filePath) if len(lst) > 10: lst = lst[:10] self.setValue("editorRecent", ts2.utils.to_json(lst)) return lst def saveWindow(self, window): """Save window geometry and state""" self.setValue("window/%s/geometry" % window.objectName(), window.saveGeometry()) <|code_end|> using the current file's imports: import os import sys import ts2 import ts2.utils from os import path from Qt import QtCore, QtWidgets and any relevant context from other files: # Path: Qt.py . Output only the next line.
if isinstance(window, QtWidgets.QDialog):
Given the following code snippet before the placeholder: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # class TrainTypesModel(QtCore.QAbstractTableModel): """Model for TrainType class used in the editor """ def __init__(self, editor): """Constructor for the TrainTypesModel class""" super().__init__(editor) self._editor = editor def rowCount(self, parent=None, *args, **kwargs): """Returns the number of rows of the model, corresponding to the number of rolling stock types.""" return len(self._editor.trainTypes) def columnCount(self, parent=None, *args, **kwargs): """Returns the number of columns of the model""" return 8 <|code_end|> , predict the next line using imports from the current file: from Qt import QtCore, Qt from ts2 import utils and context including class names, function names, and sometimes code from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
def data(self, index, role=Qt.DisplayRole):
Based on the snippet: <|code_start|> def initialize(self, simulation): """Initializes the simulation variable once it is loaded.""" self.simulation = simulation def for_json(self): """Dumps this trainType to JSON""" return { "__type__": "TrainType", "code": self.code, "description": self.description, "maxSpeed": self.maxSpeed, "stdAccel": self.stdAccel, "stdBraking": self.stdBraking, "emergBraking": self.emergBraking, "length": self.length, "elements": self._elements } @property def code(self): """ :return: the unique code of this rolling stock type :rtype: str """ return self._code @code.setter def code(self, value): """Setter function for the code property""" <|code_end|> , predict the immediate next line with the help of imports: from Qt import QtCore, Qt from ts2 import utils and context (classes, functions, sometimes code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
if self.simulation.context == utils.Context.EDITOR_TRAINTYPES:
Given the code snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # class SettingsDialog(QtWidgets.QDialog): """Settings dialog""" def __init__(self, parent): """Constructor for the OpenDialog.""" super().__init__(parent) self.setWindowTitle( self.tr("Settings") ) self.setMinimumWidth(550) containerLayout = QtWidgets.QVBoxLayout() containerLayout.setContentsMargins(0, 0, 0, 0) self.setLayout(containerLayout) # Header headerLabel = widgets.HeaderLabel(text=self.tr("User Settings"), <|code_end|> , generate the next line using the imports in this file: import os import stat import sys import zipfile import requests import ts2 from io import BytesIO from os import path from Qt import QtWidgets, Qt from ts2.gui import widgets from ts2.utils import settings and context (functions, classes, or occasionally code) from other files: # Path: Qt.py # # Path: ts2/gui/widgets.py # class ClockWidget(QtWidgets.QLCDNumber): # class ZoomWidget(QtWidgets.QWidget): # class XGraphicsView(QtWidgets.QGraphicsView): # class StatusBar(QtWidgets.QStatusBar): # class ToolBarGroup(QtWidgets.QWidget): # class VBoxWidget(QtWidgets.QWidget): # class HBoxWidget(QtWidgets.QWidget): # class HeaderLabel(QtWidgets.QLabel): # def __init__(self, parent): # def setTime(self, t): # def __init__(self, parent=None): # def setDefaultZoom(self): # def __init__(self, parent=None): # def wheelEvent(self, ev): # def __init__(self, parent=None): # def showMessage(self, txt, timeout=0, info=False, warn=False): # def onProgressTimeout(self): # def showBusy(self, is_busy): # def __init__(self, parent=None, title=None, fg=None, bg=None): # def updateStyle(self): # def setTitle(self, title): # def addWidget(self, widget): # def addAction(self, action): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, text="", start=None, end=None, align=None): # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
align=Qt.AlignRight)
Given snippet: <|code_start|># but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # class SettingsDialog(QtWidgets.QDialog): """Settings dialog""" def __init__(self, parent): """Constructor for the OpenDialog.""" super().__init__(parent) self.setWindowTitle( self.tr("Settings") ) self.setMinimumWidth(550) containerLayout = QtWidgets.QVBoxLayout() containerLayout.setContentsMargins(0, 0, 0, 0) self.setLayout(containerLayout) # Header <|code_end|> , continue by predicting the next line. Consider current file imports: import os import stat import sys import zipfile import requests import ts2 from io import BytesIO from os import path from Qt import QtWidgets, Qt from ts2.gui import widgets from ts2.utils import settings and context: # Path: Qt.py # # Path: ts2/gui/widgets.py # class ClockWidget(QtWidgets.QLCDNumber): # class ZoomWidget(QtWidgets.QWidget): # class XGraphicsView(QtWidgets.QGraphicsView): # class StatusBar(QtWidgets.QStatusBar): # class ToolBarGroup(QtWidgets.QWidget): # class VBoxWidget(QtWidgets.QWidget): # class HBoxWidget(QtWidgets.QWidget): # class HeaderLabel(QtWidgets.QLabel): # def __init__(self, parent): # def setTime(self, t): # def __init__(self, parent=None): # def setDefaultZoom(self): # def __init__(self, parent=None): # def wheelEvent(self, ev): # def __init__(self, parent=None): # def showMessage(self, txt, timeout=0, info=False, warn=False): # def onProgressTimeout(self): # def showBusy(self, is_busy): # def __init__(self, parent=None, title=None, fg=None, bg=None): # def updateStyle(self): # def setTitle(self, title): # def addWidget(self, widget): # def addAction(self, action): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, text="", start=None, end=None, align=None): # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): which might include code, classes, or functions. Output only the next line.
headerLabel = widgets.HeaderLabel(text=self.tr("User Settings"),
Given the code snippet: <|code_start|> self.txtServerDir.setEnabled(False) grid.addWidget(self.txtServerDir, row, 1, 1, 1) butt = QtWidgets.QToolButton() butt.setText(self.tr("Default")) grid.addWidget(butt, row, 2, 1, 1) # Sims dir row += 1 grid.addWidget(QtWidgets.QLabel(self.tr("Simulations Dir")), row, 0, 1, 1, Qt.AlignRight) self.txtSimsDir = QtWidgets.QLineEdit() self.txtSimsDir.setEnabled(False) grid.addWidget(self.txtSimsDir, row, 1, 1, 1) butt = QtWidgets.QToolButton() butt.setText(self.tr("Default")) grid.addWidget(butt, row, 2, 1, 1) grid.setColumnStretch(0, 0) grid.setColumnStretch(1, 10) grid.setColumnStretch(2, 0) # ====== containerLayout.addStretch(20) self.loadSettings() def updateServerLabel(self): pass <|code_end|> , generate the next line using the imports in this file: import os import stat import sys import zipfile import requests import ts2 from io import BytesIO from os import path from Qt import QtWidgets, Qt from ts2.gui import widgets from ts2.utils import settings and context (functions, classes, or occasionally code) from other files: # Path: Qt.py # # Path: ts2/gui/widgets.py # class ClockWidget(QtWidgets.QLCDNumber): # class ZoomWidget(QtWidgets.QWidget): # class XGraphicsView(QtWidgets.QGraphicsView): # class StatusBar(QtWidgets.QStatusBar): # class ToolBarGroup(QtWidgets.QWidget): # class VBoxWidget(QtWidgets.QWidget): # class HBoxWidget(QtWidgets.QWidget): # class HeaderLabel(QtWidgets.QLabel): # def __init__(self, parent): # def setTime(self, t): # def __init__(self, parent=None): # def setDefaultZoom(self): # def __init__(self, parent=None): # def wheelEvent(self, ev): # def __init__(self, parent=None): # def showMessage(self, txt, timeout=0, info=False, warn=False): # def onProgressTimeout(self): # def showBusy(self, is_busy): # def __init__(self, parent=None, title=None, fg=None, bg=None): # def updateStyle(self): # def setTitle(self, title): # def addWidget(self, widget): # def addAction(self, action): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, text="", start=None, end=None, align=None): # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): . Output only the next line.
if path.isfile(settings.serverLoc):
Predict the next line for this snippet: <|code_start|># Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # class EditorSceneBackground(QtWidgets.QGraphicsRectItem): """The EditorSceneBackground is a graphics item set at the background of the editor scene to handle drag and drop events.""" def __init__(self, editor, x, y, width, height): """Constructor for the EditorSceneBackground class""" super().__init__(x, y, width, height) self.setZValue(-100) self.setAcceptDrops(True) self.editor = editor # pen = QtGui.QPen(Qt.cyan) # self.setPen(pen) def dragEnterEvent(self, event): """dragEnterEvent handler for the EditorSceneBackground.""" if event.mimeData().hasText(): event.accept() self.update() def dragMoveEvent(self, event): """dragMoveEvent handler for the EditorSceneBackground.""" if event.mimeData().hasText(): tiType, tiId, ox, oy, point = event.mimeData().text().split("#") if not tiId.startswith("__EDITOR__"): <|code_end|> with the help of current file imports: from Qt import QtCore, QtWidgets, Qt and context from other files: # Path: Qt.py , which may contain function names, class names, or code. Output only the next line.
clickPos = QtCore.QPointF(float(ox), float(oy))
Here is a snippet: <|code_start|> super().__init__(x, y, width, height) self.setZValue(-100) self.setAcceptDrops(True) self.editor = editor # pen = QtGui.QPen(Qt.cyan) # self.setPen(pen) def dragEnterEvent(self, event): """dragEnterEvent handler for the EditorSceneBackground.""" if event.mimeData().hasText(): event.accept() self.update() def dragMoveEvent(self, event): """dragMoveEvent handler for the EditorSceneBackground.""" if event.mimeData().hasText(): tiType, tiId, ox, oy, point = event.mimeData().text().split("#") if not tiId.startswith("__EDITOR__"): clickPos = QtCore.QPointF(float(ox), float(oy)) self.editor.moveTrackItem(tiId, event.scenePos(), clickPos, point) def dropEvent(self, event): """dropEvent handler for the EditorSceneBackground. If the dragged item is already on this scene, it moves the item. If the dragged item is dragged from the library scene, a new item is created.""" if event.mimeData().hasText(): tiType, tiId, ox, oy, point = event.mimeData().text().split("#") if tiId.startswith("__EDITOR__"): <|code_end|> . Write the next line using the current file imports: from Qt import QtCore, QtWidgets, Qt and context from other files: # Path: Qt.py , which may include functions, classes, or code. Output only the next line.
event.setDropAction(Qt.CopyAction)
Given the code snippet: <|code_start|> translate = QtWidgets.qApp.translate class C: name = 0 file_name = 1 description = 2 file_path = 3 class NAV: sims = 0 recent = 1 filesystem = 2 network = 3 class OpenDialog(QtWidgets.QDialog): """Open sim file dialog""" <|code_end|> , generate the next line using the imports in this file: import os import tempfile import zipfile import fnmatch import json import ts2 from urllib import request from Qt import QtCore, QtWidgets, Qt from ts2.utils import settings from ts2.gui import widgets and context (functions, classes, or occasionally code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/gui/widgets.py # class ClockWidget(QtWidgets.QLCDNumber): # class ZoomWidget(QtWidgets.QWidget): # class XGraphicsView(QtWidgets.QGraphicsView): # class StatusBar(QtWidgets.QStatusBar): # class ToolBarGroup(QtWidgets.QWidget): # class VBoxWidget(QtWidgets.QWidget): # class HBoxWidget(QtWidgets.QWidget): # class HeaderLabel(QtWidgets.QLabel): # def __init__(self, parent): # def setTime(self, t): # def __init__(self, parent=None): # def setDefaultZoom(self): # def __init__(self, parent=None): # def wheelEvent(self, ev): # def __init__(self, parent=None): # def showMessage(self, txt, timeout=0, info=False, warn=False): # def onProgressTimeout(self): # def showBusy(self, is_busy): # def __init__(self, parent=None, title=None, fg=None, bg=None): # def updateStyle(self): # def setTitle(self, title): # def addWidget(self, widget): # def addAction(self, action): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, text="", start=None, end=None, align=None): . Output only the next line.
openFile = QtCore.pyqtSignal(str)
Continue the code snippet: <|code_start|> tbNetworkBarLayout.addWidget(QtWidgets.QLabel(self.tr("Host:"))) self.networkServer = QtWidgets.QLineEdit(self) self.networkServer.setText("localhost") tbNetworkBarLayout.addWidget(self.networkServer, 2) tbNetworkBarLayout.addWidget(QtWidgets.QLabel(self.tr("Port:"))) self.networkPort = QtWidgets.QLineEdit(self) self.networkPort.setInputMask("00000") self.networkPort.setText("22222") tbNetworkBarLayout.addWidget(self.networkPort, 1) self.connectAction = QtWidgets.QAction(self.tr("Connect")) self.connectAction.triggered.connect(self.onConnect) btn = QtWidgets.QToolButton() btn.setDefaultAction(self.connectAction) self.buttConnect = tbNetworkBarLayout.addWidget(btn) self.networkLayout.addStretch(1) # ================================= # Bottom status self.statusBar = widgets.StatusBar() mainLayout.addWidget(self.statusBar, 0) if settings.debug: self.statusBar.showMessage(settings.simulationsDir) self.buttGroup.buttonToggled.connect(self.onNavButtClicked) self.buttGroup.button(tab).setChecked(True) def onDownload(self): """Downloads zip when Download button clicked""" <|code_end|> . Use current file imports: import os import tempfile import zipfile import fnmatch import json import ts2 from urllib import request from Qt import QtCore, QtWidgets, Qt from ts2.utils import settings from ts2.gui import widgets and context (classes, functions, or code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/gui/widgets.py # class ClockWidget(QtWidgets.QLCDNumber): # class ZoomWidget(QtWidgets.QWidget): # class XGraphicsView(QtWidgets.QGraphicsView): # class StatusBar(QtWidgets.QStatusBar): # class ToolBarGroup(QtWidgets.QWidget): # class VBoxWidget(QtWidgets.QWidget): # class HBoxWidget(QtWidgets.QWidget): # class HeaderLabel(QtWidgets.QLabel): # def __init__(self, parent): # def setTime(self, t): # def __init__(self, parent=None): # def setDefaultZoom(self): # def __init__(self, parent=None): # def wheelEvent(self, ev): # def __init__(self, parent=None): # def showMessage(self, txt, timeout=0, info=False, warn=False): # def onProgressTimeout(self): # def showBusy(self, is_busy): # def __init__(self, parent=None, title=None, fg=None, bg=None): # def updateStyle(self): # def setTitle(self, title): # def addWidget(self, widget): # def addAction(self, action): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, text="", start=None, end=None, align=None): . Output only the next line.
QtWidgets.qApp.setOverrideCursor(Qt.WaitCursor)
Continue the code snippet: <|code_start|> labelLayout = QtWidgets.QHBoxLayout() labelLayout.addStretch(1) labelLayout.addWidget(networkLabel) labelLayout.addStretch(1) self.networkLayout.addLayout(labelLayout) tbNetworkBarLayout = QtWidgets.QHBoxLayout() self.networkLayout.addLayout(tbNetworkBarLayout) tbNetworkBarLayout.addWidget(QtWidgets.QLabel(self.tr("Host:"))) self.networkServer = QtWidgets.QLineEdit(self) self.networkServer.setText("localhost") tbNetworkBarLayout.addWidget(self.networkServer, 2) tbNetworkBarLayout.addWidget(QtWidgets.QLabel(self.tr("Port:"))) self.networkPort = QtWidgets.QLineEdit(self) self.networkPort.setInputMask("00000") self.networkPort.setText("22222") tbNetworkBarLayout.addWidget(self.networkPort, 1) self.connectAction = QtWidgets.QAction(self.tr("Connect")) self.connectAction.triggered.connect(self.onConnect) btn = QtWidgets.QToolButton() btn.setDefaultAction(self.connectAction) self.buttConnect = tbNetworkBarLayout.addWidget(btn) self.networkLayout.addStretch(1) # ================================= # Bottom status self.statusBar = widgets.StatusBar() mainLayout.addWidget(self.statusBar, 0) <|code_end|> . Use current file imports: import os import tempfile import zipfile import fnmatch import json import ts2 from urllib import request from Qt import QtCore, QtWidgets, Qt from ts2.utils import settings from ts2.gui import widgets and context (classes, functions, or code) from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/gui/widgets.py # class ClockWidget(QtWidgets.QLCDNumber): # class ZoomWidget(QtWidgets.QWidget): # class XGraphicsView(QtWidgets.QGraphicsView): # class StatusBar(QtWidgets.QStatusBar): # class ToolBarGroup(QtWidgets.QWidget): # class VBoxWidget(QtWidgets.QWidget): # class HBoxWidget(QtWidgets.QWidget): # class HeaderLabel(QtWidgets.QLabel): # def __init__(self, parent): # def setTime(self, t): # def __init__(self, parent=None): # def setDefaultZoom(self): # def __init__(self, parent=None): # def wheelEvent(self, ev): # def __init__(self, parent=None): # def showMessage(self, txt, timeout=0, info=False, warn=False): # def onProgressTimeout(self): # def showBusy(self, is_busy): # def __init__(self, parent=None, title=None, fg=None, bg=None): # def updateStyle(self): # def setTitle(self, title): # def addWidget(self, widget): # def addAction(self, action): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, text="", start=None, end=None, align=None): . Output only the next line.
if settings.debug:
Predict the next line for this snippet: <|code_start|> networkLabel = QtWidgets.QLabel(self.tr("Connect to simulation server")) networkLabel.setStyleSheet("font-size: 15px; font-weight: bold;") labelLayout = QtWidgets.QHBoxLayout() labelLayout.addStretch(1) labelLayout.addWidget(networkLabel) labelLayout.addStretch(1) self.networkLayout.addLayout(labelLayout) tbNetworkBarLayout = QtWidgets.QHBoxLayout() self.networkLayout.addLayout(tbNetworkBarLayout) tbNetworkBarLayout.addWidget(QtWidgets.QLabel(self.tr("Host:"))) self.networkServer = QtWidgets.QLineEdit(self) self.networkServer.setText("localhost") tbNetworkBarLayout.addWidget(self.networkServer, 2) tbNetworkBarLayout.addWidget(QtWidgets.QLabel(self.tr("Port:"))) self.networkPort = QtWidgets.QLineEdit(self) self.networkPort.setInputMask("00000") self.networkPort.setText("22222") tbNetworkBarLayout.addWidget(self.networkPort, 1) self.connectAction = QtWidgets.QAction(self.tr("Connect")) self.connectAction.triggered.connect(self.onConnect) btn = QtWidgets.QToolButton() btn.setDefaultAction(self.connectAction) self.buttConnect = tbNetworkBarLayout.addWidget(btn) self.networkLayout.addStretch(1) # ================================= # Bottom status <|code_end|> with the help of current file imports: import os import tempfile import zipfile import fnmatch import json import ts2 from urllib import request from Qt import QtCore, QtWidgets, Qt from ts2.utils import settings from ts2.gui import widgets and context from other files: # Path: Qt.py # # Path: ts2/utils.py # class Context: # class FormatException(Exception): # class MissingDependencyException(Exception): # class DurationProba(QtCore.QObject): # GAME = 10 # EDITORS = [20, 21, 22, 23, 24, 25] # EDITOR_GENERAL = 20 # EDITOR_SCENERY = 21 # EDITOR_ROUTES = 22 # EDITOR_TRAINTYPES = 23 # EDITOR_SERVICES = 24 # EDITOR_TRAINS = 25 # def __init__(self, arg): # def __init__(self, arg): # def cumsum(lis): # def __init__(self, data): # def __str__(self): # def list(self): # def isNull(self): # def yieldValue(self): # def to_json(data): # def from_json(json_str): # # Path: ts2/gui/widgets.py # class ClockWidget(QtWidgets.QLCDNumber): # class ZoomWidget(QtWidgets.QWidget): # class XGraphicsView(QtWidgets.QGraphicsView): # class StatusBar(QtWidgets.QStatusBar): # class ToolBarGroup(QtWidgets.QWidget): # class VBoxWidget(QtWidgets.QWidget): # class HBoxWidget(QtWidgets.QWidget): # class HeaderLabel(QtWidgets.QLabel): # def __init__(self, parent): # def setTime(self, t): # def __init__(self, parent=None): # def setDefaultZoom(self): # def __init__(self, parent=None): # def wheelEvent(self, ev): # def __init__(self, parent=None): # def showMessage(self, txt, timeout=0, info=False, warn=False): # def onProgressTimeout(self): # def showBusy(self, is_busy): # def __init__(self, parent=None, title=None, fg=None, bg=None): # def updateStyle(self): # def setTitle(self, title): # def addWidget(self, widget): # def addAction(self, action): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, margin=0): # def addWidget(self, widget, stretch=0): # def addLayout(self, layout, stretch=0): # def __init__(self, parent=None, text="", start=None, end=None, align=None): , which may contain function names, class names, or code. Output only the next line.
self.statusBar = widgets.StatusBar()
Given snippet: <|code_start|># the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # class ClockWidget(QtWidgets.QLCDNumber): """Clock LCD Widget""" def __init__(self, parent): """Constructor for the ClockWidget class.""" super().__init__(parent) self.setFrameShape(QtWidgets.QFrame.NoFrame) self.setFrameShadow(QtWidgets.QFrame.Plain) self.setSegmentStyle(QtWidgets.QLCDNumber.Flat) self.setNumDigits(8) self.display("--:--:--") self.resize(100, 20) <|code_end|> , continue by predicting the next line. Consider current file imports: from Qt import QtCore, QtWidgets, Qt and context: # Path: Qt.py which might include code, classes, or functions. Output only the next line.
@QtCore.pyqtSlot(QtCore.QTime)
Using the snippet: <|code_start|> """Constructor for the ClockWidget class.""" super().__init__(parent) self.setFrameShape(QtWidgets.QFrame.NoFrame) self.setFrameShadow(QtWidgets.QFrame.Plain) self.setSegmentStyle(QtWidgets.QLCDNumber.Flat) self.setNumDigits(8) self.display("--:--:--") self.resize(100, 20) @QtCore.pyqtSlot(QtCore.QTime) def setTime(self, t): if t.isNull(): self.display("--:--:--") return self.display(t.toString("hh:mm:ss")) class ZoomWidget(QtWidgets.QWidget): """Zoom slider bar with associated spinBox.""" valueChanged = QtCore.pyqtSignal(int) def __init__(self, parent=None): """Constructor for the ZoomWidget class.""" super().__init__(parent) self.button = QtWidgets.QToolButton(self) self.button.setText(self.tr("100%")) self.button.setAutoRaise(True) <|code_end|> , determine the next line of code. You have imports: from Qt import QtCore, QtWidgets, Qt and context (class names, function names, or code) available: # Path: Qt.py . Output only the next line.
self.slider = QtWidgets.QSlider(Qt.Horizontal, self)
Predict the next line for this snippet: <|code_start|># # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # translate = QtWidgets.qApp.translate class LineItem(abstract.ResizableItem): """A line is a simple track used to connect other items together. The important parameter of a line is its real length, i.e. the length it would have in real life, since this will determine the time the train takes to travel on it. """ def __init__(self, parameters): """Constructor for the LineItem class""" self._placeCode = "" self._trackCode = "" self._realLength = "" super().__init__(parameters) self.defaultZValue = 1 <|code_end|> with the help of current file imports: import ts2.routing.position import ts2.utils as utils from Qt import QtCore, QtGui, QtWidgets, Qt from ts2.scenery import helper, abstract and context from other files: # Path: Qt.py # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): , which may contain function names, class names, or code. Output only the next line.
self._line = QtCore.QLineF()
Using the snippet: <|code_start|> # Library item in editor lx -= 15 rx += 15 ty -= 20 by += 20 self._boundingRect = QtCore.QRectF(lx, ty, rx - lx, by - ty) @QtCore.pyqtSlot() def updateGraphics(self): """Updates the TrackGraphicsItem owned by this LineItem""" if self.simulation.context == utils.Context.GAME: self.updateTrain() else: super().updateGraphics() def updateTrain(self): """Updates the graphics for trains movements only""" self.drawTrain() super().updateGraphics() # ## Graphics Methods ############################################### def graphicsBoundingRect(self, itemId): """Returns the bounding rectangle of the line item""" return self._boundingRect def graphicsShape(self, shape, itemId): """This function is called by the owned TrackGraphicsItem to return its shape. The given argument is the shape given by the parent class. """ <|code_end|> , determine the next line of code. You have imports: import ts2.routing.position import ts2.utils as utils from Qt import QtCore, QtGui, QtWidgets, Qt from ts2.scenery import helper, abstract and context (class names, function names, or code) available: # Path: Qt.py # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): . Output only the next line.
path = QtGui.QPainterPath(self._boundingRect.topLeft())
Based on the snippet: <|code_start|> def __init__(self, parameters): """Constructor for the LineItem class""" self._placeCode = "" self._trackCode = "" self._realLength = "" super().__init__(parameters) self.defaultZValue = 1 self._line = QtCore.QLineF() self._boundingRect = QtCore.QRectF() self.updateGeometry() gli = helper.TrackGraphicsItem(self) gli.setPos(self._origin) gli.setZValue(self.defaultZValue) self._gi[0] = gli self._tli = [] def updateFromParameters(self, parameters): super(LineItem, self).updateFromParameters(parameters) self._placeCode = parameters.get("placeCode", "") self._trackCode = parameters.get("trackCode", "") self._realLength = parameters.get('realLength', 1.0) def initialize(self, simulation): """Initialize the item after all items are loaded.""" self._place = simulation.place(self._placeCode) trackCode = self._parameters.get("trackCode") if self._place is not None: self._trackCode = trackCode self._place.addTrack(self) if simulation.context in utils.Context.EDITORS: <|code_end|> , predict the immediate next line with the help of imports: import ts2.routing.position import ts2.utils as utils from Qt import QtCore, QtGui, QtWidgets, Qt from ts2.scenery import helper, abstract and context (classes, functions, sometimes code) from other files: # Path: Qt.py # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): . Output only the next line.
self._gi[0].setCursor(Qt.PointingHandCursor)
Using the snippet: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the # Free Software Foundation, Inc., # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # translate = QtWidgets.qApp.translate class LineItem(abstract.ResizableItem): """A line is a simple track used to connect other items together. The important parameter of a line is its real length, i.e. the length it would have in real life, since this will determine the time the train takes to travel on it. """ def __init__(self, parameters): """Constructor for the LineItem class""" self._placeCode = "" self._trackCode = "" self._realLength = "" super().__init__(parameters) self.defaultZValue = 1 self._line = QtCore.QLineF() self._boundingRect = QtCore.QRectF() self.updateGeometry() <|code_end|> , determine the next line of code. You have imports: import ts2.routing.position import ts2.utils as utils from Qt import QtCore, QtGui, QtWidgets, Qt from ts2.scenery import helper, abstract and context (class names, function names, or code) available: # Path: Qt.py # # Path: ts2/scenery/helper.py # class TrackGraphicsItem(QtWidgets.QGraphicsItem): # class TrackPropertiesModel(QtCore.QAbstractTableModel): # class TIProperty: # def __init__(self, trackItem, itemId=0): # def boundingRect(self): # def shape(self): # def paint(self, painter, option, widget=None): # def mousePressEvent(self, event): # def mouseMoveEvent(self, event): # def dragEnterEvent(self, event): # def dragLeaveEvent(self, event): # def dropEvent(self, event): # def __init__(self, trackItems): # def rowCount(self, parent=None, *args): # def columnCount(self, parent=None, *args): # def data(self, index, role=Qt.DisplayRole): # def setData(self, index, value, role=Qt.EditRole): # def headerData(self, section, orientation, role=Qt.DisplayRole): # def flags(self, index): # def __init__(self, name, display, readOnly=False, propType="str", # enumNames=None, enumValues=None): # # Path: ts2/scenery/abstract.py # def qPointFStrizer(attr): # def getter(self): # def qPointFDestrizer(attr): # def setter(self, value): # def qPointFTupler(attr): # def getter(self): # def qPointFDetupler(attr): # def setter(self, value): # def __init__(self, parameters): # def updateFromParameters(self, parameters): # def initialize(self, simulation): # def updateData(self, msg): # def getProperties(): # def getMultiProperties(): # def for_json(self): # def _getOrigin(self): # def _setOrigin(self, pos): # def _getEnd(self): # def _getName(self): # def _setName(self, value): # def maxSpeed(self): # def maxSpeed(self, value): # def toolTipText(self): # def tiTypeStr(self): # def highlighted(self): # def _getRealLength(self): # def place(self): # def nextItem(self): # def nextItem(self, ni): # def previousItem(self): # def previousItem(self, pi): # def _getGraphicsItem(self): # def _getSelected(self): # def _setSelected(self, value): # def conflictTI(self): # def conflictTiId(self): # def conflictTiId(self, value): # def getFollowingItem(self, precedingItem, direction=-1): # def trainPresent(self): # def distanceToTrainEnd(self, pos): # def isOnPosition(self, p): # def setupTriggers(self): # def __eq__(self, ti): # def __ne__(self, ti): # def __updateGraphics(self): # def removeAllGraphicsItems(self): # def updateGraphics(self): # def updateTrain(self): # def getPen(self): # def drawConnectionRect(self, painter, point): # def graphicsBoundingRect(self, itemId): # def graphicsShape(self, shape, itemId): # def graphicsPaint(self, painter, options, itemId, widget=None): # def graphicsMousePressEvent(self, event, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # def graphicsDragEnterEvent(self, event, itemId): # def graphicsDragLeaveEvent(self, event, itemId): # def graphicsDropEvent(self, event, itemId): # def updateFromParameters(self, parameters): # def getProperties(): # def for_json(self): # def _setOrigin(self, pos): # def _setEnd(self, pos): # def _getStart(self): # def _setStart(self, pos): # def graphicsBoundingRect(self, itemId): # def graphicsMouseMoveEvent(self, event, itemId=0): # class TrackItem(QtCore.QObject): # class ResizableItem(TrackItem): . Output only the next line.
gli = helper.TrackGraphicsItem(self)
Given the code snippet: <|code_start|> if __name__ == "__main__": try: config_path = sys.argv[1] except: config_path = 'config.json' <|code_end|> , generate the next line using the imports in this file: import sys from watashi import Watashi and context (functions, classes, or occasionally code) from other files: # Path: watashi.py # class Watashi(commands.Bot): # def __init__(self, config_path: str, *args, **kwargs): # self.config_path = config_path # with open(self.config_path) as f: # self.configs = json.load(f) # # self.starttime = datetime.datetime.now() # # self.default_cogs = [f'cogs.{x.stem}' for x in Path('cogs').glob('*.py')] # # self.user_color = int(self.configs['embed_colour'], 16) # # super().__init__(command_prefix=self.configs['prefix'], self_bot=True) # # self.remove_command("help") # # # Colors can be called via shortcut # # class Foo: # # def __init__(self, bot): # # self.bot = bot # # self.color = bot.color.gold() # # Note: this is nearly useless considering how short the command is anyway but whatever. # # discord.color.gold() -> self.color.gold() # self.color = discord.Color # # self.aiohttp_session = aiohttp.ClientSession(loop=self.loop) # # def run(self): # super().run(self.configs['token'], bot=False) # # # Custom context which includes better error support # async def on_message(self, message): # ctx = await self.get_context(message, cls=custom_context.WatashiContext) # await self.invoke(ctx) # # async def on_ready(self): # print("<----------------->\n" # "Watashi SelfBot\n" # "<----------------->\n" # "Coded by:\nPrestige#9162\nDemo#9465\nnaught0#4417\n" # "<----------------->\n" # "Warning:\n" # "Under the MIT license, the makers of Watashi-SelfBot are not liable for any\n" # "damage caused/action taken against you for using a selfbot, which is in \n" # "violation of Discord's TOS") # # for cog in self.default_cogs: # self.load_extension(cog) . Output only the next line.
bot = Watashi(config_path)
Based on the snippet: <|code_start|># Copyright 2017 Bo Shao. All Rights Reserved. # # 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. # ============================================================================== os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def bot_ui(): corp_dir = os.path.join(PROJECT_ROOT, 'Data', 'Corpus') knbs_dir = os.path.join(PROJECT_ROOT, 'Data', 'KnowledgeBase') res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: <|code_end|> , predict the immediate next line with the help of imports: import os import re import sys import tensorflow as tf from settings import PROJECT_ROOT from chatbot.botpredictor import BotPredictor and context (classes, functions, sometimes code) from other files: # Path: settings.py # PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) # # Path: chatbot/botpredictor.py # class BotPredictor(object): # def __init__(self, session, corpus_dir, knbase_dir, result_dir, result_file): # """ # Args: # session: The TensorFlow session. # corpus_dir: Name of the folder storing corpus files and vocab information. # knbase_dir: Name of the folder storing data files for the knowledge base. # result_dir: The folder containing the trained result files. # result_file: The file name of the trained model. # """ # self.session = session # # # Prepare data and hyper parameters # print("# Prepare dataset placeholder and hyper parameters ...") # tokenized_data = TokenizedData(corpus_dir=corpus_dir, training=False) # # self.knowledge_base = KnowledgeBase() # self.knowledge_base.load_knbase(knbase_dir) # # self.session_data = SessionData() # # self.hparams = tokenized_data.hparams # self.src_placeholder = tf.placeholder(shape=[None], dtype=tf.string) # src_dataset = tf.data.Dataset.from_tensor_slices(self.src_placeholder) # self.infer_batch = tokenized_data.get_inference_batch(src_dataset) # # # Create model # print("# Creating inference model ...") # self.model = ModelCreator(training=False, tokenized_data=tokenized_data, # batch_input=self.infer_batch) # # Restore model weights # print("# Restoring model weights ...") # self.model.saver.restore(session, os.path.join(result_dir, result_file)) # # self.session.run(tf.tables_initializer()) # # def predict(self, session_id, question): # chat_session = self.session_data.get_session(session_id) # chat_session.before_prediction() # Reset before each prediction # # if question.strip() == '': # answer = "Don't you want to say something to me?" # chat_session.after_prediction(question, answer) # return answer # # pat_matched, new_sentence, para_list = check_patterns_and_replace(question) # # for pre_time in range(2): # tokens = nltk.word_tokenize(new_sentence.lower()) # tmp_sentence = [' '.join(tokens[:]).strip()] # # self.session.run(self.infer_batch.initializer, # feed_dict={self.src_placeholder: tmp_sentence}) # # outputs, _ = self.model.infer(self.session) # # if self.hparams.beam_width > 0: # outputs = outputs[0] # # eos_token = self.hparams.eos_token.encode("utf-8") # outputs = outputs.tolist()[0] # # if eos_token in outputs: # outputs = outputs[:outputs.index(eos_token)] # # if pat_matched and pre_time == 0: # out_sentence, if_func_val = self._get_final_output(outputs, chat_session, # para_list=para_list) # if if_func_val: # chat_session.after_prediction(question, out_sentence) # return out_sentence # else: # new_sentence = question # else: # out_sentence, _ = self._get_final_output(outputs, chat_session) # chat_session.after_prediction(question, out_sentence) # return out_sentence # # def _get_final_output(self, sentence, chat_session, para_list=None): # sentence = b' '.join(sentence).decode('utf-8') # if sentence == '': # return "I don't know what to say.", False # # if_func_val = False # last_word = None # word_list = [] # for word in sentence.split(' '): # word = word.strip() # if not word: # continue # # if word.startswith('_func_val_'): # if_func_val = True # word = call_function(word[10:], knowledge_base=self.knowledge_base, # chat_session=chat_session, para_list=para_list) # if word is None or word == '': # continue # else: # if word in self.knowledge_base.upper_words: # word = self.knowledge_base.upper_words[word] # # if (last_word is None or last_word in ['.', '!', '?']) and not word[0].isupper(): # word = word.capitalize() # # if not word.startswith('\'') and word != 'n\'t' \ # and (word[0] not in string.punctuation or word in ['(', '[', '{', '``', '$']) \ # and last_word not in ['(', '[', '{', '``', '$']: # word = ' ' + word # # word_list.append(word) # last_word = word # # return ''.join(word_list).strip(), if_func_val . Output only the next line.
predictor = BotPredictor(sess, corpus_dir=corp_dir, knbase_dir=knbs_dir,
Predict the next line after this snippet: <|code_start|> complexType += '</%s:complexType>\n'%prefix complexType += '<%s:element name="%s" type="tns:%sParams"/>\n'%(prefix,name,name) return complexType class Array: """ Create arrays of xml elements. Here an example: @webservices(_params=xmltypes.Array(xmltypes.Integer),_returns=xmltypes.Integer) def function(sefl, list_of_elements): for e in list_of_elements: # Do something with the element return len(list_of_elements) xmltypes.Array(xmltype.Integer) generate an xml element into schema definition: <xsd:element name="arrayOfElement" type="xsd:integer" maxOccurs="unbounded"/> this make the parameter of the function list_of_elements is a python list. if you specify xmltypes.Array(xmltypes.Integer,10), is generated: <xsd:element name="arrayOfElement" type="xsd:integer" maxOccurs="10"/> """ def __init__(self,type,maxOccurs=None): self._type = type self._n = maxOccurs def createArray(self,name): type = None if inspect.isclass(self._type) and not issubclass(self._type,PrimitiveType): <|code_end|> using the current file's imports: import inspect from webui.server.tornadows import complextypes and any relevant context from other files: # Path: webui/server/tornadows/complextypes.py # class Property: # class IntegerProperty(Property): # class DecimalProperty(Property): # class DoubleProperty(Property): # class FloatProperty(Property): # class DurationProperty(Property): # class DateProperty(Property): # class TimeProperty(Property): # class DateTimeProperty(Property): # class StringProperty(Property): # class BooleanProperty(Property): # class ArrayProperty(list): # class ComplexType(object): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self, object, minOccurs = 1, maxOccurs=None, data=[]): # def toXSD(self,namespace='xsd',nameelement=None): # def __init__(self): # def toXML(self,name=None,method=''): # def toXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd',method='', ltype=[]): # def _generateXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd', ltype=[]): # def getName(cls): # def _createAttributeType(self,element): # def xml2object(xml,xsd,complex,method=''): # def cls2dict(complex): # def xsd2dict(xsd,namespace='xsd'): # def xml2list(xmldoc,name,types,method=''): # def generateOBJ(d,namecls,types): # def createProperty(typ,value): # def genattr(elems): # def findElementFromDict(dictionary,key): # def convert(typeelement,value): # def createPythonType2XMLType(pyType): . Output only the next line.
type = complextypes.createPythonType2XMLType(self._type.__name__)
Given the code snippet: <|code_start|># you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' app = Flask(__name__) @app.route('/reply', methods=['POST', 'GET']) def reply(): session_id = int(request.args.get('sessionId')) question = request.args.get('question') if session_id not in predictor.session_data.session_dict: # Including the case of 0 session_id = predictor.session_data.add_session() answer = predictor.predict(session_id, question) return jsonify({'sessionId': session_id, 'sentence': answer}) if __name__ == "__main__": <|code_end|> , generate the next line using the imports in this file: import os import tensorflow as tf from flask import Flask, request, jsonify from settings import PROJECT_ROOT from chatbot.botpredictor import BotPredictor and context (functions, classes, or occasionally code) from other files: # Path: settings.py # PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) # # Path: chatbot/botpredictor.py # class BotPredictor(object): # def __init__(self, session, corpus_dir, knbase_dir, result_dir, result_file): # """ # Args: # session: The TensorFlow session. # corpus_dir: Name of the folder storing corpus files and vocab information. # knbase_dir: Name of the folder storing data files for the knowledge base. # result_dir: The folder containing the trained result files. # result_file: The file name of the trained model. # """ # self.session = session # # # Prepare data and hyper parameters # print("# Prepare dataset placeholder and hyper parameters ...") # tokenized_data = TokenizedData(corpus_dir=corpus_dir, training=False) # # self.knowledge_base = KnowledgeBase() # self.knowledge_base.load_knbase(knbase_dir) # # self.session_data = SessionData() # # self.hparams = tokenized_data.hparams # self.src_placeholder = tf.placeholder(shape=[None], dtype=tf.string) # src_dataset = tf.data.Dataset.from_tensor_slices(self.src_placeholder) # self.infer_batch = tokenized_data.get_inference_batch(src_dataset) # # # Create model # print("# Creating inference model ...") # self.model = ModelCreator(training=False, tokenized_data=tokenized_data, # batch_input=self.infer_batch) # # Restore model weights # print("# Restoring model weights ...") # self.model.saver.restore(session, os.path.join(result_dir, result_file)) # # self.session.run(tf.tables_initializer()) # # def predict(self, session_id, question): # chat_session = self.session_data.get_session(session_id) # chat_session.before_prediction() # Reset before each prediction # # if question.strip() == '': # answer = "Don't you want to say something to me?" # chat_session.after_prediction(question, answer) # return answer # # pat_matched, new_sentence, para_list = check_patterns_and_replace(question) # # for pre_time in range(2): # tokens = nltk.word_tokenize(new_sentence.lower()) # tmp_sentence = [' '.join(tokens[:]).strip()] # # self.session.run(self.infer_batch.initializer, # feed_dict={self.src_placeholder: tmp_sentence}) # # outputs, _ = self.model.infer(self.session) # # if self.hparams.beam_width > 0: # outputs = outputs[0] # # eos_token = self.hparams.eos_token.encode("utf-8") # outputs = outputs.tolist()[0] # # if eos_token in outputs: # outputs = outputs[:outputs.index(eos_token)] # # if pat_matched and pre_time == 0: # out_sentence, if_func_val = self._get_final_output(outputs, chat_session, # para_list=para_list) # if if_func_val: # chat_session.after_prediction(question, out_sentence) # return out_sentence # else: # new_sentence = question # else: # out_sentence, _ = self._get_final_output(outputs, chat_session) # chat_session.after_prediction(question, out_sentence) # return out_sentence # # def _get_final_output(self, sentence, chat_session, para_list=None): # sentence = b' '.join(sentence).decode('utf-8') # if sentence == '': # return "I don't know what to say.", False # # if_func_val = False # last_word = None # word_list = [] # for word in sentence.split(' '): # word = word.strip() # if not word: # continue # # if word.startswith('_func_val_'): # if_func_val = True # word = call_function(word[10:], knowledge_base=self.knowledge_base, # chat_session=chat_session, para_list=para_list) # if word is None or word == '': # continue # else: # if word in self.knowledge_base.upper_words: # word = self.knowledge_base.upper_words[word] # # if (last_word is None or last_word in ['.', '!', '?']) and not word[0].isupper(): # word = word.capitalize() # # if not word.startswith('\'') and word != 'n\'t' \ # and (word[0] not in string.punctuation or word in ['(', '[', '{', '``', '$']) \ # and last_word not in ['(', '[', '{', '``', '$']: # word = ' ' + word # # word_list.append(word) # last_word = word # # return ''.join(word_list).strip(), if_func_val . Output only the next line.
corp_dir = os.path.join(PROJECT_ROOT, 'Data', 'Corpus')
Using the snippet: <|code_start|># Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' app = Flask(__name__) @app.route('/reply', methods=['POST', 'GET']) def reply(): session_id = int(request.args.get('sessionId')) question = request.args.get('question') if session_id not in predictor.session_data.session_dict: # Including the case of 0 session_id = predictor.session_data.add_session() answer = predictor.predict(session_id, question) return jsonify({'sessionId': session_id, 'sentence': answer}) if __name__ == "__main__": corp_dir = os.path.join(PROJECT_ROOT, 'Data', 'Corpus') knbs_dir = os.path.join(PROJECT_ROOT, 'Data', 'KnowledgeBase') res_dir = os.path.join(PROJECT_ROOT, 'Data', 'Result') with tf.Session() as sess: <|code_end|> , determine the next line of code. You have imports: import os import tensorflow as tf from flask import Flask, request, jsonify from settings import PROJECT_ROOT from chatbot.botpredictor import BotPredictor and context (class names, function names, or code) available: # Path: settings.py # PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) # # Path: chatbot/botpredictor.py # class BotPredictor(object): # def __init__(self, session, corpus_dir, knbase_dir, result_dir, result_file): # """ # Args: # session: The TensorFlow session. # corpus_dir: Name of the folder storing corpus files and vocab information. # knbase_dir: Name of the folder storing data files for the knowledge base. # result_dir: The folder containing the trained result files. # result_file: The file name of the trained model. # """ # self.session = session # # # Prepare data and hyper parameters # print("# Prepare dataset placeholder and hyper parameters ...") # tokenized_data = TokenizedData(corpus_dir=corpus_dir, training=False) # # self.knowledge_base = KnowledgeBase() # self.knowledge_base.load_knbase(knbase_dir) # # self.session_data = SessionData() # # self.hparams = tokenized_data.hparams # self.src_placeholder = tf.placeholder(shape=[None], dtype=tf.string) # src_dataset = tf.data.Dataset.from_tensor_slices(self.src_placeholder) # self.infer_batch = tokenized_data.get_inference_batch(src_dataset) # # # Create model # print("# Creating inference model ...") # self.model = ModelCreator(training=False, tokenized_data=tokenized_data, # batch_input=self.infer_batch) # # Restore model weights # print("# Restoring model weights ...") # self.model.saver.restore(session, os.path.join(result_dir, result_file)) # # self.session.run(tf.tables_initializer()) # # def predict(self, session_id, question): # chat_session = self.session_data.get_session(session_id) # chat_session.before_prediction() # Reset before each prediction # # if question.strip() == '': # answer = "Don't you want to say something to me?" # chat_session.after_prediction(question, answer) # return answer # # pat_matched, new_sentence, para_list = check_patterns_and_replace(question) # # for pre_time in range(2): # tokens = nltk.word_tokenize(new_sentence.lower()) # tmp_sentence = [' '.join(tokens[:]).strip()] # # self.session.run(self.infer_batch.initializer, # feed_dict={self.src_placeholder: tmp_sentence}) # # outputs, _ = self.model.infer(self.session) # # if self.hparams.beam_width > 0: # outputs = outputs[0] # # eos_token = self.hparams.eos_token.encode("utf-8") # outputs = outputs.tolist()[0] # # if eos_token in outputs: # outputs = outputs[:outputs.index(eos_token)] # # if pat_matched and pre_time == 0: # out_sentence, if_func_val = self._get_final_output(outputs, chat_session, # para_list=para_list) # if if_func_val: # chat_session.after_prediction(question, out_sentence) # return out_sentence # else: # new_sentence = question # else: # out_sentence, _ = self._get_final_output(outputs, chat_session) # chat_session.after_prediction(question, out_sentence) # return out_sentence # # def _get_final_output(self, sentence, chat_session, para_list=None): # sentence = b' '.join(sentence).decode('utf-8') # if sentence == '': # return "I don't know what to say.", False # # if_func_val = False # last_word = None # word_list = [] # for word in sentence.split(' '): # word = word.strip() # if not word: # continue # # if word.startswith('_func_val_'): # if_func_val = True # word = call_function(word[10:], knowledge_base=self.knowledge_base, # chat_session=chat_session, para_list=para_list) # if word is None or word == '': # continue # else: # if word in self.knowledge_base.upper_words: # word = self.knowledge_base.upper_words[word] # # if (last_word is None or last_word in ['.', '!', '?']) and not word[0].isupper(): # word = word.capitalize() # # if not word.startswith('\'') and word != 'n\'t' \ # and (word[0] not in string.punctuation or word in ['(', '[', '{', '``', '$']) \ # and last_word not in ['(', '[', '{', '``', '$']: # word = ' ' + word # # word_list.append(word) # last_word = word # # return ''.join(word_list).strip(), if_func_val . Output only the next line.
predictor = BotPredictor(sess, corpus_dir=corp_dir, knbase_dir=knbs_dir,
Using the snippet: <|code_start|> types += '<xsd:schema targetNamespace="%s">\n'%self._namespace namespace = 'xsd' types_list = [] ltype = [] for wsdl_data in self._methods: self._arguments = wsdl_data['args'] self._elementNameInput = wsdl_data['input'][0] self._elementInput = wsdl_data['input'][1] self._elementNameOutput = wsdl_data['output'][0] self._elementOutput = wsdl_data['output'][1] self._operation = wsdl_data['operation'] method = self._operation if len(self._methods) == 1: method = '' if inspect.isclass(self._elementInput) and issubclass(self._elementInput,complextypes.ComplexType): typeInput = self._elementInput.getName()+method if ltype.count(self._elementInput.getName()) == 0: ltype.append(self._elementInput.getName()) types += self._elementInput.toXSD(method=method,ltype=ltype) types += '<%s:element name="%s" type="tns:%s"/>'%(namespace,typeInput,self._elementInput.getName()) elif isinstance(self._elementInput,dict): typeInput = self._elementNameInput+method types += self._createComplexTypes(self._elementNameInput+method, self._arguments, self._elementInput) <|code_end|> , determine the next line of code. You have imports: import xml.dom.minidom import inspect from webui.server.tornadows import xmltypes from webui.server.tornadows import complextypes and context (class names, function names, or code) available: # Path: webui/server/tornadows/xmltypes.py # def createElementXML(name,type,prefix='xsd'): # def createArrayXML(name,type,prefix='xsd',maxoccurs=None): # def __init__(self,type,maxOccurs=None): # def createArray(self,name): # def createType(self,name): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # class Array: # class PrimitiveType: # class Integer(PrimitiveType): # class Decimal(PrimitiveType): # class Double(PrimitiveType): # class Float(PrimitiveType): # class Duration(PrimitiveType): # class Date(PrimitiveType): # class Time(PrimitiveType): # class DateTime(PrimitiveType): # class String(PrimitiveType): # class Boolean(PrimitiveType): # # Path: webui/server/tornadows/complextypes.py # class Property: # class IntegerProperty(Property): # class DecimalProperty(Property): # class DoubleProperty(Property): # class FloatProperty(Property): # class DurationProperty(Property): # class DateProperty(Property): # class TimeProperty(Property): # class DateTimeProperty(Property): # class StringProperty(Property): # class BooleanProperty(Property): # class ArrayProperty(list): # class ComplexType(object): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self, object, minOccurs = 1, maxOccurs=None, data=[]): # def toXSD(self,namespace='xsd',nameelement=None): # def __init__(self): # def toXML(self,name=None,method=''): # def toXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd',method='', ltype=[]): # def _generateXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd', ltype=[]): # def getName(cls): # def _createAttributeType(self,element): # def xml2object(xml,xsd,complex,method=''): # def cls2dict(complex): # def xsd2dict(xsd,namespace='xsd'): # def xml2list(xmldoc,name,types,method=''): # def generateOBJ(d,namecls,types): # def createProperty(typ,value): # def genattr(elems): # def findElementFromDict(dictionary,key): # def convert(typeelement,value): # def createPythonType2XMLType(pyType): . Output only the next line.
elif isinstance(self._elementInput,xmltypes.Array):
Given the code snippet: <|code_start|> """ def __init__(self,nameservice=None,targetNamespace=None,methods=None,location=None): self._nameservice = nameservice self._namespace = targetNamespace self._methods = methods self._location = location def createWsdl(self): """ Method that allows create the wsdl file """ typeInput = None typeOutput = None types = '<wsdl:types>\n' types += '<xsd:schema targetNamespace="%s">\n'%self._namespace namespace = 'xsd' types_list = [] ltype = [] for wsdl_data in self._methods: self._arguments = wsdl_data['args'] self._elementNameInput = wsdl_data['input'][0] self._elementInput = wsdl_data['input'][1] self._elementNameOutput = wsdl_data['output'][0] self._elementOutput = wsdl_data['output'][1] self._operation = wsdl_data['operation'] method = self._operation if len(self._methods) == 1: method = '' <|code_end|> , generate the next line using the imports in this file: import xml.dom.minidom import inspect from webui.server.tornadows import xmltypes from webui.server.tornadows import complextypes and context (functions, classes, or occasionally code) from other files: # Path: webui/server/tornadows/xmltypes.py # def createElementXML(name,type,prefix='xsd'): # def createArrayXML(name,type,prefix='xsd',maxoccurs=None): # def __init__(self,type,maxOccurs=None): # def createArray(self,name): # def createType(self,name): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # def createElement(name,prefix='xsd'): # def getType(self): # def genType(self,v): # class Array: # class PrimitiveType: # class Integer(PrimitiveType): # class Decimal(PrimitiveType): # class Double(PrimitiveType): # class Float(PrimitiveType): # class Duration(PrimitiveType): # class Date(PrimitiveType): # class Time(PrimitiveType): # class DateTime(PrimitiveType): # class String(PrimitiveType): # class Boolean(PrimitiveType): # # Path: webui/server/tornadows/complextypes.py # class Property: # class IntegerProperty(Property): # class DecimalProperty(Property): # class DoubleProperty(Property): # class FloatProperty(Property): # class DurationProperty(Property): # class DateProperty(Property): # class TimeProperty(Property): # class DateTimeProperty(Property): # class StringProperty(Property): # class BooleanProperty(Property): # class ArrayProperty(list): # class ComplexType(object): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self): # def __init__(self, object, minOccurs = 1, maxOccurs=None, data=[]): # def toXSD(self,namespace='xsd',nameelement=None): # def __init__(self): # def toXML(self,name=None,method=''): # def toXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd',method='', ltype=[]): # def _generateXSD(cls,xmlns='http://www.w3.org/2001/XMLSchema',namespace='xsd', ltype=[]): # def getName(cls): # def _createAttributeType(self,element): # def xml2object(xml,xsd,complex,method=''): # def cls2dict(complex): # def xsd2dict(xsd,namespace='xsd'): # def xml2list(xmldoc,name,types,method=''): # def generateOBJ(d,namecls,types): # def createProperty(typ,value): # def genattr(elems): # def findElementFromDict(dictionary,key): # def convert(typeelement,value): # def createPythonType2XMLType(pyType): . Output only the next line.
if inspect.isclass(self._elementInput) and issubclass(self._elementInput,complextypes.ComplexType):
Based on the snippet: <|code_start|># 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. # ============================================================================== COMMENT_LINE_STT = "#==" CONVERSATION_SEP = "===" AUG0_FOLDER = "Augment0" AUG1_FOLDER = "Augment1" AUG2_FOLDER = "Augment2" MAX_LEN = 1000 # Assume no line in the training data is having more than this number of characters VOCAB_FILE = "vocab.txt" class TokenizedData: def __init__(self, corpus_dir, hparams=None, training=True, buffer_size=8192): """ Args: corpus_dir: Name of the folder storing corpus files for training. hparams: The object containing the loaded hyper parameters. If None, it will be initialized here. training: Whether to use this object for training. buffer_size: The buffer size used for mapping process during data processing. """ if hparams is None: <|code_end|> , predict the immediate next line with the help of imports: import codecs import os import tensorflow as tf from collections import namedtuple from tensorflow.python.ops import lookup_ops from chatbot.hparams import HParams and context (classes, functions, sometimes code) from other files: # Path: chatbot/hparams.py # class HParams: # def __init__(self, model_dir): # """ # Args: # model_dir: Name of the folder storing the hparams.json file. # """ # self.hparams = self.load_hparams(model_dir) # # @staticmethod # def load_hparams(model_dir): # """Load hparams from an existing directory.""" # hparams_file = os.path.join(model_dir, "hparams.json") # if tf.gfile.Exists(hparams_file): # print("# Loading hparams from {} ...".format(hparams_file)) # with codecs.getreader("utf-8")(tf.gfile.GFile(hparams_file, "rb")) as f: # try: # hparams_values = json.load(f) # hparams = tf.contrib.training.HParams(**hparams_values) # except ValueError: # print("Error loading hparams file.") # return None # return hparams # else: # return None . Output only the next line.
self.hparams = HParams(corpus_dir).hparams