text:
"""Datastore query expressions.

This module provides constants and a factory class to compose structured queries against a datastore,
including resources, events, objects datastores. It is inspired by the capabilities of a SQL query language
such as Postgres+PostGIS, but is not targeted at a specific DMBS. Specific mapping classes can then provide
a mapping to the datastore technology.
"""

__author__ = 'Michael Meisinger'

import datetime
import time

from pyon.core.exception import BadRequest
from pyon.datastore.datastore_common import DataStore

class DatastoreQueryConst(object):
    """Constants for generic datastore query expressions"""

    # Expression
    EXP_PREFIX = "exp:"
    EXP_AND = EXP_PREFIX + "and"
    EXP_OR = EXP_PREFIX + "or"
    EXP_NOT = EXP_PREFIX + "not"

    # Operators
    OP_PREFIX = "op:"                # Simple operators prefix
    OP_EQ = OP_PREFIX + "eq"         # Find objects with special attr equal to given value
    OP_NEQ = OP_PREFIX + "neq"       # Find objects with special attr not equal to given value
    OP_LT = OP_PREFIX + "lt"         # Find objects with special attr lower than given value
    OP_LTE = OP_PREFIX + "lte"       # Find objects with special attr lower than or equal given value
    OP_GT = OP_PREFIX + "gt"         # Find objects with special attr greater than given value
    OP_GTE = OP_PREFIX + "gte"       # Find objects with special attr greater than or equal given value
    OP_LIKE = OP_PREFIX + "like"     # Find objects with special attr matching given pattern (case sensitive)
    OP_ILIKE = OP_PREFIX + "ilike"   # Find objects with special attr matching given pattern (case insensitive)
    OP_FUZZY = OP_PREFIX + "fuzzy"   # Find objects with special attr similar to given value (case insensitive)
    OP_REGEX = OP_PREFIX + "regex"   # Find objects with special attr matching given value POSIX regex
    OP_IREGEX = OP_PREFIX + "iregex" # Find objects with special attr matching given value POSIX regex (case insensitive)

    XOP_PREFIX = "xop:"                     # Extended operators prefix
    XOP_IN = XOP_PREFIX + "in"              # Find objects with attr equal to one of given values
    XOP_BETWEEN = XOP_PREFIX + "between"    # Find objects with attr between 2 given values (inclusive)
    XOP_ATTLIKE = XOP_PREFIX + "attlike"    # Find objects with attr matching given pattern (case sensitive)
    XOP_ATTILIKE = XOP_PREFIX + "attilike"  # Find objects with attr matching given pattern (case insensitive)
    XOP_ALLMATCH = XOP_PREFIX + "allmatch"  # Find objects where values occurs within any of the first level attributes
    XOP_ISTYPE = XOP_PREFIX + "istype"      # Find objects with type or base type equal to given value (e.g. events)

    GOP_PREFIX = "gop:"                               # Geospatial operators prefix
    GOP_OVERLAPS_BBOX = GOP_PREFIX + "overlaps"       # Find objects with geometry overlapping given bbox
    GOP_WITHIN_BBOX = GOP_PREFIX + "within"           # Find objects with geometry within given bbox
    GOP_CONTAINS_BBOX = GOP_PREFIX + "contains"       # Find objects with geometry containing given bbox

    GOP_OVERLAPS_GEOM = GOP_PREFIX + "overlaps_geom"  # Find objects with geometry overlapping given WKT geometry
    GOP_WITHIN_GEOM = GOP_PREFIX + "within_geom"      # Find objects with geometry within given WKT geometry
    GOP_CONTAINS_GEOM = GOP_PREFIX + "contains_geom"  # Find objects with geometry containing given WKT geometry

    ROP_PREFIX = "rop:"                               # Range operators prefix
    ROP_OVERLAPS_RANGE = ROP_PREFIX + "overlaps"      # Find objects with range overlapping given range
    ROP_WITHIN_RANGE = ROP_PREFIX + "within"          # Find objects with range containing given range
    ROP_CONTAINS_RANGE = ROP_PREFIX + "contains"      # Find objects with range containing given range

    ASSOP_PREFIX = "assop:"                           # Association operators prefix
    ASSOP_ASSOCIATED = ASSOP_PREFIX + "associated"    # Resource is associated with other resources
    ASSOP_DESCEND_O = ASSOP_PREFIX + "descend_o"      # Find all descendants of resource (object direction)
    ASSOP_DESCEND_S = ASSOP_PREFIX + "descend_s"      # Find all descendants of resource (subject direction)

    # Object, resource and event attributes
    ATT_ID = "att:id"
    ATT_TYPE = "att:type_"
    RA_NAME = "ra:name"
    RA_TS_CREATED = "ra:ts_created"
    RA_TS_UPDATED = "ra:ts_updated"
    RA_LCSTATE = "ra:lcstate"
    RA_AVAILABILITY = "ra:availability"
    RA_GEOM = "ra:geom"
    RA_GEOM_LOC = "ra:geom_loc"
    RA_VERT_RANGE = "ra:vertical_range"
    RA_TEMP_RANGE = "ra:temporal_range"
    EA_ORIGIN = "ea:origin"
    EA_ORIGIN_TYPE = "ea:origin_type"
    EA_SUB_TYPE = "ea:sub_type"
    EA_ACTOR_ID = "ea:actor_id"
    EA_TS_CREATED = RA_TS_CREATED
    AA_SUBJECT = "aa:s"
    AA_SUBJECT_TYPE = "aa:st"
    AA_OBJECT = "aa:o"
    AA_OBJECT_TYPE = "aa:ot"
    AA_PREDICATE = "aa:p"

    # Query types
    QTYPE_RES = "qt:resource"
    QTYPE_ASSOC = "qt:association"
    QTYPE_OBJ = "qt:object"

    # Order
    ORDER_ASC = "asc"
    ORDER_DESC = "desc"

    # Text comparisons
    TXT_EQUALS = "txt:equals"
    TXT_IEQUALS = "txt:iequals"
    TXT_CONTAINS = "txt:contains"
    TXT_ICONTAINS = "txt:icontains"
    TXT_MATCH = "txt:match"
    TXT_IMATCH = "txt:imatch"
    TXT_REGEX = "txt:regex"
    TXT_IREGEX = "txt:iregex"

DQ = DatastoreQueryConst
QUERY_EXP_KEY = "QUERYEXP"
QUERY_EXP_ID = "qexp_v1.0"

class DatastoreQueryBuilder(DatastoreQueryConst):
    """Helps create structured queries to the datastore"""

    def __init__(self, profile=None, datastore=None, ds_sub=None, where=None, order_by=None, id_only=False, limit=0, skip=0, **kwargs):
        self.query = {}
        self.query["QUERYEXP"] = QUERY_EXP_ID
        qargs = self.query.setdefault("query_args", {})
        qargs["profile"] = profile or DataStore.DS_PROFILE.RESOURCES
        qargs["datastore"] = datastore or DataStore.DS_RESOURCES
        qargs["ds_sub"] = ds_sub or ""
        self.build_query(where=where, order_by=order_by, id_only=id_only, limit=limit, skip=skip)

    def build_query(self, where=None, order_by=None, id_only=None, limit=None, skip=None, **kwargs):
        qargs = self.query["query_args"]
        if id_only is not None:
            qargs["id_only"] = id_only
        if limit is not None:
            qargs["limit"] = limit
        if skip is not None:
            qargs["skip"] = skip
        qargs.update(kwargs)
        self.query["where"] = where if where is not None else self.query.get("where", "")
        self.query["order_by"] = order_by if order_by is not None else self.query.get("order_by", {})

    def get_query_arg(self, argname, default=None):
        return self.query["query_args"].get(argname, default)

    def get_query(self):
        self.check_query(self.query)
        return self.query

    # -------------------------------------------------------------------------
    # Helpers to construct query filter expressions. Nest with and_ and or_

    def where(self, where_expr, *args, **kwargs):
        """Sets the filter expression (where clause) of the query"""
        if where_expr is not None and args:
            if kwargs.get("or_filters", False):
                self.query["where"] = self.or_(where_expr, *args)
            else:
                self.query["where"] = self.and_(where_expr, *args)
        else:
            self.query["where"] = where_expr if where_expr is not None else ""

    def and_(self, *args):
        return self.op_expr(self.EXP_AND, *args)

    def or_(self, *args):
        return self.op_expr(self.EXP_OR, *args)

    def not_(self, *args):
        return self.op_expr(self.EXP_NOT, *args)

    set_filter = where
    filter_and = and_
    filter_or = or_
    filter_not = not_

    def op_expr(self, operator, *args):
        return [operator, args or []]

    def eq(self, col, value):
        colname = self._get_attname(col)
        return self.op_expr(self.OP_EQ, colname, value)

    def neq(self, col, value):
        colname = self._get_attname(col)
        return self.op_expr(self.OP_NEQ, colname, value)

    def gt(self, col, value):
        colname = self._get_attname(col)
        return self.op_expr(self.OP_GT, colname, value)

    def gte(self, col, value):
        colname = self._get_attname(col)
        return self.op_expr(self.OP_GTE, colname, value)

    def lt(self, col, value):
        colname = self._get_attname(col)
        return self.op_expr(self.OP_LT, colname, value)

    def lte(self, col, value):
        colname = self._get_attname(col)
        return self.op_expr(self.OP_LTE, colname, value)

    def in_(self, col, *args):
        colname = self._get_attname(col)
        return self.op_expr(self.XOP_IN, colname, *args)

    def like(self, col, value, case_sensitive=True):
        colname = self._get_attname(col)
        if case_sensitive:
            return self.op_expr(self.OP_LIKE, colname, value)
        else:
            return self.op_expr(self.OP_ILIKE, colname, value)

    def fuzzy(self, col, value):
        colname = self._get_attname(col)
        return self.op_expr(self.OP_FUZZY, colname, value)

    def regex(self, col, value, case_sensitive=True):
        colname = self._get_attname(col)
        if case_sensitive:
            return self.op_expr(self.OP_REGEX, colname, value)
        else:
            return self.op_expr(self.OP_IREGEX, colname, value)

    def eq_in(self, col, expr):
        """Filter to list of values if type iterable else value equality"""
        if type(expr) in (list, tuple):
            return self.in_(col, *expr)
        else:
            return self.eq(col, expr)

    def txt_cmp(self, col, value, cmpop):
        """Text comparison"""
        cmpop = cmpop or self.TXT_EQUALS
        if cmpop != self.TXT_EQUALS and type(value) in (list, tuple):
            raise BadRequest("Filter does not support list of values")
        if cmpop == self.TXT_EQUALS:
            if type(value) in (list, tuple):
                return self.in_(col, *value)
            else:
                return self.eq(col, value)
        elif cmpop == self.TXT_IEQUALS:
            return self.like(col, value, case_sensitive=False)
        elif cmpop == self.TXT_CONTAINS:
            return self.like(col, "%" + value + "%")
        elif cmpop == self.TXT_ICONTAINS:
            return self.like(col, "%" + value + "%", case_sensitive=False)
        elif cmpop == self.TXT_MATCH:
            return self.like(col, value, case_sensitive=True)
        elif cmpop == self.TXT_IMATCH:
            return self.like(col, value, case_sensitive=False)
        elif cmpop == self.TXT_REGEX:
            return self.regex(col, value, case_sensitive=True)
        elif cmpop == self.TXT_IREGEX:
            return self.regex(col, value, case_sensitive=False)
        else:
            raise BadRequest("Filter compare op not supported: %s" % cmpop)

    # --- Special operators

    def between(self, col, val1, val2):
        self._check_col(col)
        colname = col.split(":", 1)[1]
        return self.op_expr(self.XOP_BETWEEN, colname, val1, val2)

    def all_match(self, value):
        return self.op_expr(self.XOP_ALLMATCH, value)

    def attr_like(self, attr, value, case_sensitive=True):
        if case_sensitive:
            return self.op_expr(self.XOP_ATTLIKE, attr, value)
        else:
            return self.op_expr(self.XOP_ATTILIKE, attr, value)

    # --- Range operators

    def overlaps_range(self, col, x1, y1):
        self._check_col(col)
        colname = col.split(":", 1)[1]
        return self.op_expr(self.ROP_OVERLAPS_RANGE, colname, x1, y1)

    def contains_range(self, col, x1, y1):
        self._check_col(col)
        colname = col.split(":", 1)[1]
        return self.op_expr(self.ROP_CONTAINS_RANGE, colname, x1, y1)

    def within_range(self, col, x1, y1):
        self._check_col(col)
        colname = col.split(":", 1)[1]
        return self.op_expr(self.ROP_WITHIN_RANGE, colname, x1, y1)

    # --- Geospatial operators

    def overlaps_bbox(self, col, x1, y1, x2, y2):
        self._check_col(col)
        colname = col.split(":", 1)[1]
        return self.op_expr(self.GOP_OVERLAPS_BBOX, colname, x1, y1, x2, y2)

    def contains_bbox(self, col, x1, y1, x2, y2):
        self._check_col(col)
        colname = col.split(":", 1)[1]
        return self.op_expr(self.GOP_CONTAINS_BBOX, colname, x1, y1, x2, y2)

    def within_bbox(self, col, x1, y1, x2, y2):
        self._check_col(col)
        colname = col.split(":", 1)[1]
        return self.op_expr(self.GOP_WITHIN_BBOX, colname, x1, y1, x2, y2)

    # --- Geospatial (WKT) operators

    def overlaps_geom(self, col, wkt, buf):
        self._check_col(col)
        colname = col.split(":", 1)[1]
        return self.op_expr(self.GOP_OVERLAPS_GEOM, colname, wkt, buf)

    def contains_geom(self, col, wkt, buf):
        self._check_col(col)
        colname = col.split(":", 1)[1]
        return self.op_expr(self.GOP_CONTAINS_GEOM, colname, wkt, buf)

    def within_geom(self, col, wkt, buf):
        self._check_col(col)
        colname = col.split(":", 1)[1]
        return self.op_expr(self.GOP_WITHIN_GEOM, colname, wkt, buf)

    # --- By association

    def associated_with(self, target=None, target_type=None, predicate=None, direction=None, target_filter=None):
        return self.op_expr(self.ASSOP_ASSOCIATED, target, target_type, predicate, direction, target_filter)

    # --- Ordering

    def order_by(self, column, sort="asc", *args):
        order_by_list = []
        if type(column) in (list, tuple):
            for col in column:
                if type(col) in (list, tuple):
                    colname, colsort = col
                    order_by_list.append((colname, colsort))
                else:
                    order_by_list.append((col, sort))
        else:
            order_by_list = [(column, sort)]

        return order_by_list

    # --- Other query parameters

    def set_skip(self, skip):
        qargs = self.query["query_args"]
        if skip is not None:
            qargs["skip"] = skip

    def set_limit(self, limit):
        qargs = self.query["query_args"]
        if limit is not None:
            qargs["limit"] = limit

    def set_id_only(self, id_only):
        qargs = self.query["query_args"]
        if id_only is not None:
            qargs["id_only"] = id_only

    def set_query_parameters(self, params):
        if not params:
            return
        self.query.setdefault("query_params", {}).update(params)

    # --- Internal functions

    def _check_col(self, col):
        profile = self.query["query_args"]["profile"]
        if profile == DataStore.DS_PROFILE.RESOURCES:
            if not (col.startswith("ra") or col.startswith("att") or col.startswith("aa")):
                raise BadRequest("Query column unknown: %s" % col)
        elif profile == DataStore.DS_PROFILE.EVENTS:
            if not (col.startswith("ea") or col.startswith("att") or col == DQ.RA_TS_CREATED):
                raise BadRequest("Query column unknown: %s" % col)

    def _get_attname(self, col):
        attname = col.split(":", 1)[-1]
        return attname

    def _make_ion_ts(self, value):
        if value is None:
            return None
        if isinstance(value, datetime.datetime):
            return str(int(time.mktime(value.timetuple()) * 1000))
        if type(value) is float:
            return str(int(value))
        return str(value)

    @classmethod
    def check_query(cls, query):
        """Check a query expression (dict) for basic compliance"""
        if not isinstance(query, dict):
            raise BadRequest("query type dict expected, not: %s" % type(query))
        if not "query_args" in query:
            raise BadRequest("query_args expected in query")
        if query["QUERYEXP"] != QUERY_EXP_ID:
            raise BadRequest("Unknown query expression language: %s" % query["query_args"]["QUERYEXP"])
        if not "where" in query:
            raise BadRequest("where expected in query")
        if not "order_by" in query:
            raise BadRequest("order_by expected in query")


text:
import argparse
import logging
import os
import string
from codecs import open

try:
    from queue import Queue, Empty
except ImportError:
    from Queue import Queue, Empty

from numpy import dot, float32 as REAL, \
    array, ndarray

from gensim import matutils
from six import string_types
from gensim.models import Word2Vec

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

exclude = set(string.punctuation).union({u""", u"'", u""", "."})
def fix(s):
    s = ''.join(ch for ch in s if ch not in exclude)
    return s.lower()

def most_similar_all(word2vec, positive=[], negative=[], topn=10, restrict_vocab=None):
    word2vec.init_sims()

    if isinstance(positive, string_types) and not negative:
        # allow calls like most_similar('dog'), as a shorthand for most_similar(['dog'])
        positive = [positive]

    # add weights for each word, if not already present; default to 1.0 for positive and -1.0 for negative words
    positive = [
        (word, 1.0) if isinstance(word, string_types + (ndarray,)) else word
        for word in positive
        ]
    negative = [
        (word, -1.0) if isinstance(word, string_types + (ndarray,)) else word
        for word in negative
        ]

    # compute the weighted average of all words
    all_words, mean = set(), []
    for word, weight in positive + negative:
        if isinstance(word, ndarray):
            mean.append(weight * word)
        elif word in word2vec.vocab:
            mean.append(weight * word2vec.syn0norm[word2vec.vocab[word].index])
            all_words.add(word2vec.vocab[word].index)
        else:
            raise KeyError("word '%s' not in vocabulary" % word)
    if not mean:
        raise ValueError("cannot compute similarity with no input")
    mean = matutils.unitvec(array(mean).mean(axis=0)).astype(REAL)

    limited = word2vec.syn0norm if restrict_vocab is None else word2vec.syn0norm[:restrict_vocab]
    dists = dot(limited, mean)
    if not topn:
        return dists
    best = matutils.argsort(dists, topn=topn + len(all_words), reverse=True)
    # ignore (don't return) words from the input
    result = [(word2vec.index2word[sim], float(dists[sim])) for sim in best if sim not in all_words]
    # do return words from the input
    # result = [(word2vec.index2word[sim], float(dists[sim])) for sim in best]
    return result[:topn]

if __name__ == "__main__":
    parser = argparse.ArgumentParser("")
    parser.add_argument("--embedding-model", type=str)
    parser.add_argument("--topic-model", type=str)
    args = parser.parse_args()

    model = Word2Vec.load_word2vec_format(args.embedding_model, binary=True)
    print " ".join([w for w, _ in model.most_similar(["queen"])])

    embedding_name = os.path.basename(args.embedding_model)

    with open(args.topic_model + "." + embedding_name + ".raw-we-tm.head", "w", encoding="utf-8") as topics:
        with open(args.topic_model, "r") as f:
            for line in f:
                if "topic-count" not in line:
                    word_found = False
                    i = -10
                    while not word_found:
                        word = line.rstrip().split(" ")[i]
                        word_found = word in model
                        i += 1

                    similar_words = [fix(w) for w, _ in most_similar_all(model, [word], topn=30)]
                    used = []
                    similar_words = [x for x in similar_words if x not in used and (used.append(x) or True)]
                    topic_line = " ".join(similar_words[:10])
                    print word + " --> " + topic_line

                    topics.write(topic_line)
                    topics.write("\n")

    with open(args.topic_model + "." + embedding_name + ".raw-we-tm.avg", "w", encoding="utf-8") as topics:
        with open(args.topic_model, "r") as f:
            for line in f:
                if "topic-count" not in line:
                    words = line.rstrip().split(" ")[-10:]
                    words = [word for word in words if word in model]

                    similar_words = [fix(w) for w, _ in most_similar_all(model, words, topn=30)]
                    used = []
                    similar_words = [x for x in similar_words if x not in used and (used.append(x) or True)]
                    topic_line = " ".join(similar_words[:10])
                    print " ".join(words) + " --> " + topic_line

                    topics.write(topic_line)
                    topics.write("\n")

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <include layout="@layout/title_layout" android:id="@+id/layout_title_bar"/>
    <TextView android:layout_width="fill_parent" android:layout_height="fill_parent"
              android:gravity="center" android:textColor="#ffffff"
            android:text="。。。。。。。。content 。。。。。。。。"/>
</LinearLayout>


text:
using namespace utils;

int main(int argc, char *argv[]) {
	// Check if the number of arguments is valid
	if (argc != 2) {
		// Print error
		std::cerr << "\033[1;31mError: Invalid number of arguments!\033[0m\n";
	} else {
		try {
			// Scene
	        Scene scene;
	        Camera* cam;
			Shader* shader;
			// Ray tracer settings
			int samples;
			int nrays;
			// Output settings
			OutputSettings os;
			std::cout << "Opening scene description file...\n";
			// Read scene description file
        	SceneReader::read(argv[1], scene, cam, shader, os, samples, nrays);
			std::cout << "\033[1;34mScene description file "
					  << "opened successfully!\033[0m\n";
			// Start rendering
			std::cout << "Starts to rendering...\n";
			// Get start time
			time_t start = time(0);
			// Render
	        Image img = *(RayTracer::render(cam, scene, shader, os.width,
				os.height, samples, nrays));
			// Get end time
			time_t end = time(0);
			// Print render time
			std::cout << "\033[1;34m\nThe image was rendered in "
					  << difftime(end, start) << " seconds.\033[0m\n";
  	        // Print image
			std::cout << "Printing image...\n";
	        Printer::print(img, os, "");
			std::cout << "\033[1;34mThe image was printed successfully.\033[0m\n";
		} catch (const char* e) {
			// Print error
			std::cerr << "\033[1;31m" << e << "\033[0m\n";
		}
	}
    return EXIT_SUCCESS;
}


text:
layout: post
title: Blackberry Built A Car, And It's Beautiful
thumbnail: /img/blackberry-car.png
---

Blackberry's days of smartphone dominance are long over, but surprisingly the company still has a few brilliant, valuable technologies in other verticals.

QNX Software Systems, a division of Blackberry acquired in 2010, builds high-tech car systems for auto manufacturers.

To demonstrate its latest technology, the QNX team built an insane concept car based on the Maserati  Quattroporte GTS.

The QNX team took the $150,000 car and retrofitted it with brand new discrete systems, video screens, and a beautiful user interface that perhaps puts even Tesla to shame.

  {{ site.theme.header_text }}

Among the many modifications, QNX replaced every mirror in the car with an equivalent digital screen. The screens show live feeds from cameras mounted around the car, practically eliminating common blind spots.

QNX's tricked-out car isn't commercially available (yet), but the QNX platform is the basis for many car entertainment and control systems, so many of the technologies seen here should soon be coming to a car near you.


text:
""" Implementation of tree structure.

Including a parser that can
parse tree structures from text.

"""

from ppci.lang.tools.baselex import BaseLexer

class Tree:
    """ Tree node with a name and possibly some child nodes """

    __slots__ = ("name", "value", "children", "state")

    def __init__(self, name, *args, value=None):
        self.name = name
        self.value = value
        self.children = args

    def __repr__(self):
        if self.children:
            ch = ", ".join(str(c) for c in self.children)
            children = "({})".format(ch)
        else:
            children = ""
        if self.value is not None:
            val = "[{}]".format(self.value)
        else:
            val = ""
        return "{}{}{}".format(self.name, val, children)

    def __getitem__(self, index):
        return self.children[index]

    def structural_equal(self, other):
        """ Determine if this tree is structurally equivalent to another """
        return (
            self.name == other.name
            and len(self.children) == len(other.children)
            and all(
                a.structural_equal(b)
                for a, b in zip(self.children, other.children)
            )
        )

    def get_defined_names(self):
        """ Returns a set of all names defined by this tree """
        names = set([self.name])
        for child in self.children:
            names = names | child.get_defined_names()
        return names

class TreeLexer(BaseLexer):
    def __init__(self):
        tok_spec = [
            ("ID", r"[A-Za-z][A-Za-z\d_]*", lambda typ, val: (typ, val)),
            ("SKIP", r"[ \t]", None),
            ("LEESTEKEN", r"[,\(\)]", lambda typ, val: (val, val)),
        ]
        super().__init__(tok_spec)

class TreeParser:
    """Parser that can parse tree expressions.

    For example:
        A(B(1,2,3),2,1,C)
    """

    def __init__(self):
        self.lexer = TreeLexer()
        self.peak = None

    def pop(self):
        t = self.peak
        self.peak = self.lexer.next_token()
        return t

    def consume(self, typ):
        t = self.pop()
        assert t.typ == typ
        return t

    def has_consumed(self, typ):
        if self.peak.typ == typ:
            self.pop()
            return True
        return False

    def parse(self, s):
        self.lexer.feed(s)
        self.peak = self.lexer.next_token()
        return self.parse_tree()

    def parse_tree(self):
        name = self.consume("ID").val
        children = []
        if self.has_consumed("("):
            children.append(self.parse_tree())
            while self.has_consumed(","):
                children.append(self.parse_tree())
            self.consume(")")
        return Tree(name, *children)

tree_parser = TreeParser()

def from_string(s):
    """ Create tree from string definition """
    return tree_parser.parse(s)


text:
module Lissajous( main ) where

{- |
Module      :   Lissajous
Description :   Draw a Lissajous-figure
Copyright   :   (c) Thomas Lang, 2014
License     :   BSD3

Stability   :   stable
Portability :   uses GLUT package

This module uses the GLUT graphics package for drawing a Lissajous-figure.
The parameter can be changed from outside.
 -}

import Graphics.UI.GLUT
import System.IO         ( getChar    )
import Data.Char         ( digitToInt )

-- main function, does impure things
main :: IO()
main = do
    (_progname, _args) <- getArgsAndInitialize
    putStrLn "Enter a: "
    a <- getChar
    getChar                 -- second time "getChar" because of  '\n' character
    putStrLn "Enter b: "
    b <- getChar
    _window <- createWindow "Lissajous figures"
    displayCallback $= display (fromIntegral (digitToInt a)::GLfloat) (fromIntegral (digitToInt b)::GLfloat)
    mainLoop

-- display-callback that does the drawing
display :: GLfloat -> GLfloat -> DisplayCallback
display a b = do
    clear [ ColorBuffer ]
    renderPrimitive LineLoop $
        mapM_ (\(x,y,z) -> vertex $ Vertex3 x y z) (myPoints a b pi)
    flush

-- function for calculating the points
-- note: as we take Vertex3 above, we have
--       to define a third param that
--       is set to 0
myPoints :: GLfloat -> GLfloat -> GLfloat -> [(GLfloat, GLfloat, GLfloat)]
myPoints a b d = [ ( sin(a*t+d), sin(b*t), 0 ) | t <- [0,0.005..(7*pi)] ]


text:
import sys
import time

from sklearn.datasets import load_svmlight_file
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

prefix_file = sys.argv[1]
train_file = prefix_file
test_file = '%s.t' % prefix_file

t0 = time.clock()
x_train, y_train = load_svmlight_file(train_file)
r_train, c_train = x_train.shape

x_test, y_test = load_svmlight_file(test_file)
r_test, c_test = x_test.shape

if c_train != c_test:
  x_test = x_test[:, 0:c_train]
t1 = time.clock()

m = LogisticRegression(C = 1)
m.fit(x_train, y_train)
t_train = time.clock()
y1_test = m.predict(x_test)
t_test = time.clock()

precision = precision_score(y_test, y1_test)
recall = recall_score(y_test, y1_test)
accuracy = accuracy_score(y_test, y1_test)
f1 = f1_score(y_test, y1_test)

print "python: train=%s test=%s [%s]" % (x_train.shape, x_test.shape, prefix_file)
print "  precision=%.5f recall=%.5f f1=%.5f" % (precision, recall, f1)
print "  read=%.5f train=%.5f test=%.5f" % (t1-t0, t_train-t1, t_test-t_train)


text:
const five     = require('johnny-five');
const Tessel   = require('tessel-io');
const express  = require('express');
const SocketIO = require('socket.io');

const path = require('path');
const http = require('http');
const os   = require('os');

const app    = new express();
const server = new http.Server(app);
const socket = new SocketIO(server);
app.use(express.static(path.join(__dirname, '/app')));

const board = new five.Board({ io: new Tessel() });

board.on('ready', () => {
  const weatherSensor = new five.Multi({
    controller: 'BMP180',
    freq: 5000
  });

  socket.on('connection', client => {
    weatherSensor.on('change', () => {
      client.emit('weather', {
        temperature: weatherSensor.thermometer.F,
        pressure: (weatherSensor.barometer.pressure * 10)
      });
    });
  });

  server.listen(3000, () => {
    console.log(`http://${os.networkInterfaces().wlan0[0].address}:3000`);
  });
});


text:
It's a service (aka a bot) that commits rietveld changes for you, instead of
you directly committing the change. We support a wide variety of projects
already and can support your project too (see [internal docs]).

For enabled projects, we display a CQ checkbox/button on Rietveld interface.

## How (does it work)?

The commit queue is not really a queue at the moment, since it processes the
changes out of order. This may be changed eventually. This means a CL can be
committed before another CL that was triggered much later. This can happen when
a try job is flaky.

### Current process for the user

1. Upload a review to rietveld where it gets reviewed and LGTM'ed.
1. One of:
    1. Check (select) the 'Commit' checkbox on a Rietveld issue, on the
       particular patchset that has been approved. Checking the checkbox is the
       only action required and there will be no immediate feedback in the form
       of messages, etc, to notify you that something has happened.
        1. Only the issue owner, someone at @chromium.org or @google.com can
           check the box.
        1. Yes, **non-Chromium committers are allowed** to use the commit queue
           but their LGTM (approval) on other issues is not accepted.
    1. At the command line, type `git cl set_commit`.
    1. Have a reviewer use 'Quick LGTM & CQ'.
1. Wait an hour. The current list of patches to be queued can be found at
   [Commit Queue Patches], while CQ progress can be tracked at the link posted
   by CQ on the CL (after some delay at which CQ checks for new CLs). The commit
   queue will wait automatically for the tree to reopen.
1. Wait for an email from commit-bot@chromium.org with success or failure.

### Why (is it broken)?

Please follow these general guidelines:

1. Please report issues to [chrome-troopers].
1. If you have a feature request, feel free to file a bug, use label
   Build-CommitQueue. Be sure to search for [current feature requests] first.

## Options

You may include the following options into the desription of your CL.

    COMMIT=false

If you are working on experimental code and do not want to risk accidentally
submitting it via the CQ, then you can mark it with `COMMIT=false`. The CQ will
immediately abandon the change if it contains this option. To dry run through
the CQ please use Rietveld's dry run feature.

    TBR=<username>

This stands for "to be reviewed". If a change has a TBR line with a valid
reviewer, the CQ will skip checks for LGTMs. See [guidelines] of when it's
acceptable to use this.

    NOPRESUBMIT=true

If you want to skip the presubmit check you can add this line and the commit
queue won't run the presubmit for your change. This should only be used when
there's a bug in the PRESUBMIT scripts. Please check that there's a bug filed
against the bad script, and if there isn't, file one.

    NOTRY=true

This should only be used for reverts to make the tree green, since it skips try
bots and might therefore break the tree. You shouldn't use this otherwise.

    NOTREECHECKS=true

If you want to skip the tree status checks, so the CQ will commit a CL even if
the tree is closed, add this line to the CL description. Obviously this is
strongly discouraged, since the tree is closed for a reason. However, in rare
cases this is acceptable, primarily to fix build breakages (i.e., your CL will
help in reopening the tree).

    NO_DEPENDENCY_CHECKS=true

The CQ rejects patchsets with open dependencies. An open dependency exists when
a CL depends on another CL that is not yet closed. You can skip this check with
this keyword.

    CQ_INCLUDE_TRYBOTS=<trybots>

This flag allows you to specify some additional bots to run for this CL, in
addition to the default bots. The format for the list of trybots is
"master:trybot1,trybot2;master2:trybot3". This feature only works for recipe
based bots right now.

## FAQ

### Is the CQ broken?

Take a look at
https://codereview.chromium.org/search?closed=3&commit=2&limit=100&order=modified.
If there are issues older than ~4 hours, they could probably be stuck. Note
that the Commit Queue could be stuck only for some issues but not all of them.
In case of doubt, please contact [chrome-troopers].

### The CQ seems hung

Is the tree open? It commits 4 CLs every 8 minutes, so a maximum rate of 30
commits per hour.

### Please Help! I just want to ask on irc!

Please report issues to [chrome-troopers].

### My patch failed to apply

See the [Try Server FAQ].

### What about LKGR?

The Commit Queue has never known, used or cared about LKGR. It always uses
HEAD, the tip of tree.

### What's my position on the queue?

The CLs are processed out of order, so it's not because another is "before"
yours that means it'll be committed before yours. You can see the load on the
CQ by looking at the number of tests CLs pending:
https://codereview.chromium.org/search?closed=3&commit=2&limit=1000&order=modified

### Sending a TBR patch fast

You can't wait for review? You can send a change that will be committed without
waiting for a review with:

    git fetch origin
    git new-branch work_fast
    # Quick, write your fix.
    echo "A copy is available for 100000$USD upon request." >> LICENSE
    git commit -a -m "Fix the license, show new opportunities

    TBR=danny@chromium.org"
    git cl upload --send-mail -c

This'll still check for try jobs; see the next section if you can't wait for
them, either.

The important part is to have **TBR**=foo@chromium.org in the CL description.

* `--send-mail` sends an email right away.
* `-c` sets the commit bit right away, short for `--use-commit-queue`.
* `--cc joe@chromium.org,hppo@chromium.org` to cc more people instead of
  putting everyone as reviewer.

Now, did you know there's `git cl help upload`?

### Sending CL through CQ without committing (dry run)

To dry run through the CQ please use Rietveld's [dry run] feature.

### Picking custom trybots

See the `CQ_INCLUDE_TRYBOTS` option, above.

### Try job results aren't showing up consistently on Rietveld

If you never had a HTTP 500 on GAE, chances are that [you will][gae-500].

### Binary files?

Yes, binary files are supported by try jobs as well as CQ now!

### My CL has a bazillion files, will it blend?

The CQ was able to commit a CL with 838 files so it is technically possible:
https://codereview.chromium.org/12261012/. The likelihood of the CQ failing
increases exponentially with the number of files in the CL.

### Moving, renaming or copying files

Was implemented in [bug 125984] and [bug 125983]. If the diff on Rietveld
doesn't look right, use the `--similarity` (defaults to 50%) and disable/enable
file copy with `--find-copies`/`--no-find-copies`. For more help please run:

    git cl help
    man git diff

### Are CQ users required to be around when the patch is landed?

In general, no, as the CQ can land at any time (including very long time), and
any breaking patches can be kicked about by the sheriff. After all, that's the
job of the sheriff. You will get an email when the CQ commits, so you can jump
on your nearest laptop if necessary.

If you expect your patch to be hard to revert, is touching several files and
directories or move files around, you may want to stay around in case there is
an incremental build failure or something hard to diagnose.

Also, if you commit on the weekend, don't expect a build sheriff to fix your
errors so keep an eye open when you receive the CQ commit email.

### What determines the set of tests and targets the try bots run?

This is controlled by a config file cq.cfg (e.g.
[config for chromium][chromium-cq-cfg]). Also see [this document][analyze-step]
for details on the analyze step.

[internal docs]: https://chrome-internal.googlesource.com/infra/infra_internal/+/master/doc/commit_queue.md
[Commit Queue Patches]: https://codereview.chromium.org/search?closed=3&commit=2
[chrome-troopers]: https://chromium.googlesource.com/infra/infra/+/master/doc/users/contacting_troopers.md
[current feature requests]: https://code.google.com/p/chromium/issues/list?q=label:Build-CommitQueue
[guidelines]: http://www.chromium.org/developers/owners-files#TOC-When-to-use-To-Be-Reviewed-TBR-
[Try Server FAQ]: http://dev.chromium.org/developers/testing/try-server-usage
[dry run]: https://groups.google.com/a/chromium.org/forum/#!topic/chromium-dev/G5-X0_tfmok
[gae-500]: http://code.google.com/status/appengine
[bug 125984]: https://code.google.com/p/chromium/issues/detail?id=125984
[bug 125983]: https://code.google.com/p/chromium/issues/detail?id=125983
[chromium-cq-cfg]: https://chromium.googlesource.com/chromium/src/+/master/infra/config/cq.cfg
[analyze-step]: http://dev.chromium.org/developers/testing/commit-queue/chromium_trybot-json


text:
LUA_EXTERNC DLL_EXPORT int luaopen_libnn(lua_State *L);

int luaopen_libnn(lua_State *L)
{
  lua_newtable(L);
  lua_pushvalue(L, -1);
  lua_setglobal(L, "nn");

  nn_FloatSqrt_init(L);
  nn_FloatSquare_init(L);
  nn_FloatHardTanh_init(L);
  nn_FloatLogSoftMax_init(L);
  nn_FloatClassNLLCriterion_init(L);
  nn_FloatMSECriterion_init(L);
  nn_FloatSmoothL1Criterion_init(L);
  nn_FloatMarginCriterion_init(L);
  nn_FloatAbsCriterion_init(L);
  nn_FloatDistKLDivCriterion_init(L);
  nn_FloatLogSigmoid_init(L);
  nn_FloatSigmoid_init(L);
  nn_FloatSoftMax_init(L);
  nn_FloatSoftPlus_init(L);
  nn_FloatTanh_init(L);
  nn_FloatAbs_init(L);
  nn_FloatHardShrink_init(L);
  nn_FloatSoftShrink_init(L);
  nn_FloatThreshold_init(L);
  nn_FloatPReLU_init(L);
  nn_FloatSparseLinear_init(L);
  nn_FloatTemporalConvolution_init(L);
  nn_FloatTemporalSubSampling_init(L);
  nn_FloatTemporalMaxPooling_init(L);
  nn_FloatSpatialConvolution_init(L);
  nn_FloatSpatialFullConvolution_init(L);
  nn_FloatSpatialFullConvolutionMap_init(L);
  nn_FloatSpatialConvolutionMM_init(L);
  nn_FloatSpatialConvolutionMap_init(L);
  nn_FloatSpatialSubSampling_init(L);
  nn_FloatSpatialMaxPooling_init(L);
  nn_FloatSpatialAveragePooling_init(L);
  nn_FloatSpatialAdaptiveMaxPooling_init(L);
  nn_FloatVolumetricConvolution_init(L);
  nn_FloatVolumetricMaxPooling_init(L);
  nn_FloatVolumetricAveragePooling_init(L);
  nn_FloatMultiMarginCriterion_init(L);
  nn_FloatMultiLabelMarginCriterion_init(L);
  nn_FloatL1Cost_init(L);
  nn_FloatSpatialUpSamplingNearest_init(L);
  nn_FloatLookupTable_init(L);

  nn_DoubleSqrt_init(L);
  nn_DoubleSquare_init(L);
  nn_DoubleHardTanh_init(L);
  nn_DoubleLogSoftMax_init(L);
  nn_DoubleClassNLLCriterion_init(L);
  nn_DoubleMSECriterion_init(L);
  nn_DoubleSmoothL1Criterion_init(L);
  nn_DoubleMarginCriterion_init(L);
  nn_DoubleAbsCriterion_init(L);
  nn_DoubleDistKLDivCriterion_init(L);
  nn_DoubleLogSigmoid_init(L);
  nn_DoubleSigmoid_init(L);
  nn_DoubleSoftMax_init(L);
  nn_DoubleSoftPlus_init(L);
  nn_DoubleTanh_init(L);
  nn_DoubleAbs_init(L);
  nn_DoubleHardShrink_init(L);
  nn_DoubleSoftShrink_init(L);
  nn_DoubleThreshold_init(L);
  nn_DoublePReLU_init(L);
  nn_DoubleSparseLinear_init(L);
  nn_DoubleTemporalConvolution_init(L);
  nn_DoubleTemporalSubSampling_init(L);
  nn_DoubleTemporalMaxPooling_init(L);
  nn_DoubleSpatialConvolution_init(L);
  nn_DoubleSpatialFullConvolution_init(L);
  nn_DoubleSpatialFullConvolutionMap_init(L);
  nn_DoubleSpatialConvolutionMM_init(L);
  nn_DoubleSpatialConvolutionMap_init(L);
  nn_DoubleSpatialSubSampling_init(L);
  nn_DoubleSpatialMaxPooling_init(L);
  nn_DoubleSpatialAveragePooling_init(L);
  nn_DoubleSpatialAdaptiveMaxPooling_init(L);
  nn_DoubleVolumetricConvolution_init(L);
  nn_DoubleVolumetricMaxPooling_init(L);
  nn_DoubleVolumetricAveragePooling_init(L);
  nn_DoubleMultiMarginCriterion_init(L);
  nn_DoubleMultiLabelMarginCriterion_init(L);
  nn_DoubleL1Cost_init(L);
  nn_DoubleSpatialUpSamplingNearest_init(L);
  nn_DoubleLookupTable_init(L);

  return 1;
}


text:
package org.apache.commons.vfs2.provider.webdav;

import java.io.IOException;

import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodRetryHandler;

/**
 * A retry handler which will retry a failed webdav method one time.

 * Now that webdavlib didnt support adding a MethodRetryHandler only a few operations are restartable yet.
 *
 * @author Commons VFS team
 * @version $Revision$ $Date$
 * @since 2.0
 */
public final class WebdavMethodRetryHandler implements HttpMethodRetryHandler
{
    private static final WebdavMethodRetryHandler INSTANCE = new WebdavMethodRetryHandler();

    private WebdavMethodRetryHandler()
    {
    }

    public static WebdavMethodRetryHandler getInstance()
    {
        return INSTANCE;
    }

    public boolean retryMethod(HttpMethod method, IOException exception, int executionCount)
    {
        return executionCount < 2;
    }
}


text:
package hashedcomputation

import org.scalatest.funsuite.AnyFunSuite

class HashTagTest extends AnyFunSuite {
  test("same HashTag() twice") {
    //noinspection AccessorLikeMethodIsEmptyParen
    def getHashTag() = HashTag()
    val tag1 = getHashTag()
    val tag2 = getHashTag()
    assert(tag1 == tag2)
  }

  test("different HashTag()") {
    val tag1 = HashTag()
    val tag2 = HashTag()
    assert(tag1 != tag2)
  }
}


text:
package com.hp.full.web.action;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;

/**
 * Class BaseAction.java
 *
 * @author Ethan Huang (yiqingh@hp.com)
 * @since Aug 7, 2012
 */
public class BaseAction extends ActionSupport implements SessionAware, ApplicationAware, ServletRequestAware {

    /** serialVersionUID */
    private static final long serialVersionUID = 3925678722522497889L;
    private Map<String, Object> session = new HashMap<String, Object>();
    private Map<String, Object> application = new HashMap<String, Object>();
    private HttpServletRequest request;

    public String execute() {
        return SUCCESS;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public Map<String, Object> getSession() {
        return session;
    }

    public Map<String, Object> getApplication() {
        return application;
    }

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public void setApplication(Map<String, Object> application) {
        this.application = application;
    }

    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

}


text:
package com.fns.xlator.client.impl.google;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

import java.util.ArrayList;
import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({ "translations" })
public class Data {

    private List<Translation> translations;

    @JsonCreator
    public Data(@JsonProperty("translations") List<Translation> translations) {
        this.translations = translations;
    }

    @JsonIgnore
    public static Data error(String errorText) {
        List<Translation> translations = new ArrayList<Translation>();
        translations.add(new Translation(errorText));
        Data result = new Data(translations);
        return result;
    }

    public List<Translation> getTranslations() {
        if (translations == null) {
            translations = new ArrayList<Translation>();
        }
        return translations;
    }

}


text:
set +e

export TMPDIR=$(mktemp -d)
trap "rm -rf ${TMPDIR}" EXIT

clean () {
  for i in {1..10}; do
    jobs -p | xargs -n1 pkill -P
    # A simple "wait" just hangs sometimes.  Running `jobs` seems to help.
    sleep 1
    if jobs | read; then
      return
    fi
  done
  echo "$(tput setaf 1) clean failed to kill tests $(tput sgr 0)"
  jobs
  pstree
  rm ${CLIENT_LOG}
  rm ${SERVER_LOG}
  rm ${KEY_FILE_PATH}
  rm ${CERT_FILE_PATH}
  exit 1
}

fail () {
    echo "$(tput setaf 1) $1 $(tput sgr 0)"
    clean
    exit 1
}

pass () {
    echo "$(tput setaf 2) $1 $(tput sgr 0)"
}

EXAMPLES=(
    "credential_reloading_from_files"
)

declare -a EXPECTED_SERVER_OUTPUT=("Client common name: foo.bar.hoo.com" "Client common name: foo.bar.another.client.com")

cd ./security/advancedtls/examples

for example in ${EXAMPLES[@]}; do
    echo "$(tput setaf 4) testing: ${example} $(tput sgr 0)"

    KEY_FILE_PATH=$(mktemp)
    cat ../testdata/client_key_1.pem > ${KEY_FILE_PATH}

    CERT_FILE_PATH=$(mktemp)
    cat ../testdata/client_cert_1.pem > ${CERT_FILE_PATH}

    # Build server.
    if ! go build -o /dev/null ./${example}/*server/*.go; then
        fail "failed to build server"
    else
        pass "successfully built server"
    fi

    # Build client.
    if ! go build -o /dev/null ./${example}/*client/*.go; then
        fail "failed to build client"
    else
        pass "successfully built client"
    fi

    # Start server.
    SERVER_LOG="$(mktemp)"
    go run ./$example/*server/*.go &> $SERVER_LOG  &

    # Run client binary.
    CLIENT_LOG="$(mktemp)"
    go run ${example}/*client/*.go -key=${KEY_FILE_PATH} -cert=${CERT_FILE_PATH} &> $CLIENT_LOG  &

    # Wait for the client to send some requests using old credentials.
    sleep 4s

    # Switch to the new credentials.
    cat ../testdata/another_client_key_1.pem > ${KEY_FILE_PATH}
    cat ../testdata/another_client_cert_1.pem > ${CERT_FILE_PATH}

    # Wait for the client to send some requests using new credentials.
    sleep 4s

    # Check server log for expected output.
    for output in "${EXPECTED_SERVER_OUTPUT[@]}"; do
      if ! grep -q "$output" $SERVER_LOG; then
          fail "server log missing output: $output
          got server log:
          $(cat $SERVER_LOG)
          "
      else
          pass "server log contains expected output: $output"
      fi
    done

    clean
done


text:
namespace liteser
{
	Serializable::Serializable()
	{
	}

	Serializable::~Serializable()
	{
	}

	Serializable* Serializable::clone()
	{
		Serializable* object = NULL;
		liteser::clone(this, &object);
		return object;
	}

}


text:
class ItemsController < ApplicationController
  before_action :set_item, only: [:show, :edit, :update]

  def index
    @item_types = ItemType.all
    @q = Item.search(params[:q])
    @items = @q.result.paginate(page: params[:page], per_page: 8)
  end

  def show; end

  def edit
    @item_types = ItemType.all
  end

  def update
    if @item.update(item_params)
      flash[:success] = 'Item Type Successfully Updated'
      redirect_to @item
    else
      @item.errors.full_messages.each { |e| flash_message :warning, e, :now }
      render :edit
    end
  end

  def destroy
    @item = Item.find(params[:id])
    @item.destroy
    flash[:success] = 'Cart Successfully Deleted'
    redirect_to items_path
  end

  def new_item
    @item_types = ItemType.all
  end

  def create_item
    name = params[:name]
    type = params[:type]
    if name.present?
      ItemType.where(name: type).each do |itype|
        create_item_helper(itype.uuid, name)
      end
    else
      flash[:danger] = 'Invalid Cart Name'
      redirect_to new_items_path
    end
  end

  def refresh_items
    begin
      ItemType.all.each do |item_type|
        refresh_items_helper(item_type)
      end

      flash[:success] ||= 'Items Successfully Updated'
    rescue => error
      flash[:danger] = "Failed To Refresh Items From API. #{error.inspect}"
    end
    redirect_to items_path
  end

  private

  def create_item_helper(uuid, name)
    Inventory.create_item(uuid, name, true, {})
    flash[:success] = 'Cart Successfully Created'
    refresh_items
  rescue => error
    flash[:danger] = "Failed To Create Cart In API. #{error.inspect}"
    redirect_to new_items_path
  end

  def refresh_items_helper(item_type)
    items = Inventory.items_by_type(item_type.uuid)
    items.each do |item|
      Item.where(name: item['name']).first_or_create(item_type_id: item_type.id, uuid: item['uuid'])
    end
  end

  def set_item
    @item = Item.find(params[:id])
  end

  def item_params
    params.require(:item).permit(:name, :item_type_id)
  end
end


text:
package de.tomgrill.gdxfirebase.bindings.googlemobileads;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import de.tomgrill.gdxfirebase.bindings.googlemobileads.protocol.GADAdSizeDelegate;
import de.tomgrill.gdxfirebase.bindings.googlemobileads.protocol.GADAppEventDelegate;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

@Generated
@Library("GoogleMobileAds")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class DFPBannerViewOptions extends GADAdLoaderOptions {
	static {
		NatJ.register();
	}

	@Generated
	protected DFPBannerViewOptions(Pointer peer) {
		super(peer);
	}

	@Generated
	@Selector("accessInstanceVariablesDirectly")
	public static native boolean accessInstanceVariablesDirectly();

	@Generated
	@Selector("adSizeDelegate")
	@MappedReturn(ObjCObjectMapper.class)
	public native GADAdSizeDelegate adSizeDelegate();

	@Generated
	@Owned
	@Selector("alloc")
	public static native DFPBannerViewOptions alloc();

	@Generated
	@Selector("allocWithZone:")
	@MappedReturn(ObjCObjectMapper.class)
	public static native Object allocWithZone(VoidPtr zone);

	@Generated
	@Selector("appEventDelegate")
	@MappedReturn(ObjCObjectMapper.class)
	public native GADAppEventDelegate appEventDelegate();

	@Generated
	@Selector("automaticallyNotifiesObserversForKey:")
	public static native boolean automaticallyNotifiesObserversForKey(String key);

	@Generated
	@Selector("cancelPreviousPerformRequestsWithTarget:")
	public static native void cancelPreviousPerformRequestsWithTarget(
			@Mapped(ObjCObjectMapper.class) Object aTarget);

	@Generated
	@Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
	public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
			@Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
			@Mapped(ObjCObjectMapper.class) Object anArgument);

	@Generated
	@Selector("classFallbacksForKeyedArchiver")
	public static native NSArray<String> classFallbacksForKeyedArchiver();

	@Generated
	@Selector("classForKeyedUnarchiver")
	public static native Class classForKeyedUnarchiver();

	@Generated
	@Selector("debugDescription")
	public static native String debugDescription_static();

	@Generated
	@Selector("description")
	public static native String description_static();

	@Generated
	@Selector("enableManualImpressions")
	public native boolean enableManualImpressions();

	@Generated
	@Selector("hash")
	@NUInt
	public static native long hash_static();

	@Generated
	@Selector("init")
	public native DFPBannerViewOptions init();

	@Generated
	@Selector("instanceMethodForSelector:")
	@FunctionPtr(name = "call_instanceMethodForSelector_ret")
	public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(
			SEL aSelector);

	@Generated
	@Selector("instanceMethodSignatureForSelector:")
	public static native NSMethodSignature instanceMethodSignatureForSelector(
			SEL aSelector);

	@Generated
	@Selector("instancesRespondToSelector:")
	public static native boolean instancesRespondToSelector(SEL aSelector);

	@Generated
	@Selector("isSubclassOfClass:")
	public static native boolean isSubclassOfClass(Class aClass);

	@Generated
	@Selector("keyPathsForValuesAffectingValueForKey:")
	public static native NSSet<String> keyPathsForValuesAffectingValueForKey(
			String key);

	@Generated
	@Owned
	@Selector("new")
	@MappedReturn(ObjCObjectMapper.class)
	public static native Object new_objc();

	@Generated
	@Selector("resolveClassMethod:")
	public static native boolean resolveClassMethod(SEL sel);

	@Generated
	@Selector("resolveInstanceMethod:")
	public static native boolean resolveInstanceMethod(SEL sel);

	@Generated
	@Selector("setAdSizeDelegate:")
	public native void setAdSizeDelegate_unsafe(
			@Mapped(ObjCObjectMapper.class) GADAdSizeDelegate value);

	@Generated
	public void setAdSizeDelegate(
			@Mapped(ObjCObjectMapper.class) GADAdSizeDelegate value) {
		Object __old = adSizeDelegate();
		if (value != null) {
			org.moe.natj.objc.ObjCRuntime.associateObjCObject(this, value);
		}
		setAdSizeDelegate_unsafe(value);
		if (__old != null) {
			org.moe.natj.objc.ObjCRuntime.dissociateObjCObject(this, __old);
		}
	}

	@Generated
	@Selector("setAppEventDelegate:")
	public native void setAppEventDelegate_unsafe(
			@Mapped(ObjCObjectMapper.class) GADAppEventDelegate value);

	@Generated
	public void setAppEventDelegate(
			@Mapped(ObjCObjectMapper.class) GADAppEventDelegate value) {
		Object __old = appEventDelegate();
		if (value != null) {
			org.moe.natj.objc.ObjCRuntime.associateObjCObject(this, value);
		}
		setAppEventDelegate_unsafe(value);
		if (__old != null) {
			org.moe.natj.objc.ObjCRuntime.dissociateObjCObject(this, __old);
		}
	}

	@Generated
	@Selector("setEnableManualImpressions:")
	public native void setEnableManualImpressions(boolean value);

	@Generated
	@Selector("setVersion:")
	public static native void setVersion(@NInt long aVersion);

	@Generated
	@Selector("superclass")
	public static native Class superclass_static();

	@Generated
	@Selector("version")
	@NInt
	public static native long version_static();
}


text:
package de.markiew.netbeans.plugin.actions.closedocuments;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.netbeans.api.project.FileOwnerQuery;
import org.netbeans.api.project.Project;
import org.openide.loaders.DataObject;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;

@ActionID(
        category = "Project",
        id = "closedocuments.ProjectAwareCloseDocumentsInProjectAction"
        )
@ActionRegistration(
        displayName = "#CTL_ProjectAwareCloseDocumentsInProjectAction"
        )
@ActionReferences({
    @ActionReference(path = "Projects/Actions", position = 10)})

@Messages("CTL_ProjectAwareCloseDocumentsInProjectAction=Close Documents From Project")
public final class ProjectAwareCloseDocumentsInProjectAction implements ActionListener {

    private final Project context;
    private final boolean documentsFromSameProject = true;

    public ProjectAwareCloseDocumentsInProjectAction(Project context) {
        this.context = context;
    }

    @Override
    public void actionPerformed(ActionEvent ev) {
        Project currentProject = context;
        for (TopComponent tc : DocumentManager.getInstance().getDocumentsForProject(currentProject, documentsFromSameProject)) {
            tc.close();
        }
    }

}


text:
import sqlite3
import os

import constants

# Check if DB directory exists
if not os.path.exists(constants.dbdir):
    os.makedirs(constants.dbdir)

#query = "INSERT INTO media (title, artist, album, recording_date, "+\
#  4            "original_release_date, genre, file, user, composer) VALUES ('"

conn = sqlite3.connect(constants.dbfile)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS media
                     (id INTEGER PRIMARY KEY AUTOINCREMENT,
                     title text,
                     artist text,
                     composer text,
                     album text,
                     recording_date int,
                     original_release_date int,
                     genre text,
                     comments text,
                     link text,
                     user text,
                     file text)''')

c.execute('''CREATE TABLE IF NOT EXISTS features
                     (id INTEGER PRIMARY KEY AUTOINCREMENT,
                     media_id int,
                     algorithm text,
                     metadata text,
                     value text)''')

c.execute('''CREATE TABLE IF NOT EXISTS users
                    (username text PRIMARY KEY,
                    password text)''')

conn.commit()

for table in ['media', 'features', 'users']:
    results = c.execute('''SELECT * FROM ''' + table)
    print "TABLE", table, "has", len(list(results)), "lines"


text:
<?php

namespace Intaro\RuleEngineBundle\Manager;

interface RuleManagerInterface
{
    /**
     * Returns rules array related to the event
     *
     * @access public
     * @param mixed $name
     * @return array
     */
    public function findRulesByEventName($name);
}


text:
package android.os;

import android.os.IInterface;
import android.os.Parcel;
import android.os.Parcelable;
import android.test.suitebuilder.annotation.SmallTest;
import com.google.android.collect.Lists;
import junit.framework.TestCase;

import java.util.List;

public class AidlTest extends TestCase {

    private IAidlTest mRemote;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        AidlObject mLocal = new AidlObject();
        mRemote = IAidlTest.Stub.asInterface(mLocal);
    }

    private static boolean check(TestParcelable p, int n, String s) {
        return p.mAnInt == n &&
                ((s == null && p.mAString == null) || s.equals(p.mAString));
    }

    public static class TestParcelable implements Parcelable {
        public int mAnInt;
        public String mAString;

        public TestParcelable() {
        }

        public TestParcelable(int i, String s) {
            mAnInt = i;
            mAString = s;
        }

        public int describeContents() {
            return 0;
        }

        public void writeToParcel(Parcel parcel, int flags) {
            parcel.writeInt(mAnInt);
            parcel.writeString(mAString);
        }

        public void readFromParcel(Parcel parcel) {
            mAnInt = parcel.readInt();
            mAString = parcel.readString();
        }

        public static final Parcelable.Creator<TestParcelable> CREATOR
                = new Parcelable.Creator<TestParcelable>() {
            public TestParcelable createFromParcel(Parcel parcel) {
                return new TestParcelable(parcel.readInt(),
                        parcel.readString());
            }

            public TestParcelable[] newArray(int size) {
                return new TestParcelable[size];
            }
        };

        public String toString() {
            return super.toString() + " {" + mAnInt + "/" + mAString + "}";
        }
    }

    private static class AidlObject extends IAidlTest.Stub {
        public IInterface queryLocalInterface(String descriptor) {
            // overriding this to return null makes asInterface always
            // generate a proxy
            return null;
        }

        public int intMethod(int a) {
            return a;
        }

        public TestParcelable parcelableIn(TestParcelable p) {
            p.mAnInt++;
            return p;
        }

        public TestParcelable parcelableOut(TestParcelable p) {
            p.mAnInt = 44;
            return p;
        }

        public TestParcelable parcelableInOut(TestParcelable p) {
            p.mAnInt++;
            return p;
        }

        public TestParcelable listParcelableLonger(List<TestParcelable> list, int index) {
            list.add(list.get(index));
            return list.get(index);
        }

        public int listParcelableShorter(List<TestParcelable> list, int index) {
            list.remove(index);
            return list.size();
        }

        public boolean[] booleanArray(boolean[] a0, boolean[] a1, boolean[] a2) {
            for (int i = 0; i < a0.length && i < a2.length; i++) {
                a2[i] = a0[i];
            }
            for (int i = 0; i < a0.length && i < a1.length; i++) {
                a1[i] = a0[i];
            }
            return a0;
        }

        public char[] charArray(char[] a0, char[] a1, char[] a2) {
            for (int i = 0; i < a0.length && i < a2.length; i++) {
                a2[i] = a0[i];
            }
            for (int i = 0; i < a0.length && i < a1.length; i++) {
                a1[i] = a0[i];
            }
            return a0;
        }

        public int[] intArray(int[] a0, int[] a1, int[] a2) {
            for (int i = 0; i < a0.length && i < a2.length; i++) {
                a2[i] = a0[i];
            }
            for (int i = 0; i < a0.length && i < a1.length; i++) {
                a1[i] = a0[i];
            }
            return a0;
        }

        public long[] longArray(long[] a0, long[] a1, long[] a2) {
            for (int i = 0; i < a0.length && i < a2.length; i++) {
                a2[i] = a0[i];
            }
            for (int i = 0; i < a0.length && i < a1.length; i++) {
                a1[i] = a0[i];
            }
            return a0;
        }

        public float[] floatArray(float[] a0, float[] a1, float[] a2) {
            for (int i = 0; i < a0.length && i < a2.length; i++) {
                a2[i] = a0[i];
            }
            for (int i = 0; i < a0.length && i < a1.length; i++) {
                a1[i] = a0[i];
            }
            return a0;
        }

        public double[] doubleArray(double[] a0, double[] a1, double[] a2) {
            for (int i = 0; i < a0.length && i < a2.length; i++) {
                a2[i] = a0[i];
            }
            for (int i = 0; i < a0.length && i < a1.length; i++) {
                a1[i] = a0[i];
            }
            return a0;
        }

        public String[] stringArray(String[] a0, String[] a1, String[] a2) {
            for (int i = 0; i < a0.length && i < a2.length; i++) {
                a2[i] = a0[i];
            }
            for (int i = 0; i < a0.length && i < a1.length; i++) {
                a1[i] = a0[i];
            }
            return a0;
        }

        public TestParcelable[] parcelableArray(TestParcelable[] a0,
                TestParcelable[] a1, TestParcelable[] a2) {
            return null;
        }

        public void voidSecurityException() {
            throw new SecurityException("gotcha!");
        }

        public int intSecurityException() {
            throw new SecurityException("gotcha!");
        }
    }

    @SmallTest
    public void testInt() throws Exception {
        int result = mRemote.intMethod(42);
        assertEquals(42, result);
    }

    @SmallTest
    public void testParcelableIn() throws Exception {
        TestParcelable arg = new TestParcelable(43, "hi");
        TestParcelable result = mRemote.parcelableIn(arg);
        assertNotSame(arg, result);

        assertEquals(43, arg.mAnInt);
        assertEquals(44, result.mAnInt);
    }

    @SmallTest
    public void testParcelableOut() throws Exception {
        TestParcelable arg = new TestParcelable(43, "hi");
        TestParcelable result = mRemote.parcelableOut(arg);
        assertNotSame(arg, result);
        assertEquals(44, arg.mAnInt);
    }

    @SmallTest
    public void testParcelableInOut() throws Exception {
        TestParcelable arg = new TestParcelable(43, "hi");
        TestParcelable result = mRemote.parcelableInOut(arg);
        assertNotSame(arg, result);
        assertEquals(44, arg.mAnInt);
    }

    @SmallTest
    public void testListParcelableLonger() throws Exception {
        List<TestParcelable> list = Lists.newArrayList();
        list.add(new TestParcelable(33, "asdf"));
        list.add(new TestParcelable(34, "jkl;"));

        TestParcelable result = mRemote.listParcelableLonger(list, 1);

//        System.out.println("result=" + result);
//        for (TestParcelable p : list) {
//            System.out.println("longer: " + p);
//        }

        assertEquals("jkl;", result.mAString);
        assertEquals(34, result.mAnInt);

        assertEquals(3, list.size());
        assertTrue("out parameter 0: " + list.get(0), check(list.get(0), 33, "asdf"));
        assertTrue("out parameter 1: " + list.get(1), check(list.get(1), 34, "jkl;"));
        assertTrue("out parameter 2: " + list.get(2), check(list.get(2), 34, "jkl;"));

        assertNotSame(list.get(1), list.get(2));
    }

    @SmallTest
    public void testListParcelableShorter() throws Exception {
        List<TestParcelable> list = Lists.newArrayList();
        list.add(new TestParcelable(33, "asdf"));
        list.add(new TestParcelable(34, "jkl;"));
        list.add(new TestParcelable(35, "qwerty"));

        int result = mRemote.listParcelableShorter(list, 2);

//        System.out.println("result=" + result);
//        for (TestParcelable p : list) {
//            System.out.println("shorter: " + p);
//        }

        assertEquals(2, result);
        assertEquals(2, list.size());
        assertTrue("out parameter 0: " + list.get(0), check(list.get(0), 33, "asdf"));
        assertTrue("out parameter 1: " + list.get(1), check(list.get(1), 34, "jkl;"));

        assertNotSame(list.get(0), list.get(1));
    }

    @SmallTest
    public void testArrays() throws Exception {
        // boolean
        boolean[] b0 = new boolean[]{true};
        boolean[] b1 = new boolean[]{false, true};
        boolean[] b2 = new boolean[]{true, false, true};
        boolean[] br = mRemote.booleanArray(b0, b1, b2);

        assertEquals(1, br.length);
        assertTrue(br[0]);

        assertTrue(b1[0]);
        assertFalse(b1[1]);

        assertTrue(b2[0]);
        assertFalse(b2[1]);
        assertTrue(b2[2]);

        // char
        char[] c0 = new char[]{'a'};
        char[] c1 = new char[]{'b', 'c'};
        char[] c2 = new char[]{'d', 'e', 'f'};
        char[] cr = mRemote.charArray(c0, c1, c2);

        assertEquals(1, cr.length);
        assertEquals('a', cr[0]);

        assertEquals('a', c1[0]);
        assertEquals('\0', c1[1]);

        assertEquals('a', c2[0]);
        assertEquals('e', c2[1]);
        assertEquals('f', c2[2]);

        // int
        int[] i0 = new int[]{34};
        int[] i1 = new int[]{38, 39};
        int[] i2 = new int[]{42, 43, 44};
        int[] ir = mRemote.intArray(i0, i1, i2);

        assertEquals(1, ir.length);
        assertEquals(34, ir[0]);

        assertEquals(34, i1[0]);
        assertEquals(0, i1[1]);

        assertEquals(34, i2[0]);
        assertEquals(43, i2[1]);
        assertEquals(44, i2[2]);

        // long
        long[] l0 = new long[]{50};
        long[] l1 = new long[]{51, 52};
        long[] l2 = new long[]{53, 54, 55};
        long[] lr = mRemote.longArray(l0, l1, l2);

        assertEquals(1, lr.length);
        assertEquals(50, lr[0]);

        assertEquals(50, l1[0]);
        assertEquals(0, l1[1]);

        assertEquals(50, l2[0]);
        assertEquals(54, l2[1]);
        assertEquals(55, l2[2]);

        // float
        float[] f0 = new float[]{90.1f};
        float[] f1 = new float[]{90.2f, 90.3f};
        float[] f2 = new float[]{90.4f, 90.5f, 90.6f};
        float[] fr = mRemote.floatArray(f0, f1, f2);

        assertEquals(1, fr.length);
        assertEquals(90.1f, fr[0]);

        assertEquals(90.1f, f1[0]);
        assertEquals(0f, f1[1], 0.0f);

        assertEquals(90.1f, f2[0]);
        assertEquals(90.5f, f2[1]);
        assertEquals(90.6f, f2[2]);

        // double
        double[] d0 = new double[]{100.1};
        double[] d1 = new double[]{100.2, 100.3};
        double[] d2 = new double[]{100.4, 100.5, 100.6};
        double[] dr = mRemote.doubleArray(d0, d1, d2);

        assertEquals(1, dr.length);
        assertEquals(100.1, dr[0]);

        assertEquals(100.1, d1[0]);
        assertEquals(0, d1[1], 0.0);

        assertEquals(100.1, d2[0]);
        assertEquals(100.5, d2[1]);
        assertEquals(100.6, d2[2]);

        // String
        String[] s0 = new String[]{"s0[0]"};
        String[] s1 = new String[]{"s1[0]", "s1[1]"};
        String[] s2 = new String[]{"s2[0]", "s2[1]", "s2[2]"};
        String[] sr = mRemote.stringArray(s0, s1, s2);

        assertEquals(1, sr.length);
        assertEquals("s0[0]", sr[0]);

        assertEquals("s0[0]", s1[0]);
        assertNull(s1[1]);

        assertEquals("s0[0]", s2[0]);
        assertEquals("s2[1]", s2[1]);
        assertEquals("s2[2]", s2[2]);
    }

    @SmallTest
    public void testVoidSecurityException() throws Exception {
        boolean good = false;
        try {
            mRemote.voidSecurityException();
        } catch (SecurityException e) {
            good = true;
        }
        assertEquals(good, true);
    }

    @SmallTest
    public void testIntSecurityException() throws Exception {
        boolean good = false;
        try {
            mRemote.intSecurityException();
        } catch (SecurityException e) {
            good = true;
        }
        assertEquals(good, true);
    }
}


text:
package sun.awt.X11;

//import static sun.awt.X11.XEmbed.*;
import java.awt.*;
import java.awt.event.*;
import sun.util.logging.PlatformLogger;
import static sun.awt.X11.XConstants.*;
import java.util.LinkedList;

/**
 * Test XEmbed server implementation. See file:///home/dom/bugs/4931668/test_plan.html for
 * specification and references.
 */
public class XEmbedServerTester implements XEventDispatcher {
    private static final PlatformLogger xembedLog = PlatformLogger.getLogger("sun.awt.X11.xembed.XEmbedServerTester");
    private final Object EVENT_LOCK = new Object();
    static final int SYSTEM_EVENT_MASK = 0x8000;
    int my_version, server_version;
    XEmbedHelper xembed = new XEmbedHelper();
    boolean focused;
    int focusedKind;
    int focusedServerComponent;
    boolean reparent;
    long parent;
    boolean windowActive;
    boolean xembedActive;
    XBaseWindow window;
    volatile int eventWaited = -1, eventReceived = -1;
    int mapped;
    int accel_key, accel_keysym, accel_mods;
    static Rectangle initialBounds = new Rectangle(0, 0, 100, 100);
    Robot robot;
    Rectangle serverBounds[]; // first rectangle is for the server frame, second is for dummy frame, others are for its children
    private static final int SERVER_BOUNDS = 0, OTHER_FRAME = 1, SERVER_FOCUS = 2, SERVER_MODAL = 3, MODAL_CLOSE = 4;

    LinkedList<Integer> events = new LinkedList<Integer>();

    private XEmbedServerTester(Rectangle serverBounds[], long parent) {
        this.parent = parent;
        focusedKind = -1;
        focusedServerComponent = -1;
        reparent = false;
        windowActive = false;
        xembedActive = false;
        my_version = XEmbedHelper.XEMBED_VERSION;
        mapped = XEmbedHelper.XEMBED_MAPPED;
        this.serverBounds = serverBounds;
        if (serverBounds.length < 5) {
            throw new IllegalArgumentException("There must be at least five areas: server-activation, server-deactivation, server-focus, " +
                                               "server-modal show, modal-close");
        }
        try {
            robot = new Robot();
            robot.setAutoDelay(100);
        } catch (Exception e) {
            throw new RuntimeException("Can't create robot");
        }
        initAccel();
        if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
            xembedLog.finer("XEmbed client(tester), embedder window: " + Long.toHexString(parent));
        }
    }

    public static XEmbedServerTester getTester(Rectangle serverBounds[], long parent) {
        return new XEmbedServerTester(serverBounds, parent);
    }

    private void dumpReceivedEvents() {
        if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
            xembedLog.finer("Events received so far:");
            int pos = 0;
            for (Integer event : events) {
                xembedLog.finer((pos++) + ":" + XEmbedHelper.msgidToString(event));
            }
            xembedLog.finer("End of event dump");
        }
    }

    public void test1_1() {
        int res = embedCompletely();
        waitWindowActivated(res);
        requestFocus();
        deactivateServer();
        res = activateServer(getEventPos());
        waitFocusGained(res);
        checkFocusGained(XEmbedHelper.XEMBED_FOCUS_CURRENT);
    }

    public void test1_2() {
        int res = embedCompletely();
        waitWindowActivated(res);
        requestFocus();
        checkFocusGained(XEmbedHelper.XEMBED_FOCUS_CURRENT);
    }

    public void test1_3() {
        embedCompletely();
        deactivateServer();
        requestFocusNoWait();
        checkNotFocused();
    }

    public void test1_4() {
        embedCompletely();
        deactivateServer();
        requestFocusNoWait();
        checkNotFocused();
        int res = getEventPos();
        activateServer(res);
        waitFocusGained(res);
        checkFocusGained(XEmbedHelper.XEMBED_FOCUS_CURRENT);
    }

    public void test1_5() {
        int res = embedCompletely();
        waitWindowActivated(res);
        checkWindowActivated();
    }

    public void test1_6() {
        int res = embedCompletely();
        waitWindowActivated(res);
        requestFocus();
        res = deactivateServer();
        checkFocused();
    }

    public void test1_7() {
        int res = embedCompletely();
        waitWindowActivated(res);
        requestFocus();
        focusServer();
        checkFocusLost();
    }

    public void test2_5() {
        int res = embedCompletely();
        waitWindowActivated(res);
        requestFocus();
        focusServerNext();
        checkFocusedServerNext();
        checkFocusLost();
    }

    public void test2_6() {
        int res = embedCompletely();
        waitWindowActivated(res);
        requestFocus();
        focusServerPrev();
        checkFocusedServerPrev();
        checkFocusLost();
    }

    public void test3_1() {
        reparent = false;
        embedCompletely();
    }

    public void test3_3() {
        reparent = true;
        embedCompletely();
    }

    public void test3_4() {
        my_version = 10;
        embedCompletely();
        if (server_version != XEmbedHelper.XEMBED_VERSION) {
            throw new RuntimeException("Version " + server_version + " is not minimal");
        }
    }

    public void test3_5() {
        embedCompletely();

        window.destroy();
        // TODO: how can we detect that XEmbed ended?  So far we are
        // just checking that XEmbed server won't end up with an
        // exception, which should end up testing, hopefully.

        // Sleep before exiting the tester application
        sleep(1000);
    }

    public void test3_6() {
        embedCompletely();

        sleep(1000);
        XToolkit.awtLock();
        try {
            XlibWrapper.XUnmapWindow(XToolkit.getDisplay(), window.getWindow());
            XlibWrapper.XReparentWindow(XToolkit.getDisplay(), window.getWindow(), XToolkit.getDefaultRootWindow(), 0, 0);
        } finally {
            XToolkit.awtUnlock();
        }

        int res = getEventPos();

        activateServerNoWait(res);

        sleep(1000);
        if (checkEventList(res, XEmbedHelper.XEMBED_WINDOW_ACTIVATE) != -1) {
            throw new RuntimeException("Focus was been given to the client after XEmbed has ended");
        }
    }

    public void test4_1() {
        mapped = XEmbedHelper.XEMBED_MAPPED;
        int res = getEventPos();
        embedCompletely();
        sleep(1000);
        checkMapped();
    }

    public void test4_2() {
        mapped = 0;
        embedCompletely();
        sleep(1000);

        int res = getEventPos();
        mapped = XEmbedHelper.XEMBED_MAPPED;
        updateEmbedInfo();
        sleep(1000);
        checkMapped();
    }

    public void test4_3() {
        int res = getEventPos();
        mapped = XEmbedHelper.XEMBED_MAPPED;
        embedCompletely();

        res = getEventPos();
        mapped = 0;
        updateEmbedInfo();
        sleep(1000);
        checkNotMapped();
    }

    public void test4_4() {
        mapped = 0;
        embedCompletely();
        sleep(1000);
        if (XlibUtil.getWindowMapState(window.getWindow()) != IsUnmapped) {
            throw new RuntimeException("Client has been mapped");
        }
    }

    public void test6_1_1() {
        embedCompletely();
        registerAccelerator();
        focusServer();
        int res = pressAccelKey();
        waitForEvent(res, XEmbedHelper.XEMBED_ACTIVATE_ACCELERATOR);
    }

    public void test6_1_2() {
        embedCompletely();
        registerAccelerator();
        focusServer();
        deactivateServer();
        int res = pressAccelKey();
        sleep(1000);
        if (checkEventList(res, XEmbedHelper.XEMBED_ACTIVATE_ACCELERATOR) != -1) {
            throw new RuntimeException("Accelerator has been activated in inactive embedder");
        }
    }

    public void test6_1_3() {
        embedCompletely();
        registerAccelerator();
        focusServer();
        deactivateServer();
        unregisterAccelerator();
        int res = pressAccelKey();
        sleep(1000);
        if (checkEventList(res, XEmbedHelper.XEMBED_ACTIVATE_ACCELERATOR) != -1) {
            throw new RuntimeException("Accelerator has been activated after unregistering");
        }
    }

    public void test6_1_4() {
        embedCompletely();
        registerAccelerator();
        requestFocus();
        int res = pressAccelKey();
        sleep(1000);
        if (checkEventList(res, XEmbedHelper.XEMBED_ACTIVATE_ACCELERATOR) != -1) {
            throw new RuntimeException("Accelerator has been activated in focused client");
        }
    }
    public void test6_2_1() {
        embedCompletely();
        grabKey();
        focusServer();
        int res = pressAccelKey();
        waitSystemEvent(res, KeyPress);
    }

    public void test6_2_2() {
        embedCompletely();
        grabKey();
        focusServer();
        deactivateServer();
        int res = pressAccelKey();
        sleep(1000);
        if (checkEventList(res, SYSTEM_EVENT_MASK | KeyPress) != -1) {
            throw new RuntimeException("Accelerator has been activated in inactive embedder");
        }
    }

    public void test6_2_3() {
        embedCompletely();
        grabKey();
        focusServer();
        deactivateServer();
        ungrabKey();
        int res = pressAccelKey();
        sleep(1000);
        if (checkEventList(res, SYSTEM_EVENT_MASK | KeyPress) != -1) {
            throw new RuntimeException("Accelerator has been activated after unregistering");
        }
    }

    public void test6_2_4() {
        embedCompletely();
        grabKey();
        requestFocus();
        int res = pressAccelKey();
        sleep(1000);
        int pos = checkEventList(res, SYSTEM_EVENT_MASK | KeyPress);
        if (pos != -1) {
            pos = checkEventList(pos+1, SYSTEM_EVENT_MASK | KeyPress);
            if (pos != -1) { // Second event
                throw new RuntimeException("Accelerator has been activated in focused client");
            }
        }
    }

    public void test7_1() {
        embedCompletely();
        int res = showModalDialog();
        waitForEvent(res, XEmbedHelper.XEMBED_MODALITY_ON);
    }

    public void test7_2() {
        embedCompletely();
        int res = showModalDialog();
        waitForEvent(res, XEmbedHelper.XEMBED_MODALITY_ON);
        res = hideModalDialog();
        waitForEvent(res, XEmbedHelper.XEMBED_MODALITY_OFF);
    }

    public void test9_1() {
        embedCompletely();
        requestFocus();
        int res = pressAccelKey();
        waitForEvent(res, SYSTEM_EVENT_MASK | KeyPress);
    }

    private int embed() {
        int res = getEventPos();
        XToolkit.awtLock();
        try {
            XCreateWindowParams params =
                new XCreateWindowParams(new Object[] {
                    XBaseWindow.PARENT_WINDOW, Long.valueOf(reparent?XToolkit.getDefaultRootWindow():parent),
                    XBaseWindow.BOUNDS, initialBounds,
                    XBaseWindow.EMBEDDED, Boolean.TRUE,
                    XBaseWindow.VISIBLE, Boolean.valueOf(mapped == XEmbedHelper.XEMBED_MAPPED),
                    XBaseWindow.EVENT_MASK, Long.valueOf(VisibilityChangeMask | StructureNotifyMask |
                                                     SubstructureNotifyMask | KeyPressMask)});
            window = new XBaseWindow(params);

            if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                xembedLog.finer("Created tester window: " + window);
            }

            XToolkit.addEventDispatcher(window.getWindow(), this);
            updateEmbedInfo();
            if (reparent) {
                xembedLog.finer("Reparenting to embedder");
                XlibWrapper.XReparentWindow(XToolkit.getDisplay(), window.getWindow(), parent, 0, 0);
            }
        } finally {
            XToolkit.awtUnlock();
        }
        return res;
    }

    private void updateEmbedInfo() {
        long[] info = new long[] { my_version, mapped };
        long data = Native.card32ToData(info);
        try {
            XEmbedHelper.XEmbedInfo.setAtomData(window.getWindow(), data, info.length);
        } finally {
            XEmbedHelper.unsafe.freeMemory(data);
        }
    }

    private int getEventPos() {
        synchronized(EVENT_LOCK) {
            return events.size();
        }
    }

    private int embedCompletely() {
        xembedLog.fine("Embedding completely");
        int res = getEventPos();
        embed();
        waitEmbeddedNotify(res);
        return res;
    }
    private int requestFocus() {
        xembedLog.fine("Requesting focus");
        int res = getEventPos();
        sendMessage(XEmbedHelper.XEMBED_REQUEST_FOCUS);
        waitFocusGained(res);
        return res;
    }
    private int requestFocusNoWait() {
        xembedLog.fine("Requesting focus without wait");
        int res = getEventPos();
        sendMessage(XEmbedHelper.XEMBED_REQUEST_FOCUS);
        return res;
    }
    private int activateServer(int prev) {
        int res = activateServerNoWait(prev);
        waitWindowActivated(res);
        return res;
    }
    private int activateServerNoWait(int prev) {
        xembedLog.fine("Activating server");
        int res = getEventPos();
        if (checkEventList(prev, XEmbedHelper.XEMBED_WINDOW_ACTIVATE) != -1) {
            xembedLog.fine("Activation already received");
            return res;
        }
        Point loc = serverBounds[SERVER_BOUNDS].getLocation();
        loc.x += serverBounds[SERVER_BOUNDS].getWidth()/2;
        loc.y += 5;
        robot.mouseMove(loc.x, loc.y);
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);
        return res;
    }
    private int deactivateServer() {
        xembedLog.fine("Deactivating server");
        int res = getEventPos();
        Point loc = serverBounds[OTHER_FRAME].getLocation();
        loc.x += serverBounds[OTHER_FRAME].getWidth()/2;
        loc.y += serverBounds[OTHER_FRAME].getHeight()/2;
        robot.mouseMove(loc.x, loc.y);
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.delay(50);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);
        waitWindowDeactivated(res);
        return res;
    }
    private int focusServer() {
        xembedLog.fine("Focusing server");
        boolean weFocused = focused;
        int res = getEventPos();
        Point loc = serverBounds[SERVER_FOCUS].getLocation();
        loc.x += 5;
        loc.y += 5;
        robot.mouseMove(loc.x, loc.y);
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.delay(50);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);
        if (weFocused) {
            waitFocusLost(res);
        }
        return res;
    }
    private int focusServerNext() {
        xembedLog.fine("Focusing next server component");
        int res = getEventPos();
        sendMessage(XEmbedHelper.XEMBED_FOCUS_NEXT);
        waitFocusLost(res);
        return res;
    }
    private int focusServerPrev() {
        xembedLog.fine("Focusing previous server component");
        int res = getEventPos();
        sendMessage(XEmbedHelper.XEMBED_FOCUS_PREV);
        waitFocusLost(res);
        return res;
    }

    private void waitEmbeddedNotify(int pos) {
        waitForEvent(pos, XEmbedHelper.XEMBED_EMBEDDED_NOTIFY);
    }
    private void waitFocusGained(int pos) {
        waitForEvent(pos, XEmbedHelper.XEMBED_FOCUS_IN);
    }
    private void waitFocusLost(int pos) {
        waitForEvent(pos, XEmbedHelper.XEMBED_FOCUS_OUT);
    }
    private void waitWindowActivated(int pos) {
        waitForEvent(pos, XEmbedHelper.XEMBED_WINDOW_ACTIVATE);
    }
    private void waitWindowDeactivated(int pos) {
        waitForEvent(pos, XEmbedHelper.XEMBED_WINDOW_DEACTIVATE);
    }

    private void waitSystemEvent(int position, int event) {
        waitForEvent(position, event | SYSTEM_EVENT_MASK);
    }

    private void waitForEvent(int position, int event) {
        synchronized(EVENT_LOCK) {
            // Check for already received events after the request
            if (checkEventList(position, event) != -1) {
                if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                    xembedLog.finer("The event " + XEmbedHelper.msgidToString(event) + " has already been received");
                }
                return;
            }

            if (eventReceived == event) {
                // Already received
                if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                    xembedLog.finer("Already received " + XEmbedHelper.msgidToString(event));
                }
                return;
            }
            eventReceived = -1;
            eventWaited = event;
            if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                xembedLog.finer("Waiting for " + XEmbedHelper.msgidToString(event) + " starting from " + position);
            }
            try {
                EVENT_LOCK.wait(3000);
            } catch (InterruptedException ie) {
                xembedLog.warning("Event wait interrupted", ie);
            }
            eventWaited = -1;
            if (checkEventList(position, event) == -1) {
                dumpReceivedEvents();
                throw new RuntimeException("Didn't receive event " + XEmbedHelper.msgidToString(event) + " but recevied " + XEmbedHelper.msgidToString(eventReceived));
            } else {
                if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                    xembedLog.finer("Successfully recevied " + XEmbedHelper.msgidToString(event));
                }
            }
        }
    }
    /**
     * Checks if the event is already in a list at position >= position
     */
    private int checkEventList(int position, int event) {
        if (position == -1) {
            return -1;
        }
        synchronized(EVENT_LOCK) {
            for (int i = position; i < events.size(); i++) {
                if (events.get(i) == event) {
                    return i;
                }
            }
            return -1;
        }
    }

    private void checkFocusedServerNext() {
        if (focusedServerComponent != 0) {
            throw new RuntimeException("Wrong focused server component, should be 0, but it is " + focusedServerComponent);
        }
    }
    private void checkFocusedServerPrev() {
        if (focusedServerComponent != 2) {
            throw new RuntimeException("Wrong focused server component, should be 2, but it is " + focusedServerComponent);
        }
    }
    private void checkFocusGained(int kind) {
        if (!focused) {
            throw new RuntimeException("Didn't receive FOCUS_GAINED");
        }
        if (focusedKind != kind) {
            throw new RuntimeException("Kinds don't match, required: " + kind + ", current: " + focusedKind);
        }
    }
    private void checkNotFocused() {
        if (focused) {
            throw new RuntimeException("Focused");
        }
    }
    private void checkFocused() {
        if (!focused) {
            throw new RuntimeException("Not Focused");
        }
    }

    private void checkFocusLost() {
        checkNotFocused();
        if (focusedKind != XEmbedHelper.XEMBED_FOCUS_OUT) {
            throw new RuntimeException("Didn't receive FOCUS_LOST");
        }
    }
    private void checkWindowActivated() {
        if (!windowActive) {
            throw new RuntimeException("Window is not active");
        }
    }
    private void checkMapped() {
        if (XlibUtil.getWindowMapState(window.getWindow()) == IsUnmapped) {
            throw new RuntimeException("Client is not mapped");
        }
    }
    private void checkNotMapped() {
        if (XlibUtil.getWindowMapState(window.getWindow()) != IsUnmapped) {
            throw new RuntimeException("Client is mapped");
        }
    }

    private void sendMessage(int message) {
        xembed.sendMessage(parent, message);
    }
    private void sendMessage(int message, int detail, long data1, long data2) {
        xembed.sendMessage(parent, message, detail, data1, data2);
    }

    public void dispatchEvent(XEvent ev) {
        if (ev.get_type() == ClientMessage) {
            XClientMessageEvent msg = ev.get_xclient();
            if (msg.get_message_type() == xembed.XEmbed.getAtom()) {
                if (xembedLog.isLoggable(PlatformLogger.Level.FINE)) {
                    xembedLog.fine("Embedded message: " + XEmbedHelper.msgidToString((int)msg.get_data(1)));
                }
                switch ((int)msg.get_data(1)) {
                  case XEmbedHelper.XEMBED_EMBEDDED_NOTIFY: // Notification about embedding protocol start
                      xembedActive = true;
                      server_version = (int)msg.get_data(3);
                      break;
                  case XEmbedHelper.XEMBED_WINDOW_ACTIVATE:
                      windowActive = true;
                      break;
                  case XEmbedHelper.XEMBED_WINDOW_DEACTIVATE:
                      windowActive = false;
                      break;
                  case XEmbedHelper.XEMBED_FOCUS_IN: // We got focus!
                      focused = true;
                      focusedKind = (int)msg.get_data(2);
                      break;
                  case XEmbedHelper.XEMBED_FOCUS_OUT:
                      focused = false;
                      focusedKind = XEmbedHelper.XEMBED_FOCUS_OUT;
                      focusedServerComponent = (int)msg.get_data(2);
                      break;
                }
                synchronized(EVENT_LOCK) {
                    events.add((int)msg.get_data(1));

                    if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                        xembedLog.finer("Tester is waiting for " +  XEmbedHelper.msgidToString(eventWaited));
                    }
                    if ((int)msg.get_data(1) == eventWaited) {
                        eventReceived = (int)msg.get_data(1);
                        if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                            xembedLog.finer("Notifying waiting object for event " + System.identityHashCode(EVENT_LOCK));
                        }
                        EVENT_LOCK.notifyAll();
                    }
                }
            }
        } else {
            synchronized(EVENT_LOCK) {
                int eventID = (int)ev.get_type() | SYSTEM_EVENT_MASK;
                events.add(eventID);

                if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                    xembedLog.finer("Tester is waiting for " + XEmbedHelper.msgidToString(eventWaited) + ", but we received " + ev + "(" + XEmbedHelper.msgidToString(eventID) + ")");
                }
                if (eventID == eventWaited) {
                    eventReceived = eventID;
                    if (xembedLog.isLoggable(PlatformLogger.Level.FINER)) {
                        xembedLog.finer("Notifying waiting object" + System.identityHashCode(EVENT_LOCK));
                    }
                    EVENT_LOCK.notifyAll();
                }
            }
        }
    }

    private void sleep(int amount) {
        try {
            Thread.sleep(amount);
        } catch (Exception e) {
        }
    }

    private void registerAccelerator() {
        sendMessage(XEmbedHelper.XEMBED_REGISTER_ACCELERATOR, 1, accel_keysym, accel_mods);
    }

    private void unregisterAccelerator() {
        sendMessage(XEmbedHelper.XEMBED_UNREGISTER_ACCELERATOR, 1, 0, 0);
    }

    private int pressAccelKey() {
        int res = getEventPos();
        robot.keyPress(accel_key);
        robot.keyRelease(accel_key);
        return res;
    }

    private void initAccel() {
        accel_key = KeyEvent.VK_A;
        accel_keysym = XWindow.getKeySymForAWTKeyCode(accel_key);
        accel_mods = 0;
    }

    private void grabKey() {
        sendMessage(XEmbedHelper.NON_STANDARD_XEMBED_GTK_GRAB_KEY, 0, accel_keysym, accel_mods);
    }
    private void ungrabKey() {
        sendMessage(XEmbedHelper.NON_STANDARD_XEMBED_GTK_UNGRAB_KEY, 0, accel_keysym, accel_mods);
    }
    private int showModalDialog() {
        xembedLog.fine("Showing modal dialog");
        int res = getEventPos();
        Point loc = serverBounds[SERVER_MODAL].getLocation();
        loc.x += 5;
        loc.y += 5;
        robot.mouseMove(loc.x, loc.y);
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.delay(50);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);
        return res;
    }
    private int hideModalDialog() {
        xembedLog.fine("Hide modal dialog");
        int res = getEventPos();
//         Point loc = serverBounds[MODAL_CLOSE].getLocation();
//         loc.x += 5;
//         loc.y += 5;
//         robot.mouseMove(loc.x, loc.y);
//         robot.mousePress(InputEvent.BUTTON1_MASK);
//         robot.delay(50);
//         robot.mouseRelease(InputEvent.BUTTON1_MASK);
        robot.keyPress(KeyEvent.VK_SPACE);
        robot.keyRelease(KeyEvent.VK_SPACE);
        return res;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Bon, Docums Mycol. 5(no. 18): 155 (1975)

#### Original name
Tricholoma umbonatum Clémençon & Bon

### Remarks
null


text:
<?php

/**
 * @package Template
 * @subpackage Tests
 */
class ezcTemplateValidationItemTest extends ezcTestCase
{
    public static function suite()
    {
         return new PHPUnit_Framework_TestSuite( "ezcTemplateValidationItemTest" );
    }

    /**
     * Test passing constructor values
     */
    public function testInit()
    {
        $validation = new ezcTemplateValidationItem( ezcTemplateValidationItem::TYPE_ERROR,
                                                     'templates/zhadum.tpl', 4, 20,
                                                     'template is not valid', 'unknown function "list_types"' );

        self::assertSame( ezcTemplateValidationItem::TYPE_ERROR, $validation->type, 'Property <type> does not return correct value.' );
        self::assertSame( 'templates/zhadum.tpl', $validation->filePath, 'Property <filePath> does not return correct value.' );
        self::assertSame( 4, $validation->line, 'Property <line> does not return correct value.' );
        self::assertSame( 20, $validation->column, 'Property <column> does not return correct value.' );
        self::assertSame( 'template is not valid', $validation->description, 'Property <description> does not return correct value.' );
        self::assertSame( 'unknown function "list_types"', $validation->details, 'Property <details> does not return correct value.' );
    }

    /**
     * Test modifying properties
     */
    public function testSetProperties()
    {
        $validation = new ezcTemplateValidationItem( ezcTemplateValidationItem::TYPE_ERROR,
                                                     'templates/zhadum.tpl', 4, 20,
                                                     'template is not valid', 'unknown function "list_types"' );

        self::assertSetProperty( $validation, 'type', array( ezcTemplateValidationItem::TYPE_WARNING, ezcTemplateValidationItem::TYPE_ERROR ) );
        self::assertSetProperty( $validation, 'filePath', array( 'templates/pagelayout.tpl', '', 'templates/zhadum.tpl' ) );
        self::assertSetProperty( $validation, 'line', array( 0, 1, 200, 4 ) );
        self::assertSetProperty( $validation, 'column', array( 0, 1, 5, 20 ) );
        self::assertSetProperty( $validation, 'description', array( 'errors in template', 'template is not valid' ) );
        self::assertSetProperty( $validation, 'details', array( 'invalid syntax {$list|wash}', 'unknown function "list_types"' ) );
    }
}

?>