text:
class BSTnode(object):
    """
Representation of a node in a binary search tree.
Has a left child, right child, and key value, and stores its subtree size.
"""
    def __init__(self, parent, t):
        """Create a new leaf with key t."""
        self.key = t
        self.parent = parent
        self.left = None
        self.right = None
        self.size = 1

    def update_stats(self):
        """Updates this node's size based on its children's sizes."""
        self.size = (0 if self.left is None else self.left.size) + (0 if self.right is None else self.right.size)

    def insert(self, t, NodeType):
        """Insert key t into the subtree rooted at this node (updating subtree size)."""
        self.size += 1
        if t < self.key:
            if self.left is None:
                self.left = NodeType(self, t)
                return self.left
            else:
                return self.left.insert(t, NodeType)
        else:
            if self.right is None:
                self.right = NodeType(self, t)
                return self.right
            else:
                return self.right.insert(t, NodeType)

    def find(self, t):
        """Return the node for key t if it is in this tree, or None otherwise."""
        if t == self.key:
            return self
        elif t < self.key:
            if self.left is None:
                return None
            else:
                return self.left.find(t)
        else:
            if self.right is None:
                return None
            else:
                return self.right.find(t)

    def rank(self, t):
        """Return the number of keys <= t in the subtree rooted at this node."""
        left_size = 0 if self.left is None else self.left.size
        if t == self.key:
            return left_size + 1
        elif t < self.key:
            if self.left is None:
                return 0
            else:
                return self.left.rank(t)
        else:
            if self.right is None:
                return left_size + 1
            else:
                return self.right.rank(t) + left_size + 1

    def minimum(self):
        """Returns the node with the smallest key in the subtree rooted by this node."""
        current = self
        while current.left is not None:
            current = current.left
        return current

    def successor(self):
        """Returns the node with the smallest key larger than this node's key, or None if this has the largest key in the tree."""
        if self.right is not None:
            return self.right.minimum()
        current = self
        while current.parent is not None and current.parent.right is current:
            current = current.parent
        return current.parent

    def delete(self):
        """"Delete this node from the tree."""
        if self.left is None or self.right is None:
            if self is self.parent.left:
                self.parent.left = self.left or self.right
                if self.parent.left is not None:
                    self.parent.left.parent = self.parent
            else:
                self.parent.right = self.left or self.right
                if self.parent.right is not None:
                    self.parent.right.parent = self.parent
            current = self.parent
            while current.key is not None:
                current.update_stats()
                current = current.parent
            return self
        else:
            s = self.successor()
            self.key, s.key = s.key, self.key
            return s.delete()

    def check(self, lokey, hikey):
        """Checks that the subtree rooted at t is a valid BST and all keys are between (lokey, hikey)."""
        if lokey is not None and self.key <= lokey:
            raise "BST RI violation"
        if hikey is not None and self.key >= hikey:
            raise "BST RI violation"
        if self.left is not None:
            if self.left.parent is not self:
                raise "BST RI violation"
            self.left.check(lokey, self.key)
        if self.right is not None:
            if self.right.parent is not self:
                raise "BST RI violation"
            self.right.check(self.key, hikey)
        if self.size != 1 + (0 if self.left is None else self.left.size) + (0 if self.right is None else self.right.size):
            raise "BST RI violation"

    def __repr__(self):
        return "<BST Node, key:" + str(self.key) + ">"

class BST(object):
    """
Simple binary search tree implementation, augmented with subtree sizes.
This BST supports insert, find, and delete-min operations.
Each tree contains some (possibly 0) BSTnode objects, representing nodes,
and a pointer to the root.
"""

    def __init__(self, NodeType=BSTnode):
        self.root = None
        self.NodeType = NodeType
        self.psroot = self.NodeType(None, None)

    def reroot(self):
        self.root = self.psroot.left

    def insert(self, t):
        """Insert key t into this BST, modifying it in-place."""
        if self.root is None:
            self.psroot.left = self.NodeType(self.psroot, t)
            self.reroot()
            return self.root
        else:
            return self.root.insert(t, self.NodeType)

    def find(self, t):
        """Return the node for key t if is in the tree, or None otherwise."""
        if self.root is None:
            return None
        else:
            return self.root.find(t)

    def rank(self, t):
        """The number of keys <= t in the tree."""
        if self.root is None:
            return 0
        else:
            return self.root.rank(t)

    def delete(self, t):
        """Delete the node for key t if it is in the tree."""
        node = self.find(t)
        deleted = self.root.delete()
        self.reroot()
        return deleted

    def check(self):
        if self.root is not None:
            self.root.check(None, None)

    def __str__(self):
        if self.root is None: return '<empty tree>'
        def recurse(node):
            if node is None: return [], 0, 0
            label = str(node.key)
            left_lines, left_pos, left_width = recurse(node.left)
            right_lines, right_pos, right_width = recurse(node.right)
            middle = max(right_pos + left_width - left_pos + 1, len(label), 2)
            pos = left_pos + middle // 2
            width = left_pos + middle + right_width - right_pos
            while len(left_lines) < len(right_lines):
                left_lines.append(' ' * left_width)
            while len(right_lines) < len(left_lines):
                right_lines.append(' ' * right_width)
            if (middle - len(label)) % 2 == 1 and node.parent is not None and \
               node is node.parent.left and len(label) < middle:
                label += '.'
            label = label.center(middle, '.')
            if label[0] == '.': label = ' ' + label[1:]
            if label[-1] == '.': label = label[:-1] + ' '
            lines = [' ' * left_pos + label + ' ' * (right_width - right_pos),
                     ' ' * left_pos + '/' + ' ' * (middle-2) +
                     '\\' + ' ' * (right_width - right_pos)] + \
              [left_line + ' ' * (width - left_width - right_width) +
               right_line
               for left_line, right_line in zip(left_lines, right_lines)]
            return lines, pos, width
        return '\n'.join(recurse(self.root) [0])

test1 = range(0, 100, 10)
test2 = [31, 41, 59, 26, 53, 58, 97, 93, 23]
test3 = "algorithms"

def printsizes(node):
    if node is None:
        print "node is nil"
    else:
        print "node", node.key, "has a subtree of size", node.size

def test(args=None, BSTtype=BST):
    import random, sys
    if not args:
        args = sys.argv[1:]
    if not args:
        print 'usage: %s <number-of-random-items | item item item ...>' % \
              sys.argv[0]
        sys.exit()
    elif len(args) == 1:
        items = (random.randrange(100) for i in xrange(int(args[0])))
    else:
        items = [int(i) for i in args]

    tree = BSTtype()
    print tree
    for item in items:
        tree.insert(item)
        print
        print tree

if __name__ == '__main__': test()


text:
// clang-format off

/**
 * Allows keyNew() to determine which information comes next.
 *
 * @ingroup key
 * @see keyNew()
 */
enum keyswitch_t
{
	KEY_NAME=1,		/*!< Flag for the key name */
	KEY_VALUE=1<<1,		/*!< Flag for the key data */
	KEY_FLAGS=3,		/*!< Allows to define multiple flags at once. */
	KEY_OWNER=1<<2,		/*!< Flag for the key user domain */
	KEY_COMMENT=1<<3,	/*!< Flag for the key comment */
	KEY_BINARY=1<<4,	/*!< Flag if the key is binary */
	KEY_UID=1<<5,		/*!< Flag for the key UID @deprecated do not use */
	KEY_GID=1<<6,		/*!< Flag for the key GID @deprecated do not use  */
	KEY_MODE=1<<7,		/*!< Flag for the key permissions @deprecated do not use  */
	KEY_ATIME=1<<8,		/*!< Flag for the key access time @deprecated do not use  */
	KEY_MTIME=1<<9,		/*!< Flag for the key change time @deprecated do not use  */
	KEY_CTIME=1<<10,	/*!< Flag for the key status change time @deprecated do not use  */
	KEY_SIZE=1<<11,		/*!< Flag for maximum size to limit value */
	KEY_DIR=1<<14,		/*!< Flag for the key directories @deprecated do not use */
	KEY_META=1<<15,		/*!< Flag for metadata */
	KEY_NULL=1<<16,		/*!< Is *not* a flag, only as return value @deprecated do not use */
	// see elektraLockOptions
	KEY_CASCADING_NAME=1<<20,	/*!< Is default, no need to use it @deprecated do not use */
	KEY_META_NAME=1<<21,	/*!< Allow any key names (not only with known namespaces+cascading */
	KEY_END=0		/*!< Used as a parameter terminator to keyNew() */
};

/**
 * Lock options
 *
 * @ingroup key
 * @see keyLock(), keyIsLocked()
 */
enum elektraLockOptions
{
	KEY_LOCK_NAME=1<<17,  ///< lock the name of a key
	KEY_LOCK_VALUE=1<<18, ///< lock the value of a key
	KEY_LOCK_META=1<<19   ///< lock the meta data of a key
};

/**
 * Elektra currently supported Key namespaces.
 *
 * @ingroup key
 * @see kdbGet(), keyGetNamespace()
 */
enum elektraNamespace
{
	KEY_NS_NONE=0,          ///< no key given as parameter to keyGetNamespace()
	KEY_NS_EMPTY=1,         ///< key name was empty, e.g. invalid key name
	KEY_NS_META=2,          ///< metakey, i.e. any key name not under other categories
	KEY_NS_CASCADING=3,     ///< cascading key, starts with /, abstract name for any of the namespaces below
	KEY_NS_FIRST=4,         ///< For iteration over namespaces (first element, inclusive)
	KEY_NS_SPEC=4,          ///< spec contains the specification of the other namespaces
	KEY_NS_PROC=5,          ///< proc contains process-specific configuration
	KEY_NS_DIR=6,           ///< dir contains configuration from a specific directory
	KEY_NS_USER=7,          ///< user key in the home directory of the current user
	KEY_NS_SYSTEM=8,        ///< system key is shared for a computer system
	KEY_NS_LAST=8           ///< For iteration over namespaces (last element, inclusive)
};

/**
 * End of a list of keys.
 *
 * Use this macro to define the end of a variable-length list
 * of keys.
 *
 * @def KS_END
 * @see ksNew() and ksVNew()
 */
#define KS_END ((Key*)0)

/**
 * Options to change the default behavior of
 * ksLookup() functions.
 *
 * These options can be ORed. That is the |-Operator in C.
 *
 * @ingroup keyset
 * @see kdbGet(), kdbSet()
 */
enum option_t
{

/**
 * No Option set.
 *
 * @see ksLookup()
 */
	KDB_O_NONE=0,
/**
 * Delete parentKey key in ksLookup().
 *
 * @see ksLookup()
 */
	KDB_O_DEL=1,
/** Pop Parent out of keyset key in ksLookup().
 *
 * @see ksPop().
 */
	KDB_O_POP=1<<1
};

redpajama_set_name: RedPajamaGithub


text:
Spring-StringTemplate-SiteMesh
==============================

This library provides a reusable integration mechanism between the [StringTemplate](http://www.stringtemplate.org/) java
template engine and the Spring MVC Framework. The pattern used is very similar to the way that the Freemarker template
engine is already integrated with Spring's MVC. In addition this project provides a StringTemplateDecoratorServlet that
can be used to allow StringTemplate's templates to act as [SiteMesh](http://www.opensymphony.com/sitemesh/) decorators.

An example of this integration with both Spring MVC and SiteMesh can be found in the `src/test/webapp/WEB-INF` directory
of this project and is actually used to verify runtime compatiblity with both Spring and SiteMesh.

Runtime dependencies:

- stringtemplate 3.2.1 (required)
- antlr 2.7.7 (stringtemplate dependency)
- springframework 3.x (required)
- commons-lang 2.7.7 (required)
- sitemesh 2.4.1 (optional)

Note: Release 1.5.1 has been uploaded to the Maven Repository so you can fetch it via:

```xml
<dependency>
  <groupId>com.watchitlater</groupId>
	<artifactId>spring-stringtemplate</artifactId>
	<version>1.5.1</version>
</dependency>
```


text:
<?php

include_once 'phing/system/io/PhingFile.php';
include_once 'phing/system/io/Reader.php';

/**
 * Writer class for OutputStream objects.
 *
 * Unlike the Java counterpart, this class does not (yet) handle
 * character set transformations.  This will be an important function
 * of this class with move to supporting PHP6.
 *
 * @package   phing.system.io
 */
class InputStreamReader extends Reader {

    /**
     * @var InputStream
     */
    protected $inStream;

    /**
     * Construct a new InputStreamReader.
     * @param InputStream $$inStream InputStream to read from
     */
    public function __construct(InputStream $inStream) {
        $this->inStream = $inStream;
    }

    /**
     * Close the stream.
     */
    public function close() {
        return $this->inStream->close();
    }

    /**
     * Skip over $n bytes.
     * @param int $n
     */
    public function skip($n) {
        return $this->inStream->skip($n);
    }

    /**
     * Read data from file.
     * @param int $len Num chars to read.
     * @return string chars read or -1 if eof.
     */
    public function read($len = null) {
        return $this->inStream->read($len);
    }

    /**
     * Marks the current position in this input stream.
     * @throws IOException - if the underlying stream doesn't support this method.
     */
    public function mark() {
        $this->inStream->mark();
    }

    /**
     * Whether the attached stream supports mark/reset.
     * @return boolean
     */
    public function markSupported() {
        return $this->inStream->markSupported();
    }

    /**
     * Repositions this stream to the position at the time the mark method was last called on this input stream.
     * @throws IOException - if the underlying stream doesn't support this method.
     */
    public function reset() {
        $this->inStream->reset();
    }

    /**
     * Whether eof has been reached with stream.
     * @return boolean
     */
    public function eof() {
        return $this->inStream->eof();
    }

    /**
     * Reads a entire file and stores the data in the variable
     * passed by reference.
     *
     * @param    string $file    String. Path and/or name of file to read.
     * @param    object &$rBuffer    Reference. Variable of where to put contents.
     *
     * @return    TRUE on success. Err object on failure.
     * @author  Charlie Killian, charlie@tizac.com
     * @deprecated Use read() or BufferedReader instead.
     */
    public function readInto(&$rBuffer) {
        return $this->inStream->readInto($rBuffer);
    }

    /**
     * Returns string representation of attached stream.
     * @return string
     */
    public function getResource() {
        return $this->inStream->__toString();
    }
}


text:
<!doctype html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<title>jQuery Bar Rating - Minimal, light-weight jQuery ratings</title>
		<meta name="description" content="">
		<meta name="viewport" content="width=1024">

		<link rel="stylesheet" href="css/rating/normalize.min.css">
		<link rel="stylesheet" href="css/rating/main.css">
		<link rel="stylesheet" href="css/rating/examples.css">

		<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">

		<link rel="stylesheet" href="css/rating/bars-1to10.css">
		<link rel="stylesheet" href="css/rating/bars-movie.css">
		<link rel="stylesheet" href="css/rating/bars-square.css">
		<link rel="stylesheet" href="css/rating/bars-pill.css">
		<link rel="stylesheet" href="css/rating/bars-reversed.css">
		<link rel="stylesheet" href="css/rating/bars-horizontal.css">

		<link rel="stylesheet" href="css/rating/fontawesome-stars.css">
		<link rel="stylesheet" href="css/rating/css-stars.css">
		<link rel="stylesheet" href="css/rating/bootstrap-stars.css">

		<link href="http://fonts.googleapis.com/css?family=Lato:300,400" rel="stylesheet" type="text/css">
		<link href="http://fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">

jQuery Bar Rating

Minimal, light-weight jQuery ratings.

				jQuery Bar Rating Plugin works by transforming a standard
				select field into a rating widget. The rating widget can be
				flexibly styled with CSS. Take a look at a few examples.

				enable
				disable

1/10 Rating

										<select id="example-1to10" name="rating">
											<option value="1">1</option>
											<option value="2">2</option>
											<option value="3">3</option>
											<option value="4">4</option>
											<option value="5">5</option>
											<option value="6">6</option>
											<option value="7" selected="selected">7</option>
											<option value="8">8</option>
											<option value="9">9</option>
											<option value="10">10</option>
										</select>

Movie Rating

										<select id="example-movie" name="rating">
											<option value="Bad">Bad</option>
											<option value="Mediocre">Mediocre</option>
											<option value="Good" selected="selected">Good</option>
											<option value="Awesome">Awesome</option>
										</select>

Square Rating

										<select id="example-square" name="rating">
												<option value=""></option>
												<option value="1">1</option>
												<option value="2">2</option>
												<option value="3">3</option>
												<option value="4">4</option>
												<option value="5">5</option>
										</select>

Pill Rating

										<select id="example-pill" name="rating">
											<option value="A">A</option>
											<option value="B">B</option>
											<option value="C">C</option>
											<option value="D">D</option>
											<option value="E">E</option>
											<option value="F">F</option>
										</select>

Reversed Rating

										<select id="example-reversed" name="rating">
											<option value="Strongly Agree">Strongly Agree</option>
											<option value="Agree">Agree</option>
											<option value="Neither Agree or Disagree" selected="selected">Neither Agree or Disagree</option>
											<option value="Disagree">Disagree</option>
											<option value="Strongly Disagree">Strongly Disagree</option>
										</select>

Horizontal Rating

										<select id="example-horizontal" name="rating">
											<option value="10">10</option>
											<option value="9">9</option>
											<option value="8">8</option>
											<option value="7">7</option>
											<option value="6">6</option>
											<option value="5">5</option>
											<option value="4">4</option>
											<option value="3">3</option>
											<option value="2">2</option>
											<option value="1" selected="selected">1</option>
										</select>

How about star ratings?

The plugin comes with a few flavours of star ratings compatible with popular libraries.

									<select id="example-fontawesome" name="rating">
										<option value="1">1</option>
										<option value="2">2</option>
										<option value="3">3</option>
										<option value="4">4</option>
										<option value="5">5</option>
									</select>

									Font Awesome

									<select id="example-css" name="rating">
										<option value="1">1</option>
										<option value="2">2</option>
										<option value="3">3</option>
										<option value="4">4</option>
										<option value="5">5</option>
									</select>

									CSS Stars

									<select id="example-bootstrap" name="rating">
										<option value="1">1</option>
										<option value="2">2</option>
										<option value="3">3</option>
										<option value="4">4</option>
										<option value="5">5</option>
									</select>

									Bootstrap

					How to use

									Get the plugin from GitHub
									or install with Bower:

bower install jquery-bar-rating

Create a select field:

<select id="example">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

									If you would like to use one of the provided themes
									include the theme in the head section of the page.

<link rel="stylesheet" href="fontawesome-stars.css">

									Include and call the plugin (after jQuery v1.7.2+)

<script src="jquery.barrating.min.js"></script>
<script type="text/javascript">
   $(function() {
      $('#example').barrating({
        theme: 'fontawesome-stars'
      });
   });
</script>

									The select field will be wrapped in a div with a `.br-theme-fontawesome-stars` class.
									For a full list of available options please refer to configuration.

Expected result:

<div class="br-wrapper br-theme-fontawesome-stars">
  <select id="example">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
  </select>
  ...rating widget...
</div>

					Configuration

							theme: ''

							Specify a theme.

							initialRating: null

							Specify initial rating by passing select field's option value. If null, the plugin will try to set the initial rating by finding an option with a `selected` attribute.

							showValues: false

							If set to true, rating values will be displayed on the bars.

							showSelectedRating: true

							If set to true, user selected rating will be displayed next to the widget.

							reverse: false

							If set to true, the ratings will be reversed.

							readonly: false

							If set to true, the ratings will be read-only.

							fastClicks: true

							Remove 300ms click delay on touch devices.

							hoverState: true

							Change state on hover.

							wrapperClass: 'br-wrapper'

							Specify the name of wrapper div's class.

					Methods

							$('select').barrating('show');

							Shows the rating widget.

							$('select').barrating('set', value);

							Sets the value of rating widget.

							$('select').barrating('clear');

							Clears the rating.

							$('select').barrating('destroy');

							Destroys the rating widget.

					Callbacks

							onSelect:function(value, text)

							Fired when a rating is selected.

							onClear:function(value, text)

							Fired when a rating is cleared.

							onDestroy:function(value, text)

							Fired when a rating is destroyed.

					FAQ

								How do I allow users to select empty ratings?

								To allow users to select empty ratings simply include an empty
								option in your select field:

<select id="example">
  <option value=""></option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

								How can I specify text that is displayed on the bars?

								The `showValues` plugin setting already makes it easy to display
								option values directly on the bars. For more control over the text
								that is displayed on the bars you can define `data-html` attribute
								on each of the <option> elements that will take precedence
								over actual option value.

<select id="example">
  <option value="1" data-html="good">1</option>
  <option value="2" data-html="better">2</option>
  <option value="3" data-html="best">3</option>
</select>

					License

Dual licensed under the MIT and GPL licenses:

								http://www.opensource.org/licenses/mit-license.php

								http://www.gnu.org/licenses/gpl.html

					Download

Download it at GitHub:

								http://github.com/antennaio/jquery-bar-rating

			Made by ANTENNA.IO


text:
package org.javarosa.xpath.expr;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.condition.IFunctionHandler;
import org.javarosa.core.model.condition.pivot.UnpivotableExpressionException;
import org.javarosa.core.model.data.GeoPointData;
import org.javarosa.core.model.data.GeoShapeData;
import org.javarosa.core.model.data.UncastData;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.services.PropertyManager;
import org.javarosa.core.util.GeoUtils;
import org.javarosa.core.util.MathUtils;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapListPoly;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xpath.IExprDataType;
import org.javarosa.xpath.XPathNodeset;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.XPathUnhandledException;

/**
 * Representation of an xpath function expression.
 *
 * All of the built-in xpath functions are included here, as well as the xpath type conversion logic
 *
 * Evaluation of functions can delegate out to custom function handlers that must be registered at
 * runtime.
 *
 * @author Drew Roos
 *
 */
public class XPathFuncExpr extends XPathExpression {
	public XPathQName id;			//name of the function
	public XPathExpression[] args;	//argument list

	public XPathFuncExpr () { } //for deserialization

	public XPathFuncExpr (XPathQName id, XPathExpression[] args) {
		this.id = id;
		this.args = args;
	}

	public String toString () {
		StringBuilder sb = new StringBuilder();

		sb.append("{func-expr:");
		sb.append(id.toString());
		sb.append(",{");
		for (int i = 0; i < args.length; i++) {
			sb.append(args[i].toString());
			if (i < args.length - 1)
				sb.append(",");
		}
		sb.append("}}");

		return sb.toString();
	}

	public boolean equals (Object o) {
		if (o instanceof XPathFuncExpr) {
			XPathFuncExpr x = (XPathFuncExpr)o;

			//Shortcuts for very easily comprable values
			//We also only return "True" for methods we expect to return the same thing. This is not good
			//practice in Java, since o.equals(o) will return false. We should evaluate that differently.
			//Dec 8, 2011 - Added "uuid", since we should never assume one uuid equals another
			//May 6, 2013 - Added "random", since two calls asking for a random
			//Jun 4, 2013 - Added "now" and "today", since these could change during the course of a survey
			if(!id.equals(x.id) || args.length != x.args.length ||
				id.toString().equals("uuid") ||
				id.toString().equals("random") ||
				id.toString().equals("once") ||
				id.toString().equals("now") ||
				id.toString().equals("today")) {
				return false;
			}

			return ExtUtil.arrayEquals(args, x.args);
		} else {
			return false;
		}
	}

	public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
		id = (XPathQName)ExtUtil.read(in, XPathQName.class);
        List<Object> v = (List<Object>)ExtUtil.read(in, new ExtWrapListPoly(), pf);

		args = new XPathExpression[v.size()];
		for (int i = 0; i < args.length; i++)
			args[i] = (XPathExpression)v.get(i);
	}

	public void writeExternal(DataOutputStream out) throws IOException {
      List<XPathExpression> v = Arrays.asList(args);

		ExtUtil.write(out, id);
		ExtUtil.write(out, new ExtWrapListPoly(v));
	}

	/**
	 * Evaluate the function call.
	 *
	 * First check if the function is a member of the built-in function suite. If not, then check
	 * for any custom handlers registered to handler the function. If not, throw and exception.
	 *
	 * Both function name and appropriate arguments are taken into account when finding a suitable
	 * handler. For built-in functions, the number of arguments must match; for custom functions,
	 * the supplied arguments must match one of the function prototypes defined by the handler.
	 *
	 */
	public Object eval (FormInstance model, EvaluationContext evalContext) {
		String name = id.toString();
		Object[] argVals = new Object[args.length];

		HashMap<String, IFunctionHandler> funcHandlers = evalContext.getFunctionHandlers();

		//TODO: Func handlers should be able to declare the desire for short circuiting as well
		if (name.equals("if")) {
			assertArgsCount(name, args, 3);
			return ifThenElse(model, evalContext, args, argVals);
		} else if (name.equals("coalesce")) {
			assertArgsCount(name, args, 2);
			argVals[0] = args[0].eval(model, evalContext);
			if (!isNull(argVals[0])) {
				return argVals[0];
			} else {
				// that was null, so try the other one...
				argVals[1] = args[1].eval(model, evalContext);
				return argVals[1];
			}
		} else if (name.equals("indexed-repeat")) {
			if ((args.length == 3 || args.length == 5 || args.length == 7 || args.length == 9 || args.length == 11)) {
				return indexedRepeat(model, evalContext, args, argVals);
			} else {
				throw new XPathUnhandledException("function \'" + name + "\' requires " +
						  "3, 5, 7, 9 or 11 arguments. Only " + args.length + " provided.");
			}
		}

		for (int i = 0; i < args.length; i++) {
			argVals[i] = args[i].eval(model, evalContext);
		}

		//check built-in functions
		if (name.equals("true")) {
			assertArgsCount(name, args, 0);
			return Boolean.TRUE;
		} else if (name.equals("false")) {
			assertArgsCount(name, args, 0);
			return Boolean.FALSE;
		} else if (name.equals("boolean")) {
			assertArgsCount(name, args, 1);
			return toBoolean(argVals[0]);
		} else if (name.equals("number")) {
			assertArgsCount(name, args, 1);
			return toNumeric(argVals[0]);
		} else if (name.equals("int")) { //non-standard
			assertArgsCount(name, args, 1);
			return toInt(argVals[0]);
		} else if (name.equals("round")) { // non-standard Excel-style round(value,decimal place)
			assertArgsCount(name, args, 2);
			Double aval = toNumeric(argVals[0]);
			Double bval = toInt(argVals[1]);
			return round(aval, bval);
		} else if (name.equals("string")) {
			assertArgsCount(name, args, 1);
			return toString(argVals[0]);
		} else if (name.equals("date")) { //non-standard
			assertArgsCount(name, args, 1);
			return toDate(argVals[0], false);
		} else if (name.equals("date-time")) { //non-standard -- convert double/int/string to Date object
			assertArgsCount(name, args, 1);
			return toDate(argVals[0], true);
		} else if (name.equals("decimal-date-time")) { //non-standard -- convert string/date to decimal days off 1970-01-01T00:00:00.000-000
			assertArgsCount(name, args, 1);
			return toDecimalDateTime(argVals[0], true);
		} else if (name.equals("decimal-time")) { //non-standard -- convert string/date to decimal days off 1970-01-01T00:00:00.000-000
			assertArgsCount(name, args, 1);
			return toDecimalDateTime(argVals[0], false);
		} else if (name.equals("not")) {
			assertArgsCount(name, args, 1);
			return boolNot(argVals[0]);
		} else if (name.equals("boolean-from-string")) {
			assertArgsCount(name, args, 1);
			return boolStr(argVals[0]);
		} else if (name.equals("format-date")) {
			assertArgsCount(name, args, 2);
			return dateStr(argVals[0], argVals[1], false);
		} else if (name.equals("format-date-time")) { // non-standard
			assertArgsCount(name, args, 2);
			return dateStr(argVals[0], argVals[1], true);
		} else if ((name.equals("selected") || name.equals("is-selected"))) { //non-standard
			assertArgsCount(name, args, 2);
			return multiSelected(argVals[0], argVals[1], name);
		} else if (name.equals("count-selected")) { //non-standard
			assertArgsCount(name, args, 1);
			return countSelected(argVals[0]);
		} else if (name.equals("selected-at")) { //non-standard
			assertArgsCount(name, args, 2);
			return selectedAt(argVals[0], argVals[1]);
		} else if (name.equals("position")) {
			//TODO: Technically, only the 0 length argument is valid here.
			if (args.length == 1) {
				XPathNodeset nodes = (XPathNodeset) argVals[0];
				if (nodes.size() == 0) {
					// Added to prevent an exception within ODK Validate.
					// Will likely cause an error downstream when used in an XPath.
					return new Double(1 + TreeReference.INDEX_UNBOUND);
				} else {
					// This is weird -- we are returning the position of the first
					// Nodeset element but there may be a list of elements. Unclear
					// if or how this might manifest into a bug... .
					return position(nodes.getRefAt(0));
				}
			} else if (args.length == 0) {
				if (evalContext.getContextPosition() != -1) {
					return new Double(1 + evalContext.getContextPosition());
				}
				return position(evalContext.getContextRef());
			} else {
				throw new XPathUnhandledException("function \'" + name +
						  "\' requires either exactly one argument or no arguments. Only " + args.length + " provided.");
			}
		} else if (name.equals("count")) {
			assertArgsCount(name, args, 1);
			return count(argVals[0]);
		} else if (name.equals("sum")) {
			assertArgsCount(name, args, 1);
			if (argVals[0] instanceof XPathNodeset) {
				return sum(((XPathNodeset) argVals[0]).toArgList());
			} else {
				throw new XPathTypeMismatchException("not a nodeset");
			}
		} else if (name.equals("max")) {
			if (args.length == 1 && argVals[0] instanceof XPathNodeset) {
				return max(((XPathNodeset) argVals[0]).toArgList());
			} else {
				return max(argVals);
			}
		} else if (name.equals("min")) {
			if (args.length == 1 && argVals[0] instanceof XPathNodeset) {
				return min(((XPathNodeset) argVals[0]).toArgList());
			} else {
				return min(argVals);
			}
		} else if (name.equals("today")) {
			assertArgsCount(name, args, 0);
			return DateUtils.roundDate(new Date());
		} else if (name.equals("now")) {
			assertArgsCount(name, args, 0);
			return new Date();
		} else if (name.equals("concat")) {
			if (args.length == 1 && argVals[0] instanceof XPathNodeset) {
				return join("", ((XPathNodeset) argVals[0]).toArgList());
			} else {
				return join("", argVals);
			}
		} else if (name.equals("join") && args.length >= 1) {
			if (args.length == 2 && argVals[1] instanceof XPathNodeset) {
				return join(argVals[0], ((XPathNodeset) argVals[1]).toArgList());
			} else {
				return join(argVals[0], subsetArgList(argVals, 1));
			}
		} else if (name.equals("substr") && (args.length == 2 || args.length == 3)) {
			return substring(argVals[0], argVals[1], args.length == 3 ? argVals[2] : null);
		} else if (name.equals("string-length")) {
			assertArgsCount(name, args, 1);
			return stringLength(argVals[0]);
		} else if (name.equals("checklist") && args.length >= 2) { //non-standard
			if (args.length == 3 && argVals[2] instanceof XPathNodeset) {
				return checklist(argVals[0], argVals[1], ((XPathNodeset) argVals[2]).toArgList());
			} else {
				return checklist(argVals[0], argVals[1], subsetArgList(argVals, 2));
			}
		} else if (name.equals("weighted-checklist") && args.length >= 2 && args.length % 2 == 0) { //non-standard
			if (args.length == 4 && argVals[2] instanceof XPathNodeset && argVals[3] instanceof XPathNodeset) {
				Object[] factors = ((XPathNodeset) argVals[2]).toArgList();
				Object[] weights = ((XPathNodeset) argVals[3]).toArgList();
				if (factors.length != weights.length) {
					throw new XPathTypeMismatchException("weighted-checklist: nodesets not same length");
				}
				return checklistWeighted(argVals[0], argVals[1], factors, weights);
			} else {
				return checklistWeighted(argVals[0], argVals[1], subsetArgList(argVals, 2, 2), subsetArgList(argVals, 3, 2));
			}
		} else if (name.equals("regex")) { //non-standard
			assertArgsCount(name, args, 2);
			return regex(argVals[0], argVals[1]);
		} else if (name.equals("depend") && args.length >= 1) { //non-standard
			return argVals[0];
		} else if (name.equals("random")) { //non-standard
			assertArgsCount(name, args, 0);
			//calculated expressions may be recomputed w/o warning! use with caution!!
			return new Double(MathUtils.getRand().nextDouble());
		} else if (name.equals("once")) {
			assertArgsCount(name, args, 1);
			XPathPathExpr currentFieldPathExpr = XPathPathExpr.fromRef(evalContext.getContextRef());
			Object currValue = currentFieldPathExpr.eval(model, evalContext).unpack();
			if (currValue == null || toString(currValue).length() == 0) {
				// this is the "once" case
				return argVals[0];
			} else {
				return currValue;
			}
		} else if (name.equals("uuid") && (args.length == 0 || args.length == 1)) { //non-standard
			//calculated expressions may be recomputed w/o warning! use with caution!!
			if (args.length == 0) {
				return PropertyUtils.genUUID();
			}

			int len = toInt(argVals[0]).intValue();
			return PropertyUtils.genGUID(len);
		} else if (name.equals("version")) { //non-standard
			assertArgsCount(name, args, 0);
			return model.formVersion == null ? "" : model.formVersion;
		} else if (name.equals("property")) { // non-standard
			// return a property defined by the property manager.
			// NOTE: Property should be immutable.
			// i.e., does not work with 'start' or 'end' property.
			assertArgsCount(name, args, 1);
			String s = toString(argVals[0]);
			return PropertyManager._().getSingularProperty(s);
		} else if (name.equals("pow") && (args.length == 2)) { //XPath 3.0
			double a = toDouble(argVals[0]).doubleValue();
			double b = toDouble(argVals[1]).doubleValue();
			return Math.pow(a, b);
		} else if (name.equals("enclosed-area") || name.equals("area")) {
			assertArgsCount(name, args, 1);

			Object argVal = argVals[0];
			if (!(argVal instanceof XPathNodeset)) {
				throw new XPathUnhandledException("function \'" + name + "\' requires a field as the parameter.");
			}
			Object[] argList = ((XPathNodeset) argVal).toArgList();
			int repeatSize = argList.length;

			List<GeoUtils.GPSCoordinates> gpsCoordinatesList;

			if (repeatSize == 1) {
				// Try to determine if the argument is of type GeoShapeData
				try {
					GeoShapeData geoShapeData = new GeoShapeData().cast(new UncastData(toString(argList[0])));
					if (geoShapeData.points.size() <= 2) {
						return 0d;
					} else {
						gpsCoordinatesList = new ArrayList<GeoUtils.GPSCoordinates>();
						for (GeoPointData point : geoShapeData.points) {
							gpsCoordinatesList.add(new GeoUtils.GPSCoordinates(point.getPart(0), point.getPart(1)));
						}
					}
				} catch (Exception e) {
					throw new XPathTypeMismatchException("The function \'" + name + "\' received a value that does not represent GPS coordinates: " + argList[0]);
				}
			} else {
				if (repeatSize <= 2) {
					return 0d;
				} else {
					// treat the input as a series of GeoPointData

					gpsCoordinatesList = new ArrayList<GeoUtils.GPSCoordinates>();
					for (Object arg : argList) {
						try {
							GeoPointData geoPointData = new GeoPointData().cast(new UncastData(toString(arg)));
							gpsCoordinatesList.add(new GeoUtils.GPSCoordinates(geoPointData.getPart(0), geoPointData.getPart(1)));
						} catch (Exception e) {
							throw new XPathTypeMismatchException("The function \'" + name + "\' received a value that does not represent GPS coordinates: " + arg);
						}
					}
				}
			}

			return GeoUtils.calculateAreaOfGPSPolygonOnEarthInSquareMeters(gpsCoordinatesList);
		} else {
			//check for custom handler
			IFunctionHandler handler = funcHandlers.get(name);
			if (handler != null) {
				return evalCustomFunction(handler, argVals, evalContext);
			} else {
				throw new XPathUnhandledException("function \'" + name + "\'");
			}
		}
	}

	private static void assertArgsCount(String name, Object[] args, int count) {
		if ( args.length != count ) {
			throw new XPathUnhandledException("function \'" + name + "\' requires " +
					count + " arguments. Only " + args.length + " provided.");
		}
	}

	/**
	 * Given a handler registered to handle the function, try to coerce the function arguments into
	 * one of the prototypes defined by the handler. If no suitable prototype found, throw an eval
	 * exception. Otherwise, evaluate.
	 *
	 * Note that if the handler supports 'raw args', it will receive the full, unaltered argument
	 * list if no prototype matches. (this lets functions support variable-length argument lists)
	 *
	 * @param handler
	 * @param args
	 * @return
	 */
	private static Object evalCustomFunction (IFunctionHandler handler, Object[] args, EvaluationContext ec) {
      List<Class[]> prototypes = handler.getPrototypes();
		Object[] typedArgs = null;

		int i = 0;
		while (typedArgs == null && prototypes.size() > i) {
			typedArgs = matchPrototype(args, prototypes.get(i++));
		}

		if (typedArgs != null) {
			return handler.eval(typedArgs, ec);
		} else if (handler.rawArgs()) {
			return handler.eval(args, ec);  //should we have support for expanding nodesets here?
		} else {
			throw new XPathTypeMismatchException("for function \'" + handler.getName() + "\'");
		}
	}

	/**
	 * Given a prototype defined by the function handler, attempt to coerce the function arguments
	 * to match that prototype (checking # args, type conversion, etc.). If it is coercible, return
	 * the type-converted argument list -- these will be the arguments used to evaluate the function.
	 * If not coercible, return null.
	 *
	 * @param args
	 * @param prototype
	 * @return
	 */
	private static Object[] matchPrototype (Object[] args, Class[] prototype) {
		Object[] typed = null;

		if (prototype.length == args.length) {
			typed = new Object[args.length];

			for (int i = 0; i < prototype.length; i++) {
				typed[i] = null;

				//how to handle type conversions of custom types?
				if (prototype[i].isAssignableFrom(args[i].getClass())) {
					typed[i] = args[i];
				} else {
					try {
						if (prototype[i] == Boolean.class) {
							typed[i] = toBoolean(args[i]);
						} else if (prototype[i] == Double.class) {
							typed[i] = toNumeric(args[i]);
						} else if (prototype[i] == String.class) {
							typed[i] = toString(args[i]);
						} else if (prototype[i] == Date.class) {
							typed[i] = toDate(args[i], false);
						}
					} catch (XPathTypeMismatchException xptme) { /* swallow type mismatch exception */ }
				}

				if (typed[i] == null)
					return null;
			}
		}

		return typed;
	}

	/******** HANDLERS FOR BUILT-IN FUNCTIONS ********
	 *
	 * the functions below are the handlers for the built-in xpath function suite
	 *
	 * if you add a function to the suite, it should adhere to the following pattern:
	 *
	 *   * the function takes in its arguments as objects (DO NOT cast the arguments when calling
	 *     the handler up in eval() (i.e., return stringLength((String)argVals[0])  <--- NO!)
	 *
	 *   * the function converts the generic argument(s) to the desired type using the built-in
	 *     xpath type conversion functions (toBoolean(), toNumeric(), toString(), toDate())
	 *
	 *   * the function MUST return an object of type Boolean, Double, String, or Date; it may
	 *     never return null (instead return the empty string or NaN)
	 *
	 *   * the function may throw exceptions, but should try as hard as possible not to, and if
	 *     it must, strive to make it an XPathException
	 *
	 */

	public static boolean isNull (Object o) {
		if (o == null) {
			return true; //true 'null' values aren't allowed in the xpath engine, but whatever
		}

		o = unpack(o);
		if (o instanceof String && ((String)o).length() == 0) {
			return true;
		} else if (o instanceof Double && ((Double)o).isNaN()) {
			return true;
		} else {
			return false;
		}
	}

	public static Double stringLength (Object o) {
		String s = toString(o);
		if(s == null) {
			return new Double(0.0);
		}
		return new Double(s.length());
	}

	/**
	 * convert a value to a boolean using xpath's type conversion rules
     *
	 * @param o
	 * @return
	 */
	public static Boolean toBoolean (Object o) {
		Boolean val = null;

		o = unpack(o);

		if (o instanceof Boolean) {
			val = (Boolean)o;
		} else if (o instanceof Double) {
			double d = ((Double)o).doubleValue();
			val = new Boolean(Math.abs(d) > 1.0e-12 && !Double.isNaN(d));
		} else if (o instanceof String) {
			String s = (String)o;
			val = new Boolean(s.length() > 0);
		} else if (o instanceof Date) {
			val = Boolean.TRUE;
		} else if (o instanceof IExprDataType) {
			val = ((IExprDataType)o).toBoolean();
		}

		if (val != null) {
			return val;
		} else {
			throw new XPathTypeMismatchException("converting to boolean");
		}
	}

    public static Double toDouble(Object o ){
            if(o instanceof Date) {
                    return DateUtils.fractionalDaysSinceEpoch((Date)o);
            } else {
                    return toNumeric(o);
            }

    }

	/**
	 * convert a value to a number using xpath's type conversion rules (note that xpath itself makes
	 * no distinction between integer and floating point numbers)
	 *
	 * @param o
	 * @return
	 */
	public static Double toNumeric (Object o) {
		Double val = null;

		o = unpack(o);

		if (o instanceof Boolean) {
			val = new Double(((Boolean)o).booleanValue() ? 1 : 0);
		} else if (o instanceof Double) {
			val = (Double)o;
		} else if (o instanceof String) {
			/* annoying, but the xpath spec doesn't recognize scientific notation, or +/-Infinity
			 * when converting a string to a number
			 */

			String s = (String)o;
			double d;
			try {
				s = s.trim();
				for (int i = 0; i < s.length(); i++) {
					char c = s.charAt(i);
					if (c != '-' && c != '.' && (c < '0' || c > '9'))
						throw new NumberFormatException();
				}

				d = Double.parseDouble(s);
				val = new Double(d);
			} catch (NumberFormatException nfe) {
				val = new Double(Double.NaN);
			}
		} else if (o instanceof Date) {
			val = new Double(DateUtils.daysSinceEpoch((Date)o));
		} else if (o instanceof IExprDataType) {
			val = ((IExprDataType)o).toNumeric();
		}

		if (val != null) {
			return val;
		} else {
			throw new XPathTypeMismatchException("converting to numeric");
		}
	}

	/**
	 * convert a number to an integer by truncating the fractional part. if non-numeric, coerce the
	 * value to a number first. note that the resulting return value is still a Double, as required
	 * by the xpath engine
	 *
	 * @param o
	 * @return
	 */
	public static Double toInt (Object o) {
		Double val = toNumeric(o);

		if (val.isInfinite() || val.isNaN()) {
			return val;
		} else if (val.doubleValue() >= Long.MAX_VALUE || val.doubleValue() <= Long.MIN_VALUE) {
			return val;
		} else {
			long l = val.longValue();
			Double dbl = new Double(l);
			if (l == 0 && (val.doubleValue() < 0. || val.equals(new Double(-0.)))) {
				dbl = new Double(-0.);
			}
			return dbl;
		}
	}

	/**
	 * convert a value to a string using xpath's type conversion rules
	 *
	 * @param o
	 * @return
	 */
	public static String toString (Object o) {
		String val = null;

		o = unpack(o);

		if (o instanceof Boolean) {
			val = (((Boolean)o).booleanValue() ? "true" : "false");
		} else if (o instanceof Double) {
			double d = ((Double)o).doubleValue();
			if (Double.isNaN(d)) {
				val = "NaN";
			} else if (Math.abs(d) < 1.0e-12) {
				val = "0";
			} else if (Double.isInfinite(d)) {
				val = (d < 0 ? "-" : "") + "Infinity";
			} else if (Math.abs(d - (int)d) < 1.0e-12) {
				val = String.valueOf((int)d);
			} else {
				val = String.valueOf(d);
			}
		} else if (o instanceof String) {
			val = (String)o;
		} else if (o instanceof Date) {
			val = DateUtils.formatDate((Date)o, DateUtils.FORMAT_ISO8601);
		} else if (o instanceof IExprDataType) {
			val = ((IExprDataType)o).toString();
		}

		if (val != null) {
			return val;
		} else {
			throw new XPathTypeMismatchException("converting to string");
		}
	}

	/**
	 * convert a value to a date. note that xpath has no intrinsic representation of dates, so this
	 * is off-spec. dates convert to strings as 'yyyy-mm-dd', convert to numbers as # of days since
	 * the unix epoch, and convert to booleans always as 'true'
	 *
	 * string and int conversions are reversable, however:
	 *   * cannot convert bool to date
	 *   * empty string and NaN (xpath's 'null values') go unchanged, instead of being converted
	 *     into a date (which would cause an error, since Date has no null value (other than java
	 *     null, which the xpath engine can't handle))
	 *   * note, however, than non-empty strings that aren't valid dates _will_ cause an error
	 *     during conversion
	 *
	 * @param o
	 * @return
	 */
	public static Object toDate (Object o, boolean preserveTime) {
		o = unpack(o);

		if (o instanceof Double) {
			if (preserveTime) {
				Double n = (Double) o;

				if (n.isNaN()) {
					return n;
				}

				if (n.isInfinite() || n.doubleValue() > Integer.MAX_VALUE || n.doubleValue() < Integer.MIN_VALUE) {
					throw new XPathTypeMismatchException("converting out-of-range value to date");
				}

				long timeMillis = (long) (n * DateUtils.DAY_IN_MS);

				Date d = new Date(timeMillis);
				return d;
			} else {
				Double n = toInt(o);

				if (n.isNaN()) {
					return n;
				}

				if (n.isInfinite() || n.doubleValue() > Integer.MAX_VALUE || n.doubleValue() < Integer.MIN_VALUE) {
					throw new XPathTypeMismatchException("converting out-of-range value to date");
				}

				return DateUtils.dateAdd(DateUtils.getDate(1970, 1, 1), n.intValue());
			}
		} else if (o instanceof String) {
			String s = (String)o;

			if (s.length() == 0) {
				return s;
			}

			Date d = DateUtils.parseDateTime(s);
			if (d == null) {
				throw new XPathTypeMismatchException("converting to date");
			} else {
				return d;
			}
		} else if (o instanceof Date) {
			if ( preserveTime ) {
				return (Date) o;
			} else {
				return DateUtils.roundDate((Date)o);
			}
		} else {
			throw new XPathTypeMismatchException("converting to date");
		}
	}

	public static Object toDecimalDateTime (Object o, boolean keepDate) {
		o = unpack(o);

		if (o instanceof Double) {
			Double n = (Double) o;

			if (n.isNaN()) {
				return n;
			}

			if (n.isInfinite() || n.doubleValue() > Integer.MAX_VALUE || n.doubleValue() < Integer.MIN_VALUE) {
				throw new XPathTypeMismatchException("converting out-of-range value to date");
			}

			if ( keepDate ) {
				return n;
			} else {
				return n - Math.floor(n);
			}
		} else if (o instanceof String) {
			String s = (String)o;

			if (s.length() == 0) {
				return s;
			}

			Date d = DateUtils.parseDateTime(s);
			if (d == null) {
				throw new XPathTypeMismatchException("converting to date");
			} else {
				if ( keepDate ) {
					long milli = d.getTime();
					Double v = ((double) milli) / DateUtils.DAY_IN_MS;
					return v;
				} else {
					return DateUtils.decimalTimeOfLocalDay(d);
				}
			}
		} else if (o instanceof Date) {
			Date d = (Date) o;
			if ( keepDate ) {
				long milli = d.getTime();
				Double v = ((double) milli) / DateUtils.DAY_IN_MS;
				return v;
			} else {
				return DateUtils.decimalTimeOfLocalDay(d);
			}
		} else {
			throw new XPathTypeMismatchException("converting to date");
		}
	}

	public static Boolean boolNot (Object o) {
		boolean b = toBoolean(o).booleanValue();
		return new Boolean(!b);
	}

	public static Boolean boolStr (Object o) {
		String s = toString(o);
		if (s.equalsIgnoreCase("true") || s.equals("1"))
			return Boolean.TRUE;
		else
			return Boolean.FALSE;
	}

	public static String dateStr (Object od, Object of, boolean preserveTime) {
		od = toDate(od, preserveTime);
		if (od instanceof Date) {
			return DateUtils.format((Date)od, toString(of));
		} else {
			return "";
		}
	}

	private Double position(TreeReference refAt) {
		return new Double(1+refAt.getMultLast());
	}

	public static Object ifThenElse (FormInstance model, EvaluationContext ec, XPathExpression[] args, Object[] argVals) {
		argVals[0] = args[0].eval(model, ec);
		boolean b = toBoolean(argVals[0]).booleanValue();
		return (b ? args[1].eval(model, ec) : args[2].eval(model, ec));
	}

 	/**
	 * This provides a method of indexing fields stored in prior repeat groups.
	 *
	 * args[0] = generic XPath expression to index
	 * args[1] = generic XPath expression for group to index
	 * args[2] = index number for group
	 * args[3] = generic XPath expression for add'l group to index (if 5 or 7 parameters passed)
	 * args[4] = index number for group (if 5 or 7 parameters passed)
	 * args[5] = generic XPath expression for add'l group to index (if 7 parameters passed)
	 * args[6] = index number for group (if 7 parameters passed)
	 *
	 * @param model
	 * @param ec
	 * @param args
	 * @param argVals
	 * @return
	 */
	public static Object indexedRepeat (FormInstance model, EvaluationContext ec, XPathExpression[] args, Object[] argVals) throws XPathTypeMismatchException {
		// initialize target and context references
		if (!(args[0] instanceof XPathPathExpr)) {
			throw new XPathTypeMismatchException("indexed-repeat(): first parameter must be XPath field reference");
		}
		XPathPathExpr targetPath=(XPathPathExpr)args[0];
		TreeReference targetRef=targetPath.getReference();
		TreeReference contextRef=targetRef.clone();

		// process passed index(es)
		for (int pathargi=1, idxargi=2 ; idxargi < args.length ; pathargi+=2, idxargi+=2) {
			// confirm that we were passed an XPath
			if (!(args[pathargi] instanceof XPathPathExpr)) {
				throw new XPathTypeMismatchException("indexed-repeat(): parameter " + (pathargi+1) + " must be XPath repeat-group reference");
			}
			// confirm that the passed XPath is a parent of our overall target path
			TreeReference groupRef=((XPathPathExpr)args[pathargi]).getReference();
			if (!groupRef.isParentOf(targetRef,true)) {
				throw new XPathTypeMismatchException("indexed-repeat(): parameter " + (pathargi+1) + " must be a parent of the field in parameter 1");
			}

			// process index (if valid)
			int groupIdx = toInt(args[idxargi].eval(model, ec)).intValue();
			if (groupIdx <= 0) {
				// ignore invalid indexes (primarily happens during validation)
			}
			else {
				// otherwise, add the index to the context reference
				contextRef.setMultiplicity(groupRef.size()-1, groupIdx-1);
			}
		}

		// evaluate and return the XPath expression, in context
		EvaluationContext revisedec = new EvaluationContext(ec, contextRef);
		return (targetPath.eval(model, revisedec));
	}

	/**
	 * return whether a particular choice of a multi-select is selected
	 *
	 * @param o1 XML-serialized answer to multi-select question (i.e, space-delimited choice values)
	 * @param o2 choice to look for
	 * @return
	 */
	public static Boolean multiSelected (Object o1, Object o2, String functionName) {
        Object indexObject = unpack(o2);
        if (!(indexObject instanceof String)) {
            throw new XPathTypeMismatchException("The second parameter to the " + functionName + "() function must be in quotes (like '1').");
        }
        String s1 = (String)unpack(o1);
        String s2 = ((String) indexObject).trim();

		return new Boolean((" " + s1 + " ").indexOf(" " + s2 + " ") != -1);
	}

	/**
	 * return the number of choices in a multi-select answer
	 *
	 * @param o XML-serialized answer to multi-select question (i.e, space-delimited choice values)
	 * @return
	 */
	public static Double countSelected (Object o) {
		String s = (String)unpack(o);

		return new Double(DateUtils.split(s, " ", true).size());
	}

    /**
     * Get the Nth item in a selected list
     *
     * @param o1 XML-serialized answer to multi-select question (i.e, space-delimited choice values)
     * @param o2 the integer index into the list to return
     * @return
     */
    public static String selectedAt (Object o1, Object o2) {
        String selection = (String)unpack(o1);
        int index = toInt(o2).intValue();
       List<String> stringVector = DateUtils.split(selection, " ", true);
        if (stringVector.size() > index && index >= 0) {
            return stringVector.get(index);
        } else {
        	return ""; // empty string if outside of array
        }
    }

	/**
	 * count the number of nodes in a nodeset
	 *
	 * @param o
	 * @return
	 */
	public static Double count (Object o) {
		if (o instanceof XPathNodeset) {
			return new Double(((XPathNodeset)o).size());
		} else {
			throw new XPathTypeMismatchException("not a nodeset");
		}
	}

	/**
	 * sum the values in a nodeset; each element is coerced to a numeric value
	 *
	 * @param model
	 * @param o
	 * @return
	 */
	public static Double sum (Object argVals[]) {
		double sum = 0.0;
		for (int i = 0; i < argVals.length; i++) {
			Double dargVal=toNumeric(argVals[i]);
			if (!dargVal.isNaN()) {
				sum += dargVal.doubleValue();
			}
		}
		return new Double(sum);
	}

	/**
	 * round function like in Excel.
	 *
	 * @param num
	 * @param dblDecim
	 * @return
	 */
	private static Double round(double num, double numDecim) {
		long p=0;

		// rounding doesn't affect special values...
		if ( num == Double.NaN ||
			 num == Double.NEGATIVE_INFINITY ||
			 num == Double.POSITIVE_INFINITY ) {
			return new Double(num);
		}

		// absurdly large rounding requests yield NaN...
		if ( numDecim > 30.0 || numDecim < -30.0 ) {
			return new Double(Double.NaN);
		}

		// ignore fractional numDecim rounding values.
		// any numDecim that is more than 0.5 is considered "1"

		if ( numDecim < 0.0 ) {
			// we want to retain 100's or higher value
			// round( 33.33, 1) = 30.0
			// divide everything by 10's.
			while ( numDecim <= -0.5 ) {
				num /= 10.0;
				++p;
				++numDecim;
			}
		} else {
			// we want to retain a fractional value
			// round( 33.33, -1) = 3.3
			// multiply everything by 10's.
			while ( numDecim >= 0.5 ) {
				num *= 10.0;
				--p;
				--numDecim;
			}
		}
		// truncate with a 0.5 offset to round to the nearest long...
		num = (double)((long) (num+0.5));

		// and now restore the number to the appropriate scale.
		if ( p < 0 ) {
			while ( p < 0 ) {
				num /= 10.0;
				++p;
			}
		} else {
			while ( p > 0 ) {
				num *= 10.0;
				--p;
			}
		}
		return new Double(num);
	}

    /**
     * Identify the largest value from the list of provided values.
     *
     * @param argVals
     * @return
     */
    private static Object max(Object[] argVals) {
        double max = Double.MIN_VALUE;
        boolean returnNaN = true;
        for (int i = 0; i < argVals.length; i++) {
            Double dargVal = toNumeric(argVals[i]);
            if (!dargVal.isNaN()) {
                max = Math.max(max, dargVal.doubleValue());
                returnNaN = false;
            }
        }
        return new Double(returnNaN ? Double.NaN : max);
    }

    private static Object min(Object[] argVals) {
        double min = Double.MAX_VALUE;
        boolean returnNaN = true;
        for (int i = 0; i < argVals.length; i++) {
            Double dargVal = toNumeric(argVals[i]);
            if (!dargVal.isNaN()) {
                min = Math.min(min, dargVal.doubleValue());
                returnNaN = false;
            }
        }
        return new Double(returnNaN ? Double.NaN : min);
    }

	/**
	 * concatenate an abritrary-length argument list of string values together
	 *
	 * @param argVals
	 * @return
	 */
	public static String join (Object oSep, Object[] argVals) {
		String sep = toString(oSep);
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < argVals.length; i++) {
			sb.append(toString(argVals[i]));
			if (i < argVals.length - 1)
				sb.append(sep);
		}

		return sb.toString();
	}

	public static String substring (Object o1, Object o2, Object o3) {
		String s = toString(o1);
		int start = toInt(o2).intValue();

		int len = s.length();

		int end = (o3 != null ? toInt(o3).intValue() : len);
		if (start < 0) {
			start = len + start;
		}
		if (end < 0) {
			end = len + end;
		}
		end = Math.min(Math.max(0, end), len);
		start = Math.min(Math.max(0, start), len);

		return (start <= end ? s.substring(start, end) : "");
	}

	/**
	 * perform a 'checklist' computation, enabling expressions like 'if there are at least 3 risk
	 * factors active'
	 *
	 * @param argVals
	 *   the first argument is a numeric value expressing the minimum number of factors required.
	 *     if -1, no minimum is applicable
	 *   the second argument is a numeric value expressing the maximum number of allowed factors.
	 *     if -1, no maximum is applicalbe
	 *   arguments 3 through the end are the individual factors, each coerced to a boolean value
	 * @return true if the count of 'true' factors is between the applicable minimum and maximum,
	 *   inclusive
	 */
	public static Boolean checklist (Object oMin, Object oMax, Object[] factors) {
		int min = toNumeric(oMin).intValue();
		int max = toNumeric(oMax).intValue();

		int count = 0;
		for (int i = 0; i < factors.length; i++) {
			if (toBoolean(factors[i]).booleanValue())
				count++;
		}

		return new Boolean((min < 0 || count >= min) && (max < 0 || count <= max));
	}

	/**
	 * very similar to checklist, only each factor is assigned a real-number 'weight'.
	 *
	 * the first and second args are again the minimum and maximum, but -1 no longer means
	 * 'not applicable'.
	 *
	 * subsequent arguments come in pairs: first the boolean value, then the floating-point
	 * weight for that value
	 *
	 * the weights of all the 'true' factors are summed, and the function returns whether
	 * this sum is between the min and max
	 *
	 * @param argVals
	 * @return
	 */
	public static Boolean checklistWeighted (Object oMin, Object oMax, Object[] flags, Object[] weights) {
		double min = toNumeric(oMin).doubleValue();
		double max = toNumeric(oMax).doubleValue();

		double sum = 0.;
		for (int i = 0; i < flags.length; i++) {
			boolean flag = toBoolean(flags[i]).booleanValue();
			double weight = toNumeric(weights[i]).doubleValue();

			if (flag)
				sum += weight;
		}

		return new Boolean(sum >= min && sum <= max);
	}

	/**
	 * determine if a string matches a regular expression.
	 *
	 * @param o1 string being matched
	 * @param o2 regular expression
	 * @return
	 */
	public static Boolean regex (Object o1, Object o2) {
		String str = toString(o1);
		String re = toString(o2);

		boolean result = Pattern.matches(re, str);
		return new Boolean(result);
	}

	private static Object[] subsetArgList (Object[] args, int start) {
		return subsetArgList(args, start, 1);
	}

	/**
	 * return a subset of an argument list as a new arguments list
	 *
	 * @param args
	 * @param start index to start at
	 * @param skip sub-list will contain every nth argument, where n == skip (default: 1)
	 * @return
	 */
	private static Object[] subsetArgList (Object[] args, int start, int skip) {
		if (start > args.length || skip < 1) {
			throw new RuntimeException("error in subsetting arglist");
		}

		Object[] subargs = new Object[(int)MathUtils.divLongNotSuck(args.length - start - 1, skip) + 1];
		for (int i = start, j = 0; i < args.length; i += skip, j++) {
			subargs[j] = args[i];
		}

		return subargs;
	}

	public static Object unpack (Object o) {
		if (o instanceof XPathNodeset) {
			return ((XPathNodeset)o).unpack();
		} else {
			return o;
		}
	}

	/**
	 *
	 */
	public Object pivot (FormInstance model, EvaluationContext evalContext, List<Object> pivots, Object sentinal) throws UnpivotableExpressionException {
		String name = id.toString();

		//for now we'll assume that all that functions do is return the composition of their components
		Object[] argVals = new Object[args.length];

		//Identify whether this function is an identity: IE: can reflect back the pivot sentinal with no modification
		String[] identities = new String[] {"string-length"};
		boolean id = false;
		for(String identity : identities) {
			if(identity.equals(name)) {
				id = true;
			}
		}

		//get each argument's pivot
		for (int i = 0; i < args.length; i++) {
			argVals[i] = args[i].pivot(model, evalContext, pivots, sentinal);
		}

		boolean pivoted = false;
		//evaluate the pivots
		for(int i = 0 ; i < argVals.length; ++i) {
			if(argVals[i] == null) {
				//one of our arguments contained pivots,
				pivoted = true;
			} else if(sentinal.equals(argVals[i])) {
				//one of our arguments is the sentinal, return the sentinal if possible
				if(id) {
					return sentinal;
				} else {
					//This function modifies the sentinal in a way that makes it impossible to capture
					//the pivot.
					throw new UnpivotableExpressionException();
				}
			}
		}

		if(pivoted) {
			if(id) {
				return null;
			} else {
				//This function modifies the sentinal in a way that makes it impossible to capture
				//the pivot.
				throw new UnpivotableExpressionException();
			}
		}

		//TODO: Inner eval here with eval'd args to improve speed
		return eval(model, evalContext);

	}

}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<title>Keyprotect AB</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" type="image/png" sizes="32x32" href="/assets/Images/favicon-72x72.png">

		<link href="lib/bootstrap/bootstrap.css" rel="stylesheet" >
        <link href="assets/css/modern-business.css" rel="stylesheet">
        <link href="assets/css/style.css" rel="stylesheet" />
        <link href="assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
        <link href='https://fonts.googleapis.com/css?family=Raleway:400,700' rel='stylesheet' type='text/css'><link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
        <link href='https://fonts.googleapis.com/css?family=PT+Sans' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                KeyProtect AB

                        Hem

                        Produkter

                        Om

                        Referenser

                        Kontakt

Produkter

                        Hem

Produkter

Calmare Nyckel erbjuder fastighetsägaren ett säkert och enkelt sätt att göra fastighetens nyckel tillgänglig för räddningstjänsten

                Vår produkt gynnar därmed både fastighetsägaren själv och de som arbetar med brandbekämpning.
                Ett Calmare Nyckel skåp installeras helt sonika utanför fastigheten och fastighetens nycklar låses säkert in i detta skåp.

Dokument

                         Produktblad

                         Moteringsanvisning

                    Calmare Nyckel kan placeras i fasaden oavsett struktur.

Produktfördelar

                                        Räddningstjänsten kan snabbare och lättare få access till fastighetsägarens byggnad när ett brandlarm har aktiverats.
                                        Detta kan eliminera stora ekonomiska förluster för fastighetsägaren eftersom onödiga driftstopp förhindras. Varje sekund är viktig när ett släckningsarbete utförs!

                                    Läs mer..

                                    Räddningstjänstens insatsstyrka är inte alltid på stationen när ett brandlarm går. Detta kan leda till att en insatsstyrka kan bli tvingade att återvända till stationen för att hämta de rätta nycklarna till den fastighet där larmet gått. På så sätt kan mycket dyrbar tid gå till spillo. Vid Räddningstjänstens utryckningar är tid en mycket dyrbar bristvara. Sekunder kan vara avgörande i fråga om de skador en eldsvåda kan åverka på din verksamhets fastigheter, eller vara avgörandet mellan liv och död.
                                    Eftersom nyckeln till ett Calmare Nyckel skåp går till flertalet fastigheter så kan denna nyckel enkelt tas med av Räddningstjänstens insatsstyrka. Räddningstjänsten slipper på så sätt att åka förbi stationen för att hämta just din fastighets nyckel ur deras nyckelskåp. Något som både du och räddningstjänsten tjänar på.

                                        Nyckelskåpet Calmare Nyckel är larmat, inbrottssäkert, rostfritt. Skåpet kan endast öppnas när ett brandlarm har gått.
                                        Detta gör att fastighetsägarens nyckel är skyddad mot all obehörig ankomst på ett mycket säkrare sätt.

                                    Läs mer..

                                    Calmare Nyckel skåpet är testat och håller högsta skyddsklass, vilket innebär att skåpet har utsatts för ett antal normtester såsom mekanisk påverkan, dyrkning, manipulering, huggning, korrosion samt borrning. Skåpet kan även larmas med befintlig microbrytare som ansluts till lämplig larmsändareutrustning. Dessutom så kan skåpet kopplas till automatlarmet vilket innebär att man endast har åtkomst till ett Calmare Nyckelskåp när brandlarmet har gått. Risken för obehörig åtkomst elimineras därmed.

                                        Dessutom så kan den nyckel som leder till Calmare Nyckel skåpen deaktiveras ifall den skulle komma bort.
                                        På så sätt behöver inga lås bytas ut ifall en enskild nyckel kommer på avvägar och kostnaderna minimeras därmed.
                                        Man kan även spåra vilken nyckel som har används för att öppna ditt Calmare Nyckel skåp vid ett givet tillfälle.

                                    Läs mer..

                                    Nyckeln som används heter Assa IQ Twin och är en elektronisk kodifierad nyckel.
                                    Kodifieringen är uppbyggt på ett DES krypteringssystem med 10 upphöjt till 19 koder och ansees vara en av de högst stående krypteringsformerna utanför den militära världen.
                                    Assa IQ Twin Set-Up nyckeln kan dessutom bära information såsom till exempel en tänkt omprogrammering eller en utläsning av vilka nycklar som försökt manövrera cylindern.
                                    Detta möjliggör att man kan spåra den senaste användaren av en specifik nyckel samt restriktera specifika nycklar tillträde till ett lås.
                                    Man kan även spåra vilken nyckel som har används för att öppna ditt Calmare Nyckel skåp vid ett givet tillfälle.

Södra vägen 56, 392 45 Kalmar Tel. 0731-500 900

            Design - SoSobchak creation

© 2016 - Key Protect


text:
[![Build Status](https://travis-ci.org/clebi/gofin.svg?branch=master)](https://travis-ci.org/clebi/gofin)
[![codecov](https://codecov.io/gh/clebi/gofin/branch/master/graph/badge.svg)](https://codecov.io/gh/clebi/gofin)
[![Go Report Card](https://goreportcard.com/badge/github.com/clebi/gofin)](https://goreportcard.com/report/github.com/clebi/gofin)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

### Warning : Yahoo finance api has been terminated by Yahoo

Gofin retrieves stocks history from yahoo finance API and computes indicators abouts stocks.


text:
package com.android.systemui.statusbar.phone;

import android.app.PendingIntent;
import android.content.Intent;

/**
 * An interface to start activities. This is used to as a callback from the views to
 * {@link PhoneStatusBar} to allow custom handling for starting the activity, i.e. dismissing the
 * Keyguard.
 */
public interface ActivityStarter {
    void startPendingIntentDismissingKeyguard(PendingIntent intent);
    void startActivity(Intent intent, boolean dismissShade);
    void startActivity(Intent intent, boolean dismissShade, Callback callback);
    void preventNextAnimation();

    interface Callback {
        void onActivityStarted(int resultCode);
    }
}


text:
SELECT y, coalesce(sum(x),0) FROM
(SELECT null AS x, y+1 AS y FROM t1 UNION SELECT * FROM t1)
GROUP BY y ORDER BY y;


text:
// Code generated by ffjson <https://github.com/pquerna/ffjson>. DO NOT EDIT.
// source: connections/output_message.go

package connections

import (
	fflib "github.com/pquerna/ffjson/fflib/v1"
)

// MarshalJSON marshal bytes to json - template
func (j *OutputMessage) MarshalJSON() ([]byte, error) {
	var buf fflib.Buffer
	if j == nil {
		buf.WriteString("null")
		return buf.Bytes(), nil
	}
	err := j.MarshalJSONBuf(&buf)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

// MarshalJSONBuf marshal buff to json - template
func (j *OutputMessage) MarshalJSONBuf(buf fflib.EncodingBuffer) error {
	if j == nil {
		buf.WriteString("null")
		return nil
	}
	var err error
	var obj []byte
	_ = obj
	_ = err
	buf.WriteString(`{"type":`)

	{

		obj, err = j.Type.MarshalJSON()
		if err != nil {
			return err
		}
		buf.Write(obj)

	}
	buf.WriteString(`,"payload":`)
	/* Interface types must use runtime reflection. type=interface {} kind=interface */
	err = buf.Encode(j.Payload)
	if err != nil {
		return err
	}
	buf.WriteByte('}')
	return nil
}


text:
package bnfc.abs.Absyn; // Java Package generated by the BNF Converter.

public class CaseBranc extends CaseBranch {
  public final Pattern pattern_;
  public final PureExp pureexp_;
  public CaseBranc(Pattern p1, PureExp p2) { pattern_ = p1; pureexp_ = p2; }

  public <R,A> R accept(bnfc.abs.Absyn.CaseBranch.Visitor<R,A> v, A arg) { return v.visit(this, arg); }

  public boolean equals(Object o) {
    if (this == o) return true;
    if (o instanceof bnfc.abs.Absyn.CaseBranc) {
      bnfc.abs.Absyn.CaseBranc x = (bnfc.abs.Absyn.CaseBranc)o;
      return this.pattern_.equals(x.pattern_) && this.pureexp_.equals(x.pureexp_);
    }
    return false;
  }

  public int hashCode() {
    return 37*(this.pattern_.hashCode())+this.pureexp_.hashCode();
  }

}


text:
var JX = require('javelin').JX;
JX.require('AphlictListener', __dirname);

JX.install('AphlictListenerList', {
  construct : function() {
    this._listeners = {};
  },

  members : {
    _listeners : null,
    _nextID : 0,
    _activeListenerCount : 0,
    _totalListenerCount : 0,

    addListener : function(socket) {
      var listener = new JX.AphlictListener(
        this._generateNextID(),
        socket);

      this._listeners[listener.getID()] = listener;
      this._activeListenerCount++;
      this._totalListenerCount++;

      return listener;
    },

    removeListener : function(listener) {
      var id = listener.getID();
      if (id in this._listeners) {
        delete this._listeners[id];
        this._activeListenerCount--;
      }
    },

    getListeners : function() {
      return this._listeners;
    },

    getActiveListenerCount : function() {
      return this._activeListenerCount;
    },

    getTotalListenerCount : function() {
      return this._totalListenerCount;
    },

    _generateNextID : function() {
      do {
        this._nextID = ((this._nextID + 1) % 1000000000000);
      } while (this._nextID in this._listeners);

      return this._nextID;
    }

  }

});


text:
ACCEPTED

#### According to
Integrated Taxonomic Information System

#### Published in
null

#### Original name
Lathyrus leucanthus Rydb.

### Remarks
null


text:
set -e

pushd Tests

pod install
xcodebuild -sdk iphonesimulator7.1 -workspace ISCacheTests.xcworkspace -scheme ISCacheTests test || exit 1

popd


text:
package dto.Summoner;

import java.io.Serializable;

public class Mastery implements Serializable {

	private static final long serialVersionUID = -1053051501742552701L;
	private int id, rank;

	public int getId() {
		return id;
	}

	public int getRank() {
		return rank;
	}
}


text:
<?php

namespace ZF2rapid\Task\Display;

use Zend\Console\ColorInterface as Color;
use ZF2rapid\Task\AbstractTask;

/**
 * Class LoadedFilters
 *
 * @package ZF2rapid\Task\Display
 */
class LoadedFilters extends AbstractTask
{
    /**
     * Process the command
     *
     * @return integer
     */
    public function processCommandTask()
    {
        // output done message
        $this->console->writeTaskLine(
            'task_display_loaded_filters_found_in_path',
            array(
                $this->console->colorize(
                    $this->params->projectPath, Color::GREEN
                )
            )
        );

        // loop through modules
        foreach ($this->params->loadedModules as $moduleName => $moduleObject) {
            $this->console->writeListItemLine(
                'task_display_loaded_filters_module_class',
                array(
                    $this->console->colorize(
                        $moduleName, Color::GREEN
                    ),
                    $this->console->colorize(
                        get_class($moduleObject), Color::BLUE
                    )
                )
            );

            // check for empty filter list
            if (empty($this->params->loadedFilters[$moduleName])) {
                $this->console->writeListItemLineLevel2(
                    'task_display_loaded_filters_no_filters'
                );

                continue;
            }

            // loop through controllers
            foreach (
                $this->params->loadedFilters[$moduleName]
                as $pluginType => $pluginList
            ) {
                $this->console->writeListItemLineLevel2(
                    'task_display_loaded_filters_type',
                    array(
                        $this->console->colorize(
                            $pluginType, Color::GREEN
                        ),
                    ),
                    false
                );

                // output controllers for module
                foreach (
                    $pluginList as $pluginName => $pluginClass
                ) {
                    $this->console->writeListItemLineLevel3(
                        'task_display_loaded_filters_filter_class',
                        array(
                            $this->console->colorize(
                                $pluginName, Color::GREEN
                            ),
                            $this->console->colorize(
                                $pluginClass, Color::BLUE
                            )
                        ),
                        false
                    );
                }
            }
        }

        return 0;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="@dimen/toolbar_height"
                android:layout_centerHorizontal="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.balysv.materialmenu.MaterialMenuView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:layout_centerVertical="true"
            android:background="@drawable/selector_trans_to_white"
            android:id="@+id/sidebarBtnMaterial"/>

        <com.clover_studio.spikachatmodule.view.CustomTextView
            android:id="@+id/toolbarTitle"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:gravity="center_vertical"
            android:text="@string/chat"
            android:textColor="@color/title_text_color"
            android:textSize="@dimen/title_text_size"/>

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_centerVertical="true"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:id="@+id/settings"
            android:background="@drawable/selector_trans_to_white"
            android:layout_alignParentRight="true"
            android:src="@drawable/ic_setting"/>
    </RelativeLayout>

</RelativeLayout>


text:
Block groups have responsive `tablet-` and `phone-` prefix classes. These allow the flow of content across repeating rows of content to be easily tweaked across viewport widths in scenarios where the default [column resizing](#columns) or [responsive column classes](#responsive-columns) would be too verbose or cumbersome.

Block

Block

Block

Block

```
<div class="block-group block-group-4-up tablet-block-group-2-up phone-block-group-1-up">
  <div class="block trailer-half">
    <div class="panel">Block</div>
  </div>
  <div class="block trailer-half">
    <div class="panel">Block</div>
  </div>
  <div class="block trailer-half">
    <div class="panel">Block</div>
  </div>
  <div class="block trailer-half">
    <div class="panel">Block</div>
  </div>
</div>
```

[View the example]({{relativePath}}/examples/grid/#responsive-block-groups)


text:
using IdleLandsGUI.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IdleLandsGUI
{
    public partial class BuyPetForm : Form
    {
        private IdleLandsComms _comms { get; set; }
        private string _petType { get; set; }
        public BuyPetForm(IdleLandsComms comms, string petType, string petCost)
        {
            _comms = comms;
            _petType = petType;
            InitializeComponent();
            this.Icon = Icon.FromHandle(Resources.IdleLandsIcon.GetHicon());

            PetTypeLabel.Text = "Pet Type: " + petType;
            PetCostLabel.Text = "Pet Cost: " + petCost;
        }

        private void CancelBuyButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void BuyButton_Click(object sender, EventArgs e)
        {
            if(!PetNameTextbox.Text.Any())
            {
                MessageBox.Show("Name cannot be empty.");
                return;
            }

            PetNameTextbox.Enabled = false;
            PetFirstAttributeTextbox.Enabled = false;
            PetSecondAttributeTextbox.Enabled = false;
            BuyButton.Enabled = false;
            CancelBuyButton.Enabled = false;

            _comms.SendBuyPet(_petType, PetNameTextbox.Text,
                new List<string> { PetFirstAttributeTextbox.Text, PetSecondAttributeTextbox.Text }, () =>
            {
                this.Close();
                return true;
            }, (string msg, int code) =>
            {
                MessageBox.Show(code + ": " + msg);
                return true;
            });
        }
    }
}


text:
<?php
cw_load('files','mail');

function cw_spam($message, $recipients, $send_language, $list_id) {

	global $config, $smarty;
	global $current_language, $tables;
	global $app_main_dir;

	$saved_language = $current_language;

	$current_language = $send_language;

	$email_spec = "###EMAIL###";

	$smarty->assign('email', $email_spec);
	$smarty->assign('list_id', $list_id);

	$signature_template = "mail/newsletter_signature.tpl";
	$sign_delim = "\n\n";

    $message['headers'] = array("Content-Type"=>"text/html");
	$sign_delim = "

";

	$signature = cw_display($signature_template,$smarty,false);

    $extra = array("Content-Type" => "text/html");
	foreach($recipients as $recipient) {
	    cw_send_simple_mail($config['news']['newsletter_email'], $recipient, $message['subject'], $message['body'].$sign_delim.preg_replace("/$email_spec/S", $recipient, $signature), $extra);
    }

	$current_language = $saved_language;
}

$do_not_update_status = false;

$recipients = array();

$limit = '';

if (is_array($message)) {
	$message = cw_array_map('stripslashes',$message);

	foreach (array("email1", "email2", "email3") as $f) {
		if (!empty($message[$f]))
			$recipients[] = $message[$f];
	}
	$do_not_update_status = true;

	$list_lng = cw_query_first_cell("SELECT lngcode FROM $tables[newslists] WHERE list_id='$list_id'");
}
else {
	$list = cw_query_first("SELECT * FROM $tables[newslists] WHERE list_id='$list_id'");
	if (empty($list)) return;

	$list_lng = $list['lngcode'];

    $fields = array();
    $from_tbls = array();
    $query_joins = array();
    $where = array();
    $groupbys = array();
    $having = array();
    $orderbys = array();

    $fields[] = 'distinct(c.email)';

    $from_tbls['c'] = 'customers';

    $groupbys[] = 'c.customer_id';

    $where[] = 'c.usertype = "'.$list['usertype'].'"';

    // send notifications by memberships, not a customers
    $mems = cw_query_column("select membership_id from $tables[newslists_memberships] where list_id='$list[list_id]'");
    if (count($mems)) {
        $where[] = 'c.membership_id in ('.implode(', ', $mems).')';
    }

    $countries = cw_query_column("select code from $tables[newsletter_countries] where news_id='$messageid'");
    if (count($countries)) {
        $from_tbls['ca'] = 'customers_addresses';
        $where[] = 'ca.customer_id=c.customer_id';
        $where[] = "ca.country in ('".implode("', '", $countries)."')";
    }

	if ($config['news']['news_emails_per_pass'] > 0) {
		$news_send_data = &cw_session_register('news_send_data');

		if ($action == 'send') {
            $count_query = cw_db_generate_query(array('count(*)'), $from_tbls, $query_joins, $where, $groupbys, $having, array());
            $subscribers_count = cw_query_first_cell($count_query);
			if (!$subscribers_count) return;

			$news_send_data[$messageid] = array (
				'count' => $subscribers_count,
				'lastpos' => 0
			);

			echo cw_get_langvar_by_name("lbl_news_sending_messages", array ("count" => $news_send_data[$messageid]['count']), false, true);
		}
		else {
			echo cw_get_langvar_by_name("lbl_news_continue_sending_messages", array ("last" => $news_send_data[$messageid]['lastpos'], "count" => $news_send_data[$messageid]['count']), false, true);
		}
		cw_flush();

		$limit = sprintf(" LIMIT %d,%d", $news_send_data[$messageid]['lastpos'], $config['news']['news_emails_per_pass']);
	}

    $user_search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);

    $tmp = cw_query($user_search_query.$limit);

	if (is_array($tmp))
	foreach ($tmp as $v) {
		if (!empty($v['email']))
			$recipients[] = $v['email'];
	}
	$message = cw_query_first("SELECT * FROM $tables[newsletter] WHERE news_id='$messageid'");

    if (empty($news_send_data[$messageid]['lastpos'])) {
# kornev, simple subscribers on the first step
        $tmp = cw_query("SELECT email FROM $tables[newslist_subscription] WHERE list_id='$list_id' ORDER BY email");
        if (is_array($tmp))
        foreach ($tmp as $v)
            if (!empty($v['email']))
                $recipients[] = $v['email'];
    }
}

$recipients = array_unique($recipients);

if (count($recipients)>0) {

	cw_call('cw_spam', array($message, $recipients, $list_lng, $list_id));

	if (!$do_not_update_status)
		db_query("UPDATE $tables[newsletter] SET status = 'S', send_date = '".time()."' WHERE news_id = '$message[news_id]'");
}

if (!empty($limit) && count($recipients) > 0) {
	$news_send_data[$messageid]['lastpos'] += count($recipients);

	if ($news_send_data[$messageid]['lastpos'] >= $news_send_data[$messageid]['count']) {
		cw_unset($news_send_data, $messageid);
		return;
	}

	cw_html_location("index.php?target=$target&mode=messages&list_id=$list_id&messageid=$messageid&action=send_continue", $config['news']['news_sleep_interval']);
}

?>


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Wikipedia</title>
	<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" media="screen" />
	<link rel="stylesheet" href="css/main.css" type="text/css" media="screen" />

			View on Wikipedia


text:
<?php
namespace Afshin\LiveConfig\Model;
use Eloquent;
class AfshinLiveConfig extends Eloquent
{

	protected $table= 'afshin_live_config';
		/**
     * Get the Collection's author.
     *
     * @return Photo
     */

}


text:
@interface AFHTTPMessage_AcceptParsing : SenTestCase

@end


text:
#include <aws/autoscaling/model/RecordLifecycleActionHeartbeatResult.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>

#include <utility>

using namespace Aws::AutoScaling::Model;
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
using namespace Aws;

RecordLifecycleActionHeartbeatResult::RecordLifecycleActionHeartbeatResult()
{
}

RecordLifecycleActionHeartbeatResult::RecordLifecycleActionHeartbeatResult(const AmazonWebServiceResult<XmlDocument>& result)
{
  *this = result;
}

RecordLifecycleActionHeartbeatResult& RecordLifecycleActionHeartbeatResult::operator =(const AmazonWebServiceResult<XmlDocument>& result)
{
  const XmlDocument& xmlDocument = result.GetPayload();
  XmlNode rootNode = xmlDocument.GetRootElement();
  XmlNode resultNode = rootNode;
  if (rootNode.GetName() != "RecordLifecycleActionHeartbeatResult")
  {
    resultNode = rootNode.FirstChild("RecordLifecycleActionHeartbeatResult");
  }

  if(!resultNode.IsNull())
  {
  }

  XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata");
  m_responseMetadata = responseMetadataNode;

  return *this;
}


text:
using System;
using System.Reflection;
using System.Web.Mvc;

namespace Assman.Spark
{
	public static class MvcNamingExtensions
	{
		public static string ActionName(this MethodInfo methodInfo)
		{
			if (methodInfo.HasAttribute<ActionNameAttribute>())
			{
				return methodInfo.GetAttribute<ActionNameAttribute>().Name;
			}
			else
			{
				return methodInfo.Name;
			}
		}

		public static string ControllerName(this Type controllerType)
		{
			if (controllerType.Name.EndsWith("Controller"))
			{
				return controllerType.Name.Substring(0, controllerType.Name.Length - 10);
			}
			else
			{
				return controllerType.Name;
			}
		}
	}
}


text:
User: {{header.user.firstName}} {{header.user.lastName}}

  Role: {{header.user.id}}

  Associated Properties:

PUID:{{thing.id}} - {{thing.description}}


text:
<?php

namespace HeroBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;

/**
 * Player
 *
 * @ORM\Table(name="player")
 * @ORM\Entity(repositoryClass="HeroBundle\Repository\PlayerRepository")
 */
class Player extends BaseUser
{

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

	/**
	 * @var ArrayCollection
	 *
	 * @ORM\OneToMany(targetEntity="SaveGame", mappedBy="player", cascade={"persist"})
	 */
	private $savegames;

	public function __construct()
	{
        parent::__construct();

		$this->savegames = new ArrayCollection();
	}

	/**
	 * @param SaveGame $savegame
	 * @return mixed
	 */
	public function addSaveGame(SaveGame $savegame)
	{
		// TODO: check if already exists, in this case edit it, do not add a new one
		$this->savegames[] = $savegame;
	}

	/**
	 * @param SaveGame $savegame
	 * @return Player
	 */
	public function removeSaveGame(SaveGame $savegame)
	{
		$this->savegames->removeElement($savegame);
	}

	/**
	 * @return ArrayCollection
	 */
	public function getSaveGames()
	{
		return $this->savegames;
	}

	/**
	 * @return SaveGame
	 */
	public function getSaveGame($id)
	{
		// TODO: Not correct, look for story_id = $id
		return $this->savegames[$id];
	}

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Player
     */
    public function setUsername($name)
    {
        $this->username = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return Player
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set password
     *
     * @param string $password
     *
     * @return Player
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }
}


text:
/*
 * custom_decision_making.h
 *
 *  Created on: Nov 26, 2013
 *      Author: dan
 */

#ifndef CUSTOM_DECISION_MAKING_H_
#define CUSTOM_DECISION_MAKING_H_

#include "custom_task.h"

#include "DecisionMaking.h"

#endif /* CUSTOM_DECISION_MAKING_H_ */