persist decorator and than continue to children without touching the model
172206
private void persistDecorator(XMLExtendedStreamWriter writer, ModelNode model) throws XMLStreamException {
       if (shouldWriteDecoratorAndElements(model)) {
           writer.writeStartElement(decoratorElement);
           persistChildren(writer, model);
           writer.writeEndElement();
       }
    }
681679
def save_inst(self, obj):
        """"""
        cls = obj.__class__

        # Try the dispatch table (pickle module doesn't do it)
        f = self.dispatch.get(cls)
        if f:
            f(self, obj)  # Call unbound method with explicit self
            return

        memo = self.memo
        write = self.write
        save = self.save

        if hasattr(obj, '__getinitargs__'):
            args = obj.__getinitargs__()
            len(args)  # XXX Assert it's a sequence
            pickle._keep_alive(args, memo)
        else:
            args = ()

        write(pickle.MARK)

        if self.bin:
            save(cls)
            for arg in args:
                save(arg)
            write(pickle.OBJ)
        else:
            for arg in args:
                save(arg)
            write(pickle.INST + cls.__module__ + '\n' + cls.__name__ + '\n')

        self.memoize(obj)

        try:
            getstate = obj.__getstate__
        except AttributeError:
            stuff = obj.__dict__
        else:
            stuff = getstate()
            pickle._keep_alive(stuff, memo)
        save(stuff)
        write(pickle.BUILD)
670635
private void persistRealmChanges() {
    configManager.persistProperties(realm.getProperties(), new File(applicationContentDir, PersistablePropertiesRealm.REALM_FILE_NAME), null);
  }
323406
def thread_safe(method):
    

    @functools.wraps(method)
    def _locker(self, *args, **kwargs):
        assert hasattr(self, 'lock'), \
            'thread_safe decorator applied to method {0}.{1}: missing required field {0}.lock'\
            .format(self.__class__.__name__, method.__name__)

        try:
            self.lock.acquire()
            return method(self, *args, **kwargs)
        finally:
            try:
                self.lock.release()
            except:
                sys.stderr.write('Exception on releasing lock at method {0}'.format(method.__name__))
                traceback.print_exc(file=sys.stderr)

    return _locker
591307
def _preserve_settings(method: T.Callable) -> T.Callable:
    """"""

    @functools.wraps(method)
    def _wrapper(
            old: "ObservableProperty", handler: T.Callable
    ) -> "ObservableProperty":
        new = method(old, handler)  # type: ObservableProperty
        new.event = old.event
        new.observable = old.observable
        return new

    return _wrapper
978829
def behavior(f):
    
    @wraps(f)
    def wrapper(*args):
        message = args[-1]
        if isinstance(message, MutableMapping):
            message = Message(message)
        f(*(args[:-1] + (message,)))
    return wrapper
12302
def keep_alive(self, val: bool) -> None:
        
        self._keepalive = val
        if self._keepalive_handle:
            self._keepalive_handle.cancel()
            self._keepalive_handle = None
859727
def _make_persistent(self, model_name, pkg_name):
        """"""

        #
        # WARNING: ugly piece of monkey-patching below. Hopefully will replace
        # with native bravado-core code in the future...
        #

        # Load class at path pkg_name
        c = get_function(pkg_name)
        for name in ('load_from_db', 'save_to_db'):
            if not hasattr(c, name):
                raise PyMacaronCoreException("Class %s has no static method '%s'" % (pkg_name, name))

        log.info("Making %s persistent via %s" % (model_name, pkg_name))

        # Replace model generator with one that adds 'save_to_db' to every instance
        model = getattr(self.model, model_name)
        n = self._wrap_bravado_model_generator(model, c.save_to_db, pkg_name)
        setattr(self.model, model_name, n)

        # Add class method load_from_db to model generator
        model = getattr(self.model, model_name)
        setattr(model, 'load_from_db', c.load_from_db)
1078598
def synchronized(fn):
    '''
    
    '''
    lock = threading.Lock()

    @functools.wraps(fn)
    def decorated(*args, **kwargs):
        lock.acquire()
        try:
            return fn(*args, **kwargs)
        finally:
            lock.release()

    return decorated
652522
def ensure_state(default_getter, exc_class, default_msg=None):
    """"""
    def decorator(getter=default_getter, msg=default_msg):
        def ensure_decorator(f):
            @wraps(f)
            def inner(self, *args, **kwargs):
                if not getter(self):
                    raise exc_class(msg) if msg else exc_class()
                return f(self, *args, **kwargs)
            return inner
        return ensure_decorator
    return decorator
386936
def get_to_persist(persisters):
    
    def specs():
        for p in persisters:
            if isinstance(p, dict):
                yield p["name"], p.get("enabled", True)
            else:
                yield p, True

    components = sorted(dr.DELEGATES, key=dr.get_name)
    names = dict((c, dr.get_name(c)) for c in components)

    results = set()
    for p, e in specs():
        for c in components:
            if names[c].startswith(p):
                if e:
                    results.add(c)
                elif c in results:
                    results.remove(c)
    return results
452025
def wrap_sync(func):
    """"""
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        fut = asyncio.Future()
        def green():
            try:
                fut.set_result(func(*args, **kwargs))
            except BaseException as e:
                fut.set_exception(e)
        greenlet.greenlet(green).switch()
        return fut
    return wrapped
1133788
def saveit(func):
    """"""

    name = '_' + func.__name__

    def _wrapper(self, *args, **kwds):
        if not hasattr(self, name):
            setattr(self, name, func(self, *args, **kwds))
        return getattr(self, name)
    return _wrapper
27640
def _persist(self):
        """"""
        with open(self.file, 'w') as f:
            json.dump({
                'client': self.client,
                'creds': self.creds,
                'config': self.config
            }, f)
1232835
function persist(client, next) {
    var single = isModel(item)
      , data;

    switch (method) {
      case 'create':
        data = single ? [ item.clone() ] : item.clone().models;
        client.insert(pluck(data), config, function inserted(error, results) {
          if (error) return next(error);

          //
          // Set the _stored property for each model to true.
          //
          results.forEach(function each(model) {
            if (single) return item.stored = model._id;
            item.id(model._id).stored = model._id;
          });

          next(null, results);
        });
      break;

      case 'read':
        //
        // Models will be read by Model _id if no query was passed or if
        // the Model already exists in the database. This would otherwise
        // result in data ambiguity.
        //
        query = query || {};
        if (single && item.id) query._id = item.id;

        //
        // No query and Model has no ObjectId reference, return early.
        //
        if (single && !Object.keys(query).length) return next(null, null);

        //
        // Read the documents from the MongoDB database and process
        // the results, depending on the item being a Model or Collection.
        //
        client.find(query, config).toArray(function found(error, results) {
          if (error) return next(error);
          if (single) results = results[0];

          //
          // If the item is a model, parse first. After merge the results
          // of the read operation in the current item.
          //
          if (single && options.parse) results = item.parse(results, options);
          item.set(results);

          next(null, results);
        });
      break;

      case 'update':
      case 'patch':
        data = single ? [ item ] : item.models;
        async.reduce(data, 0, function loopModels(memo, model, fn) {
          model = model.clone();
          var update = { $set: pluck(model) };
          if (config.upsert) update = pluck(model);

          client.update({ _id: model.id }, update, config, function updated(error, results) {
            if (error) return next(error);

            model.stored = model.id;
            fn(null, memo + results);
          });
        }, next);
      break;

      case 'delete':
        data = single ? [ item ] : item.models;
        async.reduce(data, 0, function loopModels(memo, model, fn) {
          client.remove({ _id: model.id }, config, function updated(error, results) {
            if (error) return fn(error);

            //
            // Update the stored state properties to false.
            //
            model.stored = false;
            fn(null, memo + results);
          });
        }, next);
      break;
    }
  }
475383
def serializable(wrapped):
    

    @wraps(wrapped)
    def wrapper(*args, **kwargs):
        should_serialize = kwargs.pop('serialize', False)
        result = wrapped(*args, **kwargs)

        return serialize(result) if should_serialize else result

    if hasattr(wrapped, 'decorators'):
        wrapper.decorators = wrapped.decorators
        wrapper.decorators.append('serializable')
    else:
        wrapper.decorators = ['serializable']

    return wrapper
1217593
def bind(self, __fun, *args, **kwargs):
    

    with self._lock:
      if self._running or self._completed or self._cancelled:
        raise RuntimeError('Future object can not be reused')
      if self._worker:
        raise RuntimeError('Future object is already bound')
      self._worker = functools.partial(__fun, *args, **kwargs)
    return self