<commit_before># Copyright 2014 The Oppia Authors. 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.

"""Base model class."""

__author__ = '<NAME>'

from core.platform import models
transaction_services = models.Registry.import_transaction_services()
import feconf
import utils

from google.appengine.datastore import datastore_query
from google.appengine.ext import ndb

import datetime

class BaseModel(ndb.Model):
    """Base model for all persistent object storage classes."""

    # When this entity was first created.
    created_on = ndb.DateTimeProperty(auto_now_add=True, indexed=True)
    # When this entity was last updated.
    last_updated = ndb.DateTimeProperty(auto_now=True, indexed=True)
    # Whether the current version of the file is deleted.
    deleted = ndb.BooleanProperty(indexed=True, default=False)

    @property
    def id(self):
        """A unique id for this model instance."""
        return self.key.id()

    def _pre_put_hook(self):
        """This is run before model instances are saved to the datastore.

        Subclasses of BaseModel should override this method.
        """
        pass

    class EntityNotFoundError(Exception):
        """Raised when no entity for a given id exists in the datastore."""
        pass

    @classmethod
    def get(cls, entity_id, strict=True):
        """Gets an entity by id. Fails noisily if strict == True.

        Args:
          entity_id: str. The id of the entity.
          strict: bool. Whether to fail noisily if no entity with the given id
            exists in the datastore.

        Returns:
          None, if strict == False and no undeleted entity with the given id
          exists in the datastore. Otherwise, the entity instance that
          corresponds to the given id.

        Raises:
        - base_models.BaseModel.EntityNotFoundError: if strict == True and
            no undeleted entity with the given id exists in the datastore.
        """
        entity = cls.get_by_id(entity_id)
        if entity and entity.deleted:
            entity = None

        if strict and entity is None:
            raise cls.EntityNotFoundError(
                'Entity for class %s with id %s not found' %
                (cls.__name__, entity_id))
        return entity

    def put(self):
        super(BaseModel, self).put()

    @classmethod
    def get_multi(cls, entity_ids):
        entity_keys = [ndb.Key(cls, entity_id) for entity_id in entity_ids]
        return ndb.get_multi(entity_keys)

    @classmethod
    def put_multi(cls, entities):
        return ndb.put_multi(entities)

    def delete(self):
        super(BaseModel, self).key.delete()

    @classmethod
    def get_all(cls, include_deleted_entities=False):
        """Returns a filterable iterable of all entities of this class.

        If include_deleted_entities is True then entities that have been marked
        deleted are returned as well.
        """
        query = cls.query()
        if not include_deleted_entities:
            query = query.filter(cls.deleted == False)
        return query

    @classmethod
    def get_all_updated_within_timedelta(cls, timedelta):
        """Returns all instances that were updated at most timedelta time ago."""
        if not isinstance(timedelta, datetime.timedelta):
            raise ValueError("timedelta must be a datetime.timedelta instance.")

        first_date = datetime.datetime.now() - timedelta
        return cls.get_all().filter(cls.last_updated >= first_date)

    @classmethod
    def get_new_id(cls, entity_name):
        """Gets a new id for an entity, based on its name.

        The returned id is guaranteed to be unique among all instances of this
        entity.

        Args:
          entity_name: the name of the entity. Coerced to a utf-8 encoded
            string. Defaults to ''.

        Returns:
          str: a new unique id for this entity class.

        Raises:<commit_msg>removed get_all_updated_within_timedelta from base model.<commit_after># Copyright 2014 The Oppia Authors. 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.

"""Base model class."""

__author__ = '<NAME>'

from core.platform import models
transaction_services = models.Registry.import_transaction_services()
import feconf
import utils

from google.appengine.datastore import datastore_query
from google.appengine.ext import ndb

import datetime

class BaseModel(ndb.Model):
    """Base model for all persistent object storage classes."""

    # When this entity was first created.
    created_on = ndb.DateTimeProperty(auto_now_add=True, indexed=True)
    # When this entity was last updated.
    last_updated = ndb.DateTimeProperty(auto_now=True, indexed=True)
    # Whether the current version of the file is deleted.
    deleted = ndb.BooleanProperty(indexed=True, default=False)

    @property
    def id(self):
        """A unique id for this model instance."""
        return self.key.id()

    def _pre_put_hook(self):
        """This is run before model instances are saved to the datastore.

        Subclasses of BaseModel should override this method.
        """
        pass

    class EntityNotFoundError(Exception):
        """Raised when no entity for a given id exists in the datastore."""
        pass

    @classmethod
    def get(cls, entity_id, strict=True):
        """Gets an entity by id. Fails noisily if strict == True.

        Args:
          entity_id: str. The id of the entity.
          strict: bool. Whether to fail noisily if no entity with the given id
            exists in the datastore.

        Returns:
          None, if strict == False and no undeleted entity with the given id
          exists in the datastore. Otherwise, the entity instance that
          corresponds to the given id.

        Raises:
        - base_models.BaseModel.EntityNotFoundError: if strict == True and
            no undeleted entity with the given id exists in the datastore.
        """
        entity = cls.get_by_id(entity_id)
        if entity and entity.deleted:
            entity = None

        if strict and entity is None:
            raise cls.EntityNotFoundError(
                'Entity for class %s with id %s not found' %
                (cls.__name__, entity_id))
        return entity

    def put(self):
        super(BaseModel, self).put()

    @classmethod
    def get_multi(cls, entity_ids):
        entity_keys = [ndb.Key(cls, entity_id) for entity_id in entity_ids]
        return ndb.get_multi(entity_keys)

    @classmethod
    def put_multi(cls, entities):
        return ndb.put_multi(entities)

    def delete(self):
        super(BaseModel, self).key.delete()

    @classmethod
    def get_all(cls, include_deleted_entities=False):
        """Returns a filterable iterable of all entities of this class.

        If include_deleted_entities is True then entities that have been marked
        deleted are returned as well.
        """
        query = cls.query()
        if not include_deleted_entities:
            query = query.filter(cls.deleted == False)
        return query

    @classmethod
    def get_new_id(cls, entity_name):
        """Gets a new id for an entity, based on its name.

        The returned id is guaranteed to be unique among all instances of this
        entity.

        Args:
          entity_name: the name of the entity. Coerced to a utf-8 encoded
            string. Defaults to ''.

        Returns:
          str: a new unique id for this entity class.

        Raises:
{'fraction_non_alphanumeric': 0.07240934162656965, 'fraction_numerical': 0.0021124281187654033, 'mean_word_length': 2.6217594560135997, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2540421', 'n_tokens_mistral': 2301, 'n_tokens_neox': 2264, 'n_words': 901}