Wrapper to deal with Kaminari vs WillPaginate
19258
def comfy_paginate(collection)
      return unless collection
      if defined?(WillPaginate)
        will_paginate collection
      elsif defined?(Kaminari)
        paginate collection, theme: "comfy"
      end
    end
61488
def wrap_paginated(self, data, renderer_context):
        """"""

        pagination_keys = ['count', 'next', 'previous', 'results']
        for key in pagination_keys:
            if not (data and key in data):
                raise WrapperNotApplicable('Not paginated results')

        view = renderer_context.get("view", None)
        model = self.model_from_obj(view)
        resource_type = self.model_to_resource_type(model)

        try:
            from rest_framework.utils.serializer_helpers import ReturnList

            results = ReturnList(
                data["results"],
                serializer=data.serializer.fields["results"],
            )
        except ImportError:
            results = data["results"]

        # Use default wrapper for results
        wrapper = self.wrap_default(results, renderer_context)

        # Add pagination metadata
        pagination = self.dict_class()

        pagination['previous'] = data['previous']
        pagination['next'] = data['next']
        pagination['count'] = data['count']

        wrapper.setdefault('meta', self.dict_class())

        wrapper['meta'].setdefault('pagination', self.dict_class())
        wrapper['meta']['pagination'].setdefault(
            resource_type, self.dict_class()).update(pagination)

        return wrapper
1126221
function (values, options, callback) {
                var deferred = Q.defer();
                var args = ArgumentHelpers.prepareArguments(options, callback)
                    , wrapper = {};
                options = args.options;
                callback = Qext.makeNodeResolver(deferred, args.callback);

                //Check for mongo's another possible syntax with '$' operators, e.g. '$set', '$setOnInsert' and set wrapper
                values = values || {};

                for (var element in values) {
                    if (element.match(/\$/i)) {
                        wrapper[element] = values[element];
                        options.flat = options.flat != undefined ? options.flat : true
                    }
                }

                // If nothing to wrap just validate values
                if (_.isEmpty(wrapper)) {
                    ModelValidator.validate(values, this.prototype, options, function (err, validatedValues) {
                        callback(err, validatedValues);
                    });
                }
                else {
                    // If wrapping elements like $set, $inc etc found, validate each and rewrite to values
                    values = {};
                    var errors = {};
                    var wrapperOptions = {};
                    for (var wrapperElem in wrapper) {

                        wrapperOptions = _.clone(options);
                        if (options && options.partial && _.isObject(options.partial)) {
                            if (options.partial[wrapperElem] !== undefined) {
                                wrapperOptions['partial'] = options.partial[wrapperElem];
                            }
                        }

                        if (options && options.validate && _.isObject(options.validate)) {
                            if (options.validate[wrapperElem] !== undefined) {
                                wrapperOptions['validate'] = options.validate[wrapperElem];
                            }
                        }

                        if (options.validate && options.validate[wrapperElem] === false) {
                            values[wrapperElem] = wrapper[wrapperElem];
                        }
                        else {
                            ModelValidator.validate(wrapper[wrapperElem], this.prototype, wrapperOptions, function (err, validatedValues) {
                                if (err) {
                                    errors = err;
                                }
                                values[wrapperElem] = validatedValues;
                            });
                        }
                    }

                    if (_.isEmpty(errors)) {
                        errors = null;
                    }
                    callback(errors, values);
                }

                return deferred.promise;
            }
1091726
function(apiType, data) {
            var arg = (data) ? data : {};
            var collection = null;

            if (!apiType) {
              apiType = paginationAPIType.github;
            }
            if (apiType === paginationAPIType.github) {
              collection = new paginatedCollection(arg);
              collection.setPaginationConfiguration({
                currentPageParam: "page",
                pageSizeParam: "per_page"
              });
            } else if (apiType === paginationAPIType.solr) {
              collection = new paginatedCollection(arg);
              collection.setPaginationConfiguration({
                currentPageParam: "start",
                pageSizeParam: "rows"
              });
            } else if (apiType === paginationAPIType.database) {
              collection = new paginatedCollection(arg);
              collection.setPaginationConfiguration({
                currentPageParam: "offset",
                pageSizeParam: "limit"
              });
            }
            return collection;
          }
419985
public static void generateDynamicPartOfQuery(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder, SplittedSql splittedSql, boolean countQuery) {
		final JQL jql = method.jql;
		if (StringUtils.hasText(splittedSql.sqlGroupStatement)) {
			methodBuilder.addCode("\n// manage GROUP BY statement\n");
			methodBuilder.addStatement("String _sqlGroupByStatement=$S", splittedSql.sqlGroupStatement);
			methodBuilder.addStatement("_sqlBuilder.append($L)", "_sqlGroupByStatement");
		}

		if (StringUtils.hasText(splittedSql.sqlHavingStatement)) {
			methodBuilder.addCode("\n// manage HAVING statement\n");
			methodBuilder.addStatement("String _sqlHavingStatement=$S", splittedSql.sqlHavingStatement);
			methodBuilder.addStatement("_sqlBuilder.append($L)", "_sqlHavingStatement");
		}

		// add order by when the query is not a total count query
		if (countQuery == false) {

			if (jql.isOrderBy()) {
				methodBuilder.addComment("generation order - BEGIN");
				String value = splittedSql.sqlOrderByStatement;
				String valueToReplace = jql.dynamicReplace.get(JQLDynamicStatementType.DYNAMIC_ORDER_BY);

				if (jql.isStaticOrderBy() && !jql.isDynamicOrderBy()) {
					// case static statement and NO dynamic

					methodBuilder.addStatement("String _sqlOrderByStatement=$S", value);
				} else if (jql.isStaticOrderBy() && jql.isDynamicOrderBy()) {
					methodBuilder.addStatement("String _sqlOrderByStatement=$S+$T.ifNotEmptyAppend($L, \", \")", value.replace(valueToReplace, ""), StringUtils.class, "_sortOrder");
				} else if (!jql.isStaticOrderBy() && jql.isDynamicOrderBy()) {
					methodBuilder.addStatement("String _sqlOrderByStatement=$T.ifNotEmptyAppend($L,\" $L \")", StringUtils.class, "_sortOrder", JQLKeywords.ORDER_BY_KEYWORD);
				}

				methodBuilder.addStatement("_sqlBuilder.append($L)", "_sqlOrderByStatement");
				methodBuilder.addComment("generation order - END");
				methodBuilder.addCode("\n");
			}

			if (jql.dynamicReplace.containsKey(JQLDynamicStatementType.DYNAMIC_PAGE_SIZE) || jql.annotatedPageSize) {
				methodBuilder.addComment("generation limit - BEGIN");
				if (SelectBuilderUtility.detectSelectType(method) != SelectType.PAGED_RESULT && !method.isPagedLiveData()) {
					methodBuilder.addStatement("String _sqlLimitStatement=$S", splittedSql.sqlLimitStatement);
				} else if (jql.annotatedPageSize || method.isPagedLiveData()) {
					methodBuilder.addStatement("String _sqlLimitStatement=\" LIMIT \"+$L", "paginatedResult.getPageSize()");
				} else if (jql.hasParamPageSize()) {
					methodBuilder.addStatement("String _sqlLimitStatement=$T.printIf($L>0, \" LIMIT \"+$L)", SqlUtils.class, "paginatedResult.getPageSize()", "paginatedResult.getPageSize()");
				}
				methodBuilder.addStatement("_sqlBuilder.append($L)", "_sqlLimitStatement");
				methodBuilder.addComment("generation limit - END");
				methodBuilder.addCode("\n");
			}

			if (jql.dynamicReplace.containsKey(JQLDynamicStatementType.DYNAMIC_PAGE_OFFSET) && (SelectBuilderUtility.detectSelectType(method) == SelectType.PAGED_RESULT || method.isPagedLiveData())) {
				methodBuilder.addComment("generation offset - BEGIN");
				if (jql.annotatedPageSize || method.isPagedLiveData()) {
					methodBuilder.addStatement("String _sqlOffsetStatement=\" OFFSET \"+paginatedResult.getOffset()", SqlUtils.class);
				} else if (jql.hasParamPageSize()) {
					methodBuilder.addStatement("String _sqlOffsetStatement=$T.printIf($L>0 && paginatedResult.getOffset()>0, \" OFFSET \"+paginatedResult.getOffset())", SqlUtils.class,
							jql.paramPageSize);
				}

				methodBuilder.addStatement("_sqlBuilder.append($L)", "_sqlOffsetStatement");
				methodBuilder.addComment("generation offset - END");
				methodBuilder.addCode("\n");
			}
		}
	}
467110
def paginator(context, page, leading=8, out=3, adjacent=3, sep='...'):
    
    leading_pages, out_left_pages, out_right_pages, pages = [], [], [], []
    num_pages = page.paginator.num_pages
    is_paginated = num_pages > 1
    if is_paginated:
        if num_pages < leading:
            leading_pages = [x for x in range(1, leading) if x <= num_pages]
        elif page.number <= leading - 1:
            leading_pages = [x for x in range(1, leading + 1)]
            out_right_pages = [x + num_pages for x in range(-out + 1, 1) if x + num_pages > leading]
        elif page.number > num_pages - leading + 1:
            leading_pages = [x for x in range(num_pages - leading + 1, num_pages + 1) if x <= num_pages]
            out_left_pages = [x for x in range(1, out + 1) if num_pages - x >= leading]
        else:
            leading_pages = [x for x in range(page.number - adjacent, page.number + adjacent + 1)]
            out_right_pages = [x + num_pages for x in range(-out + 1, 1)]
            out_left_pages = [x for x in range(1, out + 1)]
    if out_left_pages:
        pages.extend(out_left_pages)
        pages.append(sep)
    pages.extend(leading_pages)
    if out_right_pages:
        pages.append(sep)
        pages.extend(out_right_pages)
    return {
        'page': page,
        'pages': pages,
        'is_paginated': is_paginated,
        'separator': sep,
        'request': context.get('request'),
        'param_name': page.param_name if hasattr(page, 'param_name') else 'page',
    }
1176345
private CompletableFuture<QueryResponse> queryLinearizable(Indexed<QueryEntry> entry) {
    return applyQuery(entry)
        .thenComposeAsync(response -> appender.appendEntries()
            .thenApply(index -> response)
            .exceptionally(error -> QueryResponse.builder()
                .withStatus(RaftResponse.Status.ERROR)
                .withError(RaftError.Type.QUERY_FAILURE, error.getMessage())
                .build()), raft.getThreadContext());
  }
1153963
def paginate_results(self, results, options):
        ""
        limit = options.get('limit', settings.SELECTABLE_MAX_LIMIT)
        paginator = Paginator(results, limit)
        page = options.get('page', 1)
        try:
            results = paginator.page(page)
        except (EmptyPage, InvalidPage):
            results = paginator.page(paginator.num_pages)
        return results
91080
function(lastope){
		// 前回と同じ場所なら前回の更新のみ
		var property = this.property;
		if( lastope.group    === this.group &&
			lastope.property === this.property  &&
			lastope.num      === this.old   &&
			lastope.bx       === this.bx    &&
			lastope.by       === this.by    &&
			(property === 'qnum'  || 
			 property === 'qnum2' ||
			 property === 'qchar' ||
			 property === 'anum'  ||
			(property === 'snum' && lastope.pos === this.pos))
		)
		{
			lastope.num = this.num;
			return true;
		}
		return false;
	}
189190
function NWTNodeList(nodes) {

	localnwt.implement('DelayableQueue', this);

	var wrappedNodes = [];

	for( var i = 0, node ; node = nodes[i] ; i++  ) {
		wrappedNodes.push(new NWTNodeInstance(node));
	}  
	this.nodes = wrappedNodes;

	var iteratedFunctions = [
		'anim', 'appendTo', 'remove', 'addClass', 'removeClass', 'setStyle', 'setStyles', 'removeStyle', 'removeStyles', 'swapClass', 'plug'
	],

	mythis = this;

	function getIteratedCallback(method) {
		return function() {
			for( var j = 0 , node ; node = mythis.nodes[j] ; j++ ) {
				node[method].apply(node, arguments);
			}
			return mythis;
		};		
	};

	for( var i = 0, func; func = iteratedFunctions[i] ; i++ ) {
		this[func] = getIteratedCallback(func);
	}
}
769722
private Future<?> submit(FLVFinalizer flvFinalizer) {
        if (executor != null && !executor.isTerminated()) {
            return executor.submit(flvFinalizer);
        }
        return null;
    }
1313239
private String pageUri(final UriTemplate uriTemplate, final int skip, final int limit) {
        if (limit == MAX_VALUE) {
            return uriTemplate.expand();
        }
        return uriTemplate.set(skipVar(), skip).set(limitVar(), limit).expand();
    }
748591
function wrapCallback(api, span, done) {
  var fn = function(err, res) {
    if (api.enhancedDatabaseReportingEnabled()) {
      if (err) {
        // Errors may contain sensitive query parameters.
        span.addLabel('mongoError', err);
      }
      if (res) {
        var result = res.result ? res.result : res;
        span.addLabel('result', result);
      }
    }
    span.endSpan();
    if (done) {
      done(err, res);
    }
  };
  return api.wrap(fn);
}
1155455
function ServerQueryList(qry, limit, Resource) {
      // Allow qry to be a promise
      qry = $q
        .when(qry)
        .then(normalizeQuery)
        .then(function(_qry) {
          if (limit) {
            _qry.limit = limit;
          }
          return _qry;
        });

      var emitPromise = null;
      var results = new ArrayEmitter();
      var currentLimit = 0;
      var currentSkip = 0;
      var lastBatchSize = 0;
      var _pagingOpts = {};

      results.loading = true;

      function query(data) {
        // We only want to do one emit at a time (otherwise we could get into a bad state)
        if (angular.isFunction(data)) {
          data = data();
        }

        // Store off the query - make sure its a promise
        qry = $q.when(data);

        return qry.then(function(data) {
          // If we have an existing emitPromise then wait for it to resolve before we run
          var promise;
          if (emitPromise) {
            promise = emitPromise.then(function() {
              return sock.query(data);
            });
          } else {
            emitPromise = promise = sock.query(data);
          }

          return promise;
        });
      }

      function newData(_qryId, response, force) {
        if (!response) {
          return;
        }

        var deferred = $q.defer();
        var ids = response.ids;
        var pagingOpts = response.pagingOpts;

        // So far we've only got the ids of the qry result - go and fetch the actual objects.
        // This mechanism saves bandwidth by only getting the object data once then listening
        // for changes to it
        //
        // If we are forcing we want to get both the old and new ids to check for any changes
        // deletions etc..
        var getIds = ids;
        if (force) {
          var oldIds = pluck(results, '_id');
          getIds = union(ids, oldIds);
        }

        Resource.get(getIds, force).$promise.then(function(ress) {
          var ressmap = {};
          ress.forEach(function(res) {
            ressmap[res._id] = res;
          });

          // We don't allow repeated ids so just iterate over the results
          var tmpResults = [];
          ids.forEach(function(id) {
            tmpResults.push(ressmap[id]);
          });

          // Do we need to do a transform?
          var rprom;
          if (angular.isFunction(results.transform)) {
            rprom = $q.when(results.transform(tmpResults));
          } else {
            rprom = $q.when(tmpResults);
          }

          return rprom.then(function(transformed) {
            results.length = 0;
            transformed.forEach(function(res) {
              results.push(res);
            });

            // Since we now have data in our array store off limit data
            currentLimit = tmpResults.length;
            results.$skip = currentSkip = qry && qry.skip ? qry.skip : 0;
            lastBatchSize = lastBatchSize || tmpResults.length;
            _pagingOpts = pagingOpts;
            results.hasNext = pagingOpts.next != null;
            results.hasPrev = pagingOpts.prev != null;

            // Data has come back
            results.loading = false;

            results.$emitter.emit('update', results);

            deferred.resolve(results);
          });
        });

        return deferred.promise;
      }

      function refreshQuery(force) {
        var req = query(qry);
        var promise = req.then(function(res) {
          // If we get no response (the app could be offline) then just resolve with
          // the existing results
          if (angular.isUndefined(res)) {
            results.loading = false;
            return results;
          }

          var _qryId = res.qryId;
          var response = res.data;

          return newData(_qryId, response, force);
        });
        return promise;
      }

      function replace(_qry) {
        // Do the query but replace the existing query
        return $q
          .when(_qry)
          .then(normalizeQuery)
          .then(function(normQry) {
            // We allow a query to resolve to something falsy - in which case we just
            // drop it
            if (!normQry) {
              return;
            }

            return qry.then(function(oldqry) {
              if (JSON.stringify(oldqry) !== JSON.stringify(normQry)) {
                // query is different - continue
                var req = query(normQry);

                var promise = req.then(function(res) {
                  // If we get no response (the app could be offline) then just resolve with
                  // the existing results
                  if (angular.isUndefined(res)) {
                    results.loading = false;
                    return results;
                  }

                  // We do have a response. Continue
                  var _qryId = res.qryId;
                  var data = res.data;

                  return newData(_qryId, data);
                });

                return promise;
              }
            });
          });
      }

      function extendResults(obj, noSanitize) {
        // Sanitize the object
        if (!noSanitize) {
          if (obj._q) {
            obj = obj._q;
          } else {
            obj = { find: obj };
          }
        }

        return qry.then(function(resolved) {
          var _qry = extendQuery(resolved, obj);
          return replace(_qry);
        });
      }

      function next(num) {
        var promise;
        var extendSize;
        if (_pagingOpts.next) {
          lastBatchSize = extendSize = num || lastBatchSize;
          var extendObj = {
            limit: currentLimit + extendSize
          };
          promise = extendResults(extendObj, true);
        } else {
          var deferred = $q.defer();
          deferred.resolve();
          promise = deferred.promise;
        }

        return promise;
      }

      function prev(num) {
        var promise;
        var extendSize;
        if (_pagingOpts.prev) {
          lastBatchSize = extendSize = num || lastBatchSize;
          var extendObj = {
            skip: Math.max(currentSkip - extendSize, 0),
            limit: currentLimit + extendSize
          };
          promise = extendResults(extendObj, true);
        } else {
          var deferred = $q.defer();
          deferred.resolve();
          promise = deferred.promise;
        }

        return promise;
      }

      function get() {
        return Resource.get.apply(Resource, arguments);
      }

      function chain(Model, qryFn) {
        return Chain(results, Model, qryFn);
      }

      results.$newData = newData;
      results.$refresh = refreshQuery;
      results.extend = extendResults;
      results.replace = replace;
      results.get = get;
      results.next = next;
      results.prev = prev;
      results.$promise = refreshQuery().then(function(res) {
        results.$resolved = true;
        return res;
      });
      results.$resolved = false;
      results.chain = chain;
      results.$Model = Resource;
      results.$skip = 0;

      // Put currentSkip and currentLimit onto the results
      Object.defineProperty(results, 'currentLimit', {
        enumerable: true,
        get: () => {
          return currentLimit;
        }
      });
      Object.defineProperty(results, 'currentSkip', {
        enumerable: true,
        get: () => {
          return currentSkip;
        }
      });

      return results;
    }
342251
function Paginator(options) {
  debug('initializing from <%s>', __filename);
  this.options = options || {};
  this.footer = this.options.footer;
  if (typeof this.footer !== 'string') {
    this.footer = '(Move up and down to reveal more choices)';
  }
  this.firstRender = true;
  this.lastIndex = 0;
  this.position = 0;
}
570841
function ScrollManager(options) {
                var _this = this;
                this._$root = null; //!< Scroll 対象のルートオブジェクト
                this._$map = null; //!< Scroll Map element を格納
                this._mapHeight = 0; //!< Scroll Map の高さを格納 (_$map の状態に依存させない)
                this._scroller = null; //!< Scroll に使用する IScroller インスタンス
                this._settings = null; //!< ScrollManager オプションを格納
                this._active = true; //!< UI 表示中は true に指定
                this._scrollEventHandler = null; //!< Scroll Event Handler
                this._scrollStopEventHandler = null; //!< Scroll Stop Event Handler
                this._baseHeight = 0; //!< 高さの基準値
                this._lines = []; //!< 管理下にある LineProfile 配列
                this._pages = []; //!< 管理下にある PageProfile 配列
                //! 最新の表示領域情報を格納 (Scroll 中の更新処理に使用)
                this._lastActivePageContext = {
                    index: 0,
                    from: 0,
                    to: 0,
                    pos: 0,
                };
                this._backup = {}; //!< データの backup 領域. key と _lines を格納。派生クラスで拡張可能。
                // ListViewOptions 既定値
                var defOptions = {
                    scrollerFactory: UI.ScrollerElement.getFactory(),
                    enableHiddenPage: false,
                    enableTransformOffset: false,
                    scrollMapRefreshInterval: 200,
                    scrollRefreshDistance: 200,
                    pagePrepareCount: 3,
                    pagePreloadCount: 1,
                    enableAnimation: true,
                    animationDuration: 0,
                    baseDepth: "auto",
                    itemTagName: "li",
                    removeItemWithTransition: true,
                    useDummyInactiveScrollMap: false,
                };
                // 設定格納
                this._settings = $.extend({}, defOptions, options);
                // スクロールイベント
                this._scrollEventHandler = function (event) {
                    _this.onScroll(_this._scroller.getPos());
                };
                // スクロール停止イベント
                this._scrollStopEventHandler = function (event) {
                    _this.onScrollStop(_this._scroller.getPos());
                };
            }
999337
def _entity_paginator(namespace, workspace, etype, page_size=500,
                            filter_terms=None, sort_direction="asc"):
    

    page = 1
    all_entities = []
    # Make initial request
    r = fapi.get_entities_query(namespace, workspace, etype, page=page,
                           page_size=page_size, sort_direction=sort_direction,
                           filter_terms=filter_terms)
    fapi._check_response_code(r, 200)

    response_body = r.json()
    # Get the total number of pages
    total_pages = response_body['resultMetadata']['filteredPageCount']

    # append the first set of results
    entities = response_body['results']
    all_entities.extend(entities)
    # Now iterate over remaining pages to retrieve all the results
    page = 2
    while page <= total_pages:
        r = fapi.get_entities_query(namespace, workspace, etype, page=page,
                               page_size=page_size, sort_direction=sort_direction,
                               filter_terms=filter_terms)
        fapi._check_response_code(r, 200)
        entities = r.json()['results']
        all_entities.extend(entities)
        page += 1

    return all_entities