Find page part by key or build new record
340457
def find_or_build_page_part(attr_name)
      key = normalize_page_part_key(attr_name)
      page_parts.detect { |record| record.key.to_s == key } || page_parts.build(key: key)
    end
1259406
def obtain_record(check = nil, type = nil)
      
      return check if check.is_a?(ActiveRecord::Base)

      if check.blank? 
        return nil if @content.blank? || !@content[0].blank?
        @content
      else
        records = Post.where( 'post_title = :p OR post_slug = :p2 OR id = :p3', { p: check.to_s, p2: check.to_s, p3: check.to_i} )
        if !type.blank?
          records = records.where("post_type = :p4", {p4: type})
        end
        records.first
      end

    end
702853
def get_pages(self, label=None):
        """"""
        return (
            page for page in sorted(
                self._pages.values(), key=lambda i: i.created, reverse=True
            ) if ((not label or label in page.labels) and page.visible)
        )
162599
def page_factory(request):
    
    prefix = request.matchdict['prefix']  # /{prefix}/page1/page2/page3...
    settings = request.registry.settings
    dbsession = settings[CONFIG_DBSESSION]
    config = settings[CONFIG_MODELS]

    if prefix not in config:
        # prepend {prefix} to *traverse
        request.matchdict['traverse'] =\
            tuple([prefix] + list(request.matchdict['traverse']))
        prefix = None

    # Get all resources and models from config with the same prefix.
    resources = config.get(
        prefix, config.get(   # 1. get resources with prefix same as URL prefix
            '', config.get(   # 2. if not, then try to get empty prefix
                '/', None)))  # 3. else try to get prefix '/' otherwise None

    if not hasattr(resources, '__iter__'):
        resources = (resources, )

    tree = {}

    if not resources:
        return tree

    # Add top level nodes of resources in the tree
    for resource in resources:
        table = None
        if not hasattr(resource, '__table__')\
                and hasattr(resource, 'model'):
            table = resource.model
        else:
            table = resource

        if not hasattr(table, 'slug'):
            continue

        nodes = dbsession.query(table)
        if hasattr(table, 'parent_id'):
            nodes = nodes.filter(or_(
                table.parent_id == None,  # noqa
                table.parent.has(table.slug == '/')
            ))
        for node in nodes:
            if not node.slug:
                continue
            resource = resource_of_node(resources, node)
            tree[node.slug] = resource(node, prefix=prefix)
    return tree
907901
def page_for_url(cls, url):
        """"""
        resp, elem = Resource.element_for_url(url)

        value = Resource.value_for_element(elem)

        return cls.page_for_value(resp, value)
678285
function findPage(pages, path) {
  const p = path.shift();
  const page = pages.find(page => page.path === p);

  if (!page) {
    return {redirect: getDefaultPath(pages)};
  }
  if (page.children) {
    const result = findPage(page.children, path);
    if (result.page) {
      return result;
    }
    return {redirect: [p].concat(result.redirect)};
  }
  if (path.length) {
    return {redirect: []};
  }
  return {page};
}
926244
function updateSearch() {
    var cache = {},
        pages = sections[$location.path().split('/')[1]],
        modules = $scope.modules = [],
        otherPages = $scope.pages = [],
        search = $scope.search,
        bestMatch = {page: null, rank:0};

    angular.forEach(pages, function(page) {
      var match,
        id = page.id,
        section = page.section;

      if (!(match = rank(page, search))) return;

      if (match.rank > bestMatch.rank) {
        bestMatch = match;
      }

      if (page.id == 'index') {
        //skip
      } else if (!NG_DOCS.apis[section]) {
        otherPages.push(page);
      } else if (id == 'angular.Module') {
        module('ng', section).types.push(page);
      } else if (match = id.match(GLOBALS)) {
        module('ng', section).globals.push(page);
      } else if (match = id.match(MODULE)) {
        module(page.moduleName || match[1], section);
      } else if (match = id.match(MODULE_FILTER)) {
        module(page.moduleName || match[1], section).filters.push(page);
      } else if (match = id.match(MODULE_DIRECTIVE)) {
        module(page.moduleName || match[1], section).directives.push(page);
      } else if (match = id.match(MODULE_DIRECTIVE_INPUT)) {
        module(page.moduleName || match[1], section).directives.push(page);
      } else if (match = id.match(MODULE_CUSTOM)) {
        module(page.moduleName || match[1], section).others.push(page);
      } else if (match = id.match(MODULE_TYPE)) {
        module(page.moduleName || match[1], section).types.push(page);
      } else if (match = id.match(MODULE_SERVICE)) {
        if (page.type === 'overview') {
          module(id, section);
        } else {
          module(page.moduleName || match[1], section).service(match[2])[match[3] ? 'provider' : 'instance'] = page;
        }
      } else if (match = id.match(MODULE_MOCK)) {
        module('ngMock', section).globals.push(page);
      }

    });

    $scope.bestMatch = bestMatch;

    /*************/

    function module(name, section) {
      var module = cache[name];
      if (!module) {
        module = cache[name] = {
          name: name,
          url: (NG_DOCS.html5Mode ? '' : '#/') + section + '/' + name,
          globals: [],
          directives: [],
          services: [],
          others: [],
          service: function(name) {
            var service =  cache[this.name + ':' + name];
            if (!service) {
              service = {name: name};
              cache[this.name + ':' + name] = service;
              this.services.push(service);
            }
            return service;
          },
          types: [],
          filters: []
        };
        modules.push(module);
      }
      return module;
    }

    function rank(page, terms) {
      var ranking = {page: page, rank:0},
        keywords = page.keywords,
        title = page.shortName.toLowerCase();

      terms && angular.forEach(terms.toLowerCase().split(' '), function(term) {
        var index;

        if (ranking) {
          if (keywords.indexOf(term) == -1) {
            ranking = null;
          } else {
            ranking.rank ++; // one point for each term found
            if ((index = title.indexOf(term)) != -1) {
              ranking.rank += 20 - index; // ten points if you match title
            }
          }
        }
      });
      return ranking;
    }
  }
294827
def get_page(self, paginator):
        """"""
        page = int(self.get_and_save_value('page', 1))
        if page < 1:
            return self.save_value('page', 1)

        if page > paginator.num_pages:
            return self.save_value('page', paginator.num_pages)
        return page
545404
function(typeName, id, snapshot) {
        // FIXME If there is a record, try and look up the self link
        // - Need to use the function from the serializer to build the self key
        // TODO: this basically only works in the simplest of scenarios
        var route = this.getRoute(typeName, id, snapshot);
        if(!route) {
          return this._super(typeName, id, snapshot);
        }

        var url = [];
        var host = get(this, 'host');
        var prefix = this.urlPrefix();
        var param = /\{(.*?)\}/g;

        if (id) {
          if (param.test(route)) {
            url.push(route.replace(param, id));
          } else {
            url.push(route);
          }
        } else {
          url.push(route.replace(param, ''));
        }

        if (prefix) {
          url.unshift(prefix);
        }

        url = url.join('/');

        if (!host && url) {
          url = '/' + url;
        }

        return url;
      }
806662
function route_(element, newURL, alreadyShown) {
    let lastMatch = null;
    let newHash = newURL.split('#')[1] || '';
    let lastHash = newHash.split('/').reverse()[0];
    let match = lastHash.match(
      new RegExp(element.getAttribute('hash')));
    let parents = [element];

    // if match...
    if (match && match[0] === lastHash &&
      (match.length === 1 ||
      !document.querySelector(`[hash="${lastHash}"]`))) {

      // match_ newHash pushing all matched elements to parents
      lastMatch = match_(newHash, parents, []);

      // if default route do not match
      if ((lastMatch !== newHash) && (element.getAttribute('hash') === '')) {
        lastMatch = null;
      } else {
        match = newHash.match(new RegExp(parents.reduce((acc, curr) => {
          curr && (acc = curr.getAttribute('hash') + (acc ? '/' : '') + acc);
          return acc;
        }, '')));
        (!match) && (lastMatch = null);

        // unhide all matched elements
        match && parents.forEach(element => element && unhide_(element));

        // hide_ last elements. I mean, if go
        // from /page1/page2/page3
        // to   /page1/page2/page5
        // then hide only page3
        match &&
          (alreadyShown instanceof Array) &&
          alreadyShown.reduce((acc, curr) => {
            curr && !parents.includes(curr) && acc.push(curr);
            return acc;
          }, []).reverse().forEach(item => hide_(item));

        // if match, and no stateRevert then update lastMatch and dispatch show
        match && !stateRevert && (lastMatch = parents) &&
          dispatchShow_(element, match.slice(1)
          .reduce((detail, hash, i) => {
            detail[`param${i + 1}`] = hash;
            return detail;
          }, { router: element }));
      }
    } else {
      // do not hide elements unnecessarily
      if (!(alreadyShown.find &&
          alreadyShown.find(show => show === element))) {
        hide_(element);
      }
    }
    return lastMatch;
  }
1010760
def _nextPage(self, offset):
        """"""
        self.logger.debug("Iterator crecord=%s" % str(self.crecord))
        params = {
            'q': self.q,
            'start': str(offset),
            'rows': str(self.pagesize),
            'fl': self.fields,
            'explainOther': '',
            'hl.fl': '',
        }
        if self.fq is not None:
            params['fq'] = self.fq
        self.res = self.client.search(params)
        self._numhits = int(self.res['response']['numFound'])
1206102
function findRecord(options) {
    let query = getQueryParams(options, ['name', 'content', 'type', 'query']);
    return find(options.domain, query).then(function (result) {
      return new Result(result.data.result);
    });
  }
829970
static public function findCurrentPage($key='page') {
        $f3 = \Base::instance();
        return $f3->exists('PARAMS.'.$key) ?
            preg_replace("/[^0-9]/", "", $f3->get('PARAMS.'.$key)) : 1;
    }
1031383
def _find(api_method, query, limit, return_handler, first_page_size, **kwargs):
    ''' 
    '''
    num_results = 0

    if "limit" not in query:
        query["limit"] = first_page_size

    while True:
        resp = api_method(query, **kwargs)

        by_parent = resp.get('byParent')
        descriptions = resp.get('describe')
        def format_result(result):
            if return_handler:
                result = dxpy.get_handler(result['id'], project=result.get('project'))
            if by_parent is not None:
                return result, by_parent, descriptions
            else:
                return result

        for i in resp["results"]:
            if num_results == limit:
                return
            num_results += 1
            yield format_result(i)

        # set up next query
        if resp["next"] is not None:
            query["starting"] = resp["next"]
            query["limit"] = min(query["limit"]*2, 1000)
        else:
            return
1199437
def get_bucket_page(page):
    
    key_list = page.get('Contents', [])
    logger.debug("Retrieving page with {} keys".format(
        len(key_list),
    ))
    return dict((k.get('Key'), k) for k in key_list)
671479
def duplicate!
      Page.new(attributes.except('id', 'updated_at', 'created_at')).tap do |page|
        page.title = page.title + ' (Copy)'
        page.slug = page.slug + '-copy'
        page.draft = true

        regions.each do |region|
          page.regions.build(region.attributes.except('id', 'updated_at', 'created_at'))
        end

        page.save!
      end
    end
1272952
def pages

			result_map = map_query_to_results

			query_result["query"]["pages"].each do |key, value|

				page_title = value["title"]
				original_query = find_result_map_match_for_title(result_map, page_title)
				@page_hash[original_query] = MediaWiki::Page.new(value)

			end

			@page_hash
		end