text:
// -*- mode: C++ -*-
//
// Copyright (c) 2007, 2008, 2010, 2011, 2013, 2014 The University of Utah
// All rights reserved.
//
// This file is part of `csmith', a random generator of C programs.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in the
//     documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

//
// This file was derived from a random program generator written by Bryan
// Turner.  The attributions in that file was:
//
// Random Program Generator
// Bryan Turner (bryan.turner@pobox.com)
// July, 2005
//
#ifdef WIN32
#pragma warning(disable : 4786)   /* Disable annoying warning messages */
#endif
#include "Function.h"

#include <cassert>

#include "Common.h"
#include "Block.h"
#include "CGContext.h"
#include "CGOptions.h"
#include "Constant.h"
#include "Effect.h"
#include "Statement.h"
#include "Type.h"
#include "VariableSelector.h"
#include "FactMgr.h"
#include "random.h"
#include "util.h"
#include "Fact.h"
#include "FactPointTo.h"
#include "FactMgr.h"
#include "VectorFilter.h"
#include "Error.h"
#include "DepthSpec.h"
#include "ExtensionMgr.h"
#include "OutputMgr.h"

// ****************************** ExtendedCsmith ****************************** >>
#include "RecursiveBlock.h"
#include "RecursiveFactMgr.h"
#include "RecursiveCGContext.h"
#include "ImmediateRecursiveFunction.h"
#include "MutuallyRecursiveFunction.h"
// **************************************************************************** <<

using namespace std;

///////////////////////////////////////////////////////////////////////////////

static vector<Function*> FuncList;              // List of all functions in the program
static vector<FactMgr*>  FMList;                // List of fact managers for each function
static long cur_func_idx;                       // Index into FuncList that we are currently working on
static bool param_first=true;                   // Flag to track output of commas
static int builtin_functions_cnt;

// ****************************** ExtendedCsmith ****************************** >>
static vector<RecursiveFactMgr*>  RFMList;      // List of fact managers for each recursive function
static vector<RecursiveCGContext*>  RCGCList;      // List of code generation contexts for each recursive function
// **************************************************************************** <<

/*
 * find FactMgr for a function
 */
FactMgr*
get_fact_mgr_for_func(const Function* func)
{
    // ****************************** ExtendedCsmith ****************************** >>
    if (CGOptions::recursion() && func->is_recursive()) {
        for (size_t i=0; i<RFMList.size(); i++) {
            if (RFMList[i]->get_func() == func) {
                return RFMList[i]->get_curr_fact_mgr();
            }
        }
    }
    // **************************************************************************** <<

    for (size_t i=0; i<FuncList.size(); i++) {
		if (FuncList[i] == func) {
			return FMList[i];
		}
	}
    return 0;
}

/*
 *
 */
FactMgr*
get_fact_mgr(const CGContext* cg)
{
    return get_fact_mgr_for_func(cg->get_current_func());
}

// ****************************** ExtendedCsmith ****************************** >>
void
add_fact_mgr(FactMgr* fm)
{
    FMList.push_back(fm);
}

void
add_recursive_fact_mgr(RecursiveFactMgr* rfm)
{
    RFMList.push_back(rfm);
}

void
add_recursive_cg_context(RecursiveCGContext* rcgc)
{
    RCGCList.push_back(rcgc);
}

/**
 * Finds the fact manager suitable for the given recursive function.
 */
RecursiveFactMgr*
get_rec_fact_mgr_for_func(const Function* func)
{
    if (CGOptions::recursion() && func->is_recursive()) {
        for (size_t i=0; i<RFMList.size(); i++) {
            if (RFMList[i]->get_func() == func) {
                return RFMList[i];
            }
        }
    }
    return 0;
}

/**
 * Finds the code generation context suitable for the given recursive function.
 */
RecursiveCGContext*
get_rec_cg_context_for_func(const Function* func)
{
    if (CGOptions::recursion() && func->is_recursive()) {
        for (size_t i=0; i<RCGCList.size(); i++) {
            if (RCGCList[i]->get_func() == func) {
                return RCGCList[i];
            }
        }
    }
    return 0;
}

/**
 * Removes this function from the lists FMList, RFMList and RCGCList.
 * Used for deallocation of a recursive function.
 */
void
Function::remove_from_lists(void)
{
    for (size_t i = 0; i < FuncList.size(); i++) {
        if (FuncList[i] == this) {
            FMList.erase(FMList.begin() + i);
            break;
        }
    }

    assert(RFMList.size() == RCGCList.size());
    int to_remove;
    for (size_t i = 0; i < RFMList.size(); i++) {
        if (RFMList[i]->get_func() == this) {
            to_remove = i;
            break;
        }
    }

    RFMList.erase(RFMList.begin() + to_remove);
    RCGCList.erase(RCGCList.begin() + to_remove);

    FuncList.erase(std::remove(FuncList.begin(), FuncList.end(), this), FuncList.end());
}

///////////////////////////////////////////////////////////////////////////////

class FunctionFilter : public Filter
{
public:
    explicit FunctionFilter(const CGContext &cg_context);

    virtual ~FunctionFilter(void);

    virtual bool filter(int v) const;
private:
    const CGContext &cg_context_;
};

FunctionFilter::FunctionFilter(const CGContext &cg_context)
    : cg_context_(cg_context)
{

}

FunctionFilter::~FunctionFilter(void)
{

}

// A table defining probabilities of different kinds of functions
// Must initialize it before use
ProbabilityTable<unsigned int, ProbName> *Function::funcTable_ = NULL;
bool Function::through_recursive_func = false;

void
Function::InitProbabilityTable()
{
    if (Function::funcTable_)
        return;

    Function::funcTable_ = new ProbabilityTable<unsigned int, ProbName>();
    Function::funcTable_->initialize(pFunctionProb);
}

eFunctionType
Function::number_to_type(unsigned int value)
{
    assert(Function::funcTable_);
    assert(value < 100);
    ProbName pname = Function::funcTable_->get_value(value);
    eFunctionType type = static_cast<eFunctionType>(Probabilities::pname_to_type(pname));
    return type;
}

bool FunctionFilter::filter(int value) const
{
    return false; // any function type is fine
}

static eFunctionType
FunctionProbability(const FunctionFilter *filter)
{
    int value = rnd_upto(100, filter);
    ERROR_GUARD(MAX_FUNCTION_TYPE);
    assert(value != -1);
    assert(value >= 0 && value < 100);
    return Function::number_to_type(value);
}
// **************************************************************************** <<

const Function*
find_function_by_name(const string& name)
{
	size_t i;
	for (i=0; i<FuncList.size(); i++) {
		if (FuncList[i]->name == name) {
			return FuncList[i];
		}
	}
	return NULL;
}

int
find_function_in_set(const vector<const Function*>& set, const Function* f)
{
	size_t i;
	for (i=0; i<set.size(); i++) {
		if (set[i] == f) {
			return i;
		}
	}
	return -1;
}

const Block*
find_blk_for_var(const Variable* v)
{
	if (v->is_global()) {
		return NULL;
	}
	size_t i, j;
	for (i=0; i<FuncList.size(); i++) {
		const Function* func = FuncList[i];
		// for a parameter of a function, pretend it's a variable belongs to the top block
		if (v->is_argument() && find_variable_in_set(func->param, v) != -1) {
			return func->body;
		}
		for (j=0; j<func->blocks.size(); j++) {
			const Block* blk = func->blocks[j];
			if (find_variable_in_set(blk->local_vars, v) != -1) {
				return blk;
			}
		}
	}
	return NULL;
}

bool
Function::is_var_on_stack(const Variable* var, const Statement* stm) const
{
    size_t i;
    for (i=0; i<param.size(); i++) {
        if (param[i]->match(var)) {
            return true;
        }
    }
	const Block* b = stm->parent;
	while (b) {
		if (find_variable_in_set(b->local_vars, var) != -1) {
			return true;
		}
		b = b->parent;
	}
    return false;
}

/* find whether a variable is visible in the given statement
 */
bool
Function::is_var_visible(const Variable* var, const Statement* stm) const
{
    return (var->is_global() || is_var_on_stack(var, stm)) ;
}

/*
 * return true if a variable is out-of-scope at given statement
 * note variable must be a local variable of this function to
 * be a oos variable (sometimes DFA would analyze local variables
 * from callers, they should remain "in-scope" for this function
 */
bool
Function::is_var_oos(const Variable* var, const Statement* stm) const
{
	if (!is_var_visible(var, stm)) {
		//return true;
		size_t i;
		for (i=0; i<blocks.size(); i++) {
			if (find_variable_in_set(blocks[i]->local_vars, var) != -1) {
				return true;
			}
		}
	}
	return false;
}

bool
Function::reach_max_functions_cnt()
{
	return ((static_cast<int>(FuncList.size()) - builtin_functions_cnt) >= CGOptions::max_funcs());
}

const vector<Function*>&
get_all_functions(void)
{
	return FuncList;
}

/*
 *
 */
// unsigned
long
FuncListSize(void)
{
	return FuncList.size();
}

/*
 *
 */
Function *
GetFirstFunction(void)
{
	assert((builtin_functions_cnt >= 0) && "Invalid builtin_functions_cnt!");
	return FuncList[builtin_functions_cnt];
}

/*
 *
 */
string  // ExtendedCsmith Edit
RandomFunctionName(void)
{
	return gensym("func_");
}

/*-------------------------------------------------------------
 *  choose a random return type. only struct/unions and integer types
 *  (not incl. void)  are qualified, (no arrays)
 *************************************************************/
const Type*             // ExtendedCsmith Edit
RandomReturnType(void)
{
	const Type* t = 0;
        t = Type::choose_random();
	return t;
}

Function *
Function::get_one_function(const vector<Function *> &ok_funcs)
{
	vector<Function *>::size_type ok_size = ok_funcs.size();

	if (ok_size == 0) {
		return 0;
	}
	if (ok_size == 1) {
		return ok_funcs[0];
	}
	int index = rnd_upto(ok_size);
	return ok_funcs[index];
}

/*
 * Choose a function from `funcs' to invoke.
 * Return null if no suitable function can be found.
 */
Function *
Function::choose_func(vector<Function *> funcs,
			const CGContext& cg_context,
			const Type* type,
			const CVQualifiers* qfer)
{
	vector<Function *> ok_funcs;
	vector<Function *> ok_builtin_funcs;
	vector<Function *>::iterator i;

	for (i = funcs.begin(); i != funcs.end(); ++i) {
		// skip any function which has incompatible return type
		// if type = 0, we don't care
		if (type && !type->is_convertable((*i)->return_type))
			continue;
		// Changing the behavior of is_convertable is quite dangerous.
		// Making constraint here has less global effect.
		//if (type && (*i)->return_type->is_float() && !type->is_float())
		//	continue;
		if (qfer && (*i)->rv && !qfer->match((*i)->rv->qfer))
			continue;
		// We cannot call a function that has an as-yet unknown effect.
		// TODO: in practice, this means we never call an as-yet unbuilt func.
		if ((*i)->is_effect_known() == false) {
			continue;
		}
		// We cannot call a function with a side-effect that is in conflict with the current context
		if (cg_context.in_conflict((*i)->get_feffect())) {
			continue;
		}
		if (CGOptions::strict_volatile_rule()) {
			if (!((*i)->get_feffect().is_side_effect_free())
			    && !cg_context.get_effect_context().is_side_effect_free()) {
				continue;
			}
		}
		//// TODO: is this too strong for what we want?
		//if (!((*i)->get_feffect().is_side_effect_free())
		//	&& !effect_context.is_side_effect_free()) {
		//	continue;
		//}
		//// We cannot call a function that has a race with the current context.
		//if ((*i)->get_feffect().has_race_with(effect_context)) {
		//	continue;
		//}
		// Otherwise, this is an acceptable choice.

        // ****************************** ExtendedCsmith ****************************** >>
        /*if (CGOptions::mutual_recursion() && (*i)->func_type == eMutuallyRecursive) {
            MutuallyRecursiveFunction* f = dynamic_cast<MutuallyRecursiveFunction*>(*i);
            if (!f->is_first())
                continue;
        }*/
        // disallow to call a recursive function more than once
        if (CGOptions::recursion() && (*i)->is_recursive()) {
            continue;
        }
        // **************************************************************************** <<

		if ((*i)->is_builtin)
			ok_builtin_funcs.push_back(*i);
		else
			ok_funcs.push_back(*i);
	}

	Function *f = NULL;
	if (CGOptions::builtins() && rnd_flipcoin(BuiltinFunctionProb)) {
		f = Function::get_one_function(ok_builtin_funcs);
	}
	if (f == NULL) {
		f = Function::get_one_function(ok_funcs);
	}
	return f;
}

/*
 *
 */
static unsigned int
ParamListProbability()
{
	return rnd_upto(CGOptions::max_params());
}

static void
GenerateParameterListFromString(Function &currFunc, const string &params_string)
{
	vector<string> vs;
	StringUtils::split_string(params_string, vs, ",");
	int params_cnt = vs.size();
	assert((params_cnt > 0) && "Invalid params_string!");
	if ((params_cnt == 1) && (vs[0] == "Void")) {
		return;
	}
	for (int i = 0; i < params_cnt; i++) {
		assert((vs[i] != "Void") && "Invalid parameter type!");
		CVQualifiers qfer;
		qfer.add_qualifiers(false, false);
		const Type *ty = Type::get_type_from_string(vs[0]);
		Variable *v = VariableSelector::GenerateParameterVariable(ty, &qfer);
		assert(v);
		currFunc.param.push_back(v);
	}
}

/*
 *
 */
void         // ExtendedCsmith Edit
GenerateParameterList(Function &curFunc)
{
	unsigned int max = ParamListProbability();
	ERROR_RETURN();

	for (unsigned int i =0; i <= max; i++) {
		// With some probability, choose a new random variable, or one from
		// parentParams, parentLocals, or the globals list.
		//
		// Also, build the parent's link structure for this invocation and push
		// it onto the back.
		//
		VariableSelector::GenerateParameterVariable(curFunc);
		ERROR_RETURN();
	}
}

/*
 *
 */
Function::Function(const string &name, const Type *return_type)
	: name(name),
	  return_type(return_type),
	  body(0),
	  fact_changed(false),
	  union_field_read(false),
	  is_inlined(false),
	  is_builtin(false),
	  visited_cnt(0),
	  build_state(UNBUILT),
      func_type(eNonRecursive)          // ExtendedCsmith
{
	FuncList.push_back(this);           // Add to global list of functions.
}

Function::Function(const string &name, const Type *return_type, bool builtin)
	: name(name),
	  return_type(return_type),
	  body(0),
	  fact_changed(false),
	  union_field_read(false),
	  is_inlined(false),
	  is_builtin(builtin),
	  visited_cnt(0),
	  build_state(UNBUILT),
      func_type(eNonRecursive)          // ExtendedCsmith
{
	FuncList.push_back(this);           // Add to global list of functions.
}

// ****************************** ExtendedCsmith ****************************** >>
Function::Function(const std::string &name, const Type *return_type, eFunctionType func_type)
    : name(name),
      return_type(return_type),
      body(0),
      fact_changed(false),
      union_field_read(false),
      is_inlined(false),
      is_builtin(UNBUILT),
      visited_cnt(0),
      build_state(UNBUILT),
      func_type(func_type)
{
    FuncList.push_back(this);           // Add to global list of functions.
}
// **************************************************************************** <<

Function *
Function::make_random_signature(const CGContext& cg_context, const Type* type, const CVQualifiers* qfer)
{
    if (type == 0)
		type = RandomReturnType();

	DEPTH_GUARD_BY_TYPE_RETURN(dtFunction, NULL);
	ERROR_GUARD(NULL);
    Function *f;    // ExtendedCsmith Edit

    // ****************************** ExtendedCsmith ****************************** >>
    int num_funcs;
    if (CGOptions::recursion() && !through_recursive_func) {
        // choose the function type
        Function::InitProbabilityTable();
        FunctionFilter filter(cg_context);
        eFunctionType func_type = FunctionProbability(&filter);
        ERROR_GUARD(NULL);

        switch (func_type) {
            case eNonRecursive:
                f = new Function(RandomFunctionName(), type);
                break;
            case eImmediateRecursive:
                f = new ImmediateRecursiveFunction(RandomFunctionName(), type);
                through_recursive_func = true;
                break;
            case eMutuallyRecursive:
                num_funcs = MutuallyRecursiveFunction::MutuallyRecursiveFunctionProbability();
                ERROR_GUARD(NULL);
                f = new MutuallyRecursiveFunction(RandomFunctionName(), type, num_funcs);
                through_recursive_func = true;
                break;
            default:
                assert(!"unknown function type");
                break;
        }
    } else {
        f = new Function(RandomFunctionName(), type);
    }
    // **************************************************************************** <<

	// dummy variable representing return variable, we don't care about the type, so use 0
	string rvname = f->name + "_" + "rv";
	CVQualifiers ret_qfer = qfer==0 ? CVQualifiers::random_qualifiers(type, Effect::READ, cg_context, true)
		                            : qfer->random_qualifiers(true, Effect::READ, cg_context);
	ERROR_GUARD(NULL);
	f->rv = Variable::CreateVariable(rvname, type, NULL, &ret_qfer);
	GenerateParameterList(*f);
	FMList.push_back(new FactMgr(f));
	if (CGOptions::inline_function() && rnd_flipcoin(InlineFunctionProb))
		f->is_inlined = true;

	return f;
}

/*
 *
 */
Function *
Function::make_random(const CGContext& cg_context, const Type* type, const CVQualifiers* qfer)
{
	Function* f = make_random_signature(cg_context, type, qfer);
	ERROR_GUARD(NULL);
	f->GenerateBody(cg_context);
	ERROR_GUARD(NULL);
	return f;
}

/*
 *
 */
Function *
Function::make_first(void)
{
	const Type *ty = RandomReturnType();
	ERROR_GUARD(NULL);

	Function *f = new Function(RandomFunctionName(), ty);
	// dummy variable representing return variable, we don't care about the type, so use 0
	string rvname = f->name + "_" + "rv";
	CVQualifiers ret_qfer = CVQualifiers::random_qualifiers(ty);
	ERROR_GUARD(NULL);
	f->rv = Variable::CreateVariable(rvname, ty, NULL, &ret_qfer);

	// create a fact manager for this function, with empty global facts
	FactMgr* fm = new FactMgr(f);
	FMList.push_back(fm);

	ExtensionMgr::GenerateFirstParameterList(*f);

	// No Parameter List
	f->GenerateBody(CGContext::get_empty_context());
	if (CGOptions::inline_function() && rnd_flipcoin(InlineFunctionProb))
		f->is_inlined = true;
	fm->setup_in_out_maps(true);

	// update global facts to merged facts at all possible function exits
	fm->global_facts = fm->map_facts_out[f->body];
	f->body->add_back_return_facts(fm, fm->global_facts);

	// collect info about global dangling pointers
	fm->find_dangling_global_ptrs(f);
	return f;
}

/*
 *
 */
static int
OutputFormalParam(Variable *var, std::ostream *pOut)
{
	std::ostream &out = *pOut;
	if ( !param_first ) out << ", ";
	param_first = false;
	//var->type->Output( out );
	if (!CGOptions::arg_structs() && var->type)
		assert(var->type->eType != eStruct);
	if (!CGOptions::arg_unions() && var->type)
		assert(var->type->eType != eUnion);

	var->output_qualified_type(out);
	out << " " << var->name;
    return 0;
}

/*
 *
 */
void
Function::OutputFormalParamList(std::ostream &out)
{
	if (param.size() == 0) {
		assert(Type::void_type);
		Type::void_type->Output(out);
	} else {
		param_first = true;
		for_each(param.begin(),
				 param.end(),
				 std::bind2nd(std::ptr_fun(OutputFormalParam), &out));
	}
}

/*
 *
 */
void
Function::OutputHeader(std::ostream &out)
{
	if (!CGOptions::return_structs() && return_type)
		assert(return_type->eType != eStruct);
	if (!CGOptions::return_unions() && return_type)
		assert(return_type->eType != eUnion);
	if (is_inlined)
		out << "inline ";
	// force functions to be static if necessary
	if (CGOptions::force_globals_static()) {
		out << "static ";
	}
	rv->qfer.output_qualified_type(return_type, out);
	out << " " << get_prefixed_name(name) << "(";
	OutputFormalParamList( out );
	out << ")";
}

/*
 *
 */
void
Function::OutputForwardDecl(std::ostream &out)
{
	if (is_builtin)
		return;
	OutputHeader(out);
	out << ";";
	outputln(out);
}

/*
 *
 */
void
Function::Output(std::ostream &out)
{
	if (is_builtin)
		return;
	OutputMgr::set_curr_func(name);
	output_comment_line(out, "------------------------------------------");

    // ****************************** ExtendedCsmith ****************************** >>
    if (CGOptions::recursion()) {
        if (func_type == eImmediateRecursive)
            output_comment_line(out, "Immediate recursive function");
        else if (func_type == eMutuallyRecursive)
            output_comment_line(out, "Mutually recursive function");
    }
    // **************************************************************************** <<

	if (!CGOptions::concise()) {
		feffect.Output(out);
	}
	OutputHeader(out);
	outputln(out);

	if (CGOptions::depth_protect()) {
		out << "if (DEPTH < MAX_DEPTH) ";
		outputln(out);
	}

	FactMgr* fm = get_fact_mgr_for_func(this);
	// if nothing interesting happens, we don't want to see facts for statements
	if (!fact_changed && !union_field_read && !is_pointer_referenced()) {
		fm = 0;
	}
	body->Output(out, fm);

	if (CGOptions::depth_protect()) {
		out << "else";
		outputln(out);

		// TODO: Needs to be fixed when return types are no longer simple
		// types.

		out << "return ";
		ret_c->Output(out);
		out << ";";
		outputln(out);
	}

	outputln(out);
	outputln(out);
}

/*
 * Used for protecting depth
 */
void
Function::make_return_const()
{
	if (CGOptions::depth_protect() && need_return_stmt()) {
		assert(return_type);
		if (return_type->eType == eSimple)
			assert(return_type->simple_type != eVoid);
		Constant *c = Constant::make_random(return_type);
		ERROR_RETURN();
		this->ret_c = c;
	}
}

bool Function::need_return_stmt()
{
	return (return_type->eType != eSimple || return_type->simple_type != eVoid);
}

/*
 *
 */
void
Function::GenerateBody(const CGContext &prev_context)
{
	if (build_state != UNBUILT) {
		cerr << "warning: ignoring attempt to regenerate func" << endl;
		return;
	}

	build_state = BUILDING;
	Effect effect_accum;
	CGContext cg_context(this, prev_context.get_effect_context(), &effect_accum);
	cg_context.extend_call_chain(prev_context);
	FactMgr* fm = get_fact_mgr_for_func(this);
	for (size_t i=0; i<param.size(); i++) {
		if (param[i]->type->ptr_type != 0) {
			fm->global_facts.push_back(FactPointTo::make_fact(param[i], FactPointTo::tbd_ptr));
		}
	}
	// Fill in the Function body.
	if (is_builtin)
		body = Block::make_dummy_block(cg_context);
	else
		body = Block::make_random(cg_context);
	ERROR_RETURN();
	body->set_depth_protect(true);

	// compute the pointers that are statically referenced in the function
	// including ones referenced by its callees
	body->get_referenced_ptrs(referenced_ptrs);

	// Compute the function's externally visible effect.  Currently, this
	// is just the effect on globals.
	//effect.add_external_effect(*cg_context.get_effect_accum());
	feffect.add_external_effect(fm->map_stm_effect[body]);

	make_return_const();
	ERROR_RETURN();

	// Mark this function as built.
	build_state = BUILT;
}

void
Function::generate_body_with_known_params(const CGContext &prev_context, Effect& effect_accum)
{
	if (build_state != UNBUILT) {
		cerr << "warning: ignoring attempt to regenerate func" << endl;
		return;
	}

	build_state = BUILDING;
	FactMgr* fm = get_fact_mgr_for_func(this);
	CGContext cg_context(this, prev_context.get_effect_context(), &effect_accum);
	cg_context.extend_call_chain(prev_context);

	// inherit proper no-read/write directives from caller
	VariableSet no_reads, no_writes, must_reads, must_writes, frame_vars;
	prev_context.find_reachable_frame_vars(fm->global_facts, frame_vars);
	prev_context.get_external_no_reads_writes(no_reads, no_writes, frame_vars);
	RWDirective rwd(no_reads, no_writes, must_reads, must_writes);
	cg_context.rw_directive = &rwd;
	cg_context.flags = 0;

    // ****************************** ExtendedCsmith ****************************** >>
    if (is_recursive()) {
        // create fact manager and context suitable for this recursive function,
        // then fill in the function body
        RecursiveFactMgr* rec_fm = new RecursiveFactMgr(cg_context.call_chain, fm);
        add_recursive_fact_mgr(rec_fm);
        RecursiveCGContext* rec_cg_context = new RecursiveCGContext(&cg_context);
        add_recursive_cg_context(rec_cg_context);
        body = RecursiveBlock::make_random(*rec_cg_context);
        if (!body)
            return;
    } else {
        // fill in the function body
        body = Block::make_random(cg_context);
    }
    // **************************************************************************** <<
	ERROR_RETURN();
	body->set_depth_protect(true);

	compute_summary();

	make_return_const();
	ERROR_RETURN();

	// Mark this function as built.
	build_state = BUILT;
}

void
Function::initialize_builtin_functions()
{
	// format: return_type; builtin_func_name; (param1_type, param2_type, ...)
	// supported type: Void, Char, UChar, Short, UShort, Int,
	// 		   UInt, Long, ULong, Longlong, ULonglong
	string builtin_function_strings[] = {
		"UInt; __builtin_ia32_crc32qi; (UInt, UChar); x86",
		"Int; __builtin_clz; (UInt); x86",
		"Int; __builtin_clzl; (ULong); x86",
		"Int; __builtin_clzll; (ULonglong); x86",
		"Int; __builtin_ctz; (UInt); x86",
		"Int; __builtin_ctzl; (ULong); x86",
                "Int; __builtin_ctzll; (ULonglong); x86",
		"Int; __builtin_ffs; (Int); x86",
		"Int; __builtin_ffsl; (Long); x86",
		"Int; __builtin_ffsll; (Longlong); x86",
		"Int; __builtin_parity; (UInt); x86",
		"Int; __builtin_parityl; (ULong); x86",
		"Int; __builtin_parityll; (ULonglong); x86",
		"Int; __builtin_popcount; (UInt); x86",
		"Int; __builtin_popcountl; (ULong); x86",
		"Int; __builtin_popcountll; (ULonglong); x86",
		"UInt; __builtin_bswap32; (UInt); x86",
		"ULonglong; __builtin_bswap64; (ULonglong); x86",
		"Int; __builtin_ctzs; (UShort); clang",
		"Int; __builtin_clzs; (UShort); clang",
		"UShort; __builtin_bswap16; (UShort); ppc | clang"
	};

	int cnt = sizeof(builtin_function_strings) / sizeof(builtin_function_strings[0]);
	for (int i = 0; i < cnt; i++) {
		make_builtin_function(builtin_function_strings[i]);
	}
}

void
Function::make_builtin_function(const string &function_string)
{
	vector<string> v;
	StringUtils::split_string(function_string, v, ";");
	if (v.size() == 4) {
		if (!CGOptions::enabled_builtin(v[3]))
			return;
	}
	else if (v.size() == 3) {
		if (!CGOptions::enabled_builtin("generic"))
			return;
	}
	else {
		assert(0 && "Invalid builtin function format!");
	}

	const Type *ty = Type::get_type_from_string(v[0]);
	Function *f = new Function(v[1], ty, /*is_builtin*/true);

	// dummy variable representing return variable, we don't care about the type, so use 0
	string rvname = f->name + "_" + "rv";
	CVQualifiers ret_qfer = CVQualifiers::random_qualifiers(ty);
	f->rv = Variable::CreateVariable(rvname, ty, NULL, &ret_qfer);

	// create a fact manager for this function, with empty global facts
	FactMgr* fm = new FactMgr(f);
	FMList.push_back(fm);

	GenerateParameterListFromString(*f, StringUtils::get_substring(v[2], '(', ')'));
	f->GenerateBody(CGContext::get_empty_context());

	// update global facts to merged facts at all possible function exits
	fm->global_facts = fm->map_facts_out[f->body];
	f->body->add_back_return_facts(fm, fm->global_facts);

	// collect info about global dangling pointers
	fm->find_dangling_global_ptrs(f);
	++builtin_functions_cnt;
}

void
Function::compute_summary(void)
{
	FactMgr* fm = get_fact_mgr_for_func(this);
	// compute the pointers that are statically referenced in the function
	// including ones referenced by its callees
	body->get_referenced_ptrs(referenced_ptrs);

	// Compute the function's externally visible effect.
	//effect.add_external_effect(*cg_context.get_effect_accum());
	feffect.add_external_effect(fm->map_stm_effect[body]);

	// determine whether an union field is read
	union_field_read = body->read_union_field();
}

/*
 *
 */
void
GenerateFunctions(void)
{
	FactMgr::add_interested_facts(CGOptions::interested_facts());
	if (CGOptions::builtins())
		Function::initialize_builtin_functions();
	// -----------------
	// Create a basic first function, then generate a random graph from there.
	/* Function *first = */ Function::make_first();
	ERROR_RETURN();

	// -----------------
	// Create body of each function, continue until no new functions are created.
	for (cur_func_idx = 0; cur_func_idx < FuncListSize(); cur_func_idx++) {
		// Dynamically adds new functions to the end of the list..
		if (FuncList[cur_func_idx]->is_built() == false) {
			FuncList[cur_func_idx]->GenerateBody(CGContext::get_empty_context());
			ERROR_RETURN();
		}
	}
	FactPointTo::aggregate_all_pointto_sets();
	ExtensionMgr::GenerateValues();
}

/*
 *
 */
static int
OutputForwardDecl(Function *func, std::ostream *pOut)
{
	func->OutputForwardDecl(*pOut);
	return 0;
}

/*
 *
 */
static int
OutputFunction(Function *func, std::ostream *pOut)
{
	func->Output(*pOut);
	return 0;
}

/*
 *
 */
void
OutputForwardDeclarations(std::ostream &out)
{
	outputln(out);
	outputln(out);
	output_comment_line(out, "--- FORWARD DECLARATIONS ---");
	for_each(FuncList.begin(), FuncList.end(),
			 std::bind2nd(std::ptr_fun(OutputForwardDecl), &out));
}

/*
 *
 */
void
OutputFunctions(std::ostream &out)
{
	outputln(out);
	outputln(out);
	output_comment_line(out, "--- FUNCTIONS ---");
	for_each(FuncList.begin(), FuncList.end(),
			 std::bind2nd(std::ptr_fun(OutputFunction), &out));
}

/*
 * Delete a single function
 */
int
Function::deleteFunction(Function* func)
{
	if (func) {
		delete func;
		func = 0;
	}
	return 0;
}

/*
 * Release all dynamic memory
 */
void
Function::doFinalization(void)
{
	for_each(FuncList.begin(), FuncList.end(), std::ptr_fun(deleteFunction));

	FuncList.clear();

	std::vector<FactMgr*>::iterator i;
	for (i = FMList.begin(); i != FMList.end(); ++i) {
		delete (*i);
	}
	FMList.clear();

    // ****************************** ExtendedCsmith ****************************** >>
    std::vector<RecursiveFactMgr*>::iterator iter_fm;
    for (iter_fm = RFMList.begin(); iter_fm != RFMList.end(); iter_fm++) {
        delete (*iter_fm);
    }
    RFMList.clear();

    std::vector<RecursiveCGContext*>::iterator iter_cgc;
    for (iter_cgc = RCGCList.begin(); iter_cgc != RCGCList.end(); iter_cgc++) {
        delete (*iter_cgc);
    }
    RCGCList.clear();
    // **************************************************************************** <<

	FactMgr::doFinalization();
}

Function::~Function()
{
	param.clear();

	assert(stack.empty());

	if (body) {
		delete body;
		body = NULL;
	}

	if (CGOptions::depth_protect() && ret_c) {
		delete ret_c;
		ret_c = NULL;
	}
}

///////////////////////////////////////////////////////////////////////////////

// Local Variables:
// c-basic-offset: 4
// tab-width: 4
// End:

// End of file.


text:
using namespace std;

// This function fills in a Person message based on user input.
void PromptForAddress(tutorial::Person* person) {
    cout << "Enter person ID number: ";
    int id;
    cin >> id;
    person->set_id(id);
    cin.ignore(256, '\n');

    cout << "Enter name: ";
    getline(cin, *person->mutable_name());

    cout << "Enter email address (blank for none): ";
    string email;
    getline(cin, email);
    if (!email.empty()) {
        person->set_email(email);
    }

    while (true) {
        cout << "Enter a phone number (or leave blank to finish): ";
        string number;
        getline(cin, number);
        if (number.empty()) {
            break;
        }

        tutorial::Person::PhoneNumber* phone_number = person->add_phone();
        phone_number->set_number(number);

        cout << "Is this a mobile, home, or work phone? ";
        string type;
        getline(cin, type);
        if (type == "mobile") {
            phone_number->set_type(tutorial::Person::MOBILE);
        } else if (type == "home") {
            phone_number->set_type(tutorial::Person::HOME);
        } else if (type == "work") {
            phone_number->set_type(tutorial::Person::WORK);
        } else {
            cout << "Unknown phone type.  Using default." << endl;
        }
    }
}

// Main function:  Reads the entire address book from a file,
//   adds one person based on user input, then writes it back out to the same
//   file.
int main(int argc, char* argv[]) {
    // Verify that the version of the library that we linked against is
    // compatible with the version of the headers we compiled against.
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    if (argc != 2) {
        cerr << "Usage:  " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
        return -1;
    }

    tutorial::AddressBook address_book;

    {
        // Read the existing address book.
        fstream input(argv[1], ios::in | ios::binary);
        if (!input) {
            cout << argv[1] << ": File not found.  Creating a new file." << endl;
        } else if (!address_book.ParseFromIstream(&input)) {
            cerr << "Failed to parse address book." << endl;
            return -1;
        }
    }

    // Add an address.
    PromptForAddress(address_book.add_person());

    {
        // Write the new address book back to disk.
        fstream output(argv[1], ios::out | ios::trunc | ios::binary);
        if (!address_book.SerializeToOstream(&output)) {
            cerr << "Failed to write address book." << endl;
            return -1;
        }
    }

    // Optional:  Delete all global objects allocated by libprotobuf.
    google::protobuf::ShutdownProtobufLibrary();

    return 0;
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using NullGuard;

public class SimpleClass
{
    public SimpleClass()
    {
    }

    // Why would anyone place an out parameter on a ctor?! I don't know, but I'll support your idiocy.
    public SimpleClass(out string nonNullOutArg)
    {
        nonNullOutArg = null;
    }

    public SimpleClass(string nonNullArg, [AllowNull] string nullArg)
    {
        Console.WriteLine(nonNullArg + " " + nullArg);
    }

    public void SomeMethod(string nonNullArg, [AllowNull] string nullArg)
    {
        Console.WriteLine(nonNullArg);
    }

    public string NonNullProperty { get; set; }

    [AllowNull]
    public string NullProperty { get; set; }

    public string PropertyAllowsNullGetButDoesNotAllowNullSet { [return: AllowNull] get; set; }

    public string PropertyAllowsNullSetButDoesNotAllowNullGet { get; [param: AllowNull] set; }

    public int? NonNullNullableProperty { get; set; }

    public string MethodWithReturnValue(bool returnNull)
    {
        return returnNull ? null : "";
    }

    public void MethodWithRef(ref object returnNull)
    {
    }

    public void MethodWithGeneric<T>(T returnNull)
    {
    }

    public void MethodWithGenericRef<T>(ref T returnNull)
    {
    }

    [return: AllowNull]
    public string MethodAllowsNullReturnValue()
    {
        return null;
    }

    [CanBeNull]
    public string MethodWithCanBeNullResult()
    {
        return null;
    }

    public void MethodWithOutValue(out string nonNullOutArg)
    {
        nonNullOutArg = null;
    }

    public void MethodWithAllowedNullOutValue([AllowNull]out string nonNullOutArg)
    {
        nonNullOutArg = null;
    }

    public void PublicWrapperOfPrivateMethod()
    {
        SomePrivateMethod(null);
    }

    void SomePrivateMethod(string x)
    {
        Console.WriteLine(x);
    }

    public void MethodWithTwoRefs(ref string first, ref string second)
    {
    }

    public void MethodWithTwoOuts(out string first, out string second)
    {
        first = null;
        second = null;
    }

    public void MethodWithOptionalParameter(string optional = null)
    {
    }

    public void MethodWithOptionalParameterWithNonNullDefaultValue(string optional = "default")
    {
    }

    public void MethodWithOptionalParameterWithNonNullDefaultValueButAllowNullAttribute([AllowNull] string optional = "default")
    {
    }

    public void MethodWithGenericOut<T>(out T item)
    {
        item = default(T);
    }

    public T MethodWithGenericReturn<T>(bool returnNull)
    {
        return returnNull ? default(T) : Activator.CreateInstance<T>();
    }

    public object MethodWithOutAndReturn(out string prefix)
    {
        prefix = null;
        return null;
    }

    public void MethodWithExistingArgumentGuard(string x)
    {
        if (string.IsNullOrEmpty(x))
            throw new ArgumentException("x is null or empty.", "x");

        Console.WriteLine(x);
    }

    public void MethodWithExistingArgumentNullGuard(string x)
    {
        if (string.IsNullOrEmpty(x))
            throw new ArgumentNullException("x");

        Console.WriteLine(x);
    }

    public void MethodWithExistingArgumentNullGuardWithMessage(string x)
    {
        if (string.IsNullOrEmpty(x))
            throw new ArgumentNullException("x", "x is null or empty.");

        Console.WriteLine(x);
    }

    public string ReturnValueChecksWithBranchToRetInstruction()
    {
        // This is a regression test scenario for the "Branch to RET" issue described in https://github.com/Fody/NullGuard/issues/57.

        // It is important that the return value is assinged *before* the branch, otherwise the C# compiler emits
        // instructions before the RET instructions, which wouldn't trigger the original issue.
        string returnValue = null;

        // The following, not-reachable, branch will jump directly to the RET statement (at least with Roslyn 1.0 with
        // enabled optimizations flag) which triggers the issue (the return value checks will be skipped).
        if ("".Length == 42)
            throw new Exception("Not reachable");

        return returnValue;
    }

    public void OutValueChecksWithBranchToRetInstruction(out string outParam)
    {
        // This is the same scenario as above, but for out parameters.

        outParam = null;

        if ("".Length == 42)
            throw new Exception("Not reachable");
    }

    public string GetterReturnValueChecksWithBranchToRetInstruction
    {
        get
        {
            // This is the same scenario as above, but for property getters.

            string returnValue = null;

            if ("".Length == 42)
                throw new Exception("Not reachable");

            return returnValue;
        }
    }

    public void OutValueChecksWithRetInstructionAsSwitchCase(int i, out string outParam)
    {
        // This is the same scenario as above, but with a SWITCH instruction with branch targets to RET
        // instructions (they are handled specially).
        // Note that its important to have more than sections to prove that all sections with only a RET instruction are handled.

        outParam = null;
        switch (i)
        {
            case 0:
                return;
            case 1:
                Console.WriteLine("1");
                break;
            case 2:
                return;
            case 3:
                Console.WriteLine("3");
                break;
        }
    }
}


text:
wlatp
=====

who looks at the page

Concepts
==

fancy UI with D3 and XXP Data.


text:
var Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		if(typeof test == 'function'){
			this.options = $H(options);
			this._test = test;
		} else {
			this.options = $H(test);
			this._test = function(){return true};
		}
		this.error = error || 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return (this._test(v,elm) && this.options.all(function(p){
			return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value) : true;
		}));
	}
}
Validator.methods = {
	pattern : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || opt.test(v)},
	minLength : function(v,elm,opt) {return v.length >= opt},
	maxLength : function(v,elm,opt) {return v.length <= opt},
	min : function(v,elm,opt) {return v >= parseFloat(opt)},
	max : function(v,elm,opt) {return v <= parseFloat(opt)},
	notOneOf : function(v,elm,opt) {return $A(opt).all(function(value) {
		return v != value;
	})},
	oneOf : function(v,elm,opt) {return $A(opt).any(function(value) {
		return v == value;
	})},
	is : function(v,elm,opt) {return v == opt},
	isNot : function(v,elm,opt) {return v != opt},
	equalToField : function(v,elm,opt) {return v == $F(opt)},
	notEqualToField : function(v,elm,opt) {return v != $F(opt)},
	include : function(v,elm,opt) {return $A(opt).all(function(value) {
		return Validation.get(value).test(v,elm);
	})}
}

var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var callback = this.options.onElementValidate;
			Form.getElements(this.form).each(function(input) { // Thanks Mike!
				Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()) Event.stop(ev);
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); }).all();
		}
		if(!result && this.options.focusOnError) {
			Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
		}
		this.options.onFormValidate(result, this.form);
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

Object.extend(Validation, {
	validate : function(elm, options){
		options = Object.extend({
			useTitle : false,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		var cn = elm.classNames();
		return result = cn.all(function(value) {
			var test = Validation.test(value,elm,options.useTitle);
			options.onElementValidate(test, elm);
			return test;
		});
	},
	test : function(name, elm, useTitle) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
		try {
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(advice == null) {
					var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					advice = '
' + errorMsg + '
'
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) {
								new Insertion.Bottom(p, advice);
							} else {
								new Insertion.After(elm, advice);
							}
							break;
						default:
							new Insertion.After(elm, advice);
				    }
					advice = Validation.getAdvice(name, elm);
				}
				if(typeof Effect == 'undefined') {
					advice.style.display = 'block';
				} else {
					new Effect.Appear(advice, {duration : 1 });
				}
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
			return false;
		} else {
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
		elm = $(elm);
		var cn = elm.classNames();
		cn.each(function(value) {
			var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			elm.removeClassName('validation-failed');
			elm.removeClassName('validation-passed');
		});
	},
	add : function(className, error, test, options) {
		var nv = {};
		nv[className] = new Validator(className, error, test, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var nv = {};
		$A(validators).each(function(value) {
				nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
			});
		Object.extend(Validation.methods, nv);
	},
	get : function(name) {
		return  Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
	},
	methods : {
		'_LikeNoIDIEverSaw_' : new Validator('_LikeNoIDIEverSaw_','',{})
	}
});

Validation.add('IsEmpty', '', function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});

Validation.addAllThese([
	['required', 'This is a required field.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', 'Please enter a valid number in this field.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', 'Please use letters only (a-z) in this field.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-date', 'Please enter a valid date.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-email', 'Please enter a valid email address. For example fred@domain.com .', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
			}],
	['validate-url', 'Please enter a valid URL.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
			}],
	['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
				if(!regex.test(v)) return false;
				var d = new Date(v.replace(regex, '$2/$1/$3'));
				return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) &&
							(parseInt(RegExp.$1, 10) == d.getDate()) &&
							(parseInt(RegExp.$3, 10) == d.getFullYear() );
			}],
	['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', function(v) {
				// [$]1[##][,###]+[.##]
				// [$]1###+[.##]
				// [$]0.##
				// [$].##
				return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
			}],
	['validate-selection', 'Please make a selection', function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
	['validate-one-required', 'Please select one of the above options.', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}]
]);


text:
!function(_e){var e=function(){return _e()["default"]};if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.$=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/api";
var extend = _dereq_('./util').extend;
var api = {},
    apiNodeList = {},
    $ = {};
var array = _dereq_('./array');
var attr = _dereq_('./attr');
var class_ = _dereq_('./class');
var contains = _dereq_('./contains');
var css = _dereq_('./css');
var data = _dereq_('./data');
var dom = _dereq_('./dom');
var dom_extra = _dereq_('./dom_extra');
var event = _dereq_('./event');
var html = _dereq_('./html');
var mode = _dereq_('./mode');
var noconflict = _dereq_('./noconflict');
var ready = _dereq_('./ready');
var selector = _dereq_('./selector');
var selector_extra = _dereq_('./selector_extra');
var trigger = _dereq_('./trigger');
var type = _dereq_('./type');
if (typeof selector !== 'undefined') {
  $ = selector.$;
  $.matches = selector.matches;
  api.find = selector.find;
  api.closest = selector.closest;
}
extend($, contains, mode, noconflict, type);
extend(api, array, attr, class_, css, data, dom, dom_extra, event, html, ready, selector_extra, trigger);
extend(apiNodeList, array);
$.version = '0.8.0';
$.extend = extend;
$.fn = api;
$.fnList = apiNodeList;
var $__default = $;
module.exports = {
  default: $__default,
  __esModule: true
};

},{"./array":2,"./attr":3,"./class":4,"./contains":5,"./css":6,"./data":7,"./dom":8,"./dom_extra":9,"./event":10,"./html":11,"./mode":13,"./noconflict":14,"./ready":15,"./selector":16,"./selector_extra":17,"./trigger":18,"./type":19,"./util":20}],2:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/array";
var $__0 = _dereq_('./util'),
    _each = $__0.each,
    toArray = $__0.toArray;
var $__0 = _dereq_('./selector'),
    $ = $__0.$,
    matches = $__0.matches;
var ArrayProto = Array.prototype;
var every = ArrayProto.every;
function filter(selector, thisArg) {
  var callback = typeof selector === 'function' ? selector : function(element) {
    return matches(element, selector);
  };
  return $(ArrayProto.filter.call(this, callback, thisArg));
}
function forEach(callback, thisArg) {
  return _each(this, callback, thisArg);
}
var each = forEach;
var indexOf = ArrayProto.indexOf;
var map = ArrayProto.map;
var pop = ArrayProto.pop;
var push = ArrayProto.push;
function reverse() {
  return $(toArray(this).reverse());
}
var shift = ArrayProto.shift;
var some = ArrayProto.some;
var unshift = ArrayProto.unshift;
;
module.exports = {
  each: each,
  every: every,
  filter: filter,
  forEach: forEach,
  indexOf: indexOf,
  map: map,
  pop: pop,
  push: push,
  reverse: reverse,
  shift: shift,
  some: some,
  unshift: unshift,
  __esModule: true
};

},{"./selector":16,"./util":20}],3:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/attr";
var each = _dereq_('./util').each;
function attr(key, value) {
  if (typeof key === 'string' && typeof value === 'undefined') {
    var element = this.nodeType ? this : this[0];
    return element ? element.getAttribute(key) : undefined;
  }
  each(this, function(element) {
    if (typeof key === 'object') {
      for (var attr in key) {
        element.setAttribute(attr, key[attr]);
      }
    } else {
      element.setAttribute(key, value);
    }
  });
  return this;
}
function removeAttr(key) {
  each(this, function(element) {
    element.removeAttribute(key);
  });
  return this;
}
;
module.exports = {
  attr: attr,
  removeAttr: removeAttr,
  __esModule: true
};

},{"./util":20}],4:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/class";
var $__0 = _dereq_('./util'),
    makeIterable = $__0.makeIterable,
    each = $__0.each;
function addClass(value) {
  if (value && value.length) {
    each(value.split(' '), function(className) {
      each(this, function(element) {
        element.classList.add(className);
      });
    }.bind(this));
  }
  return this;
}
function removeClass(value) {
  if (value && value.length) {
    each(value.split(' '), function(className) {
      each(this, function(element) {
        element.classList.remove(className);
      });
    }.bind(this));
  }
  return this;
}
function toggleClass(value) {
  if (value && value.length) {
    each(value.split(' '), function(className) {
      each(this, function(element) {
        element.classList.toggle(className);
      });
    }.bind(this));
  }
  return this;
}
function hasClass(value) {
  return makeIterable(this).some(function(element) {
    return element.classList.contains(value);
  });
}
;
module.exports = {
  addClass: addClass,
  removeClass: removeClass,
  toggleClass: toggleClass,
  hasClass: hasClass,
  __esModule: true
};

},{"./util":20}],5:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/contains";
function contains(container, element) {
  if (!container || !element || container === element) {
    return false;
  } else if (container.contains) {
    return container.contains(element);
  } else if (container.compareDocumentPosition) {
    return !(container.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_DISCONNECTED);
  }
  return false;
}
;
module.exports = {
  contains: contains,
  __esModule: true
};

},{}],6:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/css";
var each = _dereq_('./util').each;
function isNumeric(value) {
  return !isNaN(parseFloat(value)) && isFinite(value);
}
function camelize(value) {
  return value.replace(/-([\da-z])/gi, function(matches, letter) {
    return letter.toUpperCase();
  });
}
function dasherize(value) {
  return value.replace(/([a-z\d])([A-Z])/g, '$1-$2').toLowerCase();
}
function css(key, value) {
  var styleProps,
      prop,
      val;
  if (typeof key === 'string') {
    key = camelize(key);
    if (typeof value === 'undefined') {
      var element = this.nodeType ? this : this[0];
      if (element) {
        val = element.style[key];
        return isNumeric(val) ? parseFloat(val) : val;
      }
      return undefined;
    }
    styleProps = {};
    styleProps[key] = value;
  } else {
    styleProps = key;
    for (prop in styleProps) {
      val = styleProps[prop];
      delete styleProps[prop];
      styleProps[camelize(prop)] = val;
    }
  }
  each(this, function(element) {
    for (prop in styleProps) {
      if (styleProps[prop] || styleProps[prop] === 0) {
        element.style[prop] = styleProps[prop];
      } else {
        element.style.removeProperty(dasherize(prop));
      }
    }
  });
  return this;
}
;
module.exports = {
  css: css,
  __esModule: true
};

},{"./util":20}],7:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/data";
var each = _dereq_('./util').each;
var dataKeyProp = '__domtastic_data__';
function data(key, value) {
  if (typeof key === 'string' && typeof value === 'undefined') {
    var element = this.nodeType ? this : this[0];
    return element && element[dataKeyProp] ? element[dataKeyProp][key] : undefined;
  }
  each(this, function(element) {
    element[dataKeyProp] = element[dataKeyProp] || {};
    element[dataKeyProp][key] = value;
  });
  return this;
}
function prop(key, value) {
  if (typeof key === 'string' && typeof value === 'undefined') {
    var element = this.nodeType ? this : this[0];
    return element && element ? element[key] : undefined;
  }
  each(this, function(element) {
    element[key] = value;
  });
  return this;
}
;
module.exports = {
  data: data,
  prop: prop,
  __esModule: true
};

},{"./util":20}],8:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/dom";
var toArray = _dereq_('./util').toArray;
function append(element) {
  if (this instanceof Node) {
    if (typeof element === 'string') {
      this.insertAdjacentHTML('beforeend', element);
    } else {
      if (element instanceof Node) {
        this.appendChild(element);
      } else {
        var elements = element instanceof NodeList ? toArray(element) : element;
        elements.forEach(this.appendChild.bind(this));
      }
    }
  } else {
    var l = this.length;
    while (l--) {
      var elm = l === 0 ? element : _clone(element);
      append.call(this[l], elm);
    }
  }
  return this;
}
function prepend(element) {
  if (this instanceof Node) {
    if (typeof element === 'string') {
      this.insertAdjacentHTML('afterbegin', element);
    } else {
      if (element instanceof Node) {
        this.insertBefore(element, this.firstChild);
      } else {
        var elements = element instanceof NodeList ? toArray(element) : element;
        elements.reverse().forEach(prepend.bind(this));
      }
    }
  } else {
    var l = this.length;
    while (l--) {
      var elm = l === 0 ? element : _clone(element);
      prepend.call(this[l], elm);
    }
  }
  return this;
}
function before(element) {
  if (this instanceof Node) {
    if (typeof element === 'string') {
      this.insertAdjacentHTML('beforebegin', element);
    } else {
      if (element instanceof Node) {
        this.parentNode.insertBefore(element, this);
      } else {
        var elements = element instanceof NodeList ? toArray(element) : element;
        elements.forEach(before.bind(this));
      }
    }
  } else {
    var l = this.length;
    while (l--) {
      var elm = l === 0 ? element : _clone(element);
      before.call(this[l], elm);
    }
  }
  return this;
}
function after(element) {
  if (this instanceof Node) {
    if (typeof element === 'string') {
      this.insertAdjacentHTML('afterend', element);
    } else {
      if (element instanceof Node) {
        this.parentNode.insertBefore(element, this.nextSibling);
      } else {
        var elements = element instanceof NodeList ? toArray(element) : element;
        elements.reverse().forEach(after.bind(this));
      }
    }
  } else {
    var l = this.length;
    while (l--) {
      var elm = l === 0 ? element : _clone(element);
      after.call(this[l], elm);
    }
  }
  return this;
}
function clone() {
  return $(_clone(this));
}
function _clone(element) {
  if (typeof element === 'string') {
    return element;
  } else if (element instanceof Node) {
    return element.cloneNode(true);
  } else if ('length' in element) {
    return [].map.call(element, function(el) {
      return el.cloneNode(true);
    });
  }
  return element;
}
;
module.exports = {
  append: append,
  prepend: prepend,
  before: before,
  after: after,
  clone: clone,
  __esModule: true
};

},{"./util":20}],9:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/dom_extra";
var each = _dereq_('./util').each;
var $__0 = _dereq_('./dom'),
    append = $__0.append,
    before = $__0.before,
    after = $__0.after;
var $ = _dereq_('./selector').$;
function appendTo(element) {
  var context = typeof element === 'string' ? $(element) : element;
  append.call(context, this);
  return this;
}
function empty() {
  return each(this, function(element) {
    element.innerHTML = '';
  });
}
function remove() {
  return each(this, function(element) {
    if (element.parentNode) {
      element.parentNode.removeChild(element);
    }
  });
}
function replaceWith() {
  return before.apply(this, arguments).remove();
}
function text(value) {
  if (value == null) {
    return this[0].textContent;
  }
  each(this, function(element) {
    element.textContent = '' + value;
  });
  return this;
}
function val(value) {
  if (value == null) {
    return this[0].value;
  }
  each(this, function(element) {
    element.value = value;
  });
  return this;
}
;
module.exports = {
  appendTo: appendTo,
  empty: empty,
  remove: remove,
  replaceWith: replaceWith,
  text: text,
  val: val,
  __esModule: true
};

},{"./dom":8,"./selector":16,"./util":20}],10:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/event";
var each = _dereq_('./util').each;
var closest = _dereq_('./selector').closest;
function on(eventNames, selector, handler, useCapture) {
  if (typeof selector === 'function') {
    handler = selector;
    selector = null;
  }
  var parts,
      namespace,
      eventListener;
  eventNames.split(' ').forEach(function(eventName) {
    parts = eventName.split('.');
    eventName = parts[0] || null;
    namespace = parts[1] || null;
    eventListener = proxyHandler(handler);
    each(this, function(element) {
      if (selector) {
        eventListener = delegateHandler.bind(element, selector, eventListener);
      }
      element.addEventListener(eventName, eventListener, useCapture || false);
      getHandlers(element).push({
        eventName: eventName,
        handler: handler,
        eventListener: eventListener,
        selector: selector,
        namespace: namespace
      });
    });
  }, this);
  return this;
}
function off() {
  var eventNames = arguments[0] !== (void 0) ? arguments[0] : '';
  var selector = arguments[1];
  var handler = arguments[2];
  var useCapture = arguments[3];
  if (typeof selector === 'function') {
    handler = selector;
    selector = null;
  }
  var parts,
      namespace,
      handlers;
  eventNames.split(' ').forEach(function(eventName) {
    parts = eventName.split('.');
    eventName = parts[0] || null;
    namespace = parts[1] || null;
    each(this, function(element) {
      handlers = getHandlers(element);
      each(handlers.filter(function(item) {
        return ((!eventName || item.eventName === eventName) && (!namespace || item.namespace === namespace) && (!handler || item.handler === handler) && (!selector || item.selector === selector));
      }), function(item) {
        element.removeEventListener(item.eventName, item.eventListener, useCapture || false);
        handlers.splice(handlers.indexOf(item), 1);
      });
      if (!eventName && !namespace && !selector && !handler) {
        clearHandlers(element);
      } else if (handlers.length === 0) {
        clearHandlers(element);
      }
    });
  }, this);
  return this;
}
function delegate(selector, eventName, handler) {
  return on.call(this, eventName, selector, handler);
}
function undelegate(selector, eventName, handler) {
  return off.call(this, eventName, selector, handler);
}
var eventKeyProp = '__domtastic_event__';
var id = 1;
var handlers = {};
var unusedKeys = [];
function getHandlers(element) {
  if (!element[eventKeyProp]) {
    element[eventKeyProp] = unusedKeys.length === 0 ? ++id : unusedKeys.pop();
  }
  var key = element[eventKeyProp];
  return handlers[key] || (handlers[key] = []);
}
function clearHandlers(element) {
  var key = element[eventKeyProp];
  if (handlers[key]) {
    handlers[key] = null;
    element[key] = null;
    unusedKeys.push(key);
  }
}
function proxyHandler(handler) {
  return function(event) {
    handler.call(this, augmentEvent(event), event.detail);
  };
}
var augmentEvent = (function() {
  var methodName,
      eventMethods = {
        preventDefault: 'isDefaultPrevented',
        stopImmediatePropagation: 'isImmediatePropagationStopped',
        stopPropagation: 'isPropagationStopped'
      },
      noop = (function() {}),
      returnTrue = (function() {
        return true;
      }),
      returnFalse = (function() {
        return false;
      });
  return function(event) {
    if (!event.isDefaultPrevented || event.stopImmediatePropagation || event.stopPropagation) {
      for (methodName in eventMethods) {
        (function(methodName, testMethodName, originalMethod) {
          event[methodName] = function() {
            this[testMethodName] = returnTrue;
            return originalMethod.apply(this, arguments);
          };
          event[testMethodName] = returnFalse;
        }(methodName, eventMethods[methodName], event[methodName] || noop));
      }
      if (event._preventDefault) {
        event.preventDefault();
      }
    }
    return event;
  };
})();
function delegateHandler(selector, handler, event) {
  var eventTarget = event._target || event.target,
      currentTarget = closest.call([eventTarget], selector, this)[0];
  if (currentTarget && currentTarget !== this) {
    if (currentTarget === eventTarget || !(event.isPropagationStopped && event.isPropagationStopped())) {
      handler.call(currentTarget, event);
    }
  }
}
var bind = on,
    unbind = off;
;
module.exports = {
  on: on,
  off: off,
  delegate: delegate,
  undelegate: undelegate,
  bind: bind,
  unbind: unbind,
  __esModule: true
};

},{"./selector":16,"./util":20}],11:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/html";
var each = _dereq_('./util').each;
function html(fragment) {
  if (typeof fragment !== 'string') {
    var element = this.nodeType ? this : this[0];
    return element ? element.innerHTML : undefined;
  }
  each(this, function(element) {
    element.innerHTML = fragment;
  });
  return this;
}
;
module.exports = {
  html: html,
  __esModule: true
};

},{"./util":20}],12:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/index";
var $ = _dereq_('./api').default;
var $__default = $;
module.exports = {
  default: $__default,
  __esModule: true
};

},{"./api":1}],13:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/mode";
var global = _dereq_('./util').global;
var isNative = false;
function native() {
  var goNative = arguments[0] !== (void 0) ? arguments[0] : true;
  var wasNative = isNative;
  isNative = goNative;
  if (global.$) {
    global.$.isNative = isNative;
  }
  if (!wasNative && isNative) {
    augmentNativePrototypes(this.fn, this.fnList);
  }
  if (wasNative && !isNative) {
    unaugmentNativePrototypes(this.fn, this.fnList);
  }
  return isNative;
}
var NodeProto = typeof Node !== 'undefined' && Node.prototype,
    NodeListProto = typeof NodeList !== 'undefined' && NodeList.prototype;
function augment(obj, key, value) {
  if (!obj.hasOwnProperty(key)) {
    Object.defineProperty(obj, key, {
      value: value,
      configurable: true,
      enumerable: false
    });
  }
}
var unaugment = (function(obj, key) {
  delete obj[key];
});
function augmentNativePrototypes(methodsNode, methodsNodeList) {
  var key;
  for (key in methodsNode) {
    augment(NodeProto, key, methodsNode[key]);
    augment(NodeListProto, key, methodsNode[key]);
  }
  for (key in methodsNodeList) {
    augment(NodeListProto, key, methodsNodeList[key]);
  }
}
function unaugmentNativePrototypes(methodsNode, methodsNodeList) {
  var key;
  for (key in methodsNode) {
    unaugment(NodeProto, key);
    unaugment(NodeListProto, key);
  }
  for (key in methodsNodeList) {
    unaugment(NodeListProto, key);
  }
}
;
module.exports = {
  isNative: isNative,
  native: native,
  __esModule: true
};

},{"./util":20}],14:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/noconflict";
var global = _dereq_('./util').global;
var previousLib = global.$;
function noConflict() {
  global.$ = previousLib;
  return this;
}
;
module.exports = {
  noConflict: noConflict,
  __esModule: true
};

},{"./util":20}],15:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/ready";
function ready(handler) {
  if (/complete|loaded|interactive/.test(document.readyState) && document.body) {
    handler();
  } else {
    document.addEventListener('DOMContentLoaded', handler, false);
  }
  return this;
}
;
module.exports = {
  ready: ready,
  __esModule: true
};

},{}],16:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/selector";
var $__0 = _dereq_('./util'),
    global = $__0.global,
    makeIterable = $__0.makeIterable;
var isPrototypeSet = false,
    reFragment = /^\s*<(\w+|!)[^>]*>/,
    reSingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
    reSimpleSelector = /^[\.#]?[\w-]*$/;
function $(selector) {
  var context = arguments[1] !== (void 0) ? arguments[1] : document;
  var collection;
  if (!selector) {
    collection = document.querySelectorAll(null);
  } else if (selector instanceof Wrapper) {
    return selector;
  } else if (typeof selector !== 'string') {
    collection = makeIterable(selector);
  } else if (reFragment.test(selector)) {
    collection = createFragment(selector);
  } else {
    context = typeof context === 'string' ? document.querySelector(context) : context.length ? context[0] : context;
    collection = querySelector(selector, context);
  }
  return $.isNative ? collection : wrap(collection);
}
function find(selector) {
  return $(selector, this);
}
function closest(selector, context) {
  var node = this[0];
  for (; node.nodeType !== node.DOCUMENT_NODE && node !== context; node = node.parentNode) {
    if (matches(node, selector)) {
      return $(node);
    }
  }
  return $();
}
var matches = (function() {
  var context = typeof Element !== 'undefined' ? Element.prototype : global,
      _matches = context.matches || context.matchesSelector || context.mozMatchesSelector || context.webkitMatchesSelector || context.msMatchesSelector || context.oMatchesSelector;
  return function(element, selector) {
    return _matches.call(element, selector);
  };
})();
function querySelector(selector, context) {
  var isSimpleSelector = reSimpleSelector.test(selector);
  if (isSimpleSelector && !$.isNative) {
    if (selector[0] === '#') {
      var element = (context.getElementById ? context : document).getElementById(selector.slice(1));
      return element ? [element] : [];
    }
    if (selector[0] === '.') {
      return context.getElementsByClassName(selector.slice(1));
    }
    return context.getElementsByTagName(selector);
  }
  return context.querySelectorAll(selector);
}
function createFragment(html) {
  if (reSingleTag.test(html)) {
    return [document.createElement(RegExp.$1)];
  }
  var elements = [],
      container = document.createElement('div'),
      children = container.childNodes;
  container.innerHTML = html;
  for (var i = 0,
      l = children.length; i < l; i++) {
    elements.push(children[i]);
  }
  return elements;
}
function wrap(collection) {
  if (!isPrototypeSet) {
    Wrapper.prototype = $.fn;
    Wrapper.prototype.constructor = Wrapper;
    isPrototypeSet = true;
  }
  return new Wrapper(collection);
}
function Wrapper(collection) {
  var i = 0,
      length = collection.length;
  for (; i < length; ) {
    this[i] = collection[i++];
  }
  this.length = length;
}
;
module.exports = {
  $: $,
  find: find,
  closest: closest,
  matches: matches,
  __esModule: true
};

},{"./util":20}],17:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/selector_extra";
var $__0 = _dereq_('./util'),
    each = $__0.each,
    toArray = $__0.toArray;
var $__0 = _dereq_('./selector'),
    $ = $__0.$,
    matches = $__0.matches;
function children(selector) {
  var nodes = [];
  each(this, function(element) {
    if (element.children) {
      each(element.children, function(child) {
        if (!selector || (selector && matches(child, selector))) {
          nodes.push(child);
        }
      });
    }
  });
  return $(nodes);
}
function contents() {
  var nodes = [];
  each(this, function(element) {
    nodes.push.apply(nodes, toArray(element.childNodes));
  });
  return $(nodes);
}
function eq(index) {
  return slice.call(this, index, index + 1);
}
function get(index) {
  return this[index];
}
function parent(selector) {
  var nodes = [];
  each(this, function(element) {
    if (!selector || (selector && matches(element.parentNode, selector))) {
      nodes.push(element.parentNode);
    }
  });
  return $(nodes);
}
function slice(start, end) {
  return $([].slice.apply(this, arguments));
}
;
module.exports = {
  children: children,
  contents: contents,
  eq: eq,
  get: get,
  parent: parent,
  slice: slice,
  __esModule: true
};

},{"./selector":16,"./util":20}],18:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/trigger";
var $__0 = _dereq_('./util'),
    global = $__0.global,
    each = $__0.each;
var closest = _dereq_('./selector').closest;
var reMouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
    reKeyEvent = /^key/;
function trigger(type, data) {
  var params = arguments[2] !== (void 0) ? arguments[2] : {};
  params.bubbles = typeof params.bubbles === 'boolean' ? params.bubbles : true;
  params.cancelable = typeof params.cancelable === 'boolean' ? params.cancelable : true;
  params.preventDefault = typeof params.preventDefault === 'boolean' ? params.preventDefault : false;
  params.detail = data;
  var EventConstructor = getEventConstructor(type),
      event = new EventConstructor(type, params);
  event._preventDefault = params.preventDefault;
  each(this, function(element) {
    if (!params.bubbles || isEventBubblingInDetachedTree || isAttachedToDocument(element)) {
      dispatchEvent(element, event);
    } else {
      triggerForPath(element, type, params);
    }
  });
  return this;
}
function getEventConstructor(type) {
  return !supportsOtherEventConstructors ? CustomEvent : reMouseEvent.test(type) ? MouseEvent : reKeyEvent.test(type) ? KeyboardEvent : CustomEvent;
}
function triggerHandler(type, data) {
  if (this[0]) {
    trigger.call(this[0], type, data, {
      bubbles: false,
      preventDefault: true
    });
  }
}
function isAttachedToDocument(element) {
  if (element === window || element === document) {
    return true;
  }
  return $.contains(element.ownerDocument.documentElement, element);
}
function triggerForPath(element, type) {
  var params = arguments[2] !== (void 0) ? arguments[2] : {};
  params.bubbles = false;
  var event = new CustomEvent(type, params);
  event._target = element;
  do {
    dispatchEvent(element, event);
  } while (element = element.parentNode);
}
var directEventMethods = ['blur', 'focus', 'select', 'submit'];
function dispatchEvent(element, event) {
  if (directEventMethods.indexOf(event.type) !== -1 && typeof element[event.type] === 'function' && !event._preventDefault && !event.cancelable) {
    element[event.type]();
  } else {
    element.dispatchEvent(event);
  }
}
(function() {
  function CustomEvent(event) {
    var params = arguments[1] !== (void 0) ? arguments[1] : {
      bubbles: false,
      cancelable: false,
      detail: undefined
    };
    var customEvent = document.createEvent('CustomEvent');
    customEvent.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
    return customEvent;
  }
  CustomEvent.prototype = global.CustomEvent && global.CustomEvent.prototype;
  global.CustomEvent = CustomEvent;
})();
var isEventBubblingInDetachedTree = (function() {
  var isBubbling = false,
      doc = global.document;
  if (doc) {
    var parent = doc.createElement('div'),
        child = parent.cloneNode();
    parent.appendChild(child);
    parent.addEventListener('e', function() {
      isBubbling = true;
    });
    child.dispatchEvent(new CustomEvent('e', {bubbles: true}));
  }
  return isBubbling;
})();
var supportsOtherEventConstructors = (function() {
  try {
    new window.MouseEvent('click');
  } catch (e) {
    return false;
  }
  return true;
})();
;
module.exports = {
  trigger: trigger,
  triggerHandler: triggerHandler,
  __esModule: true
};

},{"./selector":16,"./util":20}],19:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/type";
function isFunction(obj) {
  return (typeof obj === 'function');
}
var isArray = Array.isArray;
;
module.exports = {
  isFunction: isFunction,
  isArray: isArray,
  __esModule: true
};

},{}],20:[function(_dereq_,module,exports){
"use strict";
var __moduleName = "src/util";
var global = new Function("return this")();
function toArray(collection) {
  var length = collection.length,
      result = Array(length);
  for (var i = 0; i < length; i++) {
    result[i] = collection[i];
  }
  return result;
}
var makeIterable = (function(element) {
  return element.nodeType || element === window ? [element] : element;
});
function each(collection, callback, thisArg) {
  var length = collection.length;
  if (length !== undefined && collection.nodeType === undefined) {
    for (var i = 0; i < length; i++) {
      callback.call(thisArg, collection[i], i, collection);
    }
  } else {
    callback.call(thisArg, collection, 0, collection);
  }
  return collection;
}
function extend(target) {
  for (var sources = [],
      $__0 = 1; $__0 < arguments.length; $__0++)
    sources[$__0 - 1] = arguments[$__0];
  sources.forEach(function(src) {
    if (src) {
      for (var prop in src) {
        target[prop] = src[prop];
      }
    }
  });
  return target;
}
;
module.exports = {
  global: global,
  toArray: toArray,
  makeIterable: makeIterable,
  each: each,
  extend: extend,
  __esModule: true
};

},{}]},{},[12])
(12)
});


text:
package cn.elvea.platform.core.tag.mapper;

import cn.elvea.platform.commons.data.mybatis.mapper.BaseEntityMapper;
import cn.elvea.platform.core.tag.domain.entity.TagEntity;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

/**
 * @author elvea
 * @see BaseEntityMapper
 * @since 0.0.1
 */
@Mapper
@Repository
public interface TagMapper extends BaseEntityMapper<TagEntity, Long> {
}


text:
package org.spdx.tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.spdx.rdfparser.InvalidSPDXAnalysisException;
import org.spdx.rdfparser.SPDXCreatorInformation;
import org.spdx.rdfparser.SPDXReview;
import org.spdx.rdfparser.SpdxDocumentContainer;
import org.spdx.rdfparser.SpdxRdfConstants;
import org.spdx.rdfparser.SpdxVerificationHelper;
import org.spdx.rdfparser.license.ExtractedLicenseInfo;
import org.spdx.rdfparser.license.LicenseInfoFactory;
import org.spdx.rdfparser.license.SpdxListedLicense;
import org.spdx.rdfparser.model.Annotation;
import org.spdx.rdfparser.model.ExternalDocumentRef;
import org.spdx.rdfparser.model.Relationship;
import org.spdx.rdfparser.model.SpdxDocument;
import org.spdx.rdfparser.model.SpdxElement;
import org.spdx.rdfparser.model.SpdxFile;
import org.spdx.rdfparser.model.SpdxPackage;
import org.spdx.spdxspreadsheet.AnnotationsSheet;
import org.spdx.spdxspreadsheet.DocumentInfoSheet;
import org.spdx.spdxspreadsheet.InvalidLicenseStringException;
import org.spdx.spdxspreadsheet.NonStandardLicensesSheet;
import org.spdx.spdxspreadsheet.PackageInfoSheet;
import org.spdx.spdxspreadsheet.PerFileSheet;
import org.spdx.spdxspreadsheet.RelationshipsSheet;
import org.spdx.spdxspreadsheet.ReviewersSheet;
import org.spdx.spdxspreadsheet.SPDXSpreadsheet;
import org.spdx.spdxspreadsheet.SpreadsheetException;

import com.google.common.collect.Maps;

/**
 * Converts a spreadsheet to an SPDX RDF Analysis file
 * Usage: SpreadsheetToRDF spreadsheetfile.xls rdfxmlfile.rdf
 * where spreadsheetfile.xls is a valid SPDX Spreadsheet and
 * rdfxmlfile.rdf is the output SPDX RDF Analysis file.
 * @author Gary O'Neall
 *
 */
public class SpreadsheetToRDF {

	static final Logger logger = Logger.getLogger(SpreadsheetToRDF.class.getName());
	static final int MIN_ARGS = 2;
	static final int MAX_ARGS = 2;

	private static final ThreadLocal<DateFormat> format = new ThreadLocal<DateFormat>(){
	    @Override
	    protected DateFormat initialValue() {
	        return new SimpleDateFormat(SpdxRdfConstants.SPDX_DATE_FORMAT);
	    }
	  };

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length < MIN_ARGS) {
			usage();
			return;
		}
		if (args.length > MAX_ARGS) {
			usage();
			return;
		}
		File spdxSpreadsheetFile = new File(args[0]);
		if (!spdxSpreadsheetFile.exists()) {
			System.out.printf("Spreadsheet file %1$s does not exists.\n", args[0]);
			return;
		}
		File spdxRdfFile = new File(args[1]);
		if (spdxRdfFile.exists()) {
			System.out.printf("Error: File %1$s already exists - please specify a new file.\n", args[1]);
			return;
		}

		try {
			if (!spdxRdfFile.createNewFile()) {
				System.out.println("Could not create the new SPDX RDF file "+args[1]);
				usage();
				return;
			}
		} catch (IOException e1) {
			System.out.println("Could not create the new SPDX RDF file "+args[1]);
			System.out.println("due to error "+e1.getMessage());
			usage();
			return;
		}
		FileOutputStream out;
		try {
			out = new FileOutputStream(spdxRdfFile);
		} catch (FileNotFoundException e1) {
			System.out.println("Could not write to the new SPDX RDF file "+args[1]);
			System.out.println("due to error "+e1.getMessage());
			usage();
			return;
		}

		SPDXSpreadsheet ss = null;
		try {
			ss = new SPDXSpreadsheet(spdxSpreadsheetFile, false, true);
			SpdxDocument analysis = copySpreadsheetToSPDXAnalysis(ss);
			List<String> verify = analysis.verify();
			if (verify.size() > 0) {
				System.out.println("Warning: The following verification errors were found in the resultant SPDX Document:");
				for (int i = 0; i < verify.size(); i++) {
					System.out.println("\t"+verify.get(i));
				}
			}
			analysis.getDocumentContainer().getModel().write(out, "RDF/XML-ABBREV");
		} catch (SpreadsheetException e) {
			System.out.println("Error creating or writing to spreadsheet: "+e.getMessage());
		} catch (InvalidSPDXAnalysisException e) {
			System.out.println("Error translating the RDF file: "+e.getMessage());
		} finally {
			if (ss != null) {
				try {
					ss.close();
				} catch (SpreadsheetException e) {
					System.out.println("Error closing spreadsheet: "+e.getMessage());
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					System.out.println("Error closing RDF file: "+e.getMessage());
				}
			}
		}
	}

	public static SpdxDocument copySpreadsheetToSPDXAnalysis(SPDXSpreadsheet ss) throws SpreadsheetException, InvalidSPDXAnalysisException {
		String pkgUrl = ss.getOriginsSheet().getNamespace() + "#" + SpdxRdfConstants.SPDX_DOCUMENT_ID;
		if (!SpdxVerificationHelper.isValidUri(pkgUrl)) {
			// need to create a unique URL
			// Use the download URL + "#SPDXANALYSIS"
			logger.warn("Missing or invalid document namespace.  Using download location URL for the document namespace");
			SpdxPackage[] pkgs = ss.getPackageInfoSheet().getPackages(null);
			if (pkgs.length > 0) {
				pkgUrl = pkgs[0].getDownloadLocation();
			}
		}
		if (!SpdxVerificationHelper.isValidUri(pkgUrl)) {
			// Since the download location is not valid, replace it with a spdx.org/tempspdxuri
			logger.warn("Missing or invalid download location.  Using temporary namespace http://spdx.org/tempspdxuri");
			pkgUrl = "http://spdx.org/tempspdxuri";
		}
		SpdxDocumentContainer container = new SpdxDocumentContainer(pkgUrl);
		SpdxDocument analysis = container.getSpdxDocument();
		copyOrigins(ss.getOriginsSheet(), analysis);
		copyNonStdLicenses(ss.getNonStandardLicensesSheet(), analysis);
		// note - non std licenses must be added first so that the text is available
		Map<String, SpdxPackage> pkgIdToPackage = copyPackageInfo(ss.getPackageInfoSheet(), analysis);
		// note - packages need to be added before the files so that the files can be added to the packages
		copyPerFileInfo(ss.getPerFileSheet(), analysis, pkgIdToPackage);
		copyAnnotationInfo(ss.getAnnotationsSheet(), analysis);
		copyRelationshipInfo(ss.getRelationshipsSheet(), analysis);
		copyReviewerInfo(ss.getReviewersSheet(), analysis);
		return analysis;
	}

	/**
	 * @param relationshipsSheet
	 * @param analysis
	 * @throws SpreadsheetException
	 * @throws InvalidSPDXAnalysisException
	 */
	private static void copyRelationshipInfo(
			RelationshipsSheet relationshipsSheet, SpdxDocument analysis) throws SpreadsheetException, InvalidSPDXAnalysisException {
		int i = relationshipsSheet.getFirstDataRow();
		Relationship relationship = relationshipsSheet.getRelationship(i, analysis.getDocumentContainer());
		String id = relationshipsSheet.getElmementId(i);
		while (relationship != null && id != null) {
			SpdxElement element = analysis.getDocumentContainer().findElementById(id);
			element.addRelationship(relationship);
			i = i + 1;
			relationship = relationshipsSheet.getRelationship(i, analysis.getDocumentContainer());
			id = relationshipsSheet.getElmementId(i);
		}
	}

	/**
	 * @param annotationsSheet
	 * @param analysis
	 * @throws InvalidSPDXAnalysisException
	 * @throws SpreadsheetException
	 */
	private static void copyAnnotationInfo(AnnotationsSheet annotationsSheet,
			SpdxDocument analysis) throws InvalidSPDXAnalysisException, SpreadsheetException {
		int i = annotationsSheet.getFirstDataRow();
		Annotation annotation = annotationsSheet.getAnnotation(i);
		String id = annotationsSheet.getElmementId(i);
		while (annotation != null && id != null) {
			SpdxElement element = analysis.getDocumentContainer().findElementById(id);
			element.addAnnotation(annotation);
			i = i + 1;
			annotation = annotationsSheet.getAnnotation(i);
			id = annotationsSheet.getElmementId(i);
		}

	}

	@SuppressWarnings("deprecation")
	private static void copyReviewerInfo(ReviewersSheet reviewersSheet,
			SpdxDocument analysis) throws InvalidSPDXAnalysisException {
		int numReviewers = reviewersSheet.getNumDataRows();
		int firstRow = reviewersSheet.getFirstDataRow();
		SPDXReview[] reviewers = new SPDXReview[numReviewers];
		for (int i = 0; i < reviewers.length; i++) {
			reviewers[i] = new SPDXReview(reviewersSheet.getReviewer(firstRow+i), format.get().format(reviewersSheet.getReviewerTimestamp(firstRow+i)),
					reviewersSheet.getReviewerComment(firstRow + i));
		}
		analysis.setReviewers(reviewers);
	}

	private static void copyPerFileInfo(PerFileSheet perFileSheet,
			SpdxDocument analysis, Map<String, SpdxPackage> pkgIdToPackage) throws SpreadsheetException, InvalidSPDXAnalysisException {
		int firstRow = perFileSheet.getFirstDataRow();
		int numFiles = perFileSheet.getNumDataRows();
		for (int i = 0; i < numFiles; i++) {
			SpdxFile file = perFileSheet.getFileInfo(firstRow+i, analysis.getDocumentContainer());
			String[] pkgIds = perFileSheet.getPackageIds(firstRow+i);
			boolean fileAdded = false;
			for (int j = 0;j < pkgIds.length; j++) {
				SpdxPackage pkg = pkgIdToPackage.get(pkgIds[j]);
				if (pkg != null) {
					pkg.addFile(file);
					fileAdded = true;
				} else {
					logger.warn("Can not add file "+file.getName()+" to package "+pkgIds[j]);
				}
			}
			if (!fileAdded) {
				analysis.getDocumentContainer().addElement(file);
			}
		}
	}

	private static void copyNonStdLicenses(
			NonStandardLicensesSheet nonStandardLicensesSheet, SpdxDocument analysis) throws InvalidSPDXAnalysisException {
		int numNonStdLicenses = nonStandardLicensesSheet.getNumDataRows();
		int firstRow = nonStandardLicensesSheet.getFirstDataRow();
		ExtractedLicenseInfo[] nonStdLicenses = new ExtractedLicenseInfo[numNonStdLicenses];
		for (int i = 0; i < nonStdLicenses.length; i++) {
			nonStdLicenses[i] = new ExtractedLicenseInfo(nonStandardLicensesSheet.getIdentifier(firstRow+i),
					nonStandardLicensesSheet.getExtractedText(firstRow+i),
					nonStandardLicensesSheet.getLicenseName(firstRow+i),
					nonStandardLicensesSheet.getCrossRefUrls(firstRow+i),
					nonStandardLicensesSheet.getComment(firstRow+i));
		}
		analysis.setExtractedLicenseInfos(nonStdLicenses);
	}

	private static Map<String, SpdxPackage> copyPackageInfo(PackageInfoSheet packageInfoSheet,
			SpdxDocument analysis) throws SpreadsheetException, InvalidSPDXAnalysisException {
		SpdxPackage[] packages = packageInfoSheet.getPackages(analysis.getDocumentContainer());
		Map<String, SpdxPackage> pkgIdToPackage = Maps.newHashMap();
		for (int i = 0; i < packages.length; i++) {
			pkgIdToPackage.put(packages[i].getId(), packages[i]);
			analysis.getDocumentContainer().addElement(packages[i]);
		}
		return pkgIdToPackage;
	}

	private static void copyOrigins(DocumentInfoSheet originsSheet, SpdxDocument analysis) throws InvalidSPDXAnalysisException, SpreadsheetException {
		Date createdDate = originsSheet.getCreated();
		String created  = format.get().format(createdDate);
		String[] createdBys = originsSheet.getCreatedBy();
		String creatorComment = originsSheet.getAuthorComments();
		String licenseListVersion = originsSheet.getLicenseListVersion();
		SPDXCreatorInformation creator = new SPDXCreatorInformation(createdBys, created, creatorComment, licenseListVersion);
		String specVersion = originsSheet.getSPDXVersion();
		analysis.setSpecVersion(specVersion);
		String dataLicenseId = originsSheet.getDataLicense();
		if (dataLicenseId == null || dataLicenseId.isEmpty() || dataLicenseId.equals(RdfToSpreadsheet.NOT_SUPPORTED_STRING)) {
			if (specVersion.equals(SpdxDocumentContainer.ONE_DOT_ZERO_SPDX_VERSION)) {
				dataLicenseId = SpdxRdfConstants.SPDX_DATA_LICENSE_ID_VERSION_1_0;
			} else {
				dataLicenseId = SpdxRdfConstants.SPDX_DATA_LICENSE_ID;
			}
		}
		SpdxListedLicense dataLicense = null;
		try {
			dataLicense = (SpdxListedLicense)LicenseInfoFactory.parseSPDXLicenseString(dataLicenseId, analysis.getDocumentContainer());
		} catch (Exception ex) {
			logger.warn("Unable to parse the provided standard license ID.  Using "+SpdxRdfConstants.SPDX_DATA_LICENSE_ID);
			try {
				dataLicense = (SpdxListedLicense)LicenseInfoFactory.parseSPDXLicenseString(SpdxRdfConstants.SPDX_DATA_LICENSE_ID, analysis.getDocumentContainer());
			} catch (InvalidLicenseStringException e) {
				throw(new InvalidSPDXAnalysisException("Unable to get document license"));
			}
		}
		analysis.setDataLicense(dataLicense);
		analysis.setCreationInfo(creator);
		String docComment = originsSheet.getDocumentComment();
		if (docComment != null) {
		    docComment = docComment.trim();
			if (!docComment.isEmpty()) {
				analysis.setComment(docComment);
			}
		}
		String docName = originsSheet.getDocumentName();
		if (docName != null) {
			analysis.setName(docName);
		}
		ExternalDocumentRef[] externalRefs = originsSheet.getExternalDocumentRefs();
		if (externalRefs != null) {
			analysis.setExternalDocumentRefs(externalRefs);
		}
	}

	private static void usage() {
		System.out.println("Usage: SpreadsheetToRDF spreadsheetfile.xls rdfxmlfile.rdf \n"+
				"where spreadsheetfile.xls is a valid SPDX Spreadsheet and\n"+
				"rdfxmlfile.rdf is the output SPDX RDF analysis file.");
	}

}


text:
var net = require('net');

exports.hook_data_post = function (next, connection) {
    var self = this;
    var txn = connection.transaction;

    // Fix-up rDNS for DCC
    var host;
    switch (connection.remote.host) {
        case 'Unknown':
        case 'NXDOMAIN':
        case 'DNSERROR':
        case undefined:
            break;
        default:
            host = connection.remote.host;
            break;
    }

    var rcpts = txn.rcpt_to.map(function (rcpt) { return rcpt.address(); });
    var training = (txn.notes.training_mode && txn.notes.training_mode === 'spam')
                   ? true : false;
    var response = '';
    var client = net.createConnection({
        path: '/var/dcc/dccifd'
    }, function () {
        // http://www.dcc-servers.net/dcc/dcc-tree/dccifd.html
        connection.logdebug(self, 'connected to dcc');
        var protocol_headers = [
            'header' + ((training) ? ' spam' : ''),
            connection.remote.ip + ((host) ? '\r' + host : ''),
            connection.hello.host,
            txn.mail_from.address(),
            rcpts.join('\r'),
        ].join('\n');
        connection.logdebug(self, 'sending protocol headers: ' + protocol_headers);
        this.write(protocol_headers + '\n\n', function () {
            txn.message_stream.pipe(client);
        });
    });

    client.on('error', function (err) {
        connection.logerror(self, err.message);
        return next();
    });

    client.on('data', function (chunk) {
        response += chunk.toString('utf8');
    });

    client.on('end', function () {
        var rl = response.split("\n");
        if (rl.length < 2) {
            connection.logwarn(self, 'invalid response: ' + response + 'length=' + rl.length);
            return next();
        }
        connection.logdebug(self, 'got response: ' + response);
        // Get result code
        var result = rl.shift();
        switch (result) {
            case 'A':
                // Accept
            case 'G':
                // Greylist
            case 'R':
                // Reject
            case 'S':
                // Accept for some recipients
            case 'T':
                // Temporary failure
                break;
            default:
                connection.logerror(self, 'invalid result: ' + result);
                break;
        }
        // Disposition
        var disposition = rl.shift();
        switch (disposition) {
            case 'A':    // Deliver the message
            case 'G':    // Discard the message during greylist embargo
            case 'R':    // Discard the message as spam
                break;
            default:
                connection.logerror(self, 'invalid disposition: ' + disposition);
                break;
        }
        // Read headers
        var headers = [];
        for (var i=0; i<rl.length; i++) {
            if (/^\s/.test(rl[i]) && headers.length) {
                // Continuation
                headers[headers.length-1] += rl[i];
            }
            else {
                if (rl[i]) headers.push(rl[i]);
            }
        }
        connection.logdebug(this, 'found ' + headers.length + ' headers');
        for (var h=0; h<headers.length; h++) {
            var header = headers[h].toString('utf8').trim();
            var match;
            if ((match = /^([^: ]+):\s*((?:.|[\r\n])+)/.exec(header))) {
                txn.add_header(match[1], match[2]);
            }
            else {
                connection.logerror(this, 'header did not match regexp: ' + header);
            }
        }
        connection.loginfo(self, 'training=' + (training ? 'Y' : 'N') + ' result=' + result +
                                 ' disposition=' + disposition + ' headers=' + headers.length);
        return next();
    });
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<portlet xmlns="http://www.unioninvestment.de/eai/portal/crud-portlet"
	title="Beispiel für generierte Spalte">
	<page>
		<table id="table" row-height="30">
			<database-query datasource="test">
				<query><![CDATA[
					SELECT * FROM test_crud2
				]]></query>
				<insert><![CDATA[
					INSERT INTO TEST_CRUD2
					  (
					    CNUMBER5_2,
					    CDATE,
					    CTIMESTAMP,
					    CVARCHAR5_NN,
					    CNUMBER5_2_NN,
					    CDATE_NN,
					    CTIMESTAMP_NN,
					    TESTDATA
					  )
					  VALUES
					  (
					    $row.values.CNUMBER5_2,
					    $row.values.CDATE,
					    SYSDATE,
					    $row.values.CVARCHAR5_NN,
					    $row.values.CNUMBER5_2_NN,
					    $row.values.CDATE_NN,
					    SYSDATE,
					    $row.values.TESTDATA
					  )
				]]></insert>
				<update><![CDATA[
					UPDATE TEST_CRUD2 SET
						CNUMBER5_2	  = $row.values.CNUMBER5_2,
						CDATE	      = $row.values.CDATE,
						CVARCHAR5_NN  = $row.values.CVARCHAR5_NN,
						CNUMBER5_2_NN = $row.values.CNUMBER5_2_NN,
						CDATE_NN	  = $row.values.CDATE_NN,
						TESTDATA      = $row.values.TESTDATA
					WHERE ID          = $row.values.ID
				]]></update>
				<delete><![CDATA[
					DELETE FROM TEST_CRUD2
					WHERE ID = $row.values.ID
				]]></delete>
			</database-query>
			<columns>
				<column name="ID" title="ID" primary-key="true"/>
				<column name="CNUMBER5_2" title="Zahl" editable="true" />
				<column name="CDATE" editable="false" />
				<column name="CTIMESTAMP" />
				<column name="CVARCHAR5_NN" editable="true" />
				<column name="CNUMBER5_2_NN" editable="true" />
				<column name="CDATE_NN" editable="true" />
				<column name="CTIMESTAMP_NN" hidden="true"/>
				<column name="TESTDATA" editable="true" validate="maxlen=80,required" validation-message="Pflichtfeld, Max. 80 Zeichen sind erlaubt"/>
			    <column name="Generiert" generator="detailButton(row.values)"/>
			    <column name="Image" generator="imageButton(row.values)"/>
			</columns>
		</table>
	</page>
	<script><![CDATA[
		def detailButton(values) {
			def btn = new Button("Button $values.ID")
			btn.addListener({ showDetailsPopup(values) } as Button.ClickListener)
			return btn
		}
		def imageButton(values) {
			def btn = new Button()
			btn.addListener({ showDetailsPopup(values) } as Button.ClickListener)
			btn.styleName = "link" // wenn nur das Icon ohne Rahmen sichtbar sein soll
			// Theme Icon
			btn.icon = new com.vaadin.server.ThemeResource("../runo/icons/16/trash.png")
			// External Icon
			// btn.icon = new com.vaadin.server.ExternalResource('/html/themes/_unstyled/images/dock/add_content.png')
			return btn
		}

		def showDetailsPopup(values) {
			showPopup "Details", {
				h2('Vaadin-Containerdaten')
				table {
					values.each { key, value ->
						tr {
							td(key)
							td(value)
						}
					}
				}
			}
		}
	]]></script>
</portlet>