text:
var Search = {};

Search.index = null;
Search.searchHistory = [];

Search.chromeUrls = ["accessibility", "appcache-internals", "apps", "blob-internals", "bookmarks", "cache", "chrome", "chrome-urls", "components", "crashes", "credits", "devices", "dns", "downloads", "extensions", "flags", "flash", "gcm-internals", "gpu", "help", "histograms", "history", "indexeddb-internals", "inspect", "invalidations", "ipc", "linux-proxy-config", "media-internals", "memory", "memory-internals", "nacl", "net-internals", "newtab", "omnibox", "plugins", "policy", "predictors", "print", "profiler", "quota-internals", "sandbox", "serviceworker-internals", "settings", "signin-internals", "stats", "sync-internals", "system", "terms", "tracing", "translate-internals", "user-actions", "version", "view-http-cache", "webrtc-internals", "webrtc-logs", "crash", "kill", "hang", "shorthang", "gpuclean", "gpucrash", "gpuhang", "ppapiflashcrash", "ppapiflashhang", "quit", "restart"];
Search.chromeMatch = function(string, callback) {
  if (string.trim() === "") return callback(Search.chromeUrls.slice(0, settings.searchLimit).map(function(e){return["chrome",e];}));
  var matches = [];
  callback(this.chromeUrls.filter(function(element) {
    return (string === element.substring(0, string.length));
  }).map(function(e){return["chrome",e];}));
};

Search.settings = ["smoothscroll", "scrollstep", "searchlimit", "regexsearch", "ignorecase", "hintcharacters", "showhud"];

Search.settingsMatch = function(string, callback) {
  if (string.trim() === "") return callback(Search.settings.slice(0, settings.searchLimit).map(function(e){return["settings",e];}));
  var matches = [];
  callback(this.settings.filter(function(element) {
    return (string === element.substring(0, string.length));
  }).map(function(e){return["settings",e];}));
};

Search.fetchQuery = function(query, callback) {
  Search.current = query;
  if (Search.delay) return false;
  Search.delay = true;
  var api = "https://suggestqueries.google.com/complete/search?client=firefox&q=";
  var lastQuery = query;
  setTimeout(function() {
    Search.delay = false;
    if (lastQuery !== Search.current) {
      Search.fetchQuery(query, callback);
    }
  }, 50);
  var xhr = new XMLHttpRequest();
  xhr.open("GET", api + query);
  xhr.onreadystatechange = function() {
    var matches = [];
    if (xhr.readyState === 4 && xhr.status === 200) {
      var data = JSON.parse(xhr.responseText)[1];
      for (var i = 0, l = data.length; i < l; ++i) {
        matches.push(["search", data[i]]);
      }
      callback(matches);
    }
  };
  xhr.send();
};

Search.nextResult = function(reverse) {

  if (!Command.dataElements.length) {
    return;
  }

  if (this.index === null) {
    if (!reverse) {
      this.index = 0;
    } else {
      this.index = Command.dataElements.length - 1;
    }
  } else {
    Command.dataElements[this.index].style.backgroundColor = "";
    Command.dataElements[this.index].style.color = "";
    if (Command.dataElements[this.index].children.length > 1) {
      Command.dataElements[this.index].children[0].style.color = "";
      Command.dataElements[this.index].children[1].style.color = "";
    }
    if (!reverse) {
      if (this.index + 1 < Command.dataElements.length) {
        this.index++;
      } else {
        this.index = null;
        Command.input.value = Command.typed || "";
        return;
      }
    } else {
      if (this.index === 0) {
        this.index = null;
        Command.input.value = Command.typed || "";
        return;
      } else {
        this.index--;
      }
    }
  }

  Command.dataElements[this.index].style.backgroundColor = "#fefefe";
  if (Command.dataElements[this.index].children.length > 1) {
    Command.dataElements[this.index].children[0].style.color = "#1b1d1e";
    Command.dataElements[this.index].children[1].style.color = "#1b1d1e";
  } else {
    Command.dataElements[this.index].style.color = "#1b1d1e";
  }

  switch (Command.completionResults[this.index][0]) {
    case "chrome":
      Command.input.value = "chrome://" + Command.completionResults[this.index][1];
      break;
    case "bookmark": case "history":
      Command.input.value = Command.input.value.match(/^\S+ /)[0] + Command.completionResults[this.index][2];
      break;
    case "search": case "settings": case "session":
      Command.input.value = Command.input.value.match(/^\S+/)[0] + " " + Command.completionResults[this.index][1];
      break;
    case "path":
      if (Command.completionResults[this.index][2] !== "folder") {
        Command.input.value = "bookmarks " + Command.completionResults[this.index][2];
      } else {
        Command.input.value = "bookmarks " + Command.completionResults[this.index][3] + Command.completionResults[this.index][1];
      }
      break;
    case "buffer":
      Command.input.value = Command.input.value.match(/^\S+/)[0] + " " + Command.completionResults[this.index][1][0];
      break;
    case "complete":
      if (Command.completionResults[this.index][1] !== undefined) {
        Command.input.value = Command.completionResults[this.index][1];
      }
      break;
  }

};

redpajama_set_name: RedPajamaGithub


text:
package web

import (
	"regexp"

	"github.com/lgtmco/lgtm/cache"
	"github.com/lgtmco/lgtm/model"
	"github.com/lgtmco/lgtm/remote"
	"github.com/lgtmco/lgtm/store"

	log "github.com/Sirupsen/logrus"
	"github.com/gin-gonic/gin"
)

func Hook(c *gin.Context) {
	hook, err := remote.GetHook(c, c.Request)
	if err != nil {
		log.Errorf("Error parsing hook. %s", err)
		c.String(500, "Error parsing hook. %s", err)
		return
	}
	if hook == nil {
		c.String(200, "pong")
		return
	}

	repo, err := store.GetRepoSlug(c, hook.Repo.Slug)
	if err != nil {
		log.Errorf("Error getting repository %s. %s", hook.Repo.Slug, err)
		c.String(404, "Repository not found.")
		return
	}
	user, err := store.GetUser(c, repo.UserID)
	if err != nil {
		log.Errorf("Error getting repository owner %s. %s", repo.Slug, err)
		c.String(404, "Repository owner not found.")
		return
	}

	rcfile, _ := remote.GetContents(c, user, repo, ".lgtm")
	config, err := model.ParseConfig(rcfile)
	if err != nil {
		log.Errorf("Error parsing .lgtm file for %s. %s", repo.Slug, err)
		c.String(500, "Error parsing .lgtm file. %s.", err)
		return
	}

	// THIS IS COMPLETELY DUPLICATED IN THE API SECTION. NOT IDEAL
	file, err := remote.GetContents(c, user, repo, "MAINTAINERS")
	if err != nil {
		log.Debugf("no MAINTAINERS file for %s. Checking for team members.", repo.Slug)
		members, merr := cache.GetMembers(c, user, repo.Owner)
		if merr != nil {
			log.Errorf("Error getting repository %s. %s", repo.Slug, err)
			log.Errorf("Error getting org members %s. %s", repo.Owner, merr)
			c.String(404, "MAINTAINERS file not found. %s", err)
			return
		} else {
			for _, member := range members {
				file = append(file, member.Login...)
				file = append(file, '\n')
			}
		}
	}

	maintainer, err := model.ParseMaintainer(file)
	if err != nil {
		log.Errorf("Error parsing MAINTAINERS file for %s. %s", repo.Slug, err)
		c.String(500, "Error parsing MAINTAINERS file. %s.", err)
		return
	}

	comments, err := remote.GetComments(c, user, repo, hook.Issue.Number)
	if err != nil {
		log.Errorf("Error retrieving comments for %s pr %d. %s", repo.Slug, hook.Issue.Number, err)
		c.String(500, "Error retrieving comments. %s.", err)
		return
	}
	approvers := getApprovers(config, maintainer, hook.Issue, comments)
	approved := len(approvers) >= config.Approvals
	err = remote.SetStatus(c, user, repo, hook.Issue.Number, len(approvers), config.Approvals)
	if err != nil {
		log.Errorf("Error setting status for %s pr %d. %s", repo.Slug, hook.Issue.Number, err)
		c.String(500, "Error setting status. %s.", err)
		return
	}

	log.Debugf("processed comment for %s. received %d of %d approvals", repo.Slug, len(approvers), config.Approvals)

	c.IndentedJSON(200, gin.H{
		"approvers":   maintainer.People,
		"settings":    config,
		"approved":    approved,
		"approved_by": approvers,
	})
}

// getApprovers is a helper function that analyzes the list of comments
// and returns the list of approvers.
func getApprovers(config *model.Config, maintainer *model.Maintainer, issue *model.Issue, comments []*model.Comment) []*model.Person {
	approverm := map[string]bool{}
	approvers := []*model.Person{}

	matcher, err := regexp.Compile(config.Pattern)
	if err != nil {
		// this should never happen
		return approvers
	}

	for _, comment := range comments {
		// cannot lgtm your own pull request
		if config.SelfApprovalOff && comment.Author == issue.Author {
			continue
		}
		// the user must be a valid maintainer of the project
		person, ok := maintainer.People[comment.Author]
		if !ok {
			continue
		}
		// the same author can't approve something twice
		if _, ok := approverm[comment.Author]; ok {
			continue
		}
		// verify the comment matches the approval pattern
		if matcher.MatchString(comment.Body) {
			approverm[comment.Author] = true
			approvers = append(approvers, person)
		}
	}

	return approvers
}


text:
package com.xeiam.xchange.anx.v2.dto.marketdata;

import java.math.BigDecimal;

import com.xeiam.xchange.dto.Order;
import com.xeiam.xchange.dto.trade.TradeMetaInfo;

//TODO look at this
public class ANXTradeMetaData extends TradeMetaInfo {

  private final BigDecimal amountMaximum;

  public ANXTradeMetaData(BigDecimal amountMinimum, BigDecimal amountMaximum, int priceScale) {

    super(null, amountMinimum, priceScale, null);
    this.amountMaximum = amountMaximum;
  }

  @Override
  protected void verifyOrder(Order order) {

    super.verifyOrder(order);

    if (order.getTradableAmount().compareTo(amountMaximum) > 0) {
      throw new IllegalArgumentException("Order amount exceeds maximum");
    }
  }

  public BigDecimal getAmountMaximum() {

    return amountMaximum;
  }
}


text:
"""
Distribution class

$Id$
"""
__version__='$Revision$'
# To do:
#
# - wrap bins for cyclic histograms
# - check use of float() in count_mag() etc
# - clarify comment about negative selectivity
#
# - function to return value in a range (like a real histogram)
# - cache values
# - assumes cyclic axes start at 0: include a shift based on range
#
# - is there a way to make this work for arrays without mentioning
#   "array" anywhere in here?
# - should this be two classes: one for the core (which would be
#   small though) and another for statistics?

# The basic functions do not have any dependencies, but these imports
# are needed for some of the statistical functions (e.g. vector sum).
from math import pi

from numpy.oldnumeric import innerproduct, array, exp, argmax

from topo.base.arrayutil import arg, wrap

class Distribution(object):
    """
    Holds a distribution of the values f(x) associated with a variable x.

    A Distribution is a histogram-like object that is a dictionary of
    samples.  Each sample is an x:f(x) pair, where x is called the bin
    and f(x) is called the value(). Each bin's value is typically
    maintained as the sum of all the values that have been placed into
    it.

    The bin axis is continuous, and can represent a continuous
    quantity without discretization.  Alternatively, this class can be
    used as a traditional histogram by either discretizing the bin
    number before adding each sample, or by binning the values in the
    final Distribution.

    Distributions are bounded by the specified axis_bounds, and can
    either be cyclic (like directions or hues) or non-cyclic.  For
    cyclic distributions, samples provided outside the axis_bounds
    will be wrapped back into the bound range, as is appropriate for
    quantities like directions.  For non-cyclic distributions,
    providing samples outside the axis_bounds will result in a
    ValueError.

    In addition to the values, can also return the counts, i.e., the
    number of times that a sample has been added with the given bin.

    Not all instances of this class will be a true distribution in the
    mathematical sense; e.g. the values will have to be normalized
    before they can be considered a probability distribution.

    If keep_peak=True, the value stored in each bin will be the
    maximum of all values ever added, instead of the sum.  The
    distribution will thus be a record of the maximum value
    seen at each bin, also known as an envelope.
    """

    # Holds the number of times that undefined values have been
    # returned from calculations for any instance of this class,
    # e.g. calls to vector_direction() or vector_selectivity() when no
    # value is non-zero.  Useful for warning users when the values are
    # not meaningful.
    undefined_vals = 0

    def __init__(self, axis_bounds=(0.0, 2*pi), cyclic=False, keep_peak=False):
        self._data = {}
        self._counts = {}

        # total_count and total_value hold the total number and sum
        # (respectively) of values that have ever been provided for
        # each bin.  For a simple distribution these will be the same as
        # sum_counts() and sum_values().
        self.total_count = 0
        self.total_value = 0.0

        self.axis_bounds = axis_bounds
        self.axis_range = axis_bounds[1] - axis_bounds[0]
        self.cyclic = cyclic
        self.keep_peak = keep_peak

    ### JABHACKALERT!  The semantics of this operation are incorrect, because
    ### an expression like x+y should not modify x, while this does.  It could
    ### be renamed __iadd__, to implement += (which has the correct semantics),
    ### but it's not yet clear how to do that.
    def __add__(self,a):
        """
        Allows add() method to be used via the '+' operator; i.e.,
        Distribution + dictionary does Distribution.add(dictionary).
        """
        self.add(a)
        return None

    def get_value(self, bin):
        """
        Return the value of the specified bin.

        (Return None if there is no such bin.)
        """
        return self._data.get(bin)

    def get_count(self, bin):
        """
        Return the count from the specified bin.

        (Return None if there is no such bin.)
        """
        return self._counts.get(bin)

    def values(self):
        """
        Return a list of values.

        Various statistics can then be calculated if desired:

          sum(vals)  (total of all values)
          max(vals)  (highest value in any bin)

        Note that the bin-order of values returned does not necessarily
        match that returned by counts().
        """
        return self._data.values()

    def counts(self):
        """
        Return a list of values.

        Various statistics can then be calculated if desired:

          sum(counts)  (total of all counts)
          max(counts)  (highest count in any bin)

        Note that the bin-order of values returned does not necessarily
        match that returned by values().
        """
        return self._counts.values()

    def bins(self):
        """
        Return a list of bins that have been populated.
        """
        return self._data.keys()

    def add(self, new_data):
        """
        Add a set of new data in the form of a dictionary of (bin,
        value) pairs.  If the bin already exists, the value is added
        to the current value.  If the bin doesn't exist, one is created
        with that value.

        Bin numbers outside axis_bounds are allowed for cyclic=True,
        but otherwise a ValueError is raised.

        If keep_peak=True, the value of the bin is the maximum of the
        current value and the supplied value.  That is, the bin stores
        the peak value seen so far.  Note that each call will increase
        the total_value and total_count (and thus decrease the
        value_mag() and count_mag()) even if the value doesn't happen
        to be the maximum seen so far, since each data point still
        helps improve the sampling and thus the confidence.
        """
        for bin in new_data.keys():

            if self.cyclic==False:
                if not (self.axis_bounds[0] <= bin <= self.axis_bounds[1]):
                    raise ValueError("Bin outside bounds.")
            # CEBALERT: Neet to support wrapping of bin values
            # else:  new_bin = wrap(self.axis_bounds[0], self.axis_bounds[1], bin)
            new_bin = bin

            if new_bin not in self._data:
                self._data[new_bin] = 0.0
                self._counts[new_bin] = 0

            new_value = new_data[bin]
            self.total_value += new_value
            self._counts[new_bin] += 1
            self.total_count += 1

            if self.keep_peak == True:
                if new_value > self._data[new_bin]: self._data[new_bin] = new_value
            else:
                self._data[new_bin] += new_value

    def sub_distr( self, distr ):
        """
	Subtract the given distribution from the current one.
	Only existing bins are modified, new bins in the given
	distribution are discarded without raising errors.

        Note that total_value and total_count are not affected, and
	keep_peak is ignored, therefore analysis relying on these
	values should not call this method.
        """
        for b in distr.bins():
            if b in self.bins():
		v	= distr._data.get( b )
                if v is not None:	self._data[ b ] -= v

    def max_value_bin(self):
        """Return the bin with the largest value."""
        return self._data.keys()[argmax(self._data.values())]

    def second_max_value_bin(self):
        """
	Return the bin with the second largest value.
	If there is one bin only, return it. This is not a correct result,
	however it is practical for plotting compatibility, and it will not
	mistakenly be claimed as secondary maximum, by forcing its selectivity
	to 0.0
	"""
        if len(self._data) <= 1:
            return self._data.keys()[ 0 ]

	k		= self.max_value_bin()
	v		= self._data.pop(k)
	m		= self.max_value_bin()
	self._data[k]	= v

        return m

    def second_peak_bin(self):
        """
	Return the bin with the second peak in the distribution.
	Unlike second_max_value_bin(), it does not return a bin which is the
	second largest value, if laying on a wing of the first peak, the second
	peak is returned only if the distribution is truly multimodal. If it isn't,
	return the first peak (for compatibility with numpy array type, and
	plotting compatibility), however the correspondong selectivity will be
	forced to 0.0
	"""
	l	= len( self._data )
        if l <= 1:
            return self._data.keys()[ 0 ]

	ks	= self._data.keys()
	ks.sort()
	ik0	= ks.index( self._data.keys()[ argmax( self._data.values() ) ] )
	k0	= ks[ ik0 ]
	v0	= self._data[ k0 ]

	v	= v0
	k	= k0
	ik	= ik0
	while self._data[ k ] <= v:
		ik	+= 1
		if ik >= l:
			ik	= 0
		if ik == ik0:
			return k0
		v	= self._data[ k ]
		k	= ks[ ik ]
	ik1	= ik

	v	= v0
	k	= k0
	ik	= ik0
	while self._data[ k ] <= v:
		ik	-= 1
		if ik < 0:
			ik	= l - 1
		if ik == ik0:
			return k0
		v	= self._data[ k ]
		k	= ks[ ik ]
	ik2	= ik

	if ik1 == ik2:
		return ks[ ik1 ]

	ik	= ik1
	m	= 0
	while ik != ik2:
		k	= ks[ ik ]
		if self._data[ k ] > m:
			m	= self._data[ k ]
			im	= ik
		ik	+= 1
		if ik >= l:
			ik	= 0

	return ks[ im ]

    def weighted_average(self):
        """
        Return a continuous, interpolated equivalent of the max_value_bin().

        For a cyclic distribution, this is the direction of the vector
        sum (see vector_sum()).

        For a non-cyclic distribution, this is the arithmetic average
        of the data on the bin_axis, where each bin is weighted by its
        value.
        """
        if self.cyclic == True:
            return self.vector_sum()[1]
        else:
            return self._weighted_average()

    def vector_sum(self):
        """
        Return the vector sum of the data as a tuple (magnitude, avgbinnum).

        Each bin contributes a vector of length equal to its value, at
        a direction corresponding to the bin number.  Specifically,
        the total bin number range is mapped into a direction range
        [0,2pi].

        For a cyclic distribution, the avgbinnum will be a continuous
        measure analogous to the max_value_bin() of the distribution.
        But this quantity has more precision than max_value_bin()
        because it is computed from the entire distribution instead of
        just the peak bin.  However, it is likely to be useful only
        for uniform or very dense sampling; with sparse, non-uniform
        sampling the estimates will be biased significantly by the
        particular samples chosen.

        The avgbinnum is not meaningful when the magnitude is 0,
        because a zero-length vector has no direction.  To find out
        whether such cases occurred, you can compare the value of
        undefined_vals before and after a series of calls to this
        function.

        """
        # vectors are represented in polar form as complex numbers
        r = self._data.values()
        theta = self._bins_to_radians(array(self._data.keys()))
        v_sum = innerproduct(r, exp(theta*1j))

        magnitude = abs(v_sum)
        direction = arg(v_sum)

        if v_sum == 0:
            self.undefined_vals += 1

        direction_radians = self._radians_to_bins(direction)

        # wrap the direction because arctan2 returns principal values
        wrapped_direction = wrap(self.axis_bounds[0], self.axis_bounds[1], direction_radians)

        return (magnitude, wrapped_direction)

    def weighted_sum(self):
        """Return the sum of each value times its bin."""
        return innerproduct(self._data.keys(), self._data.values())

    def _weighted_average(self):
        """
        Return the weighted_sum divided by the sum of the values
        """
        return self._safe_divide(self.weighted_sum(),sum(self._data.values()))

    def selectivity(self):
        """
        Return a measure of the peakedness of the distribution.  The
        calculation differs depending on whether this is a cyclic
        variable.  For a cyclic variable, returns the magnitude of the
        vector_sum() divided by the sum_value() (see
        _vector_selectivity for more details).  For a non-cyclic
        variable, returns the max_value_bin()) as a proportion of the
        sum_value() (see _relative_selectivity for more details).
        """
        if self.cyclic == True:
            return self._vector_selectivity()
        else:
            return self._relative_selectivity()

    # CEBHACKALERT: the definition of selectivity for non-cyclic
    # quantities probably needs some more thought.
    # Additionally, this fails the test in testfeaturemap
    # (see the comment there).
    def _relative_selectivity(self):
        """
        Return max_value_bin()) as a proportion of the sum_value().

        This quantity is a measure of how strongly the distribution is
        biased towards the max_value_bin().  For a smooth,
        single-lobed distribution with an inclusive, non-cyclic range,
        this quantity is an analog to vector_selectivity.  To be a
        precise analog for arbitrary distributions, it would need to
        compute some measure of the selectivity that works like the
        weighted_average() instead of the max_value_bin().  The result
        is scaled such that if all bins are identical, the selectivity
        is 0.0, and if all bins but one are zero, the selectivity is
        1.0.
        """
        # A single bin is considered fully selective (but could also
        # arguably be considered fully unselective)
        if len(self._data) <= 1:
            return 1.0

        proportion = self._safe_divide( max(self._data.values()),
                                        sum(self._data.values()) )
        offset = 1.0/len(self._data)
        scaled = (proportion-offset)/(1.0-offset)

        # negative scaled is possible
        # e.g. 2 bins, with values that sum to less than 0.5
        # this probably isn't what should be done in those cases
        if scaled >= 0.0:
            return scaled
        else:
            return 0.0

    def _vector_selectivity(self):
        """
        Return the magnitude of the vector_sum() divided by the sum_value().

        This quantity is a vector-based measure of the peakedness of
        the distribution.  If only a single bin has a non-zero value(),
        the selectivity will be 1.0, and if all bins have the same
        value() then the selectivity will be 0.0.  Other distributions
        will result in intermediate values.

        For a distribution with a sum_value() of zero (i.e. all bins
        empty), the selectivity is undefined.  Assuming that one will
        usually be looking for high selectivity, we return zero in such
        a case so that high selectivity will not mistakenly be claimed.
        To find out whether such cases occurred, you can compare the
        value of undefined_values() before and after a series of
        calls to this function.
        """
        return self._safe_divide(self.vector_sum()[0], sum(self._data.values()))

    def second_selectivity(self):
        """
	Return the selectivity of the second largest value in the distribution.
	If there is one bin only, the selectivity is 0, since there is no second
	peack at all, and this value is also used to discriminate the validity
	of second_max_value_bin()
	Selectivity is computed in two ways depending on whether the variable is
	a cyclic, as in selectivity()
	"""
        if len(self._data) <= 1:
            return 0.0
        if self.cyclic == True:
            return self._vector_second_selectivity()
        else:
            return self._relative_second_selectivity()

    def _relative_second_selectivity(self):
        """
        Return the value of the second maximum as a proportion of the sum_value()
	see _relative_selectivity() for further details
        """
	k		= self.max_value_bin()
	v		= self._data.pop(k)
	m		= max( self._data.values() )
	self._data[k]	= v

        proportion	= self._safe_divide( m, sum(self._data.values()) )
        offset		= 1.0/len(self._data)
        scaled		= (proportion-offset)/(1.0-offset)

	return max( scaled, 0.0 )

    def _vector_second_selectivity(self):
        """
        Return the magnitude of the vector_sum() of all bins excluding the
	maximum one, divided by the sum_value().
	see _vector_selectivity() for further details
        """
	k		= self.max_value_bin()
	v		= self._data.pop(k)
	s		= self.vector_sum()[0]
	self._data[k]	= v

        return self._safe_divide( s, sum(self._data.values()) )

    def second_peak_selectivity(self):
        """
	Return the selectivity of the second peak in the distribution.
	If the distribution has only one peak, return 0.0, and this value is
	also usefl to discriminate the validity of second_peak_bin()
	"""
        if len(self._data) <= 1:
            return 0.0

	p1	= self.max_value_bin()
	p2	= self.second_peak_bin()
	if p1 == p2:
            return 0.0

	m		= self._data[ p2 ]
        proportion	= self._safe_divide( m, sum(self._data.values()) )
        offset		= 1.0/len(self._data)
        scaled		= (proportion-offset)/(1.0-offset)

	return max( scaled, 0.0 )

    def value_mag(self, bin):
        """Return the value of a single bin as a proportion of total_value."""
        return self._safe_divide(self._data.get(bin), self.total_value)

    def count_mag(self, bin):
        """Return the count of a single bin as a proportion of total_count."""
        return self._safe_divide(float(self._counts.get(bin)), float(self.total_count))
        # use of float()

    def _bins_to_radians(self, bin):
        """
        Convert a bin number to a direction in radians.

        Works for NumPy arrays of bin numbers, returning
        an array of directions.
        """
        return (2*pi)*bin/self.axis_range

    def _radians_to_bins(self, direction):
        """
        Convert a direction in radians into a bin number.

        Works for NumPy arrays of direction, returning
        an array of bin numbers.
        """
        return direction*self.axis_range/(2*pi)

    def _safe_divide(self,numerator,denominator):
        """
        Division routine that avoids division-by-zero errors
        (returning zero in such cases) but keeps track of them
        for undefined_values().
        """
        if denominator==0:
            self.undefined_vals += 1
            return 0
        else:
            return numerator/denominator

##    # not tested - will it be needed?
##    def relative_value(self, bin):
##        """
##        Return the value of the given bin as a proportion of the
##        sum_value().
##
##        This quantity is on a scale from 0.0 (the
##        specified bin is zero and others are nonzero) to 1.0 (the
##        specified bin is the only nonzero bin).  If the distribution is
##        empty the result is undefined; in such a case zero is returned
##        and the value returned by undefined_values() is incremented.
##        """
##        return self._safe_divide(self._data.get(bin), sum(self.values()))


text:
from trtools.core.column_panel import ColumnPanel, PanelDict
import trtools.core.boolean # monkey
import trtools.core.columns # monkey
import trtools.core.select # monkey
import trtools.core.topper # monkey
import trtools.core.groupby # monkey
import trtools.core.select # monkey
import trtools.core.wrangling # monkey
import trtools.core.rolling # monkey
import trtools.core.indexing # monkey
import trtools.core.time_selector # monkey
import trtools.core.timeseries as timeseries
from trtools.core.base import *
import trtools.core.pandas_np as pnp


text:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as Payment from '../../types/paymentTypes';
import * as Electron from 'electron';
import { SelectShippingMethod } from './selectShippingMethod';
import { SelectShippingAddress } from './selectShippingAddress';
import { SelectCreditCard } from './selectCreditCard';
import { AddCreditCardView } from './addCreditCardView';
import { AddShippingAddressView } from './addShippingAddressView';
import { PaymentDetails } from './paymentDetails';
import { ICheckoutViewState, ICheckoutShippingAddress, ICheckoutCreditCard, PaymentTypeConverter } from './checkoutTypes';
import { Emulator } from '../emulator';
import { ISettings } from '../settings';
import { ConversationActions, ServerSettingsActions } from '../reducers';
import { Button } from './button';
import { CheckoutSettings } from './checkoutSettings';
import { uniqueId } from '../../shared/utils';

export class CheckoutView extends React.Component<{}, ICheckoutViewState> {
    private local: ICheckoutViewState;
    private settings: ISettings;
    private checkoutSettings: CheckoutSettings;
    private checkoutSession: Payment.ICheckoutConversationSession;

    constructor(props) {
        super(props);
        let param = location.search;
        let paymentRequest;
        if (param) {
            if(param.startsWith('?')) {
                param = param.substring(1);
            }
            paymentRequest = JSON.parse(decodeURI(param)) as Payment.IPaymentRequest;
        }

        this.checkoutSettings = new CheckoutSettings();
        let cache = this.checkoutSettings.getSettings();

        this.local = {
            paymentRequest: paymentRequest,
            selectedCreditCard: undefined,
            creditCards: [],
            selectedShippingAddress: undefined,
            shippingAddresses: [],
            emailAddress: cache.email,
            phoneNumber: cache.phoneNumber,
            selectCreditCardIsVisible: false,
            selectShippingAddressIsVisible: false,
            selectShippingMethodIsVisible: false,
            addCreditCardIsVisible: false,
            addShippingAddressIsVisible: false,
            isInValidationMode: false
        };
        cache.creditCards.forEach(x => this.local.creditCards.push(x));
        cache.shippingAddresses.forEach(x => this.local.shippingAddresses.push(x));

        this.state = this.local;

        this.emailChanged = this.emailChanged.bind(this);
        this.phoneChanged = this.phoneChanged.bind(this);

        this.setShippingMethodSelectorIsVisible = this.setShippingMethodSelectorIsVisible.bind(this);
        this.getShippingMethodSelectorIsVisible = this.getShippingMethodSelectorIsVisible.bind(this);
        this.getSelectedShippingMethod = this.getSelectedShippingMethod.bind(this);
        this.selectShippingMethod = this.selectShippingMethod.bind(this);

        this.setShippingAddressSelectorIsVisible = this.setShippingAddressSelectorIsVisible.bind(this);
        this.getShippingAddressSelectorIsVisible = this.getShippingAddressSelectorIsVisible.bind(this);
        this.getSelectedShippingAddress = this.getSelectedShippingAddress.bind(this);
        this.selectShippingAddress = this.selectShippingAddress.bind(this);
        this.addShippingAddress = this.addShippingAddress.bind(this);
        this.removeShippingAddress = this.removeShippingAddress.bind(this);
        this.onSaveShippingAddress = this.onSaveShippingAddress.bind(this);
        this.onCancelAddShippingAddress = this.onCancelAddShippingAddress.bind(this);

        this.setCreditCardSelectorIsVisible = this.setCreditCardSelectorIsVisible.bind(this);
        this.getCreditCardSelectorIsVisible = this.getCreditCardSelectorIsVisible.bind(this);
        this.getSelectedCreditCard = this.getSelectedCreditCard.bind(this);
        this.selectCreditCard = this.selectCreditCard.bind(this);
        this.addCreditCard = this.addCreditCard.bind(this);
        this.removeCreditCard = this.removeCreditCard.bind(this);
        this.onSaveCreditCard = this.onSaveCreditCard.bind(this);
        this.onCancelAddCreditCard = this.onCancelAddCreditCard.bind(this);

        this.pay = this.pay.bind(this);

        this.onPageMouseDown = this.onPageMouseDown.bind(this);

        let checkoutState: any = Electron.ipcRenderer.sendSync('getCheckoutState');
        this.checkoutSession = {
            paymentActivityId: checkoutState.paymentActivityId,
            checkoutConversationId: uniqueId(),
            checkoutFromId: uniqueId(),
        };
        this.settings = checkoutState.settings;
        Emulator.serviceUrl = checkoutState.serviceUrl;

        ConversationActions.joinConversation(this.settings.conversation.conversationId);
        ServerSettingsActions.set(this.settings.serverSettings);
    }

    private emailChanged(text: string): void {
        this.updateState({ emailAddress: text });
        this.checkoutSettings.updateEmail(text);
    }

    private phoneChanged(text: string): void {
        this.updateState({ phoneNumber: text });
        this.checkoutSettings.updatePhoneNumber(text);
    }

    private setShippingAddressSelectorIsVisible(isVisible: boolean) {
        if(isVisible) {
            this.setCreditCardSelectorIsVisible(false);
            this.setShippingMethodSelectorIsVisible(false);
        }
        this.updateState({ selectShippingAddressIsVisible: isVisible});
    }

    private getShippingAddressSelectorIsVisible(): boolean {
        return this.state.selectShippingAddressIsVisible;
    }

    private getSelectedShippingAddress() {
        return this.state.selectedShippingAddress
    }

    private selectShippingAddress(value: ICheckoutShippingAddress) {
        this.updateState({ selectedShippingAddress: value});
        let shippingOption = this.getSelectedShippingMethod();
        Emulator.updateShippingAddress(
            this.checkoutSession,
            this.state.paymentRequest,
            PaymentTypeConverter.convertAddress(value),
            shippingOption ? shippingOption.id : undefined,
            (err, statusCode: number, result: Payment.IPaymentRequestUpdateResult) => {
                if (!err && result && result.details) {
                    this.updatePaymentDetails(result.details);
                }
            });
    }

    private addShippingAddress() {
        this.updateState({ addShippingAddressIsVisible: true });
    }

    private removeShippingAddress(item: ICheckoutShippingAddress) {
        let idx = this.local.shippingAddresses.indexOf(item);
        if (idx !== -1) {
            if (this.local.selectedShippingAddress === item) {
                this.local.selectedShippingAddress = undefined;
            }
            this.local.shippingAddresses.splice(idx, 1);
            this.updateState(this.local);
            this.checkoutSettings.removeShippingAddress(item);
        }
    }

    private onSaveShippingAddress(item: ICheckoutShippingAddress) {
        this.local.shippingAddresses.push(item);
        this.local.selectedShippingAddress = item;
        this.local.addShippingAddressIsVisible = false;
        this.updateState(this.local);
        this.checkoutSettings.addShippingAddress(item);
        this.selectShippingAddress(item);
    }

    private onCancelAddShippingAddress() {
        this.updateState({ addShippingAddressIsVisible: false });
    }

    private setShippingMethodSelectorIsVisible(isVisible: boolean) {
        if(isVisible) {
            this.setCreditCardSelectorIsVisible(false);
            this.setShippingAddressSelectorIsVisible(false);
        }
        this.updateState({ selectShippingMethodIsVisible: isVisible});
    }

    private getShippingMethodSelectorIsVisible(): boolean {
        return this.state.selectShippingMethodIsVisible;
    }

    private getSelectedShippingMethod(state?) {
        if (!state) {
            state = this.state;
        }
        if (state.paymentRequest.details.shippingOptions) {
            let selected = state.paymentRequest.details.shippingOptions.filter(option => option.selected);
            return selected && selected.length >= 1 ? selected[0] : undefined;
        }
        return undefined;
    }

    private selectShippingMethod(value: Payment.IPaymentShippingOption) {
        if (this.local.paymentRequest.details.shippingOptions) {
            this.local.paymentRequest.details.shippingOptions.forEach(option => {
                if (option.id === value.id) {
                    option.selected = true;
                } else {
                    option.selected = false;
                }
            });
        }

        this.updatePaymentDetails(this.local.paymentRequest.details);

        Emulator.updateShippingOption(
            this.checkoutSession,
            this.local.paymentRequest,
            PaymentTypeConverter.convertAddress(this.local.selectedShippingAddress),
            value.id,
            (err, statusCode: number, result: Payment.IPaymentRequestUpdateResult) => {
                if (!err && result && result.details) {
                    this.updatePaymentDetails(result.details);
                }
            });
    }

    private setCreditCardSelectorIsVisible(isVisible: boolean) {
        if(isVisible) {
            this.setShippingMethodSelectorIsVisible(false);
            this.setShippingAddressSelectorIsVisible(false);
        }
        this.updateState({ selectCreditCardIsVisible: isVisible});
    }

    private getCreditCardSelectorIsVisible(): boolean {
        return this.state.selectCreditCardIsVisible;
    }

    private getSelectedCreditCard() {
        return this.state.selectedCreditCard
    }

    private selectCreditCard(value: ICheckoutCreditCard) {
        this.updateState({ selectedCreditCard: value});
    }

    private addCreditCard() {
        this.updateState({ addCreditCardIsVisible: true });
    }

    private removeCreditCard(item: ICheckoutCreditCard) {
        let idx = this.local.creditCards.indexOf(item);
        if (idx !== -1) {
            this.local.creditCards.splice(idx, 1);
            if (this.local.selectedCreditCard === item) {
                this.local.selectedCreditCard = undefined;
            }
            this.updateState(this.local);
            this.checkoutSettings.removeCreditCard(item);
        }
    }

    private onSaveCreditCard(item: ICheckoutCreditCard) {
        this.local.creditCards.push(item);
        this.local.selectedCreditCard = item;
        this.local.addCreditCardIsVisible = false;
        this.updateState(this.local);
        this.checkoutSettings.addCreditCard(item);
        this.selectCreditCard(item);
    }

    private onCancelAddCreditCard() {
        this.updateState({ addCreditCardIsVisible: false });
    }

    private pay() {
        if (this.validate()) {
            let shippingOption = this.getSelectedShippingMethod();
            Emulator.paymentComplete(
                this.checkoutSession,
                this.state.paymentRequest,
                PaymentTypeConverter.convertAddress(this.state.selectedShippingAddress),
                shippingOption ? shippingOption.id : '',
                this.state.emailAddress,
                this.state.phoneNumber,
                (err, statusCode: number, body: Payment.IPaymentRequestCompleteResult) => {
                    console.log(body.result);
                    if(body.result === 'success') {
                        window.close();
                    }
                });
        } else {
            this.updateState({isInValidationMode: true});
        }
    }

    private validate(): boolean {
        if (this.local.paymentRequest.options.requestPayerEmail && !this.hasValue(this.local.emailAddress)) {
            return false;
        }
        if (this.local.paymentRequest.options.requestPayerPhone && !this.hasValue(this.local.phoneNumber)) {
            return false;
        }
        if (this.local.paymentRequest.options.requestPayerName && !(this.local.selectedCreditCard && this.hasValue(this.local.selectedCreditCard.cardholderName))) {
            return false;
        }
        if (this.local.paymentRequest.options.requestShipping && !(this.local.selectedShippingAddress && this.getSelectedShippingMethod(this.local) !== undefined)) {
            return false;
        }
        return true;
    }

    private hasValue(value: string): boolean {
        return value && value.length > 0;
    }

    private onPageMouseDown(evt: any) {
        const selectShippingMethod = ReactDOM.findDOMNode(this.refs['select-shipping-method']);
        if (!selectShippingMethod.contains(evt.target as Node) && this.state.selectShippingMethodIsVisible) {
            this.setShippingMethodSelectorIsVisible(false);
        }

        const selectShippingAddress = ReactDOM.findDOMNode(this.refs['select-shipping-address']);
        if (!selectShippingAddress.contains(evt.target as Node) && this.state.selectShippingAddressIsVisible) {
            this.setShippingAddressSelectorIsVisible(false);
        }

        const selectCreditCard = ReactDOM.findDOMNode(this.refs['select-credit-card']);
        if (!selectCreditCard.contains(evt.target as Node) && this.state.selectCreditCardIsVisible) {
            this.setCreditCardSelectorIsVisible(false);
        }
    }

    private updatePaymentDetails(details: Payment.IPaymentDetails) {
        this.local.paymentRequest.details = details;
        this.updateState(this.local);
    }

    private updateState(update: any) {
        this.local = Object.assign({}, this.local, update);
        this.setState(this.local);
        if(this.local.isInValidationMode && this.validate()) {
            this.updateState({isInValidationMode: false});
        }
    }

    private showPayerNameValidationState(): boolean {
        return this.state.isInValidationMode && this.state.paymentRequest.options.requestPayerName &&
            !(this.state.selectedCreditCard && this.state.selectedCreditCard.cardholderName && this.state.selectedCreditCard.cardholderName.length);
    }

    private showShippingValidationState(): boolean {
        return this.state.isInValidationMode && this.state.paymentRequest.options.requestShipping &&
            !this.state.selectedShippingAddress;
    }

    private showShippingOptionValidationState(): boolean {
        return this.state.isInValidationMode && this.state.paymentRequest.options.requestShipping &&
            !this.getSelectedShippingMethod();
    }

    private showEmailValidationState(): boolean {
        return this.state.isInValidationMode && this.state.paymentRequest.options.requestPayerEmail &&
            !this.hasValue(this.state.emailAddress);
    }

    private showPhoneNumberValidationState(): boolean {
        return this.state.isInValidationMode && this.state.paymentRequest.options.requestPayerPhone &&
            !this.hasValue(this.state.phoneNumber);
    }

    render() {
        if (this.state.addCreditCardIsVisible) {
            return (

                    <AddCreditCardView
                        onSave={this.onSaveCreditCard}
                        onCancel={this.onCancelAddCreditCard}/>

);
        } else if (this.state.addShippingAddressIsVisible) {
            return (

                    <AddShippingAddressView
                        onSave={this.onSaveShippingAddress}
                        onCancel={this.onCancelAddShippingAddress}/>

);
        } else {
            let validationError;
            if (this.state.isInValidationMode) {
                validationError = (
*Some fields are required
);
            }
            return (

Emulating: Confirm and Pay

                            {validationError}

Pay with

                                <SelectCreditCard
                                    ref='select-credit-card'
                                    getIsVisible={this.getCreditCardSelectorIsVisible}
                                    setIsVisible={this.setCreditCardSelectorIsVisible}
                                    items={this.state.creditCards}
                                    getSelectedItem={this.getSelectedCreditCard}
                                    selectItem={this.selectCreditCard}
                                    placeholder='Select a way to pay'
                                    addItemLabel='+ Add a new way to pay'
                                    onClickAddItem={this.addCreditCard}
                                    onClickRemoveItem={this.removeCreditCard}
                                    classes={this.showPayerNameValidationState() ? 'invalid-input' : ''} />

Ship to

                                <SelectShippingAddress
                                    ref='select-shipping-address'
                                    getIsVisible={this.getShippingAddressSelectorIsVisible}
                                    setIsVisible={this.setShippingAddressSelectorIsVisible}
                                    items={this.state.shippingAddresses}
                                    getSelectedItem={this.getSelectedShippingAddress}
                                    selectItem={this.selectShippingAddress}
                                    placeholder='Select a shipping address'
                                    addItemLabel='+ Add a new shipping address'
                                    onClickAddItem={this.addShippingAddress}
                                    onClickRemoveItem={this.removeShippingAddress}
                                    classes={this.showShippingValidationState() ? 'invalid-input' : ''} />

Shipping options

                                <SelectShippingMethod
                                    ref='select-shipping-method'
                                    getIsVisible={this.getShippingMethodSelectorIsVisible}
                                    setIsVisible={this.setShippingMethodSelectorIsVisible}
                                    items={this.state.paymentRequest.details.shippingOptions}
                                    getSelectedItem={this.getSelectedShippingMethod}
                                    selectItem={this.selectShippingMethod}
                                    classes={this.showShippingOptionValidationState() ? 'invalid-input' : ''} />

Email receipt to

                                <input
                                    type="text"
                                    className={'checkout-input' + (this.showEmailValidationState() ? ' invalid-input' : '')}
                                    value={this.state.emailAddress}
                                    onChange={e => this.emailChanged((e.target as any).value)} />

Phone

                                <input
                                    type="text"
                                    className={'checkout-input' + (this.showPhoneNumberValidationState() ? ' invalid-input' : '')}
                                    value={this.state.phoneNumber}
                                    onChange={e => this.phoneChanged((e.target as any).value)} />

                            <PaymentDetails details={this.state.paymentRequest.details} />

                            <Button classes='primary-button pay-button' onClick={this.pay} label='Pay'/>

            );
        }
    }
}


text:
<?php

if (false) :
doSomething();
endif;


text:
require 'restclient'
require "bamboo-client/http/abstract"

module Bamboo
  module Client
    module Http
      autoload :Json, "bamboo-client/http/json"
      autoload :Xml, "bamboo-client/http/xml"
    end
  end
end


text:
<?php
/* vim: set expandtab shiftwidth=4 softtabstop=4 tabstop=4 foldmethod=marker: */

/**
 * TIP_Application definition file
 *
 * LICENSE: This source file is subject to the New BSD license that is
 * available through the world-wide-web at the following URI:
 * http://www.opensource.org/licenses/bsd-license.php
 * If you did not receive a copy of the New BSD License and are unable to
 * obtain it through the web, please send a note to license@php.net so we
 * can mail you a copy immediately.
 *
 * @author    Nicola Fontana <ntd@entidi.it>
 * @copyright Copyright © 2006-2008 Nicola Fontana
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @package   TIP
 * @since     0.0.1
 */

/**
 * The main module
 *
 * This module manages the generation of the "page" (the most dynamic part of
 * a TIP site). This is done by using the "content" property as a text buffer.
 *
 * When the tagPage() is called, usually throught a tag in the main template,
 * the TIP_Application module will call the callbacks stored in the queue
 * in sequential order. The page is the output of these callbacks.
 *
 * After a TIP_Application instantiation, the global variable $GLOBALS[TIP_MAIN]
 * will contain a reference to this TIP_Application instantiated object.
 * Your index.php, if the TIP system is properly configured, will usually be
 * as the following one:
 *
 *
 * <?php
 * require_once './logic/TIP.php';
 *
 * TIP_Type::getInstance('main');
 * $GLOBALS[TIP_MAIN]->go();
 * ?>
 *
 *
 * @package  TIP
 */
class TIP_Application extends TIP_Module
{
    //{{{ Properties

    /**
     * Page begin string (incipit)
     * @var string
     */
    protected $incipit = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n\n";

    /**
     * Page end string (explicit)
     * @var string
     */
    protected $explicit = '';

    /**
     * Namespace
     * @var string
     */
    protected $namespace = null;

    /**
     * Flag to enable global JSON infrastructure for unobtrusive javascript
     * @var boolean
     */
    protected $json = false;

    /**
     * Page title
     * @var string
     */
    protected $title = 'Untitled TIP site';

    /**
     * Page description
     * @var string
     */
    protected $description = null;

    /**
     * Robots metatag
     * @var string
     */
    protected $robots = 'index,follow';

    /**
     * Page keywords
     * @var string
     */
    protected $keywords = 'tip';

    /**
     * Additional code to add at the end of the  section
     * @var string
     */
    protected $additional = '';

    /**
     * The default data engine to use: required
     * @var TIP_Data_Engine
     */
    protected $data_engine = null;

    /**
     * The data root path
     * @var string
     */
    protected $data_root = array('data');

    /**
     * The icon root path
     * @var string
     */
    protected $icon_root = array('style', 'icons');

    /**
     * The shared modules interface
     *
     * The associative array of shared modules, organized by "job".
     * The job is the key, while the instance id is the value.
     *
     * @var array
     */
    protected $shared_modules = array(
        'user'      => 'user',
        'privilege' => 'privilege',
        'notify'    => 'notify',
        'locale'    => 'locale',
        'logger'    => 'logger'
    );

    /**
     * A prefix to prepend to all data ids
     * @var string
     */
    protected $data_prefix = '';

    /**
     * The uri to redirect the browse on fatal errors
     * @var string
     */
    protected $fatal_uri = '/fatal.html';

    /**
     * The template to run to generate the
     * @var string
     */
    protected $head_template = 'head';

    /**
     * The template to run to generate the
     * @var string
     */
    protected $body_template = 'body';

    /**
     * The template to run to generate the default page content
     * @var string
     */
    protected $default_template = 'default';

    /**
     * The file to run to notify errors
     * @var string
     */
    protected $error_template = 'error';

    /**
     * The file to run to notify warnings
     * @var string
     */
    protected $warning_template = 'warning';

    /**
     * The file to run to notify informations
     * @var string
     */
    protected $info_template = 'info';

    /**
     * The page content
     * @var string
     */
    protected $content = '';

    //}}}
    //{{{ Constructor/destructor

    /**
     * Check the options
     *
     * Overridable static method that checks $options for missing or invalid
     * values and eventually corrects its content.
     *
     * @param  array &$options Properties values
     * @return bool            true on success or false on error
     */
    static protected function checkOptions(&$options)
    {
        if (!parent::checkOptions($options) || !isset($options['engine'], $options['data_engine'])) {
            return false;
        }

        if (is_string($options['data_engine'])) {
            $options['data_engine'] =& TIP_Type::singleton(array(
                'id'   => $options['data_engine'],
                'type' => array('data_engine', $options['data_engine'])
            ));
        } elseif (is_array($options['data_engine'])) {
            $options['data_engine'] =& TIP_Type::singleton($options['data_engine']);
        }
        if (is_null($options['data_engine'])) {
            return false;
        }

        return true;
    }

    /**
     * Constructor
     *
     * Initializes a TIP_Application instance.
     *
     * @param array $options Properties values
     */
    protected function __construct($options)
    {
        $GLOBALS[TIP_MAIN] =& $this;
        parent::__construct($options);
    }

    protected function postConstructor()
    {
        parent::postConstructor();

        // This must be called here (not in checkOptions()) to avoid
        // buildActionUri() call before application instantiation
        isset($this->fatal_uri) || $this->fatal_uri = TIP::buildActionUri($this->id, 'fatal');

        $this->keys['TITLE'] =& $this->title;
        $this->keys['DESCRIPTION'] =& $this->description;
        $this->keys['KEYWORDS'] =& $this->keywords;
        $this->keys['ROOT'] = TIP::getRoot();
        $this->keys['HOME'] = TIP::getHome();
        $this->keys['REFERER'] = '';

        // Set $_request
        $module = TIP::getGet('module', 'string');
        $action = TIP::getGet('action', 'string');

        if (!$action) {
            $module = TIP::getPost('module', 'string');
            $action = TIP::getPost('action', 'string');
        }

        $this->_request = array(
            'uri'    => @$_SERVER['REQUEST_URI'],
            'module' => @strtolower($module),
            'action' => @strtolower($action),
            'id'     => TIP::getGetOrPost('id', 'string')
        );

        $this->keys['REQUEST'] = $this->_request['uri'];
        $this->keys['MODULE']  = $this->_request['module'];
        $this->keys['ACTION']  = $this->_request['action'];

        // The ID global key will be assigned when the requested module
        // is loaded, so a type casting can be forced (because the id_type
        // of the module is known)
        $this->keys['ID']      = '';

        // Start the session
        TIP_AHAH || $this->_startSession();
    }

    //}}}
    //{{{ Methods

    /**
     * Get a global property
     *
     * Returns a reference to a property in the current application instance.
     *
     * @param  string $property The property name
     * @return mixed            A reference to the requested property
     */
    static public function &getGlobal($property)
    {
        return $GLOBALS[TIP_MAIN]->$property;
    }

    /**
     * Get a global item
     *
     * @param  string $id The item id
     * @return mixed      The item value or null if not found
     */
    static public function getGlobalItem($id)
    {
        return $GLOBALS[TIP_MAIN]->getItem($id);
    }

    /**
     * Get a shared module
     *
     * Some special modules are shared between the application. A common example
     * is the logger or the notify modules.
     * To provide maximum flexibility, this method will get a reference to these
     * kind of modules accessing them by $job, not by id. $job is an arbitrary
     * string identifying the type of work the module must do: maybe in the
     * future, when TIP will be more stable, the jobs will be standardized with
     * a bounch of constant values.
     *
     * @param  string        $job The job identifier
     * @return TIP_Type|null      The requested shared module or null if not found
     */
    static public function &getSharedModule($job)
    {
        static $cache = array();

        if (!array_key_exists($job, $cache)) {
            $cache[$job] =& TIP_Type::getInstance($GLOBALS[TIP_MAIN]->shared_modules[$job], false);
        }

        return $cache[$job];
    }

    /**
     * Get a shared template
     *
     * Shared templates reside in the application directory and do not
     * depend on any particular module.
     *
     * @param  string            $name The template name
     * @return TIP_Template|null       The requested template or
     *                                 null if not found
     */
    static public function &getSharedTemplate($name)
    {
        $main =& $GLOBALS[TIP_MAIN];

        // Initialize the template instance
        $template =& TIP_Type::singleton(array(
            'type'   => array('template'),
            'engine' => &$main->engine,
            'path'   => array($main->id, $name)
        ));

        return $template;
    }

    /**
     * Generic message notification
     *
     * Outputs a generic notification message running the specified template
     * program with the current template engine. The output will be inserted
     * at the beginning of the page content.
     *
     * @param  TIP_SEVERITY_... $severity Severity level
     * @param  mixed            $id       The id of the message, without the
     *                                    "notify.$severity." prefix
     * @return bool                       true on success or false on errors
     */
    static public function notify($severity, $id)
    {
        static $running = false;

        // The running flag avoid recursive calls to notify()
        if ($running) {
            TIP::warning('recursive call to notify()');
            return false;
        }

        // Check for the locale instance (required)
        $locale =& TIP_Type::getInstance('locale', false);
        if (!$locale instanceof TIP_Module) {
            return false;
        }

        $running = true;
        $header_id = 'notify.' . $severity;
        $message_id = $header_id . '.' . $id;
        $data =& $locale->getProperty('data');

        $key = $data->getProperty('primary_key');
        $filter = $data->filter($key, $header_id) . $data->addFilter('OR', $key, $message_id);
        if (!is_null($view =& $locale->startDataView($filter))) {
            $rows =& $view->getProperty('rows');
            $locale->endView();
            $locale_id = $locale->getProperty('locale');
            $header = @$rows[$header_id][$locale_id];
            $message = @$rows[$message_id][$locale_id];
        }

        // Fallback values
        isset($header) || ($header = 'UNDEFINED') && TIP::warning("localized id not found ($header_id)");
        isset($message) || ($message = 'Undefined message') && TIP::warning("localized id not found ($message_id)");

        $main =& $GLOBALS[TIP_MAIN];
        $template = $main->{$severity . '_template'};

        $main->keys['NOTIFY_HEADER'] = $header;
        $main->keys['NOTIFY_MESSAGE'] = $message;
        empty($template) || $main->content = $main->tagRun($template) . $main->content;
        unset($main->keys['NOTIFY_HEADER'], $main->keys['NOTIFY_MESSAGE']);

        $running = false;
        return true;
    }

    /**
     * The "main" function
     *
     * The starting point of the TIP system. This must be called somewhere from
     * your index.php.
     */
    public function go()
    {
        // Configure the locale
        $locale_module = $this->shared_modules['locale'];
        if (TIP::setLocaleId(TIP::getOption($locale_module, 'locale'))) {
            date_default_timezone_set(TIP::getOption($locale_module, 'timezone'));
        }

        // Executes the action
        if ($this->_request['module'] && $this->_request['action']) {
            if (is_null($module =& TIP_Type::getInstance($this->_request['module'], false))) {
                TIP::notifyError('module');
            } else {
                if (isset($this->_request['id'])) {
                    // Now the module is loaded: force id type casting
                    $id_type = $module->getProperty('id_type');
                    isset($id_type) || $id_type = 'integer';
                    settype($this->_request['id'], $id_type);
                    $this->keys['ID'] = $this->_request['id'];
                }

                if (is_null($module->callAction($this->_request['action']))) {
                    TIP::notifyError(is_null(TIP::getUserId()) ? 'reserved' : 'denied');
                }
            }
        } elseif ($this->_request['module']) {
            TIP::notifyError('noaction');
        } elseif ($this->_request['action']) {
            TIP::notifyError('nomodule');
        } elseif (TIP_AHAH) {
            // AHAH request without module/action specified: perform a test
            $this->content = "
\n" . TIP::toHtml(print_r($_SERVER, true)) . "\n
\n";
        }

        if (TIP_AHAH) {
            // AHAH request: output the page and return
            header('Content-Type: application/xml');
            echo $this->content;
            return;
        }

        // Generates the page: body must be called before the head because
        // some head tags can be modified by body templates
        $body = $this->tagRun($this->body_template);

        echo str_replace('{locale}', TIP::getLocaleId('-'), $this->incipit);
        $this->run($this->head_template);
        echo $body . $this->explicit;

        $this->_session_started && HTTP_Session2::pause();
    }

    static public function setRobots($index, $follow)
    {
        $robots =& TIP_Application::getGlobal('robots');
        $values = explode(',', $robots);

        if (is_bool($index)) {
            if ($index) {
                $old_value = 'noindex';
                $new_value = 'index';
            } else {
                $old_value = 'index';
                $new_value = 'noindex';
            }
            if (!in_array($new_value, $values)) {
                $key = array_search($old_value, $values);
                $key === false && $key = count($values);
                $values[$key] = $new_value;
            }
        }

        if (is_bool($follow)) {
            if ($follow) {
                $old_value = 'nofollow';
                $new_value = 'follow';
            } else {
                $old_value = 'follow';
                $new_value = 'nofollow';
            }
            if (!in_array($new_value, $values)) {
                $key = array_search($old_value, $values);
                $key === false && $key = count($values);
                $values[$key] = $new_value;
            }
        }

        $robots = implode(',', $values);
    }

    //}}}
    //{{{ Tags

    /**#@+
     * @param  string      $params Parameters of the tag
     * @return string|null         The string result or null on errors
     */

    /**
     * Output the page content
     */
    protected function tagPage($params)
    {
        // Check for a notification request (from a redirection, from instance)
        $notify = HTTP_Session2::get('notify');
        if (isset($notify)) {
            // Show the notification and remove it from the session data
            list($severity, $id) = $notify;
            $this->notify($severity, $id);
            HTTP_Session2::set('notify', null);
        }

        return empty($this->content) ? $this->tagRun($this->default_template) : $this->content;
    }

    /**
     * Output some debug information
     *
     * Echoes some output and profiler information, useful in the developement
     * process. This works only if the current user has some privilege on the
     * application module.
     */
    protected function tagDebug($params)
    {
        if (!$this->keys['IS_TRUSTED']) {
            return '';
        }

        ob_start();

        // Show logged messages
        $logger =& $this->getSharedModule('logger');
        if (is_object($logger) && $logger->keys['IS_UNTRUSTED']) {
            $logger->dumpLogs();
        }

        if ($this->keys['IS_ADMIN']) {
            // Display profiling informations
            global $_tip_profiler;
            if (is_object($_tip_profiler)) {
                echo "
Profiler
\n";

                // Leave itsself, that is the tagDebug section
                $_tip_profiler->leaveSection('debug');

                $_tip_profiler->stop();
                $_tip_profiler->display('html');

                // This prevent further operation on $_tip_profiler
                $_tip_profiler = null;
            }
        }

        if ($this->keys['IS_MANAGER']) {
            // Dump the singleton register content
            echo "\n
Register content
\n
\n";
            self::_dumpRegister(TIP_Type::singleton(), '  ');
            echo "
\n";
        }

        return ob_get_clean();
    }

    /**#@-*/

    //}}}
    //{{{ Actions

    protected function runManagerAction($action)
    {
        switch($action) {

        case 'phpinfo':
            ob_start();
            phpinfo();
            $this->content .= ob_get_clean();
            return true;

        case 'clear':
            if (is_null($dir = TIP::getGet('id', 'string'))) {
                TIP::warning("GET not found ($id)");
                TIP::notifyError('noparams');
                return false;
            }

            $dir = TIP::buildDataPath(urldecode($dir));
            TIP::removeDir($dir, false);
            TIP::notifyInfo('done');
            return true;
        }

        return null;
    }

    protected function runUntrustedAction($action)
    {
        switch($action) {

        case 'backup':
            include_once 'HTTP/Download.php';
            include_once 'Archive/Tar.php';

            if (!$this->data_engine->dump(TIP::buildDataPath('dump'))) {
                TIP::notifyError('backup');
                return false;
            }

            $tar_file = TIP::buildCachePath($this->id . '-' . TIP::formatDate('date_sql') . '.tar.gz');
            $tar_object = new Archive_Tar($tar_file, 'gz');
            $result = $tar_object->createModify(TIP::buildDataPath(), '', TIP::buildPath());
            unset($tar_object);

            if ($result !== true) {
                return false;
            }

            HTTP_Download::staticSend(array(
                'file'               => $tar_file,
                'contenttype'        => 'application/x-gzip',
                'contentdisposition' => HTTP_DOWNLOAD_ATTACHMENT));
            exit;
        }

        return null;
    }

    protected function runAction($action)
    {
        switch($action) {

        case 'fatal':
            return TIP::notifyError('fatal');
        }

        return null;
    }

    //}}}
    //{{{ Internal properties

    /**
     * The current request data
     *
     * Contains three items identifying the current request:
     * - $_request['uri']:    the absolute requesting uri
     * - $_request['module']: the requesting module
     * - $_request['action']: the requesting action
     *
     * @var array
     * @internal
     */
    private $_request = null;

    /**
     * The current referer data
     *
     * Contains three items identifying the current referer:
     * - $_referer['uri']:    the absolute referring uri
     * - $_referer['module']: the refererring module
     * - $_referer['action']: the refererring action
     *
     * @var array
     * @internal
     */
    private $_referer = null;

    /**
     * Session started flag
     * @var boolean
     * @internal
     */
    private $_session_started = false;

    //}}}
    //{{{ Internal methods

    /**
     * Internal debug function
     *
     * Used to dump the register for debugging purpose.
     *
     * @param array  &$register The register to dump
     * @param string  $indent   The indentation text
     * @internal
     */
    static private function _dumpRegister(&$register, $indent = '')
    {
        foreach ($register as $id => &$obj) {
            echo "$indent$id\n";
            is_array($obj) && self::_dumpRegister($obj, $indent . '  ');
        }
    }

    private function _startSession()
    {
        // Start the session
        TIP::startSession();
        $this->_session_started = true;

        // Set $_referer
        $request = HTTP_Session2::get('request');
        $referer = HTTP_Session2::get('referer');

        if (is_null($request)) {
            // Entry page or new session: the referer is the main page
            $this->_referer = null;
        } elseif ($this->_request['uri'] == $referer['uri']) {
            // Current URI equals to the old referer URI: probably a back action
            $this->_referer = null;
        } elseif ($this->_request['module'] != $request['module'] || $this->_request['action'] != $request['action']) {
            // New action: the referer is the previous request
            $this->_referer = $request;
        } else {
            // Same action: leave the old referer
            $this->_referer = $referer;
        }

        if (!is_array($this->_referer)) {
            $this->_referer = array(
                'uri'    => TIP::getHome(),
                'module' => null,
                'action' => null
            );
            $this->_referer['action'] = null;
        }

        $this->keys['REFERER'] = $this->_referer['uri'];

        // Store request and referer
        HTTP_Session2::set('referer', $this->_referer);
        HTTP_Session2::set('request', $this->_request);

        // Profiler initialization in "admin" mode
        if ($this->keys['IS_ADMIN']) {
            require_once 'Benchmark/Profiler.php';
            $GLOBALS['_tip_profiler'] = new Benchmark_Profiler;
            $GLOBALS['_tip_profiler']->start();
        }
    }

    //}}}
}
?>


text:
date: 2014-05-26
linktitle: Usage
menu:
  main:
    parent: taxonomy
next: /taxonomies/displaying
prev: /taxonomies/overview
title: Using Taxonomies
weight: 15
---

## Defining taxonomies for a site

Taxonomies must be defined in the site configuration before they can be
used throughout the site. You need to provide both the plural and
singular labels for each taxonomy.

Here is an example configuration in TOML and YAML
that specifies three taxonomies (the default two, plus `series`).

Notice the format is singular key = "plural value" for TOML,
or singular key: "plural value" for YAML:

config.toml excerpt:	config.yaml excerpt:

[taxonomies]
  tag = "tags"
  category = "categories"
  series = "series"

taxonomies:
  tag: "tags"
  category: "categories"
  series: "series"

## Assigning taxonomy values to content

Once an taxonomy is defined at the site level, any piece of content
can be assigned to it regardless of content type or section.

Assigning content to an taxonomy is done in the front matter.
Simply create a variable with the *plural* name of the taxonomy
and assign all terms you want to apply to this content.

## Preserving taxonomy values

By default, taxonomy names are hyphenated, lower-cased and normalized, and then
fixed and titleized on the archive page.

However, if you want to have a taxonomy value with special characters
such as `Gérard Depardieu` instead of `Gerard Depardieu`,
you need to set the `preserveTaxonomyNames` [site configuration](/overview/configuration/) variable to `true`.
Hugo will then preserve special characters in taxonomy values
but will still titleize the values for titles and normalize them in URLs.

Note that if you use `preserveTaxonomyNames` and intend to manually construct URLs to the archive pages,
you will need to pass the taxonomy values through the `urlize` template function.

### Front Matter Example (in TOML)

    +++
    title = "Hugo: A fast and flexible static site generator"
    tags = [ "Development", "Go", "fast", "Blogging" ]
    categories = [ "Development" ]
    series = [ "Go Web Dev" ]
    slug = "hugo"
    project_url = "https://github.com/spf13/hugo"
    +++

### Front Matter Example (in JSON)

    {
        "title": "Hugo: A fast and flexible static site generator",
        "tags": [
            "Development",
            "Go",
            "fast",
            "Blogging"
        ],
        "categories" : [
            "Development"
        ],
        "series" : [
            "Go Web Dev"
        ],
        "slug": "hugo",
        "project_url": "https://github.com/spf13/hugo"
    }


text:
using System;
using System.Collections.Generic;

namespace simplechain
{
    public class Chain
    {
        public List<Block> BlockChain { get; set; }
        public int Difficulty { get; set; }

        public Chain(int difficulty)
        {
            this.BlockChain = new List<Block>();
            this.Difficulty = difficulty;
            this.BlockChain.Add(this.CreateGenesisBlock());
        }

        private Block CreateGenesisBlock()
        {
            return new Block(0,"00/00/00","Genesis Block","0");
        }

        public void AddBlock(Block block)
        {
            block.PreviousHash = this.GetLatestBlock().Hash;
            block.MineBlock(this.Difficulty);
            this.BlockChain.Add(block);
        }

        private Block GetLatestBlock()
        {
            return this.BlockChain[this.BlockChain.Count-1];
        }

        public bool isChainValid()
        {
            for (int i = 1; i < this.BlockChain.Count; i++)
            {
                var currentBlock = this.BlockChain[i];
                var previousBlock = this.BlockChain[i-1];

                if(currentBlock.Hash != currentBlock.CalculateHash())
                {
                    return false;
                }
                if (currentBlock.PreviousHash != previousBlock.Hash)
                {
                    return false;
                }
                if(currentBlock.Hash.Substring(0,this.Difficulty) != "".PadLeft(this.Difficulty,'0'))
                {
                    return false;
                }
            }
            return true;
        }
    }
}


text:
package com.dynious.refinedrelocation.api.tileentity.handlers;

import net.minecraft.item.ItemStack;

public interface ISortingInventoryHandler extends ISortingMemberHandler
{
    /**
     * Used when adding an item to the inventory of the TileEntity
     * (Should be called by setInventorySlotContents(...) in the TileEntity class)
     */
    public void setInventorySlotContents(int par1, ItemStack itemStack);

    /**
     * Should be called when a change is made in one of the members on the Sorting System.
     *
     */
    public void onInventoryChange();
}


text:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class p12_Extract_Emails {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String inputLine = reader.readLine();

        Pattern pattern = Pattern.compile("(?<=^|\\s)([a-z0-9]+[-._]?[a-z]+)@([a-z]+-?)+(\\.[a-z]+)+\\b");
        Matcher matcher = pattern.matcher(inputLine);

        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}


text:
@charset "UTF-8";
/*! normalize.css v3.0.3 | MIT License | git.io/normalize */
/**
 * 1. Set default font family to sans-serif.
 * 2. Prevent iOS text size adjust after orientation change, without disabling
 *    user zoom.
 */
html {
  font-family: sans-serif;
  /* 1 */
  -ms-text-size-adjust: 100%;
  /* 2 */
  -webkit-text-size-adjust: 100%;
  /* 2 */ }

/**
 * Remove default margin.
 */
body {
  margin: 0; }

/* HTML5 display definitions
   ========================================================================== */
/**
 * Correct `block` display not defined for any HTML5 element in IE 8/9.
 * Correct `block` display not defined for `details` or `summary` in IE 10/11
 * and Firefox.
 * Correct `block` display not defined for `main` in IE 11.
 */
article, aside, details, figcaption, figure, footer, header, hgroup, main, menu, nav, section, summary {
  display: block; }

/**
 * 1. Correct `inline-block` display not defined in IE 8/9.
 * 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
 */
audio, canvas, progress, video {
  display: inline-block;
  /* 1 */
  vertical-align: baseline;
  /* 2 */ }

/**
 * Prevent modern browsers from displaying `audio` without controls.
 * Remove excess height in iOS 5 devices.
 */
audio:not([controls]) {
  display: none;
  height: 0; }

/**
 * Address `[hidden]` styling not present in IE 8/9/10.
 * Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22.
 */
[hidden], template {
  display: none; }

/* Links
   ========================================================================== */
/**
 * Remove the gray background color from active links in IE 10.
 */
a {
  background-color: transparent; }

/**
 * Improve readability when focused and also mouse hovered in all browsers.
 */
a:active, a:hover {
  outline: 0; }

/* Text-level semantics
   ========================================================================== */
/**
 * Address styling not present in IE 8/9/10/11, Safari, and Chrome.
 */
abbr[title] {
  border-bottom: 1px dotted; }

/**
 * Address style set to `bolder` in Firefox 4+, Safari, and Chrome.
 */
b, strong {
  font-weight: bold; }

/**
 * Address styling not present in Safari and Chrome.
 */
dfn {
  font-style: italic; }

/**
 * Address variable `h1` font-size and margin within `section` and `article`
 * contexts in Firefox 4+, Safari, and Chrome.
 */
h1 {
  font-size: 2em;
  margin: 0.67em 0; }

/**
 * Address styling not present in IE 8/9.
 */
mark {
  background: #ff0;
  color: #000; }

/**
 * Address inconsistent and variable font size in all browsers.
 */
small {
  font-size: 80%; }

/**
 * Prevent `sub` and `sup` affecting `line-height` in all browsers.
 */
sub, sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline; }

sup {
  top: -0.5em; }

sub {
  bottom: -0.25em; }

/* Embedded content
   ========================================================================== */
/**
 * Remove border when inside `a` element in IE 8/9/10.
 */
img {
  border: 0; }

/**
 * Correct overflow not hidden in IE 9/10/11.
 */
svg:not(:root) {
  overflow: hidden; }

/* Grouping content
   ========================================================================== */
/**
 * Address margin not present in IE 8/9 and Safari.
 */
figure {
  margin: 1em 40px; }

/**
 * Address differences between Firefox and other browsers.
 */
hr {
  -moz-box-sizing: content-box;
  box-sizing: content-box;
  height: 0; }

/**
 * Contain overflow in all browsers.
 */
pre {
  overflow: auto; }

/**
 * Address odd `em`-unit font size rendering in all browsers.
 */
code, kbd, pre, samp {
  font-family: monospace, monospace;
  font-size: 1em; }

/* Forms
   ========================================================================== */
/**
 * Known limitation: by default, Chrome and Safari on OS X allow very limited
 * styling of `select`, unless a `border` property is set.
 */
/**
 * 1. Correct color not being inherited.
 *    Known issue: affects color of disabled elements.
 * 2. Correct font properties not being inherited.
 * 3. Address margins set differently in Firefox 4+, Safari, and Chrome.
 */
button, input, optgroup, select, textarea {
  color: inherit;
  /* 1 */
  font: inherit;
  /* 2 */
  margin: 0;
  /* 3 */ }

/**
 * Address `overflow` set to `hidden` in IE 8/9/10/11.
 */
button {
  overflow: visible; }

/**
 * Address inconsistent `text-transform` inheritance for `button` and `select`.
 * All other form control elements do not inherit `text-transform` values.
 * Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.
 * Correct `select` style inheritance in Firefox.
 */
button, select {
  text-transform: none; }

/**
 * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
 *    and `video` controls.
 * 2. Correct inability to style clickable `input` types in iOS.
 * 3. Improve usability and consistency of cursor style between image-type
 *    `input` and others.
 */
button, html input[type="button"], input[type="reset"], input[type="submit"] {
  -webkit-appearance: button;
  /* 2 */
  cursor: pointer;
  /* 3 */ }

/**
 * Re-set default cursor for disabled elements.
 */
button[disabled], html input[disabled] {
  cursor: default; }

/**
 * Remove inner padding and border in Firefox 4+.
 */
button::-moz-focus-inner, input::-moz-focus-inner {
  border: 0;
  padding: 0; }

/**
 * Address Firefox 4+ setting `line-height` on `input` using `!important` in
 * the UA stylesheet.
 */
input {
  line-height: normal; }

/**
 * It's recommended that you don't attempt to style these elements.
 * Firefox's implementation doesn't respect box-sizing, padding, or width.
 *
 * 1. Address box sizing set to `content-box` in IE 8/9/10.
 * 2. Remove excess padding in IE 8/9/10.
 */
input[type="checkbox"], input[type="radio"] {
  box-sizing: border-box;
  /* 1 */
  padding: 0;
  /* 2 */ }

/**
 * Fix the cursor style for Chrome's increment/decrement buttons. For certain
 * `font-size` values of the `input`, it causes the cursor style of the
 * decrement button to change from `default` to `text`.
 */
input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button {
  height: auto; }

/**
 * 1. Address `appearance` set to `searchfield` in Safari and Chrome.
 * 2. Address `box-sizing` set to `border-box` in Safari and Chrome
 *    (include `-moz` to future-proof).
 */
input[type="search"] {
  -webkit-appearance: textfield;
  /* 1 */
  -moz-box-sizing: content-box;
  -webkit-box-sizing: content-box;
  /* 2 */
  box-sizing: content-box; }

/**
 * Remove inner padding and search cancel button in Safari and Chrome on OS X.
 * Safari (but not Chrome) clips the cancel button when the search input has
 * padding (and `textfield` appearance).
 */
input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none; }

/**
 * Define consistent border, margin, and padding.
 */
fieldset {
  border: 1px solid #c0c0c0;
  margin: 0 2px;
  padding: 0.35em 0.625em 0.75em; }

/**
 * 1. Correct `color` not being inherited in IE 8/9/10/11.
 * 2. Remove padding so people aren't caught out if they zero out fieldsets.
 */
legend {
  border: 0;
  /* 1 */
  padding: 0;
  /* 2 */ }

/**
 * Remove default vertical scrollbar in IE 8/9/10/11.
 */
textarea {
  overflow: auto; }

/**
 * Don't inherit the `font-weight` (applied by a rule above).
 * NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
 */
optgroup {
  font-weight: bold; }

/* Tables
   ========================================================================== */
/**
 * Remove most spacing between table cells.
 */
table {
  border-collapse: collapse;
  border-spacing: 0; }

td, th {
  padding: 0; }

/* 载入iconfont字体 */
@font-face {
  font-family: 'Exo';
  font-style: normal;
  font-weight: 100;
  src: local('Exo Thin'), local('Exo-Thin'), url(https://luoleiorg.b0.upaiyun.com/source/fonts/exo/ek6B72kladJz_Z6o5PEplKCWcynf_cDxXwCLxiixG1c.woff) format('woff'); }

@font-face {
  font-family: 'Exo';
  font-style: normal;
  font-weight: 400;
  src: local('Exo Regular'), local('Exo-Regular'), url(https://luoleiorg.b0.upaiyun.com/source/fonts/exo/ZcGd2dvMSgl3mHN3lKAjNw.woff) format('woff'); }

@font-face {
  font-family: 'iconfont';
  src: url(../../assets/fonts/iconfont.eot);
  /* IE9*/
  src: url(../../assets/fonts/iconfont.eot?#iefix) format('embedded-opentype'), url(../../assets/fonts/iconfont.woff) format('woff'), url(../../assets/fonts/iconfont.ttf) format('truetype'), url(../../assets/fonts/iconfont.svg#uxiconfont) format('svg');
  /* iOS 4.1- */ }

.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -webkit-text-stroke-width: 0.2px;
  -moz-osx-font-smoothing: grayscale;
  display: inline-block;
  speak: none; }

.iconfont {
  vertical-align: middle; }
  .iconfont:hover {
    opacity: 0.6;
    color: #363636; }

.icon-self {
  color: red; }

.icon-weibo {
  color: #E6162D; }

.icon-twitter {
  color: #2aa9e0; }

.icon-facebook {
  color: #204385; }

.icon-google {
  color: #176DEE; }

.icon-weixin {
  color: #75D140; }

.icon-qzone {
  color: #186CC6; }

.icon-github {
  color: #333333; }

.icon-douban {
  color: #279337; }

.icon-luolei {
  color: #6596C1; }

.icon-dribble {
  color: #F72D84; }

.icon-weibo-pure {
  color: #E6162D; }

.icon-twitter-pure {
  color: #2aa9e0; }

.icon-github-pure {
  color: #333333; }

.icon-dribble-pure {
  color: #F72D84; }

.icon-weixin-pure {
  color: #75D140; }

.icon-instagram-pure {
  color: #B66F43; }

/* 自定义IconFont CSS 才用:before的形式 */
.single-post-inner .icon-local:before {
  content: "\0f00ac"; }
.single-post-inner .icon-twitter:before {
  content: "\00e763"; }
.single-post-inner .icon-qzone:before {
  content: "\00e60d"; }
.single-post-inner .icon-weibo:before {
  content: "\003432"; }
.single-post-inner .icon-facebook:before {
  content: "\003433"; }
.single-post-inner .icon-google:before {
  content: "\003434"; }
.single-post-inner .icon-github:before {
  content: "\0f01ca"; }
.single-post-inner .icon-douban:before {
  content: "\0f01c8"; }
.single-post-inner .icon-luolei:before {
  content: "\00e60e"; }

.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both; }

.animated.infinite {
  -webkit-animation-iteration-count: infinite;
  animation-iteration-count: infinite; }

@-webkit-keyframes shine {
  0% {
    opacity: .1; }

  25% {
    opacity: .2; }

  50% {
    opacity: 1; }

  75% {
    opacity: .2; }

  100% {
    opacity: .1; } }

@-webkit-keyframes animate-bg {
  from {
    background-position: 0 0; }

  to {
    background-position: 283px 212px; } }

html, body {
  width: 100%;
  min-height: 100%;
  height: 100%;
  margin: 0;
  padding: 0; }

html {
  max-height: 100%;
  font-size: 62.5%;
  -webkit-font-smoothing: antialiased;
  -webkit-tap-highlight-color: transparent;
  background: #e8e8e8;
  font-family: 'Helvetica Neue', Helvetica, 'microsoft yahei', Arial, sans-serif; }

a {
  text-decoration: none; }

h1, h2, h3, h4, h5, h6 {
  margin: 0;
  padding: 0; }

ul, li {
  margin: 0;
  padding: 0;
  list-style-type: none; }

.clearfix:before, .clearfix:after {
  content: " ";
  display: table; }

.clearfix:after {
  clear: both; }

.clearfix {
  *zoom: 1; }

.hide {
  display: none; }

.abs {
  position: absolute; }

.container {
  width: 100%;
  height: 100%;
  /*overflow: hidden; */
  max-width: 40rem;
  margin: 0 auto;
  position: relative; }

.slide_list {
  width: 100%;
  height: 100%;
  display: block;
  position: relative;
  padding: 0;
  margin: 0;
  -webkit-transform-style: preserve-3d; }

.slide_in_list {
  position: relative;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  background-size: cover; }
  .slide_in_list a {
    color: #fff;
    text-decoration: none; }
  .slide_in_list h4.t_m, .slide_in_list h6.t_m {
    display: block;
    text-align: center;
    margin: 0 auto;
    font-family: "Exo", 'Hiragino Sans GB', 'Microsoft YaHei', 微软雅黑, STHeiti, 'WenQuanYi Micro Hei', Helvetica, Arial, sans-serif;
    color: #fff;
    font-weight: lighter;
    text-transform: uppercase; }
  .slide_in_list h4.t_l, .slide_in_list h6.t_l {
    display: block;
    font-family: "Exo", 'Hiragino Sans GB', 'Microsoft YaHei', 微软雅黑, STHeiti, 'WenQuanYi Micro Hei', Helvetica, Arial, sans-serif;
    text-align: left;
    color: #fff;
    font-weight: lighter; }
  .slide_in_list li.t_l {
    font-family: "Exo", 'Hiragino Sans GB', 'Microsoft YaHei', 微软雅黑, STHeiti, 'WenQuanYi Micro Hei', Helvetica, Arial, sans-serif;
    text-align: left;
    color: #fff;
    font-weight: lighter; }
  .slide_in_list.s1 {
    background: #54B5DB; }
    .slide_in_list.s1 img.avatar {
      display: block;
      top: 50%;
      width: 8.6rem;
      left: 50%;
      margin-left: -4.3rem;
      border-radius: 50%;
      margin-top: -10rem;
      box-shadow: 0 0 1px #fff; }
    .slide_in_list.s1 img.qr {
      display: block;
      width: 40%;
      top: 65%;
      left: 50%;
      margin-left: -20%; }
    .slide_in_list.s1 h4 {
      display: block;
      width: 50%;
      left: 50%;
      font-size: 2.8rem;
      top: 50%;
      margin-left: -25%; }
    .slide_in_list.s1 h6 {
      display: block;
      width: 50%;
      left: 50%;
      font-size: 1.4rem;
      height: 2rem;
      line-height: 2rem;
      top: 58%;
      margin-left: -25%; }
  .slide_in_list.s2 {
    background: #009DF6; }
    .slide_in_list.s2 .intro {
      width: 80%;
      left: 50%;
      margin-left: -40%;
      top: 3rem; }
      .slide_in_list.s2 .intro .detail {
        margin-top: 1rem; }
    .slide_in_list.s2 h4 {
      font-size: 2.4rem;
      line-height: 2.8rem;
      padding: .8rem 0;
      font-weight: bold;
      border-bottom: 1px dashed rgba(238, 238, 238, 0.2);
      margin: .5rem 0; }
    .slide_in_list.s2 h6 {
      display: block;
      font-size: 2.4rem; }
  .slide_in_list.s3 {
    background: #94B995 url(../../assets/images/jnu.jpg);
    background-size: cover; }
    .slide_in_list.s3 .intro {
      width: 80%;
      left: 50%;
      margin-left: -40%;
      top: 3rem;
      background: rgba(0, 0, 0, 0.5);
      border-radius: .5rem; }
      .slide_in_list.s3 .intro .detail {
        margin-top: 0rem;
        padding: 0 1rem; }
    .slide_in_list.s3 h4 {
      font-size: 2.4rem;
      line-height: 2.8rem;
      padding: .8rem 0;
      font-weight: bold; }
      .slide_in_list.s3 h4.title_t {
        padding: 0; }
    .slide_in_list.s3 h6 {
      font-size: 1.4rem;
      line-height: 1.8rem; }
      .slide_in_list.s3 h6.strong {
        font-weight: bold; }
      .slide_in_list.s3 h6.t_l {
        margin-top: .3rem; }
    .slide_in_list.s3 li {
      font-size: 1.4rem;
      line-height: 1.8rem;
      list-style-type: disc; }
  .slide_in_list.s4 {
    background: #54B5DB; }
    .slide_in_list.s4 .skill {
      width: 80%;
      left: 50%;
      margin-left: -40%;
      top: 1rem; }
    .slide_in_list.s4 h4 {
      font-size: 1.8rem;
      line-height: 2.2rem;
      padding: .5rem 0;
      font-weight: bold; }
    .slide_in_list.s4 h6 {
      font-size: 1.2rem;
      line-height: 1.6rem; }
      .slide_in_list.s4 h6.strong {
        font-weight: bold; }
      .slide_in_list.s4 h6.t_l {
        margin-bottom: .3rem; }
    .slide_in_list.s4 li {
      font-size: 1.2rem;
      line-height: 1.6rem;
      list-style-type: disc; }
      .slide_in_list.s4 li a {
        display: inline-block;
        margin: 0 .3rem;
        color: #fff;
        text-decoration: none; }
  .slide_in_list.work {
    background: #2D9CCA; }
  .slide_in_list.s5 {
    background-image: url(https://luolei.org/assets/images/banner2.jpg);
    background-repeat: no-repeat;
    background-position: center;
    -webkit-background-size: cover;
    background-size: cover;
    position: relative;
    z-index: 0; }
    .slide_in_list.s5:after {
      content: "";
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      z-index: -1;
      background: url(https://luolei.org/assets/images/escheresque_ste.png);
      opacity: .25;
      background-color: rgba(0, 0, 0, 0.05);
      transition: background-color 500ms ease-out 2s;
      -webkit-animation-name: animate-bg;
      -webkit-animation-duration: 20s;
      -webkit-animation-timing-function: linear;
      -webkit-animation-iteration-count: infinite; }

.home-info-container {
  position: absolute;
  top: 28%;
  width: 80%;
  left: 50%;
  margin-left: -40%; }
  .home-info-container a {
    display: block;
    text-align: center;
    width: 50%;
    background: none;
    margin: 2.5rem auto;
    border: 1px solid #fff;
    border-radius: 0;
    color: #fff;
    font-size: 1.2rem;
    line-height: 2.4rem;
    opacity: .8;
    padding: .5rem 2.5rem;
    text-transform: uppercase;
    z-index: 99; }
    .home-info-container a:active {
      background: rgba(0, 0, 0, 0.1); }
  .home-info-container h2, .home-info-container h4 {
    display: block;
    text-align: center;
    color: #fff;
    font-family: "Exo" 'Hiragino Sans GB', 'Microsoft YaHei', 微软雅黑, STHeiti, 'WenQuanYi Micro Hei', Helvetica, Arial, sans-serif;
    font-weight: lighter;
    text-shadow: 0 1px 1px #595959; }
    .home-info-container h2:hover, .home-info-container h4:hover {
      color: #efefef;
      text-shadow: 0 1px 1px #000; }
  .home-info-container h2 {
    font-size: 3.2rem; }
  .home-info-container h4 {
    font-size: 1.6rem;
    letter-spacing: .8rem; }

.arrow_down {
  position: absolute;
  left: 50%;
  bottom: 5rem;
  height: 2rem; }
  .arrow_down a {
    z-index: 4;
    display: block;
    position: absolute;
    left: 50%;
    -webkit-transform: rotate(315deg);
    transform: rotate(315deg);
    margin-left: -1.3rem;
    width: 2.8rem;
    height: 2.8rem;
    border-left: 1px solid #fff;
    border-bottom: 1px solid #fff;
    -webkit-animation-name: shine;
    -webkit-animation-duration: 1.8s;
    -webkit-animation-timing-function: linear; }

.meter {
  height: 10px;
  /* Can be anything */
  position: relative;
  background: #555;
  -moz-border-radius: 25px;
  -webkit-border-radius: 25px;
  border-radius: 25px;
  padding: 10px;
  box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3); }

.meter > span {
  display: block;
  height: 100%;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  background-color: #2bc253;
  background-image: linear-gradient(center bottom, #2bc253 37%, #54f054 69%);
  box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);
  position: relative;
  overflow: hidden; }

@media only screen and (max-width: 321px) {
  .slide_in_list.s1 h4 {
    font-size: 2.2rem; } }

@media only screen and (max-width: 768px) {
  .slide_in_list.s1 img.qr {
    display: none; }
  .slide_in_list.s1 h6 {
    display: none; } }


text:
from tkinter import Tk, Button, Frame, Menu, messagebox

class Calendar(Tk):

    months_names = [
        'Декабрь',
        'Январь',
        'Февраль',
        'Март',
        'Апрель',
        'Май',
        'Июнь',
        'Июль',
        'Август',
        'Сентябрь',
        'Отябрь',
        'Ноябрь'
    ]

    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)
        self.make_months()
        self['menu'] = self.make_menu()
        self.title('Calendar')
        self.resizable(width=False, height=False)
        # Change this for different size
        self.geometry('580x150')

    def make_months(self):
        self.months = []
        self.frames = []
        months = list(self.months_names)
        for anchor in ['nw', 'w', 'w', 'sw']:
            frame = Frame(self)
            buttons = [Button(frame, text=months.pop(0), width=20)
                       for _ in range(3)]
            frame.pack(anchor=anchor)
            for button in buttons:
                button.pack(side='left', padx=3, pady=3)
            self.months.extend(buttons)

    def make_menu(self):
        menu = Menu(self)

        file_menu = Menu(menu, tearoff=0)
        file_menu.add_command(label='Exit', command=self.ask_for_quiting)

        help_menu = Menu(menu, tearoff=0)
        help_menu.add_command(label='About',
                              command=lambda: messagebox.showinfo('Calendar',
                                                                  'By Fedor'))

        menu.add_cascade(label='File', menu=file_menu)
        menu.add_cascade(label='Help', menu=help_menu)

        return menu

    def ask_for_quiting(self):
        answer = messagebox.askokcancel(
            title='Confirm Exit',
            message='Are you sure you want to exit program?',
            default='ok'
        )
        if answer:
            self.destroy()

if __name__ == '__main__':
    c = Calendar()
    c.mainloop()


text:
from engine.config.config import config
import re
import numpy as np
from math import log

def comp_tuple(x, y):
    assert isinstance(x, tuple) and isinstance(y, tuple), 'x and y are not tuple.'
    assert len(x) == len(y) == 2, 'lengths of x and y are not right.'
    if x[1] < y[1]:
        return 1
    elif x[1] > y[1]:
        return -1
    else:
        return 0

def weights(v1, v2):
    assert len(v1) == len(v2), 'The length of two vector is not equal.'

    return np.sum(v1 * v2)

def tokenlize(string):
    token_pattern = re.compile(r'[^a-zA-Z0-9.,_*]')
    pre_token_stream = re.split(token_pattern, string.replace('&lt', ' '))
    strip_token_stream = [x.strip(',.').replace(",", "").lower() for x in pre_token_stream if x != None]
    tokens = [x.lower() for x in strip_token_stream if x != '' and x not in config.STOP_WORDS]

    result = {}
    for token in tokens:
        if token in result:
            result[token] += 1
        else:
            result[token] = 1

    return result