Process options: filter, search, order, limit, page and finally resolve them to
primary DataSource.

@private
355668
function resolveDataSourceOptions(resourceTree, dataSources, primaryName) {
    if (resourceTree.filter) {
        dataSources[primaryName].filter = resourceTree.filter.map(andFilter =>
            andFilter.map(filter => {
                if (!filter.attribute[primaryName]) {
                    throw new ImplementationError('All filtered attributes must be mapped to primary DataSource');
                }

                filter.attribute = filter.attribute[primaryName];
                if (filter.attribute.length === 1) {
                    filter.attribute = filter.attribute[0];
                }

                return filter;
            })
        );
    }

    if ('search' in resourceTree) {
        dataSources[primaryName].search = resourceTree.search;
    }

    if (resourceTree.order) {
        dataSources[primaryName].order = resourceTree.order.map(order => {
            if (!order.attribute[primaryName]) {
                throw new ImplementationError('All ordered attributes must be mapped to primary DataSource');
            }

            order.attribute = order.attribute[primaryName];

            return order;
        });
    }

    // TODO: Allow filter/order in different than the primary DataSource?

    if (has(resourceTree, 'limit')) {
        dataSources[primaryName].limit = resourceTree.limit;
    }

    if (resourceTree.limitPerGroup && resourceTree.childKey) {
        const limitPer = resourceTree.childKey[primaryName];
        dataSources[primaryName].limitPer = limitPer.length === 1 ? limitPer[0] : limitPer;
    }

    if (resourceTree.page) {
        dataSources[primaryName].page = resourceTree.page;
    }
}
1278370
function (source, options) {
        this.index = this._geIndex(source);
        this.data = '';
        this.options = options;
        this._cache = {};
        this._usedHeaders = [];
    }
41120
function parseOptions(options) {
    if (options.path.indexOf(HOST) !== -1) {
      // Get complete URL
      return getData(options.path);
    } else if (typeof options.value === 'undefined') {
      // Get all results
      return getAll(HOST + options.path + '/');
    } else if (typeof options.value === 'string') {
      // Get search results (paged or all)
      if (options.format === 'paged') {
        return getData(HOST + options.path + '/?search=' + options.value);
      } else {
        return getAll(HOST + options.path + '/?search=' + options.value);
      }
    } else {
      // Get results by ID (paged or single)
      if (options.format === 'paged') {
        return getData(HOST + options.path + '/?page=' + options.value);
      } else {
        return getData(HOST + options.path + '/' + options.value);
      }
    }
  }
63097
function findAll(unfilteredOptions) {
        var options = this.filterOptions(unfilteredOptions, 'findAll'),
            itemCollection = this.forge();

        // @TODO: we can't use order raw when running migrations (see https://github.com/tgriesser/knex/issues/2763)
        if (this.orderDefaultRaw && !options.migrating) {
            itemCollection.query((qb) => {
                qb.orderByRaw(this.orderDefaultRaw(options));
            });
        }

        itemCollection.applyDefaultAndCustomFilters(options);
        return itemCollection.fetchAll(options).then(function then(result) {
            if (options.withRelated) {
                _.each(result.models, function each(item) {
                    item.withRelated = options.withRelated;
                });
            }

            return result;
        });
    }
936982
function (e) {
        var p       = this.paginator,
            sel     = this.select,
            options = p.get('rowsPerPageOptions'),
            opt,cfg,val,i,len;

        this.all = null;

        for (i = 0, len = options.length; i < len; ++i) {
            cfg = options[i];
            opt = sel.options[i] ||
                  sel.appendChild(document.createElement('option'));
            val = l.isValue(cfg.value) ? cfg.value : cfg;
            opt.innerHTML = l.isValue(cfg.text) ? cfg.text : cfg;

            if (l.isString(val) && val.toLowerCase() === 'all') {
                this.all  = opt;
                opt.value = p.get('totalRecords');
            } else{
                opt.value = val;
            }

        }

        while (sel.options.length > options.length) {
            sel.removeChild(sel.firstChild);
        }

        this.update();
    }
887785
function(options){
            var cleanOptions = this.parseOptions(options),
                excludes = _.clone(this.privateFields),
                includeExludes = [];

            // If any includes are passed in through the options clean up the
            // default excluded fields. A type can have some excluded fields by
            // default and if the user overrides this then we need to clean up the query.
            if(options && options.include){
                _.each(options.include, function(include){
                    //If the include matches an existing exclude then remove it from the
                    //excludes and also from the includes (you can't mix them)
                    excludes = _.remove(excludes, function(o){
                        if(o === include){
                            cleanOptions.include = _.remove(cleanOptions.include, function(i){
                                return i !== include;
                            });
                        }

                        return o !== include;
                    });

                });
            }

            includeExludes = _.union(cleanOptions.include,
                this.parseExclusion(cleanOptions.exclude),
                this.parseExclusion(excludes)
            );

            return includeExludes.join(' ');
        }
48858
function () {
    var done = this.async();
    var options = this.options();
    var data = this.data;

    // default settings, overwritten with user defined settings
    settings = {
      pattern_port: Array.isArray(data.ports) && data.ports[0] ? data.ports[0] : Array.isArray(options.ports) && options.ports[0] ? options.ports[0] : 7020,
      snapshot_port: Array.isArray(data.ports) && data.ports[1] ? data.ports[1] : Array.isArray(options.ports) && options.ports[1] ? options.ports[1] : 7040,
      wwwroot: data.wwwroot || options.wwwroot || 'public',
      src: data.src || options.src || 'public/patterns',
      files: data.files || options.files || [],
      dest: data.dest || options.dest || 'docs',
      snapshot: (data.snapshot !== undefined ? data.snapshot : (options.snapshot !== undefined ? options.snapshot : false)),
      index: data.index || options.index || null,
      css: data.css || options.css || ['global.css']
    };

    var primer;

    // local pattern folder (there are the html snapshots)
    if (settings.files.length > 0) {
      var patterns = settings.files;
      var patternsFolder = settings.src;

      // our main function that starts the process
      primer = function (cb) {
        handleFiles(patternsFolder, patterns, cb);
      };

    } else {
     var patternFolder = './' + settings.src;

      // our main function that starts the process
      primer = function (cb) {
        readPatterns(patternFolder, cb);
      };
    }

   

    // middleware to spit out 404 (in case a non existing ressource is request)
    // or to process the `non static` requests
    var middleware = function (req, resp) {
      if (req.url !== '/') {
        resp.writeHead(404, {
          'Content-Length': 0,
          'Content-Type': 'text/plain'
        });
        resp.end();
        return;
      }

      // 200, success, always
      resp.writeHead(200, {'Content-Type': 'text/html'});
      // run the primer with cb
      primer(resp.end.bind(resp));
    };

    // initialize the server with static routes & dynamic template middleware
    var liveServer = connect.createServer(
      connect.static(process.cwd() + '/' + settings.wwwroot),
      middleware
    );

    // initialize the static server pointing to your snapshots
    var snapshotServer = connect.createServer(connect.static(process.cwd() + '/' + settings.dest));

    // starts the live server
    var startLiveServer = function () {
      liveServer.listen(settings.pattern_port, function () {
        grunt.log.ok('You can now visit http://localhost:' + settings.pattern_port + '/ to see your patterns.');
      });
    };

    // starts the snapshot server
    var startSnapshotServer = function () {
      snapshotServer.listen(settings.snapshot_port, function () {
        grunt.log.ok('You can now visit http://localhost:' + settings.snapshot_port + '/ to see your snaphsot patterns.');
      });
    };

    // writes the task output to a file 
    var writeSnapshot = function () {
      primer(function (content) {
        var promises = [];
        // write the index file
        grunt.file.write('./' + settings.dest + '/index.html', content);
        // copy css files
        settings.css.forEach(function (file) {
          var deferred = Q.defer();
          promises.push(deferred.promise);
          if (file.search('http://') !== -1) {

            var data = '';
            http.get(file, function (res) {
              res.on('data', function(chunk) {
                data += chunk;
              });
              res.on('end', function () {
                grunt.file.write('./' + settings.dest + '/style.css', data);
                deferred.resolve();
              });
            })
            .on('err', deferred.reject);
          } else {
            grunt.file.copy('./' + settings.wwwroot + '/' + file, './' + settings.dest + '/' + file);
            deferred.resolve();
          }
        });

        grunt.log.ok('Stand-alone output can now be found in "' + settings.dest + '/"');
        grunt.event.emit('patternprimer:snapshot:written');
        if (promises.length === 0) {
          done();
        } else {
          Q.allSettled(promises).then(done);
        }
      });
    };

    // writes to file or starts a server,
    // depending on the given snapshot var
    if (!!settings.snapshot) {
      writeSnapshot();
    } else {
      startLiveServer();
      // only start snapshot server, if snapshots are available
      if (grunt.file.exists('./' + settings.dest + '/index.html')) {
        startSnapshotServer();
      }
    }

  }
294516
function _processOptions (options) {
        // Options parsing
        var
            name,
            maxLen;
        if (options instanceof Array) {
            options = gpf.Parameter.parse([{
                name: "port",
                type: "number",
                defaultValue: 80,
                prefix: "port"
            }, {
                name: "root",
                type: "string",
                defaultValue: ".",
                prefix: "root"
            }, {
                name: "chunkSize",
                type: "number",
                defaultValue: 65536,
                prefix: "chunk"
            }, gpf.Parameter.VERBOSE, gpf.Parameter.HELP], options);
        }
        // Server boot trace
        console.log("GPF " + gpf.version() + " web server");
        if (options.root === ".") {
            options.root = process.cwd();
        }
        if (options.verbose) {
            maxLen = 0;
            for (name in options) {
                if (options.hasOwnProperty(name)) {
                    if (name.length > maxLen) {
                        maxLen = name.length;
                    }
                }
            }
            ++maxLen;
            for (name in options) {
                if (options.hasOwnProperty(name)) {
                    console.log([
                        "\t",
                        name,
                        (new Array(maxLen - name.length + 1)).join(" "),
                        ": ",
                        options[name]
                    ].join(""));
                }
            }
        }
        return options;
    }
630934
function(options) {
  options = options || {};
  
  this.datasources = [];
  this.styles = [];
  this.projection = DEFAULT_PROJECTION;
  this.assetsPath = ".";
  
  if (options.projection){
    this.projection = projector.util.cleanProjString(options.projection);
    console.log(this.projection);
  }
  
  this.boundsBuffer =
    ("boundsBuffer" in options) ? options.boundsBuffer : BUFFER_RATIO;
  
  this._renderer = cartoRenderer;
}
1096591
function (sQuery) {
			// add filter for search
			var aFilters = [];
			if (sQuery && sQuery.length > 0) {
				aFilters = new Filter({
					filters: [
						new Filter("name", FilterOperator.Contains, sQuery),
						new Filter("fileType", FilterOperator.Contains, sQuery)
					],
					and: false
				});
			}

			// update list binding
			var oList = this.byId("masterComponentsList");
			var oBinding = oList.getBinding("items");
			oBinding.filter(aFilters, "content");
		}
1312589
function resolveResourceTree(resourceTree, parentDataSourceName) {
    const dataSources = {};
    const primaryName = selectPrimaryDataSource(resourceTree);

    if (resourceTree.attrNode) {
        resourceTree.attrNode.primaryDataSource = primaryName;
    }

    // determine needed DataSources (simple logic - to be optimized for complex cases):
    dataSources[primaryName] = true;
    resourceTree.attributes.forEach(attrInfo => {
        if (attrInfo.fromDataSource === '#all-selected' || attrInfo.fromDataSource === '#current-primary') return;

        // handle key-group (select all attributes of one composite key from same DataSource):
        if (attrInfo.fromDataSource === '#same-group') {
            let selectedDataSource = primaryName;
            const possibleDataSources = Object.keys(attrInfo.subResourceAttrNode.resolvedParentKey);

            if (possibleDataSources.indexOf(selectedDataSource) === -1) {
                // just select first possible one - optimize?
                selectedDataSource = possibleDataSources[0];
                attrInfo.subResourceAttrNode.parentDataSource = selectedDataSource;
            }

            attrInfo.attributes.forEach(groupAttrInfo => {
                groupAttrInfo.fromDataSource = selectedDataSource;
            });

            dataSources[selectedDataSource] = true;
            return;
        }

        dataSources[Object.keys(attrInfo.dataSourceMap)[0]] = true;
    });

    // initialize needed DataSources:
    Object.keys(dataSources).forEach(dataSourceName => {
        dataSources[dataSourceName] = Object.assign({}, resourceTree.dataSources[dataSourceName]);
    });
    if (resourceTree.attrNode) {
        resourceTree.attrNode.dataSources = dataSources; // for use in result-builder
    }

    resolveDataSourceAttributes(resourceTree, dataSources, primaryName);
    resolveDataSourceOptions(resourceTree, dataSources, primaryName);

    let dataSourceTree = {};
    if (resourceTree.attrPath) {
        dataSourceTree.attributePath = resourceTree.attrPath;
        dataSourceTree.dataSourceName = primaryName;
    }

    dataSourceTree.request = dataSources[primaryName];
    dataSourceTree.attributeOptions = dataSourceTree.request.attributeOptions;
    delete dataSourceTree.request.attributeOptions;

    if (resourceTree.resourceName) dataSourceTree.resourceName = resourceTree.resourceName;

    if (parentDataSourceName && resourceTree.parentKey && resourceTree.childKey) {
        if (!resourceTree.parentKey[parentDataSourceName]) {
            throw new ImplementationError(
                [
                    'Parent key' + (resourceTree.attrPath ? ' of "' + resourceTree.attrPath.join('.') + '"' : ''),
                    'not in "' + parentDataSourceName + '"-DataSource of parent resource'
                ].join(' ')
            );
        }

        dataSourceTree.parentKey = resourceTree.parentKey[parentDataSourceName];
        dataSourceTree.childKey = resourceTree.childKey[primaryName];
        if ('multiValuedParentKey' in resourceTree && 'uniqueChildKey' in resourceTree) {
            dataSourceTree.multiValuedParentKey = resourceTree.multiValuedParentKey;
            dataSourceTree.uniqueChildKey = resourceTree.uniqueChildKey;
        }
    }

    // append secondary DataSources:
    const secondaryDataSources = {};

    Object.keys(dataSources).forEach(dataSourceName => {
        if (dataSourceName === primaryName) return;
        if (dataSources[dataSourceName].joinParentKey) return;

        if (!dataSourceTree.subRequests) {
            dataSourceTree.subRequests = [];
        }

        const filter = {
            attribute: resourceTree.primaryKey[dataSourceName],
            operator: 'equal',
            valueFromParentKey: true
        };

        if (filter.attribute.length === 1) {
            filter.attribute = filter.attribute[0];
        }

        dataSources[dataSourceName].filter = [[filter]];

        const subRequest = {
            attributePath: resourceTree.attrPath,
            dataSourceName,
            parentKey: resourceTree.primaryKey[primaryName],
            childKey: resourceTree.primaryKey[dataSourceName],
            multiValuedParentKey: false,
            uniqueChildKey: true,
            request: dataSources[dataSourceName]
        };

        if (resourceTree.resourceName) subRequest.resourceName = resourceTree.resourceName;

        subRequest.attributeOptions = subRequest.request.attributeOptions;
        delete subRequest.request.attributeOptions;

        dataSourceTree.subRequests.push(subRequest);
        // also index by name to resolve dependencies later
        secondaryDataSources[dataSourceName] = subRequest;
    });

    if (resourceTree.subFilters) {
        resourceTree.subFilters.forEach(subFilterTree => {
            const subDataSourceTree = resolveResourceTree(subFilterTree, primaryName);

            if (!dataSourceTree.subFilters) {
                dataSourceTree.subFilters = [];
            }
            dataSourceTree.subFilters.push(subDataSourceTree);
        });
    }

    if (resourceTree.children) {
        resourceTree.children.forEach(subResourceTree => {
            let parentDataSourceTree = dataSourceTree;
            let dataSourceName = primaryName;

            // check if we depend on a secondary DataSource:
            if (
                subResourceTree.attrNode.parentDataSource &&
                dataSourceName !== subResourceTree.attrNode.parentDataSource
            ) {
                dataSourceName = subResourceTree.attrNode.parentDataSource;
                parentDataSourceTree = secondaryDataSources[dataSourceName];
            }

            const subDataSourceTree = resolveResourceTree(subResourceTree, dataSourceName);

            if (!parentDataSourceTree.subRequests) {
                parentDataSourceTree.subRequests = [];
            }
            parentDataSourceTree.subRequests.push(subDataSourceTree);
        });
    }

    // handle m:n relations with join-table (insert an additional request into
    // the tree and move the original request one level deeper):
    if (resourceTree.joinVia) {
        const joinDataSource = dataSources[resourceTree.joinVia];
        joinDataSource.filter = [
            [
                {
                    attribute:
                        joinDataSource.resolvedJoinParentKey.length === 1
                            ? joinDataSource.resolvedJoinParentKey[0]
                            : joinDataSource.resolvedJoinParentKey,
                    operator: 'equal',
                    valueFromParentKey: true
                }
            ]
        ];

        const originalDataSourceTree = dataSourceTree;
        dataSourceTree = {
            attributePath: resourceTree.attrPath,
            dataSourceName: resourceTree.joinVia,
            parentKey: originalDataSourceTree.parentKey,
            childKey: joinDataSource.resolvedJoinParentKey,
            multiValuedParentKey: false,
            uniqueChildKey: originalDataSourceTree.uniqueChildKey,
            request: joinDataSource,
            attributeOptions: joinDataSource.attributeOptions,
            subRequests: [originalDataSourceTree]
        };
        originalDataSourceTree.parentKey = joinDataSource.resolvedJoinChildKey;
        originalDataSourceTree.uniqueChildKey = true;

        delete joinDataSource.attributeOptions;
        delete joinDataSource.joinParentKey;
        delete joinDataSource.resolvedJoinParentKey;
        delete joinDataSource.joinChildKey;
        delete joinDataSource.resolvedJoinChildKey;
    }

    return dataSourceTree;
}
550843
function (options, callback) {
			var sampleImageCategories = ['abstract', 'animals', 'business', 'cats', 'city', 'food', 'nature', 'technics', 'transport'];
			var numItems = 200;

			// build dataSource based with options
			var resp = {
				count: numItems,
				items: [],
				pages: (Math.ceil(numItems / (options.pageSize || 30))),
				page: options.pageIndex
			};

			// get start and end limits for JSON
			var i, l;
			i = options.pageIndex * (options.pageSize || 30);
			l = i + (options.pageSize || 30);
			resp.start = i + 1;
			resp.end = l;

			// add sample items to datasource
			for (i; i < l; i++) {
				resp.items.push({
					name: ('Thumbnail ' + (i + 1)),
					src: 'http://lorempixel.com/65/65/' + sampleImageCategories[Math.floor(Math.random() * 9)] + '/?_=' + i
				});
			}

			// call and simulate latency
			setTimeout(function () {
				callback(resp);
			}, loadDelays[Math.floor(Math.random() * 4)]);
		}
1289307
def _process_options(options)
        status, content_type, location = options.values_at(:status, :content_type, :location)

        self.status = status if status
        self.content_type = content_type if content_type
        headers["Location"] = url_for(location) if location

        super
      end
1047098
function (options) {
    options = options || {};
    this.id = options['id'];
    this.strict = options['strict'] || false;
    this.meta = DataTable.createMetaItems(options['meta']);
    this.enable = options['enable'] || DataTable.DEFAULTS.enable;
    this.pageSize = ko.observable(options['pageSize'] || DataTable.DEFAULTS.pageSize)
    this.pageIndex = ko.observable(options['pageIndex'] || DataTable.DEFAULTS.pageIndex)
    this.totalPages = ko.observable(options['totalPages'] || DataTable.DEFAULTS.totalPages)
    this.totalRow = ko.observable()
    this.pageCache = options['pageCache'] === undefined ? DataTable.DEFAULTS.pageCache : options['pageCache']
    this.rows = ko.observableArray([])
    this.selectedIndices = ko.observableArray([])
    this._oldCurrentIndex = -1;
    this.focusIndex = ko.observable(-1)
    this.cachedPages = []
    this.metaChange = {};
    this.valueChange = {};//ko.observable(1);
    this.currentRowChange = ko.observable(1);
    this.enableChange = ko.observable(1);
    this.params = options['params'] || {};
    this.master = options['master'] || '';
    this.allSelected = ko.observable(false);
    if (options['root']){
        this.root = options['root']
    }else{
        this.root = this;
    }
    if (options['ns']){
        this.ns = options['ns'];
    }else{
        this.ns = '';
    }
}
1018472
function (options) {
            var processQueue = [];
            $.each(options.processQueue, function () {
                var settings = {},
                    action = this.action,
                    prefix = this.prefix === true ? action : this.prefix;
                $.each(this, function (key, value) {
                    if ($.type(value) === 'string' &&
                        value.charAt(0) === '@') {
                        settings[key] = options[
                            value.slice(1) || (prefix ? prefix +
                                key.charAt(0).toUpperCase() + key.slice(1) : key)
                            ];
                    } else {
                        settings[key] = value;
                    }

                });
                processQueue.push(settings);
            });
            options.processQueue = processQueue;
        }
998558
function resolvePage () {
      try {
        if (body.waitForJS === true && !pageJSisDone) {
          setTimeout(function () {
            resolvePage()
          }, 100)

          return
        }

        var resultData = page.evaluate(function (rawFnSource, customArgs) {
          var fnSource = rawFnSource.trim()

          fnSource = fnSource.slice(-1) === ';' ? fnSource.slice(0, -1) : fnSource

          var fn = '(function result() { '
          fn += 'return (' + fnSource + ') '
          fn += '})()'

          try {
            // eslint-disable-next-line
            fn = window.eval(fn)
          } catch (e) {
            // eslint-disable-next-line no-template-curly-in-string
            return {
              error: 'script code passed as `scriptFn` option has syntax error: ' + e.message
            }
          }

          if (typeof fn !== 'function') {
            return {
              error: 'script code passed as `scriptFn` option is not a function'
            }
          }

          return {
            result: fn.apply(null, customArgs)
          }
        }, body.scriptFn, body.args)

        // resultData can still be null if evaluated script returned
        // non-serializable value
        if (resultData && resultData.error) {
          throw new Error(resultData.error)
        }

        fs.write(body.outputFilePath, JSON.stringify({
          result: resultData != null ? resultData.result : undefined
        }), 'w')

        respond(page, {
          empty: resultData == null,
          logs: messages
        })
      } catch (e) {
        onMainError(e)
      }
    }
1118594
def search(query = nil, provider = nil, sort = nil, order = nil, limit = nil, page = nil)
      params = {
        q: query,
        provider: provider,
        sort: sort,
        order: order,
        limit: limit,
        page: page
      }.delete_if { |_, v| v.nil? }

      @client.request('get', '/search', params)
    end