Function to call before saving the model

Cleans up values of types date, time and timestamp

Turns empty values to null
516602
public function preSave() {
        $this->getCachedSettings();
        foreach ($this->toArray() as $ppt => $val) {
            $settingKey = \Util::_toCamel($ppt);
            if (@$this->settings[$settingKey]['type'] === 'ReferenceMany' && !empty($val)) {
                if (is_object($val) && is_a($val, 'DBScribe\ArrayCollection')) {
                    $val = $val->getArrayCopy();
                }

                $idSep = '__:DS:__';

                $ids = '';
                if (is_array($val)) {
                    foreach ($val as $vl) {
                        if (is_object($vl) && is_a($vl, 'DBScribe\Row')) {
                            if (!isset($vl->id)) {
                                throw new Exception('ReferenceMany requires that all objects must have an ID');
                            }
                            if (method_exists($vl, 'getId')) {
                                $vl = $vl->getId();
                            }
                            else {
                                $vl = $vl->id;
                            }
                        }

                        if (is_null($vl)) {
                            throw new Exception('ReferenceMany objects CANNOT have a null ID');
                        }

                        $ids .= (!empty($ids)) ? $idSep . $vl : $vl;
                    }

                    $this->$settingKey = $ids;
                    $val = $this->$settingKey;
                }
            }
            else if (strtolower(@$this->settings[$settingKey]['type']) === 'date' && !empty($val) && !strstr($val, '0000')) {
                $this->$settingKey = Util::createTimestamp(strtotime($val), 'Y-m-d');
                $val = $this->$settingKey;
            }
            elseif (strtolower(@$this->settings[$settingKey]['type']) === 'time' && !empty($val) && !strstr($val, '0000')) {
                $this->$settingKey = Util::createTimestamp(strtotime($val), 'H:i');
                $val = $this->$settingKey;
            }
            elseif (strtolower(@$this->settings[$settingKey]['type']) === 'timestamp' && !empty($val) && !strstr($val, '0000')) {
                $this->$settingKey = Util::createTimestamp(strtotime($val), 'Y-m-d H:i:s');
                $val = $this->$settingKey;
            }

            if (empty($val) && $val != 0) {
                if (!property_exists($this, $ppt))
                    $ppt = Util::_toCamel($ppt);
                $this->$ppt = null;
            }
        }

        if (!$this->getConnection() && $this->_table) {
            $this->setConnection($this->_table->getConnection());
            $table = $this->_table->getConnection()->table($this->getTableName());
            $this->init($table);
        }

        parent::preSave();
    }
977385
def clean(self, value):
        """"""

        if not isinstance(value, six.string_types):
            raise ParameterNotValidError

        try:
            source, value = value.split('://', 1)
        except ValueError:
            raise ParameterNotValidError

        if source == 'service':
            if '@' in value:
                value, timestamp = value.split('@', 1)

                try:
                    service_time = timestamp_to_date(int(timestamp))
                except ValueError:
                    raise ParameterNotValidError
            else:
                service_time = None

            if ':' in value:
                service_name, variable_name = value.split(':', 1)
            else:
                service_name = value
                variable_name = None

            try:
                self.service = Service.objects.get(name=service_name)
            except ObjectDoesNotExist:
                raise ParameterNotValidError("Service '{}' not found".format(service_name))

            if variable_name:
                try:
                    variable = self.service.variable_set.all().get(variable=variable_name)
                except ObjectDoesNotExist:
                    raise ParameterNotValidError("Variable '{}' not found".format(variable_name))

                if service_time is not None:
                    time_index = best_fit(variable.time_stops, service_time)
                else:
                    time_index = None

                data = self.get_grid_for_variable(variable, time_index=time_index)
                return Raster(data, variable.full_extent, 1, 0, self.is_y_increasing(variable))
            else:
                return self.dataset
        else:
            raise ParameterNotValidError('Invalid source: {}'.format(source))
28033
def pre_save(self, instance, add):
        
        if not self.natural_text_field or self.attname not in instance.__dict__:
            return

        edtf = getattr(instance, self.attname)

        # Update EDTF field based on latest natural text value, if any
        natural_text = getattr(instance, self.natural_text_field)
        if natural_text:
            edtf = text_to_edtf(natural_text)
        else:
            edtf = None

        # TODO If `natural_text_field` becomes cleared the derived EDTF field
        # value should also be cleared, rather than left at original value?

        # TODO Handle case where EDTF field is set to a string directly, not
        # via `natural_text_field` (this is a slightly unexpected use-case, but
        # is a very efficient way to set EDTF values in situations like for API
        # imports so we probably want to continue to support it?)
        if edtf and not isinstance(edtf, EDTFObject):
            edtf = parse_edtf(edtf, fail_silently=True)

        setattr(instance, self.attname, edtf)
        # set or clear related date fields on the instance
        for attr in DATE_ATTRS:
            field_attr = "%s_field" % attr
            g = getattr(self, field_attr, None)
            if g:
                if edtf:
                    try:
                        target_field = instance._meta.get_field(g)
                    except FieldDoesNotExist:
                        continue
                    value = getattr(edtf, attr)()  # struct_time
                    if isinstance(target_field, models.FloatField):
                        value = struct_time_to_jd(value)
                    elif isinstance(target_field, models.DateField):
                        value = struct_time_to_date(value)
                    else:
                        raise NotImplementedError(
                            u"EDTFField does not support %s as a derived data"
                            u" field, only FloatField or DateField"
                            % type(target_field))
                    setattr(instance, g, value)
                else:
                    setattr(instance, g, None)
        return edtf
710986
def get_db_prep_save(self, value, connection, **kwargs):
        """"""
        if value is None and self.null:
            return None
        # default values come in as strings; only non-strings should be
        # run through `dumps`
        if not isinstance(value, six.string_types):
            value = dumps(value)

        return value
1189500
def timestamps!
      [:created_at, :updated_at].each do |name|
        _add_key(name)
        attr_reader name
        class_eval(<<-RUBY, __FILE__, __LINE__)
          def #{name}=(value)                       # def created_at=(value)
            if value.kind_of?(String)               #   if value.kind_of?(String)
              value = Time.cast_from_string(value)  #     value = Time.cast_from_string(value)
            end                                     #   end
            @#{name} = value.nil? ? nil : value.utc #   @created_at = value.nil? ? nil : value.utc
          end                                       # end
        RUBY
      end

      class_eval(<<-RUBY, __FILE__, __LINE__)
        def _save(safe)
          if new_record?
            self.created_at = self.updated_at = Time.now
          else
            original_updated_at = updated_at
            self.updated_at = Time.now
          end
          super
        rescue Mongo::MongoDBError => e
          if new_record?
            self.created_at = self.updated_at = nil
          else
            self.updated_at = original_updated_at
          end
          raise e
        end

        def _update(selector, data, safe)
          original_updated_at = updated_at
          self.updated_at = Time.now
          data[:updated_at] = updated_at
          super
        rescue Mongo::MongoDBError => e
          self.updated_at = original_updated_at
          raise e
        end
      RUBY
    end
935206
function() {
            if (self._disposed) {
                clearTimeout(timeout)
                timeout = self = null
                return
            }

            var last = getTime() - timestamp

            if (last < wait && last >= 0) {
                timeout = setTimeout(later, wait - last)
            } else {
                timeout = null
                // result = func.apply(context, args)
                func()
                // context = args = null
            }
        }
1114662
function translateDateTimestamp(timestamp) {
    if (!timestamp) {
        LOG.warn("Received an invalid timestamp: {}", timestamp);
        return Date.now();
    }

    return new Date(timestamp);
}
614172
function serializeValue(value) {

    var type;
    if ( _.isNull(value) ) {
        type = ColumnType.Object;
    } else if ( _.isNumber(value) ) {
        type = ColumnType.Real;
    } else if ( _.isDate(value) ) {
        type = ColumnType.Date;
    } else if ( _.isBool(value) ) {
        type = ColumnType.Boolean;
    } else if ( _.isString(value) ) {
        type = ColumnType.String;
    } else if ( _.isArray(value) ) {
        type = ColumnType.Array;
    } else if ( _.isObject(value) ) {
        type = ColumnType.Object;
    } else {
        type = ColumnType.Object;
    }

    return serializeMember(value, type);
}
1090914
def pre_save(self, model_instance, add):
        
        # pylint: disable=newstyle
        # Retrieve the currently entered datetime
        value = super(
            LinkedTZDateTimeField,
            self
        ).pre_save(
            model_instance=model_instance,
            add=add
        )

        # Convert the value to the correct time/timezone
        value = self._convert_value(
            value=value,
            model_instance=model_instance,
            add=add
        )

        setattr(model_instance, self.attname, value)

        return value
1369308
function _handleDataReset() {
    storage.removeDataByKey(savedDataKey);

    let data = getCurrentData();

    dataEditor.setValue(prettifyJson(data));
}
1653
public function beforeSave()
    {
        if ($this->file instanceof UploadedFile) {

            if (true !== $this->owner->isNewRecord) {
                /** @var ActiveRecord $oldModel */
                $oldModel = $this->owner->findOne($this->owner->primaryKey);
                $behavior = static::getInstance($oldModel, $this->attribute);
                $behavior->cleanFiles();
            }

            $this->owner->{$this->attribute} = implode('.',
                array_filter([$this->file->baseName, $this->file->extension])
            );
        } else {
            if (true !== $this->owner->isNewRecord && empty($this->owner->{$this->attribute})) {
                $this->owner->{$this->attribute} = ArrayHelper::getValue($this->owner->oldAttributes, $this->attribute,
                    null);
            }
        }
    }
1277075
function save(val) {
  if(Array.isArray(val)) {
    val.forEach(function(item) {
      var seconds = item[0]
        , changes = item[1];
      if(seconds < 1 || changes < 0) {
        throw new Error('Invalid save parameters');
      }
    })
  }
}
17298
function toTimestamp(date) {
    var value =
        (typeof date === 'number') ? date :           // number
        (date instanceof Date)     ? date.valueOf() : // Date
        new Date(date).valueOf();                     // ISOString, momentjs, ...

    if (isNaN(value)) {
      throw new TypeError('Invalid date ' + JSON.stringify(date) + '. ' +
          'Date, number, or ISOString expected');
    }

    return value;
  }
89713
function(value) {
    var d = FxoUtils.parseDateTimeField(value);
    return d.valid ? d.parsed.getTime() : NaN;
  }
1201157
function normalizeAttributes(attrs, strip) {

            // map for converting SQL types to Sequelize DataTypes.
            var map = {
                    TINYINT: 'BOOLEAN',
                    DATETIME: 'DATE',
                    TIMESTAMP: 'DATE',
                    'VARCHAR BINARY': 'STRING.BINARY',
                    'TINYBLOB': 'BLOB',
                    VARCHAR: 'STRING[LEN]',
                    'INTEGER UNSIGNED ZEORFILL': 'INTEGER[LEN].UNSIGNED.ZEROFILL',
                    'INTEGER UNSIGNED': 'INTEGER[LEN].UNSIGNED',
                    'INTEGER ZEROFILL': 'INTEGER[LEN].ZEROFILL',
                    INTEGER: 'INTEGER[LEN]',
                    'FLOAT UNSIGNED ZEORFILL': 'FLOAT[LEN].UNSIGNED.ZEROFILL',
                    'FLOAT ZEROFILL': 'FLOAT[LEN].ZEROFILL',
                    'FLOAT UNSIGNED': 'FLOAT[LEN].UNSIGNED',
                    FLOAT: 'FLOAT[LEN]',
                    'BIGINT UNSIGNED ZEORFILL': 'BIGINT[LEN].UNSIGNED.ZEROFILL',
                    'BIGINT ZEROFILL': 'BIGINT[LEN].ZEROFILL',
                    'BIGINT UNSIGNED': 'BIGINT[LEN].UNSIGNED',
                    BIGINT: 'BIGINT[LEN]',
                    DECIMAL: 'DECIMAL[LEN]',
                    ENUM: 'ENUM'
                },
                mapKeys = Object.keys(map);

            strip = strip || [];
            strip.push('Model');

            // convert and format to Sequelize Model Type.
            function getType(type, len, name) {

                if(!type) return undefined;
                type = type.split('(')[0];

                if(map[type]){
                    var tmp = map[type];
                    if(len && !_.contains([255, 11], len)) len = '(' + len + ')';
                    else len = '';
                    type = tmp.replace('[LEN]', len);
                }

                return type;
            }

            // iterate properties.
            for(var prop in attrs) {

                if(attrs.hasOwnProperty(prop)){

                    var attr = attrs[prop],
                        type = attr.type,
                        prec = type._precision && type._scale ? type._precision + ',' + type._scale : false,
                        len = prec ? prec : type._length || false;

                    // strip properties.
                    strip.forEach(function (s) {
                        if(attr[s]) delete attr[s];
                    });

                    if(attr.validate && attr.validate._checkEnum)
                        type = 'ENUM';

                    if(!type._binary && type._length)
                        type = 'VARCHAR';

                    if(type._binary)
                        type = 'VARCHAR BINARY';

                    if(_.contains(['INTEGER', 'FLOAT', 'BIGINT'], type._typeName)){
                        var tmp = '';
                        tmp = type._unsigned ? tmp += ' UNSIGNED' : tmp;
                        tmp = type._zerofill ? tmp += ' ZEROFILL' : tmp;
                        type = type._typeName + tmp;

                    }

                    if(_.isObject(type))
                        type = type._typeName;

                    attrs[prop].type = getType(type, len, attr.fieldName);

                }

            }

            return attrs;
        }
900049
function prepareModel(modelObj) {
    /* BEFORE save */
    function onSave(iObj, opt, fn) {
      /* Check if crypto is disabled */
      if (typeof opt === 'object' && opt && opt.crypto === false) return fn();
      /* for each field, check if we have to encrypt*/
      let encrypted = modelObj.getEncrypted();
      for (let i = 0, len = encrypted.length; i < len; i++) {
        let fieldName = encrypted[i],
          fieldValue = iObj.getDataValue(fieldName);
        if (typeof fieldValue === 'undefined') {  // check default value;
          let _default = modelObj.fields[fieldName]._default;
          if (typeof _default !== 'undefined' && _default != null) {
            fieldValue = (typeof _default === 'function' ? _default() : _default);
          }
        }
        if (typeof fieldValue === 'undefined' || fieldValue === null) continue;
        // we now place it encrypted.
        if (crypto.isEncrypted(fieldValue)) continue;
        let enc = crypto.encrypt(fieldValue, opt.key);
        if (enc === null) continue;
        if (!iObj._changed[fieldName]) continue;
        iObj.setDataValue(fieldName, enc);
        if (typeof iObj.__original_encrypted === 'undefined') {
          iObj.__original_encrypted = {};
        }
        iObj.__original_encrypted[fieldName] = fieldValue;
      }
      if (typeof fn === 'function') {
        fn();
      }
    }

    function onSaved(iObj) {
      if (typeof iObj.__original_encrypted === 'undefined') return;
      let fields = Object.keys(iObj.__original_encrypted);
      for (let i = 0, len = fields.length; i < len; i++) {
        let fieldName = fields[i],
          fieldValue = iObj.__original_encrypted[fieldName];
        iObj.setDataValue(fieldName, fieldValue);
      }
      delete iObj.__original_encrypted;
    }

    /*
     * Changes the WHERE statement.
     * */
    function prepareWhere(opt, _modelObj) {
      if (!_modelObj) _modelObj = modelObj;
      if (!_modelObj) return;
      if (typeof _modelObj.isEncrypted !== 'function') {
        _modelObj = storeObj.model(storeObj.camelize(_modelObj.name), true);
      }
      /* Check if crypto is disabled */
      if (opt.crypto === false) return;
      if (typeof opt.where !== 'object' || !opt.where) return;
      let fields = Object.keys(opt.where);
      for (let i = 0, len = fields.length; i < len; i++) {
        let fieldName = fields[i];
        // Check for inner $and operator
        if (fieldName === '$and') {
          let tmp = {
            where: opt.where[fieldName],
            key: opt.key
          };
          prepareWhere(tmp, _modelObj);
          continue;
        }
        // Check for inner $or operator
        if (fieldName === '$or' && opt.where[fieldName] instanceof Array) {
          for (let j = 0, jlen = opt.where[fieldName].length; j < jlen; j++) {
            let tmp = {
              where: opt.where[fieldName][j],
              key: opt.key
            };
            prepareWhere(tmp, _modelObj);
          }
          continue;
        }
        if (!_modelObj.isEncrypted(fieldName)) continue;
        let fieldValue = opt.where[fieldName];
        let fieldValueType = typeof fieldValue;
        if (fieldValueType === 'undefined' || fieldValue === null) continue;
        if (fieldValue instanceof Array) {
          let tmp = [];
          for (let i = 0, len = fieldValue.length; i < len; i++) {
            let val = fieldValue[i],
              type = typeof val;
            if (type === 'number' || type === 'boolean') {
              val = val.toString();
              type = 'string';
            }
            if (type !== 'string') {
              tmp.push(val);
              continue;
            }
            if (crypto.isEncrypted(val)) {
              tmp.push(val);
              continue;
            }
            let enc = crypto.encrypt(val, opt.key);
            if (enc === null) continue;
            tmp.push(enc);
          }
          opt.where[fieldName] = tmp;
        } else if (fieldValueType === 'object') {
          // this is some kind of operator/aggregator
          let $ops = Object.keys(fieldValue);
          for (let j = 0, llen = $ops.length; j < llen; j++) {
            let opName = $ops[j],
              opValue = fieldValue[opName];
            // Special op: %
            if (opName === '$like') {
              if (!crypto.isEncrypted(opValue)) {
                if (opValue.charAt(0) === '%') opValue = opValue.substr(1);
                if (opValue.charAt(opValue.length - 1) === '%') opValue = opValue.substr(0, opValue.length - 1);
                opValue = crypto.encrypt(opValue, opt.key);
                fieldValue[opName] = opValue;
              }
            } else if (INNER_OPERATORS.indexOf(opName) !== -1) {
              if (opValue instanceof Array) {
                for (let k = 0, klen = opValue.length; k < klen; k++) {
                  if (!crypto.isEncrypted(opValue[k])) {
                    let enc = crypto.encrypt(opValue[k], opt.key);
                    if (enc != null) {
                      opValue[k] = enc;
                    }
                  }
                }
              } else if (!crypto.isEncrypted(opValue)) {
                let enc = crypto.encrypt(opValue, opt.key);
                if (enc === null) continue;
                fieldValue[opName] = enc;
              }
            }
          }
        } else {
          if (crypto.isEncrypted(fieldValue)) continue;
          let enc = crypto.encrypt(fieldValue, opt.key);
          if (enc === null) continue;
          opt.where[fieldName] = enc;
        }
      }
    }

    /*
     * Looks for JOINS in the include field
     * */
    function prepareInclude(opt) {
      if (opt.crypto === false) return;
      if (typeof opt.include === 'undefined') return;
      if (opt.include instanceof Array) {
        for (let i = 0, len = opt.include.length; i < len; i++) {
          singleInclude(opt.include[i]);
        }
      } else if (typeof opt.include === 'object' && opt.include) {
        singleInclude(opt.include);
      }
    }

    function singleInclude(obj) {
      if (typeof obj !== 'object' || !obj) return;
      if (typeof obj.where === 'object' && obj.where) {
        prepareWhere(obj, obj.model);
      }
      if (typeof obj.include !== 'undefined') {
        prepareInclude(obj);
      }
    }

    function bulkChanges(opt, fn) {
      if (opt.crypto === false) return fn();
      // first check for encrypted where's
      if (typeof opt.where === 'object' && opt.where) {
        prepareWhere(opt);
      }
      if (typeof opt.attributes === 'object' && opt.attributes) {
        let fields = Object.keys(opt.attributes);
        for (let i = 0, len = fields.length; i < len; i++) {
          let fieldName = fields[i];
          if (!modelObj.isEncrypted(fieldName)) continue;
          let fieldValue = opt.attributes[fieldName];
          if (typeof fieldValue === 'undefined' || fieldValue === null) continue;
          if (crypto.isEncrypted(fieldValue)) continue;
          let enc = crypto.encrypt(fieldValue, opt.key);
          if (enc === null) continue;
          opt.attributes[fieldName] = enc;
        }
      }
      fn();
    }

    /*
     * Hook inside the findAll()
     * */
    function alterMultiFind(opt, fn) {
      if (typeof opt !== 'object' || !opt) return fn(opt);
      if (opt.crypto === false) return fn(opt);
      prepareWhere(opt);
      prepareInclude(opt);
      if (opt.raw !== true) {
        return fn(opt);
      }
      return fn(opt).then((items) => {
        if (items.length === 0) return items;
        for (let i = 0, len = items.length; i < len; i++) {
          let item = items[i],
            fields = Object.keys(item);
          for (let j = 0, llen = fields.length; j < llen; j++) {
            let fieldValue = item[fields[j]];
            if (crypto.isEncrypted(fieldValue)) {
              let encr = crypto.decrypt(fieldValue, opt.key);
              if (encr) {
                item[fields[j]] = encr;
              }
            }
          }
        }
        return items;
      });
    }

    function alterSingleFind(opt, fn) {
      if (typeof opt !== 'object' || !opt) return fn(opt);
      if (opt.crypto === false) return fn(opt);
      prepareWhere(opt);
      prepareInclude(opt);
      if (opt.raw !== true) return fn(opt);
      return fn(opt).then((item) => {
        if (typeof item !== 'object' || !item) return item;
        let fields = Object.keys(item);
        for (let j = 0, llen = fields.length; j < llen; j++) {
          let fieldValue = item[fields[j]];
          if (crypto.isEncrypted(fieldValue)) {
            let encr = crypto.decrypt(fieldValue, opt.key);
            if (encr) {
              item[fields[j]] = encr;
            }
          }
        }
        return item;
      });
    }

    function alterOrFind(opt, instance, fn) {
      if (typeof opt !== 'object' || !opt) return fn(opt);
      if (opt.crypto === false) return fn(opt);
      prepareWhere(opt);
      prepareInclude(opt);
      return fn(opt, instance);
    }

    function alterCount(opt, fn, _hasRows) {
      if (typeof opt !== 'object' || !opt) return fn(opt);
      if (opt.crypto === false) return fn(opt);
      prepareWhere(opt);
      prepareInclude(opt);
      if (opt.raw !== true || _hasRows !== true) return fn(opt);
      return fn(opt).then((res) => {
        if (typeof res !== 'object' || !res) return res;
        if (!(res.rows instanceof Array)) return res;
        for (let i = 0, len = res.rows.length; i < len; i++) {
          let item = res.rows[i],
            fields = Object.keys(item);
          for (let j = 0, llen = fields.length; j < llen; j++) {
            let fieldValue = item[fields[j]];
            if (crypto.isEncrypted(fieldValue)) {
              let encr = crypto.decrypt(fieldValue, opt.key);
              if (encr) {
                item[fields[j]] = encr;
              }
            }
          }
        }
        return res;
      });
    }

    /*
     * Recursively decrypt entity data
     * */
    function decryptEntity(data, modelObj) {
      if (typeof data !== 'object' || !data) return;
      let encrypted = modelObj.getEncrypted();
      for (let i = 0, len = encrypted.length; i < len; i++) {
        let fieldName = encrypted[i],
          fieldValue = data[fieldName];
        if (typeof fieldValue !== 'string') continue;
        if (!crypto.isEncrypted(fieldValue)) continue;
        let decrypted = crypto.decrypt(fieldValue, opt.key);
        if (decrypted === null) {
          logger.warn(`Could not decrypt field ${fieldName} of entity`);
          logger.debug(data);
          continue;
        }
        data[fieldName] = decrypted;
      }
      /* now check foreign relations */
      if (!modelObj.hasRelationFields()) return;
      let relations = modelObj.getRelationFields();
      for (let i = 0, len = relations.length; i < len; i++) {
        let relation = relations[i];
        if (typeof data[relation.field] === 'undefined') continue;
        let relationModel = storeObj.model(relation.model, true);
        if (!relationModel.hasEncryptedFields()) continue;
        if (data[relation.field] instanceof Array) {
          for (let j = 0; j < data[relation.field].length; j++) {
            decryptEntity(data[relation.field][j], relationModel);
          }
        } else if (typeof data[relation.field] === 'object' && data[relation.field]) {
          decryptEntity(data[relation.field], relationModel);
        }
      }
    }

    function bindToStore(storeObj) {
      let Instance = modelObj.getInstance();
      const names = [
        'findAll', 'findById', 'findOne', 'find', 'findAndCount',
        'count', 'sum', 'max', 'min'
      ];
      names.forEach((name) => {
        let baseFn = Instance[name].bind(Instance);
        switch (name) {
          case 'findAll':
            Instance[name] = function EncryptedFindWrapper(opt) {
              return alterMultiFind(opt, baseFn);
            };
            break;
          case 'find':
          case 'findById':
          case 'findOne':
            Instance[name] = function EncryptedReadWrapper(opt) {
              return alterSingleFind(opt, baseFn);
            };
            break;
          case 'findAndCount':
            Instance[name] = function EncryptedCountWrapper(opt) {
              return alterCount(opt, baseFn, true);
            };
            break;
          case 'findOrCreate':
          case 'findOrInitialize':
            Instance[name] = function EncryptedFindWrapper(opt, instance) {
              return alterOrFind(opt, instance, baseFn);
            };
            break;
          case 'count':
            Instance[name] = function EncryptedCountWrapper(opt) {
              if (typeof opt !== 'object' || !opt) return baseFn(opt);
              if (opt.crypto === false) return baseFn(opt);
              prepareWhere(opt);
              prepareInclude(opt);
              return baseFn(opt);
            };
            break;
          case 'sum':
          case 'min':
          case 'max':
            Instance[name] = function EncryptedFuncWrapper(field, opt) {
              if (typeof opt !== 'object' || !opt) return baseFn(field, opt);
              if (opt.crypto === false) return baseFn(field, opt);
              prepareWhere(opt);
              prepareInclude(opt);
              return baseFn(field, opt);
            };
            break;
        }
      });

      /* Override the default Build() function */
      let _build = Instance.build.bind(Instance);
      Instance.build = function (values, opt) {
        decryptEntity(values, modelObj);
        return _build(values, opt);
      };
    }

    bindToStore(storeObj);

    modelObj
      .hook('beforeBulkCreate', (instances, opt, fn) => {
        for (let i = 0, len = instances.length; i < len; i++) {
          onSave(instances[i], opt);
        }
        fn();
      })
      .hook('afterBulkCreate', (instances) => {
        for (let i = 0, len = instances.length; i < len; i++) {
          onSaved(instances[i]);
        }
      })
      .hook('beforeBulkUpdate', bulkChanges)
      .hook('beforeBulkDestroy', bulkChanges);

    modelObj
      .hook('beforeCreate', onSave)
      .hook('afterCreate', onSaved)
      .hook('beforeUpdate', onSave)
      .hook('afterUpdate', onSaved);
  }
1006810
def process_formdata(self, valuelist):
        """"""
        if valuelist:
            time_str = u' '.join(valuelist)
            try:
                timetuple = time.strptime(time_str, self.format)
                self.data = datetime.time(*timetuple[3:6])
            except ValueError:
                self.data = None
                raise