Context:
        - request
        - lat
        - long
        - located
        - legislators

    Templates:
        - billy/web/public/find_your_legislator_table.html
974428
def find_your_legislator(request):
    '''
    
    '''

    # check if lat/lon are set
    # if leg_search is set, they most likely don't have ECMAScript enabled.
    # XXX: fallback behavior here for alpha.

    get = request.GET
    context = {}
    template = 'find_your_legislator'

    context['request'] = ""
    if "q" in get:
        context['request'] = get['q']

    if "lat" in get and "lon" in get:
        # We've got a passed lat/lon. Let's build off it.
        lat = get['lat']
        lon = get['lon']

        context['lat'] = lat
        context['lon'] = lon
        context['located'] = True

        qurl = "%slegislators/geo/?long=%s&lat=%s&apikey=%s" % (
            billy_settings.API_BASE_URL,
            lon,
            lat,
            getattr(billy_settings, 'API_KEY', '')
        )
        leg_resp = json.load(urllib2.urlopen(qurl, timeout=0.5))
        # allow limiting lookup to region for region map views
        if 'abbr' in get:
            leg_resp = [leg for leg in leg_resp
                        if leg[billy_settings.LEVEL_FIELD] == get['abbr']]
            context['abbr'] = get['abbr']

        # Also, allow filtering by chamber
        if 'chamber' in get:
            leg_resp = [leg for leg in leg_resp
                        if leg['chamber'] == get['chamber']]
            context['chamber'] = get['chamber']

        if "boundary" in get:
            return HttpResponse(json.dumps([]))

        context['legislators'] = map(Legislator, leg_resp)
        template = 'find_your_legislator_table'

    return render(request, templatename(template), context)
257808
function quoteEndPos( $tpl, &$text, $startPosition, $textLength, $quote )
    {
        $currentPosition = $startPosition;
        while ( $currentPosition < $textLength )
        {
            if ( $text[$currentPosition] == "\\" )
                ++$currentPosition;
            else if ( $text[$currentPosition] == $quote )
                return $currentPosition;
            ++$currentPosition;
        }
        return $currentPosition;
    }
129703
private static String mapGermanCoNLL09TagSetToNAF(final String postag) {
    if (postag.startsWith("ADV")) {
      return "A"; // adverb
    } else if (postag.startsWith("KO")) {
      return "C"; // conjunction
    } else if (postag.equalsIgnoreCase("ART")) {
      return "D"; // determiner and predeterminer
    } else if (postag.startsWith("ADJ")) {
      return "G"; // adjective
    } else if (postag.equalsIgnoreCase("NN")) {
      return "N"; // common noun
    } else if (postag.startsWith("NE")) {
      return "R"; // proper noun
    } else if (postag.startsWith("AP")) {
      return "P"; // preposition
    } else if (postag.startsWith("PD") || postag.startsWith("PI")
        || postag.startsWith("PP") || postag.startsWith("PR")
        || postag.startsWith("PW") || postag.startsWith("PA")) {
      return "Q"; // pronoun
    } else if (postag.startsWith("V")) {
      return "V"; // verb
    } else {
      return "O"; // other
    }
  }
875293
def context(self):
        """"""

        # Can't use self.columns b/c of recursion with resolved_url

        t = self.schema_term

        if not t:
            return {}

        sql_columns = []
        all_columns = []

        for i, c in enumerate(t.children):
            if c.term_is("Table.Column"):
                p = c.all_props

                if p.get('sqlselect'): # has a value for SqlSqlect
                    sql_columns.append(p.get('sqlselect'))

                all_columns.append(c.name)

        return {
            'SQL_COLUMNS': ', '.join(sql_columns),
            'ALL_COLUMNS': ', '.join(all_columns)
        }
146482
private String computeWhereFragment(List<String> searchFields) throws Exception {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		
		boolean first = true;
		for(int loop=0; loop<searchFields.size(); ++loop) {
			if( first ) {
				first = false;
				pw.print(" WHERE ");
			} else {
				pw.print(" OR ");
			}
			pw.print("lower(");
			pw.print(searchFields.get(loop));
			pw.print(") LIKE lower(?)");
		}

		pw.flush();
		return sw.toString();
	}
769799
private String appendErrorContext(String reason) {
        // Note: This relies on the calling code maintaining the ruleIndex
        // at a position that is useful for debugging.
        // For example, at the beginning of a reset or relation etc.
        StringBuilder msg = new StringBuilder(reason);
        msg.append(" at index ").append(ruleIndex);
        // We are not counting line numbers.

        msg.append(" near \"");
        // before ruleIndex
        int start = ruleIndex - (U_PARSE_CONTEXT_LEN - 1);
        if(start < 0) {
            start = 0;
        } else if(start > 0 && Character.isLowSurrogate(rules.charAt(start))) {
            ++start;
        }
        msg.append(rules, start, ruleIndex);

        msg.append('!');
        // starting from ruleIndex
        int length = rules.length() - ruleIndex;
        if(length >= U_PARSE_CONTEXT_LEN) {
            length = U_PARSE_CONTEXT_LEN - 1;
            if(Character.isHighSurrogate(rules.charAt(ruleIndex + length - 1))) {
                --length;
            }
        }
        msg.append(rules, ruleIndex, ruleIndex + length);
        return msg.append('\"').toString();
    }
144093
def search(request, template="search_results.html", extra_context=None):
    
    query = request.GET.get("q", "")
    page = request.GET.get("page", 1)
    per_page = settings.SEARCH_PER_PAGE
    max_paging_links = settings.MAX_PAGING_LINKS
    try:
        parts = request.GET.get("type", "").split(".", 1)
        search_model = apps.get_model(*parts)
        search_model.objects.search  # Attribute check
    except (ValueError, TypeError, LookupError, AttributeError):
        search_model = Displayable
        search_type = _("Everything")
    else:
        search_type = search_model._meta.verbose_name_plural.capitalize()
    results = search_model.objects.search(query, for_user=request.user)
    paginated = paginate(results, page, per_page, max_paging_links)
    context = {"query": query, "results": paginated,
               "search_type": search_type}
    context.update(extra_context or {})
    return TemplateResponse(request, template, context)
19923
private static String mapEnglishTagSetToKaf(final String postag) {
    if (postag.startsWith("RB")) {
      return "A"; // adverb
    } else if (postag.equalsIgnoreCase("CC")) {
      return "C"; // conjunction
    } else if (postag.startsWith("D") || postag.equalsIgnoreCase("PDT")) {
      return "D"; // determiner and predeterminer
    } else if (postag.startsWith("J")) {
      return "G"; // adjective
    } else if (postag.equalsIgnoreCase("NN") || postag.equalsIgnoreCase("NNS")) {
      return "N"; // common noun
    } else if (postag.startsWith("NNP")) {
      return "R"; // proper noun
    } else if (postag.equalsIgnoreCase("TO") || postag.equalsIgnoreCase("IN")) {
      return "P"; // preposition
    } else if (postag.startsWith("PRP") || postag.startsWith("WP")) {
      return "Q"; // pronoun
    } else if (postag.startsWith("V")) {
      return "V"; // verb
    } else {
      return "O"; // other
    }
  }
111293
String asString() {
        if (mParent == null) {
            return "anyPolicy  ROOT\n";
        } else {
            StringBuilder sb = new StringBuilder();
            for (int i = 0, n = getDepth(); i < n; i++) {
                sb.append("  ");
            }
            sb.append(policyToString(getValidPolicy()));
            sb.append("  CRIT: ");
            sb.append(isCritical());
            sb.append("  EP: ");
            for (String policy : getExpectedPolicies()) {
                sb.append(policyToString(policy));
                sb.append(" ");
            }
            sb.append(" (");
            sb.append(getDepth());
            sb.append(")\n");
            return sb.toString();
        }
    }
1282158
def _raise_disambiguation_error(self, page, pageid):
        
        query_params = {
            "prop": "revisions",
            "rvprop": "content",
            "rvparse": "",
            "rvlimit": 1,
        }
        query_params.update(self.__title_query_param())
        request = self.mediawiki.wiki_request(query_params)
        html = request["query"]["pages"][pageid]["revisions"][0]["*"]

        lis = BeautifulSoup(html, "html.parser").find_all("li")
        filtered_lis = [
            li for li in lis if "tocsection" not in "".join(li.get("class", list()))
        ]
        may_refer_to = [li.a.get_text() for li in filtered_lis if li.a]

        disambiguation = list()
        for lis_item in filtered_lis:
            item = lis_item.find_all("a")
            one_disambiguation = dict()
            one_disambiguation["description"] = lis_item.text
            if item and hasattr(item[0], "title"):
                one_disambiguation["title"] = item[0]["title"]
            else:
                # these are non-linked records so double up the text
                one_disambiguation["title"] = lis_item.text
            disambiguation.append(one_disambiguation)
        raise DisambiguationError(
            getattr(self, "title", page["title"]),
            may_refer_to,
            page["fullurl"],
            disambiguation,
        )
420316
def vicinity(self):
        
        if self._vicinity == '' and self.details != None and 'vicinity' in self.details:
            self._vicinity = self.details['vicinity']
        return self._vicinity
778920
def page_location_template(self):
        
        cycle = self.election_day.cycle.name
        model_class = self.model_type.model_class()
        if model_class == ElectionDay:
            return "/{}/".format(cycle)
        if model_class == Office:
            # President
            if self.jurisdiction:
                if self.division_level.name == DivisionLevel.STATE:
                    return "/{}/president/{{state}}".format(cycle)
                else:
                    return "/{}/president/".format(cycle)
            # Governor
            else:
                return "/{}/{{state}}/governor/".format(cycle)
        elif model_class == Body:
            # Senate
            if self.body.slug == "senate":
                if self.jurisdiction:
                    if self.division_level.name == DivisionLevel.STATE:
                        return "/{}/senate/{{state}}/".format(cycle)
                    else:
                        return "/{}/senate/".format(cycle)
                else:
                    return "/{}/{{state}}/senate/".format(cycle)
            # House
            else:
                if self.jurisdiction:
                    if self.division_level.name == DivisionLevel.STATE:
                        return "/{}/house/{{state}}/".format(cycle)
                    else:
                        return "/{}/house/".format(cycle)
                else:
                    return "/{}/{{state}}/house/".format(cycle)
        elif model_class == Division:
            return "/{}/{{state}}/".format(cycle)
        else:
            return "ORPHAN TYPE"
556244
def get_context(self):
        
        ctx = {}
        for clause in self.where_clauses or []:
            clause.update_context(ctx)
        return ctx
299955
function(query) {
    var i;
    var stopwords = ["a","and","are","as","at","be","but","by","for","if","in","into","is","it","near","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"];

    // stem the searchterms and add them to the correct list
    var stemmer = new Stemmer();
    var searchterms = [];
    var excluded = [];
    var hlterms = [];
    var tmp = splitQuery(query);
    var objectterms = [];
    for (i = 0; i < tmp.length; i++) {
      if (tmp[i] !== "") {
          objectterms.push(tmp[i].toLowerCase());
      }

      if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) ||
          tmp[i] === "") {
        // skip this "word"
        continue;
      }
      // stem the word
      var word = stemmer.stemWord(tmp[i].toLowerCase());
      // prevent stemmer from cutting word smaller than two chars
      if(word.length < 3 && tmp[i].length >= 3) {
        word = tmp[i];
      }
      var toAppend;
      // select the correct list
      if (word[0] == '-') {
        toAppend = excluded;
        word = word.substr(1);
      }
      else {
        toAppend = searchterms;
        hlterms.push(tmp[i].toLowerCase());
      }
      // only add if not already in the list
      if (!$u.contains(toAppend, word))
        toAppend.push(word);
    }
    var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));

    // console.debug('SEARCH: searching for:');
    // console.info('required: ', searchterms);
    // console.info('excluded: ', excluded);

    // prepare search
    var terms = this._index.terms;
    var titleterms = this._index.titleterms;

    // array of [filename, title, anchor, descr, score]
    var results = [];
    $('#search-progress').empty();

    // lookup as object
    for (i = 0; i < objectterms.length; i++) {
      var others = [].concat(objectterms.slice(0, i),
                             objectterms.slice(i+1, objectterms.length));
      results = results.concat(this.performObjectSearch(objectterms[i], others));
    }

    // lookup as search terms in fulltext
    results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));

    // let the scorer override scores with a custom scoring function
    if (Scorer.score) {
      for (i = 0; i < results.length; i++)
        results[i][4] = Scorer.score(results[i]);
    }

    // now sort the results by score (in opposite order of appearance, since the
    // display function below uses pop() to retrieve items) and then
    // alphabetically
    results.sort(function(a, b) {
      var left = a[4];
      var right = b[4];
      if (left > right) {
        return 1;
      } else if (left < right) {
        return -1;
      } else {
        // same score: sort alphabetically
        left = a[1].toLowerCase();
        right = b[1].toLowerCase();
        return (left > right) ? -1 : ((left < right) ? 1 : 0);
      }
    });

    // for debugging
    //Search.lastresults = results.slice();  // a copy
    //console.info('search results:', Search.lastresults);

    // print the results
    var resultCount = results.length;
    function displayNextItem() {
      // results left, load the summary and display it
      if (results.length) {
        var item = results.pop();
        var listItem = $('<li style="display:none"></li>');
        if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') {
          // dirhtml builder
          var dirname = item[0] + '/';
          if (dirname.match(/\/index\/$/)) {
            dirname = dirname.substring(0, dirname.length-6);
          } else if (dirname == 'index/') {
            dirname = '';
          }
          listItem.append($('<a/>').attr('href',
            DOCUMENTATION_OPTIONS.URL_ROOT + dirname +
            highlightstring + item[2]).html(item[1]));
        } else {
          // normal html builders
          listItem.append($('<a/>').attr('href',
            item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
            highlightstring + item[2]).html(item[1]));
        }
        if (item[3]) {
          listItem.append($('<span> (' + item[3] + ')</span>'));
          Search.output.append(listItem);
          listItem.slideDown(5, function() {
            displayNextItem();
          });
        } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
          var suffix = DOCUMENTATION_OPTIONS.SOURCELINK_SUFFIX;
          $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[5] + (item[5].slice(-suffix.length) === suffix ? '' : suffix),
                  dataType: "text",
                  complete: function(jqxhr, textstatus) {
                    var data = jqxhr.responseText;
                    if (data !== '' && data !== undefined) {
                      listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
                    }
                    Search.output.append(listItem);
                    listItem.slideDown(5, function() {
                      displayNextItem();
                    });
                  }});
        } else {
          // no source available, just display title
          Search.output.append(listItem);
          listItem.slideDown(5, function() {
            displayNextItem();
          });
        }
      }
      // search finished, update title and status message
      else {
        Search.stopPulse();
        Search.title.text(_('Search Results'));
        if (!resultCount)
          Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.'));
        else
            Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
        Search.status.fadeIn(500);
      }
    }
    displayNextItem();
  }
1254589
def pagination_for(context, current_page, page_var="page", exclude_vars=""):
    
    querystring = context["request"].GET.copy()
    exclude_vars = [v for v in exclude_vars.split(",") if v] + [page_var]
    for exclude_var in exclude_vars:
        if exclude_var in querystring:
            del querystring[exclude_var]
    querystring = querystring.urlencode()
    return {
        "current_page": current_page,
        "querystring": querystring,
        "page_var": page_var,
    }
1130026
private static String mapGalicianCTAGTagSetToNAF(final String postag) {
    if (postag.startsWith("R")) {
      return "A"; // adverb
    } else if (postag.equalsIgnoreCase("CC") || postag.equalsIgnoreCase("CS")) {
      return "C"; // conjunction
    } else if (postag.startsWith("D") || postag.startsWith("G")
        || postag.startsWith("X") || postag.startsWith("Q")
        || postag.startsWith("T") || postag.startsWith("I")
        || postag.startsWith("M")) {
      return "D"; // det predeterminer
    } else if (postag.startsWith("A")) {
      return "G"; // adjective
    } else if (postag.startsWith("NC")) {
      return "N"; // common noun
    } else if (postag.startsWith("NP")) {
      return "R"; // proper noun
    } else if (postag.startsWith("S")) {
      return "P"; // preposition9434233199310741
    } else if (postag.startsWith("P")) {
      return "Q"; // pronoun
    } else if (postag.startsWith("V")) {
      return "V"; // verb
    } else {
      return "O"; // other
    }
  }
434360
def get_context_data(self, **kwargs):
        
        context = super(Sitemap, self).get_context_data(**kwargs)
        context.update(
            {'entries': Entry.published.all(),
             'categories': Category.published.all(),
             'authors': Author.published.all()}
        )
        return context