Function to generate a storage object for a given namespace

@param {Object} client The redis client
@param {String} namespace The namespace to use for storing in Redis
@returns {{get: get, save: save, all: all, allById: allById}}
494411
function getStorageObj(client, namespace) {
    return {
        get: function(id, cb) {
            client.hget(namespace, id, function(err, res) {
                cb(err, res ? JSON.parse(res) : null);
            });
        },
        save: function(object, cb) {
            if (!object.id) {
                return cb(new Error('The given object must have an id property'), {});
            }

            client.hset(namespace, object.id, JSON.stringify(object), cb);
        },
        remove: function(id, cb) {
            client.hdel(namespace, [id], cb);
        },
        all: function(cb, options) {
            client.hgetall(namespace, function(err, res) {
                if (err) {
                    return cb(err);
                }

                var parsed,
                    array = [];

                for (var i in res) {
                    parsed = JSON.parse(res[i]);
                    res[i] = parsed;
                    array.push(parsed);
                }

                cb(null, options && options.type === 'object' ? res : array);
            });
        }
    };
}
376508
function(key, value) {
		if (value === undefined) {
			return this.remove(key)
		}
		this.storage.write(this._namespacePrefix + key, this._serialize(value))
		return value
	}
1082200
function RedisWrapper(opt, key) {
	return {
		_promise: new Promise(
			(resolve, reject) => opt.redis.hget(
				opt.namespace,
				key,
				(err, json) => {
					if (err) {
						reject(err);
						return;
					}
					try {
						const val = opt.deserialize(json);
						resolve(val);
					} catch (e) {
						reject(e);
					}
				}
			),
			[]
		),
		tree: []
	};
}
1351953
function(key, dest, containerName) {

      // Attempt to connect to redis
      return getRedisClient()

      // Run the redis query and then quit
      .then(function(redis) {
        log.debug(format('Setting DNS. %s => %s', key, dest));
        return Promise.fromNode(function(cb) {
          redis.multi()
          .del(key)
          .rpush(key, containerName)
          .rpush(key, dest)
          .exec(cb);
        })
        .then(function() {
          redis.quit();
        });
      });

    }
617391
public function getZendStorage(string $namespace = 'default')
    {
        static $storages = [];
        
        if (!isset($storages[$namespace])) {
            $rrm = new RedisResourceManager();
            $rrm->setResource('default', $this->getRedis());
            $rrm->setLibOption('default', Redis::OPT_SERIALIZER, $this->redis->getOption(Redis::OPT_SERIALIZER));
            $options = new RedisOptions();
            $options->setResourceManager($rrm);
            $storages[$namespace] = new RedisAdapter($options);
        }
        return $storages[$namespace];
    }
255489
def _get_namespaces(apiserver_url, name=""):
    ''''''
    # Prepare URL
    url = "{0}/api/v1/namespaces/{1}".format(apiserver_url, name)
    # Make request
    ret = http.query(url)
    if ret.get("body"):
        return salt.utils.json.loads(ret.get("body"))
    else:
        return None
118785
function namespace() {
  var args = Array.prototype.slice.call(arguments);
  var setComponents = function(context, first, rest) {
    if(!context[first]) {
      context[first] = {
        models: {},
        collections: {},
        views: {},
      };
    }
    if(rest.length) {
      setComponents(context[first], _.first(rest), _.rest(rest));
    }
  };
  setComponents(window, _.first(args), _.rest(args));
}
256912
function createModel (namespace) {
  const model = (namespace) ? { namespace: namespace } : {}
  model.models = {}
  model.reducers = {}
  model.effects = {}
  model.subscriptions = {}
  model.state = {}

  return {
    start: function () {
      return model
    },
    state: function (value) {
      mutate(model.state, value)
    },
    reducer: function (key, value) {
      model.reducers[key] = value
    },
    subscription: function (key, value) {
      model.subscriptions[key] = value
    },
    effect: function (key, value) {
      model.effects[key] = value
    }
  }
}
1289577
function RedisMulti(instance) {
  
  // The Native Storage Multi for RedisStorage works by replacing the 
  // internal calls to `this.client` with calls to a multi object. This
  // queues the calls instead of executing them immediately.
  
  // Additionally, the exec() method of the multi object has no effect,
  // in case the storage method uses multi internally, it will just reflect
  // as an additional statement being queued in the transaction.
  
  var multi = instance.client.multi();
  
  this.multi = multi;
  this.instance = instance;
  
  // Fake instance, used in place of the original storage instance
  this.fakeInstance = {client: multi}
  
  // Add original exec method
  multi.__exec = multi.exec;
  
  // Replace original multi exec method with empty function
  multi.exec = this.fakeExec;
  
}
466320
function microStorage ( namespace ) {

    list[namespace] = list[namespace] || {};
    localStorage.setItem(packageName, JSON.stringify(list));

    /**
    * Get or set value from storage
    * @param {String} name key
    * @param {AnyType} value value
    * @return {AnyType} value
    */
    function storage ( name, value ) {
        if (arguments.length == 0) {
            return;
        }
        if (arguments.length == 1) {
            let result = JSON.parse(localStorage.getItem(`${ namespace }.${ name }`));
            return result ? result.$ : result;
        }
        localStorage.setItem(`${ namespace }.${ name }`, JSON.stringify({ $ : value }));
        list[namespace][name] = '';
        localStorage.setItem(packageName, JSON.stringify(list));
        return value;
    };

    /**
    * Remove value from storage
    * @param {String} name key
    */
    storage.remove = function ( name ) {
        localStorage.removeItem(`${ namespace }.${ name }`);
        delete list[namespace][name];
        localStorage.setItem(packageName, JSON.stringify(list));
    };

    /**
     * Return value list of storage
     * @return {Array} list list of storage
     */
    storage.list = function () {
        return Object.keys(list[namespace]);
    };

    /**
     * Clear all value from storage
     */
    storage.clear = function () {
        this.list().forEach(( name ) => {
            this.remove(name);
        });
    };

    return storage;
}
333990
function get(datastore, kind, namespace) {
    return function(id, cb) {
        var keyParam = [kind, id];
        if (namespace) {
            keyParam = {
                namespace: namespace,
                path: keyParam
            };
        }
        var key = datastore.key(keyParam);

        datastore.get(key, function(err, entity) {
            if (err)
                return cb(err);

            return cb(null, entity ? entity : null);
        });
    };
}
800155
function writeFile(namespace, fileName, fileLocation) {
  if (!gfsPromise) {
    return;
  }
  return gfsPromise.then(function(gfs) {
    var deferred = q.defer();
    var options = {
      filename: fileName
    };
    if (namespace) {
      options.root = namespace;
    }
    var writeStream = gfs.createWriteStream(options);
    writeStream.on('error', function(err) {
      console.log('An error occurred!', err);
      deferred.reject(err);
    });
    writeStream.on('close', function(file) {
      deferred.resolve(file);
    });
    fs.createReadStream(fileLocation).pipe(writeStream);
    return deferred.promise;
  });
}
892894
function createZooKeeperClient(options) {
	options = options || {};

	if (!options.hosts) {
		throw new Error('Missing configuration server.discoveryService.options.hosts for ZooKeeper');
	}

	// client options, with better defaults than node-zookeeper-client provides

	var clientOpts = options.options || {};

	clientOpts.sessionTimeout = clientOpts.hasOwnProperty('sessionTimeout') ? clientOpts.sessionTimeout : 30000;
	clientOpts.spinDelay = clientOpts.hasOwnProperty('spinDelay') ? clientOpts.spinDelay : 1000;
	clientOpts.retries = clientOpts.hasOwnProperty('retries') ? clientOpts.retries : 3;

	// connect to the database

	var client = zooKeeper.createClient(options.hosts, clientOpts);

	client.on('connected', function () {
		logger.verbose('ZooKeeper connection established');
	});

	client.on('connectedReadOnly', function () {
		logger.error('ZooKeeper connection established to a read-only server');
	});

	client.on('disconnected', function () {
		logger.verbose('ZooKeeper connection dropped');
	});

	client.on('expired', function () {
		logger.verbose('ZooKeeper client session expired');
	});

	client.on('authenticationFailed', function () {
		logger.error('ZooKeeper authentication failed');
	});

	return client;
}
587254
function Model(namespace) {
    var self = this;
    this.i = 0;
    var local = {
        modelPath: null,
        entitiesPath: null,
        connection: null,
        files: {},
        toReload: [],
        trying: 0
    };

    var _configuration = null;
    var _connector = null;

    var cacheless = (process.env.IS_CACHELESS == 'false') ? false : true;
    var standalone = config.Host.isStandalone();


    var setup = function(namespace) {
        if ( typeof(namespace) == 'undefined' || namespace == '') {
            console.error('gina', 'MODEL:ERR:1', 'EEMPTY: Model namespace', __stack);
        }

        var model, namespace = namespace.split(/\//g);
        _connector = namespace[1];//Has to be writtien the same for the connetors.json decalration or for the model folder
        var bundle = namespace[0];
        namespace.shift();
        //Capitalize - Normalize
        if (namespace.length > 1) {
            //            for (var i; i<namespace.length; ++i) {
            //                namespace[i] = namespace[i].substring(0, 1).toUpperCase() + namespace[i].substring(1);
            //            }

            model = namespace.join(".");
        } else {
            //Dir name.
            model = namespace[0];
        }


        console.debug("\nBundle: ", bundle);
        console.debug("Model: ", model);
        self.name       = _connector;
        self.bundle     = bundle;
        self.model      = model;
        self.modelDirName = model;
        var modelConnectors = getContext('modelConnectors');
        if (modelConnectors) {
            self.connectors = getContext('modelConnectors')[self.name];
            self.database = self.connectors.database;
        } else {
            self.connectors = {};
        }

    }

    /**
     * Init
     *
     * @param {string} namesapce
     *
     * @private
     * */
    var init = function(reload) {

        var bundle          = self.bundle;
        var model           = self.model;
        var modelDirName    = self.modelDirName;

        // this is supposed to happen on load or for dev env; on reload, with a checksum
        var conf        = getConfigSync(bundle);
        local.locals    = conf.locals;

        if (conf) {
            _configuration = conf.connectors;

            console.debug("CONF READY ", model, conf.path);
            //TODO - More controls...

            //For now, I just need the F..ing entity name.
            var modelPath       = local.modelPath = _(conf.path + '/' + modelDirName);
            var entitiesPath    = local.entitiesPath = _(modelPath + '/entities');
            console.debug('models scaning... ', entitiesPath, fs.existsSync(entitiesPath));
            if (!fs.existsSync(entitiesPath)) {
                fs.mkdirSync(entitiesPath) // creating empty path
            }

            var connectorPath   = _(modelPath + '/lib/connector.js');
            //Getting Entities Manager.
            var exists = fs.existsSync(connectorPath);
            if (exists) {
                if (cacheless)
                    delete require.cache[_(connectorPath, true)];

                var Connector = require(_(connectorPath, true));

                self.connect(
                    Connector,
                    function onConnect(err, conn) {
                        if (err) {
                            console.error(err.stack);
                            self.emit('model#ready', err, self.bundle, self.name, null)

                        } else {
                            local.connection = conn;
                            self.emit('model#ready', false, self.bundle, self.name, conn)
                        }
                    }
                )
            } else {//Means that no connector was found in models.

                //finished.
                self.emit('model#ready', new Error('[ '+self.name+' ] No connector found'), self.bundle, self.name, conn)
            }

        } else {
            console.debug("no configuration found...");
            self.emit('model#ready', new Error('no configuration found for your model: ' + model), self.bundle, self.name, null)
        }

        return self
    }


    this.connect = function(Connector, callback) {
        if ( typeof(self.connectors[_connector]) == 'undefined' ) {
            self.connectors[_connector] = {};
            var connector = new Connector( self.getConfig(_connector) );

            connector.onReady( function(err, conn){
                self.connectors[_connector].err = err;
                self.connectors[_connector].conn = conn;

                callback(err, conn);
            });

        } else {
            callback(self.connectors[_connector].err, self.connectors[_connector].conn);
        }
    }

    this.reload = function(conf, cb) {
        setup(namespace);
        init(cb)
    }

    /**
     * Get Model configuration
     *
     * @param {string} bundle
     *
     * @callback callback
     * @param {boolean|string} err - Error Status response
     * @param {object} conf - Configuration response
     *
     * @private
     * */
    var getConfigSync = function(bundle, i) {
        var i = i || 0;
        var configuration = config.getInstance(bundle);

        try {

            var locals = _locals = utilsConfig.getSync('gina', 'locals.json')
        } catch (err) {
            console.emerg('Error while calling `Model::getConfigSync()` '+ err.stack||err.message);
            if ( i < 10) {
                console.debug('about to retry to load locals.json');
                setTimeout(function(){

                    i = i+1;
                    console.debug('retry ('+i+') ...');
                    return getConfigSync(bundle, i)
                }, 300)

            } else {
                throw new Error('Config could not be loaded');
                process.exit(1)
            }
            return false
        }

        if ( typeof(configuration) != 'undefined' && locals) {

            var env = configuration.Env.current;
            var conf = configuration.Env.getConf(bundle, env);

            // configuration object.
            var confObj = {
                connectors  : conf.content.connectors,
                path        : conf.modelsPath,
                locals      : locals
            };

            return confObj
        } else {
            throw new Error('Config not instantiated');
            return undefined
        }
    }

    /**
     * Get Model Configuration
     *
     * @return {object|undefined} configuration
     * */
    this.getConfig = function(connector){
        var connector = ( typeof(connector) == 'undefined' ) ?  _connector : connector;

        if (_configuration) {
            return ( typeof(connector) != 'undefined' ) ? _configuration[connector] : undefined
        } else {
            return undefined
        }
    }


    this.onReady = function(callback) {
        self.once('model#ready', function(err, bundle, model, conn) {
            // entities == null when the database server has not started.
            if ( err ) {
                console.error(err.stack||err.message)
                //console.log('No entities found for [ '+ self.name +':'+ entityName +'].\n 1) Check if the database is started.\n2) Check if exists: /models/entities/'+ entityName);
            }
            callback(err, bundle, model, conn)
        });
        setup(namespace);
        return init()
    };

    return this
}
594942
function storage ( name, value ) {
        if (arguments.length == 0) {
            return;
        }
        if (arguments.length == 1) {
            let result = JSON.parse(localStorage.getItem(`${ namespace }.${ name }`));
            return result ? result.$ : result;
        }
        localStorage.setItem(`${ namespace }.${ name }`, JSON.stringify({ $ : value }));
        list[namespace][name] = '';
        localStorage.setItem(packageName, JSON.stringify(list));
        return value;
    }
1046802
function(namespace, handler) {
            if (Logger.namespaces[namespace] == null) {
                Logger.namespaces[namespace] = new Logger({
                    namespace: namespace,
                    handler: handler
                });
            }
            return Logger.namespaces[namespace];
        }
79369
def get_redis_storage(data_type, full_name, args = {})
      self.class.redis_ping!
      case data_type.to_sym
      when :array
        Redis::List.new(full_name, {:marshal => true}.merge(args))
      when :hash
        Redis::HashKey.new(full_name)
      when :value
        Redis::Value.new(full_name, {:marshal => true}.merge(args))
      when :lock
        Redis::Lock.new(full_name, {:expiration => 60, :timeout => 0.1}.merge(args))
      when :stamped
        Stamped.new(full_name.sub("#{key}_", "").to_sym, get_redis_storage(:value, full_name), self)
      else
        raise TypeError.new("Unsupported caching data type encountered: #{data_type}")
      end
    end