text:
#include "postgres.h"

#include "catalog/pg_collation.h"
#include "catalog/pg_type.h"
#include "nodes/nodeFuncs.h"
#include "parser/analyze.h"
#include "parser/parse_cte.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"

/* Enumeration of contexts in which a self-reference is disallowed */
typedef enum
{
	RECURSION_OK,
	RECURSION_NONRECURSIVETERM, /* inside the left-hand term */
	RECURSION_SUBLINK,			/* inside a sublink */
	RECURSION_OUTERJOIN,		/* inside nullable side of an outer join */
	RECURSION_INTERSECT,		/* underneath INTERSECT (ALL) */
	RECURSION_EXCEPT			/* underneath EXCEPT (ALL) */
} RecursionContext;

/* Associated error messages --- each must have one %s for CTE name */
static const char *const recursion_errormsgs[] = {
	/* RECURSION_OK */
	NULL,
	/* RECURSION_NONRECURSIVETERM */
	gettext_noop("recursive reference to query \"%s\" must not appear within its non-recursive term"),
	/* RECURSION_SUBLINK */
	gettext_noop("recursive reference to query \"%s\" must not appear within a subquery"),
	/* RECURSION_OUTERJOIN */
	gettext_noop("recursive reference to query \"%s\" must not appear within an outer join"),
	/* RECURSION_INTERSECT */
	gettext_noop("recursive reference to query \"%s\" must not appear within INTERSECT"),
	/* RECURSION_EXCEPT */
	gettext_noop("recursive reference to query \"%s\" must not appear within EXCEPT")
};

/*
 * For WITH RECURSIVE, we have to find an ordering of the clause members
 * with no forward references, and determine which members are recursive
 * (i.e., self-referential).  It is convenient to do this with an array
 * of CteItems instead of a list of CommonTableExprs.
 */
typedef struct CteItem
{
	CommonTableExpr *cte;		/* One CTE to examine */
	int			id;				/* Its ID number for dependencies */
	Bitmapset  *depends_on;		/* CTEs depended on (not including self) */
} CteItem;

/* CteState is what we need to pass around in the tree walkers */
typedef struct CteState
{
	/* global state: */
	ParseState *pstate;			/* global parse state */
	CteItem    *items;			/* array of CTEs and extra data */
	int			numitems;		/* number of CTEs */
	/* working state during a tree walk: */
	int			curitem;		/* index of item currently being examined */
	List	   *innerwiths;		/* list of lists of CommonTableExpr */
	/* working state for checkWellFormedRecursion walk only: */
	int			selfrefcount;	/* number of self-references detected */
	RecursionContext context;	/* context to allow or disallow self-ref */
} CteState;

static void analyzeCTE(ParseState *pstate, CommonTableExpr *cte);

/* Dependency processing functions */
static void makeDependencyGraph(CteState *cstate);
static bool makeDependencyGraphWalker(Node *node, CteState *cstate);
static void TopologicalSort(ParseState *pstate, CteItem *items, int numitems);

/* Recursion validity checker functions */
static void checkWellFormedRecursion(CteState *cstate);
static bool checkWellFormedRecursionWalker(Node *node, CteState *cstate);
static void checkWellFormedSelectStmt(SelectStmt *stmt, CteState *cstate);

/*
 * transformWithClause -
 *	  Transform the list of WITH clause "common table expressions" into
 *	  Query nodes.
 *
 * The result is the list of transformed CTEs to be put into the output
 * Query.  (This is in fact the same as the ending value of p_ctenamespace,
 * but it seems cleaner to not expose that in the function's API.)
 */
List *
transformWithClause(ParseState *pstate, WithClause *withClause)
{
	ListCell   *lc;

	/* Only one WITH clause per query level */
	Assert(pstate->p_ctenamespace == NIL);
	Assert(pstate->p_future_ctes == NIL);

	/*
	 * For either type of WITH, there must not be duplicate CTE names in the
	 * list.  Check this right away so we needn't worry later.
	 *
	 * Also, tentatively mark each CTE as non-recursive, and initialize its
	 * reference count to zero, and set pstate->p_hasModifyingCTE if needed.
	 */
	foreach(lc, withClause->ctes)
	{
		CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
		ListCell   *rest;

		for_each_cell(rest, lnext(lc))
		{
			CommonTableExpr *cte2 = (CommonTableExpr *) lfirst(rest);

			if (strcmp(cte->ctename, cte2->ctename) == 0)
				ereport(ERROR,
						(errcode(ERRCODE_DUPLICATE_ALIAS),
					errmsg("WITH query name \"%s\" specified more than once",
						   cte2->ctename),
						 parser_errposition(pstate, cte2->location)));
		}

		cte->cterecursive = false;
		cte->cterefcount = 0;

		if (!IsA(cte->ctequery, SelectStmt))
		{
			/* must be a data-modifying statement */
			Assert(IsA(cte->ctequery, InsertStmt) ||
				   IsA(cte->ctequery, UpdateStmt) ||
				   IsA(cte->ctequery, DeleteStmt));

			pstate->p_hasModifyingCTE = true;
		}
	}

	if (withClause->recursive)
	{
		/*
		 * For WITH RECURSIVE, we rearrange the list elements if needed to
		 * eliminate forward references.  First, build a work array and set up
		 * the data structure needed by the tree walkers.
		 */
		CteState	cstate;
		int			i;

		cstate.pstate = pstate;
		cstate.numitems = list_length(withClause->ctes);
		cstate.items = (CteItem *) palloc0(cstate.numitems * sizeof(CteItem));
		i = 0;
		foreach(lc, withClause->ctes)
		{
			cstate.items[i].cte = (CommonTableExpr *) lfirst(lc);
			cstate.items[i].id = i;
			i++;
		}

		/*
		 * Find all the dependencies and sort the CteItems into a safe
		 * processing order.  Also, mark CTEs that contain self-references.
		 */
		makeDependencyGraph(&cstate);

		/*
		 * Check that recursive queries are well-formed.
		 */
		checkWellFormedRecursion(&cstate);

		/*
		 * Set up the ctenamespace for parse analysis.  Per spec, all the WITH
		 * items are visible to all others, so stuff them all in before parse
		 * analysis.  We build the list in safe processing order so that the
		 * planner can process the queries in sequence.
		 */
		for (i = 0; i < cstate.numitems; i++)
		{
			CommonTableExpr *cte = cstate.items[i].cte;

			pstate->p_ctenamespace = lappend(pstate->p_ctenamespace, cte);
		}

		/*
		 * Do parse analysis in the order determined by the topological sort.
		 */
		for (i = 0; i < cstate.numitems; i++)
		{
			CommonTableExpr *cte = cstate.items[i].cte;

			analyzeCTE(pstate, cte);
		}
	}
	else
	{
		/*
		 * For non-recursive WITH, just analyze each CTE in sequence and then
		 * add it to the ctenamespace.  This corresponds to the spec's
		 * definition of the scope of each WITH name.  However, to allow error
		 * reports to be aware of the possibility of an erroneous reference,
		 * we maintain a list in p_future_ctes of the not-yet-visible CTEs.
		 */
		pstate->p_future_ctes = list_copy(withClause->ctes);

		foreach(lc, withClause->ctes)
		{
			CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);

			analyzeCTE(pstate, cte);
			pstate->p_ctenamespace = lappend(pstate->p_ctenamespace, cte);
			pstate->p_future_ctes = list_delete_first(pstate->p_future_ctes);
		}
	}

	return pstate->p_ctenamespace;
}

/*
 * Perform the actual parse analysis transformation of one CTE.  All
 * CTEs it depends on have already been loaded into pstate->p_ctenamespace,
 * and have been marked with the correct output column names/types.
 */
static void
analyzeCTE(ParseState *pstate, CommonTableExpr *cte)
{
	Query	   *query;

	/* Analysis not done already */
	Assert(!IsA(cte->ctequery, Query));

	query = parse_sub_analyze(cte->ctequery, pstate, cte, false);
	cte->ctequery = (Node *) query;

	/*
	 * Check that we got something reasonable.  These first two cases should
	 * be prevented by the grammar.
	 */
	if (!IsA(query, Query))
		elog(ERROR, "unexpected non-Query statement in WITH");
	if (query->utilityStmt != NULL)
		elog(ERROR, "unexpected utility statement in WITH");

	/*
	 * We disallow data-modifying WITH except at the top level of a query,
	 * because it's not clear when such a modification should be executed.
	 */
	if (query->commandType != CMD_SELECT &&
		pstate->parentParseState != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("WITH clause containing a data-modifying statement must be at the top level"),
				 parser_errposition(pstate, cte->location)));

	/*
	 * CTE queries are always marked not canSetTag.  (Currently this only
	 * matters for data-modifying statements, for which the flag will be
	 * propagated to the ModifyTable plan node.)
	 */
	query->canSetTag = false;

	if (!cte->cterecursive)
	{
		/* Compute the output column names/types if not done yet */
		analyzeCTETargetList(pstate, cte, GetCTETargetList(cte));
	}
	else
	{
		/*
		 * Verify that the previously determined output column types and
		 * collations match what the query really produced.  We have to check
		 * this because the recursive term could have overridden the
		 * non-recursive term, and we don't have any easy way to fix that.
		 */
		ListCell   *lctlist,
				   *lctyp,
				   *lctypmod,
				   *lccoll;
		int			varattno;

		lctyp = list_head(cte->ctecoltypes);
		lctypmod = list_head(cte->ctecoltypmods);
		lccoll = list_head(cte->ctecolcollations);
		varattno = 0;
		foreach(lctlist, GetCTETargetList(cte))
		{
			TargetEntry *te = (TargetEntry *) lfirst(lctlist);
			Node	   *texpr;

			if (te->resjunk)
				continue;
			varattno++;
			Assert(varattno == te->resno);
			if (lctyp == NULL || lctypmod == NULL || lccoll == NULL)	/* shouldn't happen */
				elog(ERROR, "wrong number of output columns in WITH");
			texpr = (Node *) te->expr;
			if (exprType(texpr) != lfirst_oid(lctyp) ||
				exprTypmod(texpr) != lfirst_int(lctypmod))
				ereport(ERROR,
						(errcode(ERRCODE_DATATYPE_MISMATCH),
						 errmsg("recursive query \"%s\" column %d has type %s in non-recursive term but type %s overall",
								cte->ctename, varattno,
								format_type_with_typemod(lfirst_oid(lctyp),
													   lfirst_int(lctypmod)),
								format_type_with_typemod(exprType(texpr),
														 exprTypmod(texpr))),
						 errhint("Cast the output of the non-recursive term to the correct type."),
						 parser_errposition(pstate, exprLocation(texpr))));
			if (exprCollation(texpr) != lfirst_oid(lccoll))
				ereport(ERROR,
						(errcode(ERRCODE_COLLATION_MISMATCH),
						 errmsg("recursive query \"%s\" column %d has collation \"%s\" in non-recursive term but collation \"%s\" overall",
								cte->ctename, varattno,
								get_collation_name(lfirst_oid(lccoll)),
								get_collation_name(exprCollation(texpr))),
						 errhint("Use the COLLATE clause to set the collation of the non-recursive term."),
						 parser_errposition(pstate, exprLocation(texpr))));
			lctyp = lnext(lctyp);
			lctypmod = lnext(lctypmod);
			lccoll = lnext(lccoll);
		}
		if (lctyp != NULL || lctypmod != NULL || lccoll != NULL)		/* shouldn't happen */
			elog(ERROR, "wrong number of output columns in WITH");
	}
}

/*
 * Compute derived fields of a CTE, given the transformed output targetlist
 *
 * For a nonrecursive CTE, this is called after transforming the CTE's query.
 * For a recursive CTE, we call it after transforming the non-recursive term,
 * and pass the targetlist emitted by the non-recursive term only.
 *
 * Note: in the recursive case, the passed pstate is actually the one being
 * used to analyze the CTE's query, so it is one level lower down than in
 * the nonrecursive case.  This doesn't matter since we only use it for
 * error message context anyway.
 */
void
analyzeCTETargetList(ParseState *pstate, CommonTableExpr *cte, List *tlist)
{
	int			numaliases;
	int			varattno;
	ListCell   *tlistitem;

	/* Not done already ... */
	Assert(cte->ctecolnames == NIL);

	/*
	 * We need to determine column names, types, and collations.  The alias
	 * column names override anything coming from the query itself.  (Note:
	 * the SQL spec says that the alias list must be empty or exactly as long
	 * as the output column set; but we allow it to be shorter for consistency
	 * with Alias handling.)
	 */
	cte->ctecolnames = static_cast<List *>(copyObject(cte->aliascolnames));
	cte->ctecoltypes = cte->ctecoltypmods = cte->ctecolcollations = NIL;
	numaliases = list_length(cte->aliascolnames);
	varattno = 0;
	foreach(tlistitem, tlist)
	{
		TargetEntry *te = (TargetEntry *) lfirst(tlistitem);
		Oid			coltype;
		int32		coltypmod;
		Oid			colcoll;

		if (te->resjunk)
			continue;
		varattno++;
		Assert(varattno == te->resno);
		if (varattno > numaliases)
		{
			char	   *attrname;

			attrname = pstrdup(te->resname);
			cte->ctecolnames = lappend(cte->ctecolnames, makeString(attrname));
		}
		coltype = exprType((Node *) te->expr);
		coltypmod = exprTypmod((Node *) te->expr);
		colcoll = exprCollation((Node *) te->expr);

		/*
		 * If the CTE is recursive, force the exposed column type of any
		 * "unknown" column to "text".  This corresponds to the fact that
		 * SELECT 'foo' UNION SELECT 'bar' will ultimately produce text. We
		 * might see "unknown" as a result of an untyped literal in the
		 * non-recursive term's select list, and if we don't convert to text
		 * then we'll have a mismatch against the UNION result.
		 *
		 * The column might contain 'foo' COLLATE "bar", so don't override
		 * collation if it's already set.
		 */
		if (cte->cterecursive && coltype == UNKNOWNOID)
		{
			coltype = TEXTOID;
			coltypmod = -1;		/* should be -1 already, but be sure */
			if (!OidIsValid(colcoll))
				colcoll = DEFAULT_COLLATION_OID;
		}
		cte->ctecoltypes = lappend_oid(cte->ctecoltypes, coltype);
		cte->ctecoltypmods = lappend_int(cte->ctecoltypmods, coltypmod);
		cte->ctecolcollations = lappend_oid(cte->ctecolcollations, colcoll);
	}
	if (varattno < numaliases)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
				 errmsg("WITH query \"%s\" has %d columns available but %d columns specified",
						cte->ctename, varattno, numaliases),
				 parser_errposition(pstate, cte->location)));
}

/*
 * Identify the cross-references of a list of WITH RECURSIVE items,
 * and sort into an order that has no forward references.
 */
static void
makeDependencyGraph(CteState *cstate)
{
	int			i;

	for (i = 0; i < cstate->numitems; i++)
	{
		CommonTableExpr *cte = cstate->items[i].cte;

		cstate->curitem = i;
		cstate->innerwiths = NIL;
		makeDependencyGraphWalker((Node *) cte->ctequery, cstate);
		Assert(cstate->innerwiths == NIL);
	}

	TopologicalSort(cstate->pstate, cstate->items, cstate->numitems);
}

/*
 * Tree walker function to detect cross-references and self-references of the
 * CTEs in a WITH RECURSIVE list.
 */
static bool
makeDependencyGraphWalker(Node *node, CteState *cstate)
{
	if (node == NULL)
		return false;
	if (IsA(node, RangeVar))
	{
		RangeVar   *rv = (RangeVar *) node;

		/* If unqualified name, might be a CTE reference */
		if (!rv->schemaname)
		{
			ListCell   *lc;
			int			i;

			/* ... but first see if it's captured by an inner WITH */
			foreach(lc, cstate->innerwiths)
			{
				List	   *withlist = (List *) lfirst(lc);
				ListCell   *lc2;

				foreach(lc2, withlist)
				{
					CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc2);

					if (strcmp(rv->relname, cte->ctename) == 0)
						return false;	/* yes, so bail out */
				}
			}

			/* No, could be a reference to the query level we are working on */
			for (i = 0; i < cstate->numitems; i++)
			{
				CommonTableExpr *cte = cstate->items[i].cte;

				if (strcmp(rv->relname, cte->ctename) == 0)
				{
					int			myindex = cstate->curitem;

					if (i != myindex)
					{
						/* Add cross-item dependency */
						cstate->items[myindex].depends_on =
							bms_add_member(cstate->items[myindex].depends_on,
										   cstate->items[i].id);
					}
					else
					{
						/* Found out this one is self-referential */
						cte->cterecursive = true;
					}
					break;
				}
			}
		}
		return false;
	}
	if (IsA(node, SelectStmt))
	{
		SelectStmt *stmt = (SelectStmt *) node;
		ListCell   *lc;

		if (stmt->withClause)
		{
			if (stmt->withClause->recursive)
			{
				/*
				 * In the RECURSIVE case, all query names of the WITH are
				 * visible to all WITH items as well as the main query. So
				 * push them all on, process, pop them all off.
				 */
				cstate->innerwiths = lcons(stmt->withClause->ctes,
										   cstate->innerwiths);
				foreach(lc, stmt->withClause->ctes)
				{
					CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);

					(void) makeDependencyGraphWalker(cte->ctequery, cstate);
				}
				(void) raw_expression_tree_walker(node,
				                  reinterpret_cast<raw_expression_tree_walker_fptr>(makeDependencyGraphWalker),
												  (void *) cstate);
				cstate->innerwiths = list_delete_first(cstate->innerwiths);
			}
			else
			{
				/*
				 * In the non-RECURSIVE case, query names are visible to the
				 * WITH items after them and to the main query.
				 */
				ListCell   *cell1;

				cstate->innerwiths = lcons(NIL, cstate->innerwiths);
				cell1 = list_head(cstate->innerwiths);
				foreach(lc, stmt->withClause->ctes)
				{
					CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);

					(void) makeDependencyGraphWalker(cte->ctequery, cstate);
					lfirst(cell1) = lappend((List *) lfirst(cell1), cte);
				}
				(void) raw_expression_tree_walker(node,
				                  reinterpret_cast<raw_expression_tree_walker_fptr>(makeDependencyGraphWalker),
												  (void *) cstate);
				cstate->innerwiths = list_delete_first(cstate->innerwiths);
			}
			/* We're done examining the SelectStmt */
			return false;
		}
		/* if no WITH clause, just fall through for normal processing */
	}
	if (IsA(node, WithClause))
	{
		/*
		 * Prevent raw_expression_tree_walker from recursing directly into a
		 * WITH clause.  We need that to happen only under the control of the
		 * code above.
		 */
		return false;
	}
	return raw_expression_tree_walker(node,
	                  reinterpret_cast<raw_expression_tree_walker_fptr>(makeDependencyGraphWalker),
									  (void *) cstate);
}

/*
 * Sort by dependencies, using a standard topological sort operation
 */
static void
TopologicalSort(ParseState *pstate, CteItem *items, int numitems)
{
	int			i,
				j;

	/* for each position in sequence ... */
	for (i = 0; i < numitems; i++)
	{
		/* ... scan the remaining items to find one that has no dependencies */
		for (j = i; j < numitems; j++)
		{
			if (bms_is_empty(items[j].depends_on))
				break;
		}

		/* if we didn't find one, the dependency graph has a cycle */
		if (j >= numitems)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
			errmsg("mutual recursion between WITH items is not implemented"),
					 parser_errposition(pstate, items[i].cte->location)));

		/*
		 * Found one.  Move it to front and remove it from every other item's
		 * dependencies.
		 */
		if (i != j)
		{
			CteItem		tmp;

			tmp = items[i];
			items[i] = items[j];
			items[j] = tmp;
		}

		/*
		 * Items up through i are known to have no dependencies left, so we
		 * can skip them in this loop.
		 */
		for (j = i + 1; j < numitems; j++)
		{
			items[j].depends_on = bms_del_member(items[j].depends_on,
												 items[i].id);
		}
	}
}

/*
 * Check that recursive queries are well-formed.
 */
static void
checkWellFormedRecursion(CteState *cstate)
{
	int			i;

	for (i = 0; i < cstate->numitems; i++)
	{
		CommonTableExpr *cte = cstate->items[i].cte;
		SelectStmt *stmt = (SelectStmt *) cte->ctequery;

		Assert(!IsA(stmt, Query));		/* not analyzed yet */

		/* Ignore items that weren't found to be recursive */
		if (!cte->cterecursive)
			continue;

		/* Must be a SELECT statement */
		if (!IsA(stmt, SelectStmt))
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_RECURSION),
					 errmsg("recursive query \"%s\" must not contain data-modifying statements",
							cte->ctename),
					 parser_errposition(cstate->pstate, cte->location)));

		/* Must have top-level UNION */
		if (stmt->op != SETOP_UNION)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_RECURSION),
					 errmsg("recursive query \"%s\" does not have the form non-recursive-term UNION [ALL] recursive-term",
							cte->ctename),
					 parser_errposition(cstate->pstate, cte->location)));

		/* The left-hand operand mustn't contain self-reference at all */
		cstate->curitem = i;
		cstate->innerwiths = NIL;
		cstate->selfrefcount = 0;
		cstate->context = RECURSION_NONRECURSIVETERM;
		checkWellFormedRecursionWalker((Node *) stmt->larg, cstate);
		Assert(cstate->innerwiths == NIL);

		/* Right-hand operand should contain one reference in a valid place */
		cstate->curitem = i;
		cstate->innerwiths = NIL;
		cstate->selfrefcount = 0;
		cstate->context = RECURSION_OK;
		checkWellFormedRecursionWalker((Node *) stmt->rarg, cstate);
		Assert(cstate->innerwiths == NIL);
		if (cstate->selfrefcount != 1)	/* shouldn't happen */
			elog(ERROR, "missing recursive reference");

		/* WITH mustn't contain self-reference, either */
		if (stmt->withClause)
		{
			cstate->curitem = i;
			cstate->innerwiths = NIL;
			cstate->selfrefcount = 0;
			cstate->context = RECURSION_SUBLINK;
			checkWellFormedRecursionWalker((Node *) stmt->withClause->ctes,
										   cstate);
			Assert(cstate->innerwiths == NIL);
		}

		/*
		 * Disallow ORDER BY and similar decoration atop the UNION. These
		 * don't make sense because it's impossible to figure out what they
		 * mean when we have only part of the recursive query's results. (If
		 * we did allow them, we'd have to check for recursive references
		 * inside these subtrees.)
		 */
		if (stmt->sortClause)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				  errmsg("ORDER BY in a recursive query is not implemented"),
					 parser_errposition(cstate->pstate,
								  exprLocation((Node *) stmt->sortClause))));
		if (stmt->limitOffset)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("OFFSET in a recursive query is not implemented"),
					 parser_errposition(cstate->pstate,
										exprLocation(stmt->limitOffset))));
		if (stmt->limitCount)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("LIMIT in a recursive query is not implemented"),
					 parser_errposition(cstate->pstate,
										exprLocation(stmt->limitCount))));
		if (stmt->lockingClause)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("FOR UPDATE/SHARE in a recursive query is not implemented"),
					 parser_errposition(cstate->pstate,
							   exprLocation((Node *) stmt->lockingClause))));
	}
}

/*
 * Tree walker function to detect invalid self-references in a recursive query.
 */
static bool
checkWellFormedRecursionWalker(Node *node, CteState *cstate)
{
	RecursionContext save_context = cstate->context;

	if (node == NULL)
		return false;
	if (IsA(node, RangeVar))
	{
		RangeVar   *rv = (RangeVar *) node;

		/* If unqualified name, might be a CTE reference */
		if (!rv->schemaname)
		{
			ListCell   *lc;
			CommonTableExpr *mycte;

			/* ... but first see if it's captured by an inner WITH */
			foreach(lc, cstate->innerwiths)
			{
				List	   *withlist = (List *) lfirst(lc);
				ListCell   *lc2;

				foreach(lc2, withlist)
				{
					CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc2);

					if (strcmp(rv->relname, cte->ctename) == 0)
						return false;	/* yes, so bail out */
				}
			}

			/* No, could be a reference to the query level we are working on */
			mycte = cstate->items[cstate->curitem].cte;
			if (strcmp(rv->relname, mycte->ctename) == 0)
			{
				/* Found a recursive reference to the active query */
				if (cstate->context != RECURSION_OK)
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_RECURSION),
							 errmsg(recursion_errormsgs[cstate->context],
									mycte->ctename),
							 parser_errposition(cstate->pstate,
												rv->location)));
				/* Count references */
				if (++(cstate->selfrefcount) > 1)
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_RECURSION),
							 errmsg("recursive reference to query \"%s\" must not appear more than once",
									mycte->ctename),
							 parser_errposition(cstate->pstate,
												rv->location)));
			}
		}
		return false;
	}
	if (IsA(node, SelectStmt))
	{
		SelectStmt *stmt = (SelectStmt *) node;
		ListCell   *lc;

		if (stmt->withClause)
		{
			if (stmt->withClause->recursive)
			{
				/*
				 * In the RECURSIVE case, all query names of the WITH are
				 * visible to all WITH items as well as the main query. So
				 * push them all on, process, pop them all off.
				 */
				cstate->innerwiths = lcons(stmt->withClause->ctes,
										   cstate->innerwiths);
				foreach(lc, stmt->withClause->ctes)
				{
					CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);

					(void) checkWellFormedRecursionWalker(cte->ctequery, cstate);
				}
				checkWellFormedSelectStmt(stmt, cstate);
				cstate->innerwiths = list_delete_first(cstate->innerwiths);
			}
			else
			{
				/*
				 * In the non-RECURSIVE case, query names are visible to the
				 * WITH items after them and to the main query.
				 */
				ListCell   *cell1;

				cstate->innerwiths = lcons(NIL, cstate->innerwiths);
				cell1 = list_head(cstate->innerwiths);
				foreach(lc, stmt->withClause->ctes)
				{
					CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);

					(void) checkWellFormedRecursionWalker(cte->ctequery, cstate);
					lfirst(cell1) = lappend((List *) lfirst(cell1), cte);
				}
				checkWellFormedSelectStmt(stmt, cstate);
				cstate->innerwiths = list_delete_first(cstate->innerwiths);
			}
		}
		else
			checkWellFormedSelectStmt(stmt, cstate);
		/* We're done examining the SelectStmt */
		return false;
	}
	if (IsA(node, WithClause))
	{
		/*
		 * Prevent raw_expression_tree_walker from recursing directly into a
		 * WITH clause.  We need that to happen only under the control of the
		 * code above.
		 */
		return false;
	}
	if (IsA(node, JoinExpr))
	{
		JoinExpr   *j = (JoinExpr *) node;

		switch (j->jointype)
		{
			case JOIN_INNER:
				checkWellFormedRecursionWalker(j->larg, cstate);
				checkWellFormedRecursionWalker(j->rarg, cstate);
				checkWellFormedRecursionWalker(j->quals, cstate);
				break;
			case JOIN_LEFT:
				checkWellFormedRecursionWalker(j->larg, cstate);
				if (save_context == RECURSION_OK)
					cstate->context = RECURSION_OUTERJOIN;
				checkWellFormedRecursionWalker(j->rarg, cstate);
				cstate->context = save_context;
				checkWellFormedRecursionWalker(j->quals, cstate);
				break;
			case JOIN_FULL:
				if (save_context == RECURSION_OK)
					cstate->context = RECURSION_OUTERJOIN;
				checkWellFormedRecursionWalker(j->larg, cstate);
				checkWellFormedRecursionWalker(j->rarg, cstate);
				cstate->context = save_context;
				checkWellFormedRecursionWalker(j->quals, cstate);
				break;
			case JOIN_RIGHT:
				if (save_context == RECURSION_OK)
					cstate->context = RECURSION_OUTERJOIN;
				checkWellFormedRecursionWalker(j->larg, cstate);
				cstate->context = save_context;
				checkWellFormedRecursionWalker(j->rarg, cstate);
				checkWellFormedRecursionWalker(j->quals, cstate);
				break;
			default:
				elog(ERROR, "unrecognized join type: %d",
					 (int) j->jointype);
		}
		return false;
	}
	if (IsA(node, SubLink))
	{
		SubLink    *sl = (SubLink *) node;

		/*
		 * we intentionally override outer context, since subquery is
		 * independent
		 */
		cstate->context = RECURSION_SUBLINK;
		checkWellFormedRecursionWalker(sl->subselect, cstate);
		cstate->context = save_context;
		checkWellFormedRecursionWalker(sl->testexpr, cstate);
		return false;
	}
	return raw_expression_tree_walker(node,
	                  reinterpret_cast<raw_expression_tree_walker_fptr>(checkWellFormedRecursionWalker),
									  (void *) cstate);
}

/*
 * subroutine for checkWellFormedRecursionWalker: process a SelectStmt
 * without worrying about its WITH clause
 */
static void
checkWellFormedSelectStmt(SelectStmt *stmt, CteState *cstate)
{
	RecursionContext save_context = cstate->context;

	if (save_context != RECURSION_OK)
	{
		/* just recurse without changing state */
		raw_expression_tree_walker((Node *) stmt,
		               reinterpret_cast<raw_expression_tree_walker_fptr>(checkWellFormedRecursionWalker),
								   (void *) cstate);
	}
	else
	{
		switch (stmt->op)
		{
			case SETOP_NONE:
			case SETOP_UNION:
				raw_expression_tree_walker((Node *) stmt,
				               reinterpret_cast<raw_expression_tree_walker_fptr>(checkWellFormedRecursionWalker),
										   (void *) cstate);
				break;
			case SETOP_INTERSECT:
				if (stmt->all)
					cstate->context = RECURSION_INTERSECT;
				checkWellFormedRecursionWalker((Node *) stmt->larg,
											   cstate);
				checkWellFormedRecursionWalker((Node *) stmt->rarg,
											   cstate);
				cstate->context = save_context;
				checkWellFormedRecursionWalker((Node *) stmt->sortClause,
											   cstate);
				checkWellFormedRecursionWalker((Node *) stmt->limitOffset,
											   cstate);
				checkWellFormedRecursionWalker((Node *) stmt->limitCount,
											   cstate);
				checkWellFormedRecursionWalker((Node *) stmt->lockingClause,
											   cstate);
				/* stmt->withClause is intentionally ignored here */
				break;
			case SETOP_EXCEPT:
				if (stmt->all)
					cstate->context = RECURSION_EXCEPT;
				checkWellFormedRecursionWalker((Node *) stmt->larg,
											   cstate);
				cstate->context = RECURSION_EXCEPT;
				checkWellFormedRecursionWalker((Node *) stmt->rarg,
											   cstate);
				cstate->context = save_context;
				checkWellFormedRecursionWalker((Node *) stmt->sortClause,
											   cstate);
				checkWellFormedRecursionWalker((Node *) stmt->limitOffset,
											   cstate);
				checkWellFormedRecursionWalker((Node *) stmt->limitCount,
											   cstate);
				checkWellFormedRecursionWalker((Node *) stmt->lockingClause,
											   cstate);
				/* stmt->withClause is intentionally ignored here */
				break;
			default:
				elog(ERROR, "unrecognized set op: %d",
					 (int) stmt->op);
		}
	}
}


text:
import numpy as np
import pandas as pd
from emulator.env_data import high2low, fix_data
from emulator.env_factor import get_factors

quotes = fix_data('emulator/HS300.csv')
quotes = high2low(quotes, '5min')
daily_quotes = high2low(quotes, '1d')

Index = quotes.index
High = quotes.high.values
Low = quotes.low.values
Close = quotes.close.values
Open = quotes.open.values
Volume = quotes.volume.values
factors = get_factors(Index, Open, Close, High, Low, Volume, rolling=188, drop=True)

daily_quotes['returns'] = np.log(daily_quotes['close'].shift(-1) / daily_quotes['close'])
daily_quotes.dropna(inplace=True)

start_date = pd.to_datetime('2011-01-12')
end_date = pd.to_datetime('2016-12-29')
daily_quotes = daily_quotes.loc[start_date:end_date]
daily_quotes = daily_quotes.iloc[5:]
factors = factors.loc[start_date:end_date]

fac_list = []
for i in range(len(daily_quotes)):
    s = i * 50
    e = (i + 5) * 50
    f = np.array(factors.iloc[s:e])
    fac_list.append(np.expand_dims(f, axis=0))

fac_array = np.concatenate(fac_list, axis=0)
shape = [fac_array.shape[0], 5, 50, fac_array.shape[2]]
fac_array = fac_array.reshape(shape)
fac_array = np.transpose(fac_array, [0, 2, 3, 1])

DATE_QUOTES = daily_quotes
DATA_FAC = fac_array

class Account(object):
    def __init__(self):
        self.data_close = DATE_QUOTES['close']
        self.data_open = DATE_QUOTES['open']
        self.data_observation = DATA_FAC
        self.action_space = ['long', 'short', 'close']
        self.free = 1e-4
        self.reset()

    def reset(self):
        self.step_counter = 0
        self.cash = 1e5
        self.position = 0
        self.total_value = self.cash + self.position
        self.flags = 0
        return self._get_initial_state()

    def _get_initial_state(self):
        return self.data_observation[0]

    def get_action_space(self):
        return self.action_space

    def long(self):
        self.flags = 1
        quotes = self.data_open[self.step_counter] * 10
        self.cash -= quotes * (1 + self.free)
        self.position = quotes

    def short(self):
        self.flags = -1
        quotes = self.data_open[self.step_counter] * 10
        self.cash += quotes * (1 - self.free)
        self.position = - quotes

    def keep(self):
        quotes = self.data_open[self.step_counter] * 10
        self.position = quotes * self.flags

    def close_long(self):
        self.flags = 0
        quotes = self.data_open[self.step_counter] * 10
        self.cash += quotes * (1 - self.free)
        self.position = 0

    def close_short(self):
        self.flags = 0
        quotes = self.data_open[self.step_counter] * 10
        self.cash -= quotes * (1 + self.free)
        self.position = 0

    def step_op(self, action):

        if action == 'long':
            if self.flags == 0:
                self.long()
            elif self.flags == -1:
                self.close_short()
                self.long()
            else:
                self.keep()

        elif action == 'close':
            if self.flags == 1:
                self.close_long()
            elif self.flags == -1:
                self.close_short()
            else:
                pass

        elif action == 'short':
            if self.flags == 0:
                self.short()
            elif self.flags == 1:
                self.close_long()
                self.short()
            else:
                self.keep()
        else:
            raise ValueError("action should be elements of ['long', 'short', 'close']")

        position = self.data_close[self.step_counter] * 10 * self.flags
        reward = np.log((self.cash + position)/self.total_value)
        self.step_counter += 1
        self.total_value = position + self.cash
        next_observation = self.data_observation[self.step_counter]

        done = False
        if self.total_value < 4000:
            done = True
        if self.step_counter > 1000:
            done = True

        return reward, next_observation, done

    def step(self, action):
        if action == 0:
            return self.step_op('long')
        elif action == 1:
            return self.step_op('short')
        elif action == 2:
            return self.step_op('close')
        else:
            raise ValueError("action should be one of [0,1,2]")

redpajama_set_name: RedPajamaGithub


text:
#include "paddle/fluid/operators/softmax_op.h"

#include <string>

#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/cudnn_helper.h"
#endif

#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif

namespace paddle {
namespace operators {

class SoftmaxOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of SoftmaxOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of SoftmaxOp should not be null.");

    ctx->SetOutputDim("Out", ctx->GetInputDim("X"));
    ctx->ShareLoD("X", /*->*/ "Out");
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    // choose cudnn kernel if the runtime supported.
    framework::LibraryType library_{framework::LibraryType::kPlain};
    std::string data_format = ctx.Attr<std::string>("data_format");
    framework::DataLayout layout_ = framework::StringToDataLayout(data_format);

#ifdef PADDLE_WITH_CUDA
    if (platform::CanCUDNNBeUsed(ctx)) {
      library_ = framework::LibraryType::kCUDNN;
    }
#endif
#ifdef PADDLE_WITH_MKLDNN
    if (library_ == framework::LibraryType::kPlain &&
        platform::CanMKLDNNBeUsed(ctx)) {
      library_ = framework::LibraryType::kMKLDNN;
      layout_ = framework::DataLayout::kMKLDNN;
    }
#endif

    auto input_data_type =
        framework::ToDataType(ctx.Input<Tensor>("X")->type());
    if (input_data_type == framework::proto::VarType::FP16) {
      PADDLE_ENFORCE(platform::is_gpu_place(ctx.GetPlace()),
                     "float16 can only be used on GPU place");
    }

    return framework::OpKernelType(input_data_type, ctx.GetPlace(), layout_,
                                   library_);
  }
};

class SoftmaxOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "The input tensor of softmax, "
             "whose last dimension is the input_feature_dimensions.");
    AddOutput("Out", "The normalized values with the same shape as X.")
        .Reuse("X");
    AddAttr<bool>(
        "use_cudnn",
        "(bool, default false) Only used in cudnn kernel, need install cudnn")
        .SetDefault(false);
    AddAttr<std::string>(
        "data_format",
        "(string, default NCHW) Only used in "
        "An optional string from: \"NHWC\", \"NCHW\". "
        "Defaults to \"NHWC\". Specify the data format of the output data, "
        "the input will be transformed automatically. ")
        .SetDefault("AnyLayout");
    AddAttr<bool>("use_mkldnn",
                  "(bool, default false) Only used in mkldnn kernel")
        .SetDefault(false);
    AddAttr<bool>("is_test",
                  "Disable epsilon adding to softmax results. Used by MKLDNN.")
        .SetDefault(false);
    AddComment(R"DOC(
Softmax Operator.

The input of the softmax operator is a tensor of any rank. The output tensor
has the same shape as the input.

The input tensor will first be logically flattened to a 2-D matrix. The matrix's
second dimension(row length) is as same as the last dimension of the input
tensor, and the first dimension(column length) is the product of all other
dimensions of the input tensor. For each row of the matrix, the softmax operator
squashes the K-dimensional(K is the width of the matrix, which is also the size
of the input tensor's last dimension) vector of arbitrary real values to a
K-dimensional vector of real values in the range [0, 1] that add up to 1.
It computes the exponential of the given dimension and the sum of exponential
values of all the other dimensions in the K-dimensional vector input.
Then the ratio of the exponential of the given dimension and the sum of
exponential values of all the other dimensions is the output of the softmax
operator.

For each row $i$ and each column $j$ in the matrix, we have:
    $$Out[i, j] = \frac{\exp(X[i, j])}{\sum_j(exp(X[i, j])}$$

)DOC");
  }
};

class SoftmaxOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Out"), "Input(Out) should be not null.");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Input(Out@GRAD) should be not null.");
    PADDLE_ENFORCE_EQ(ctx->GetInputDim("Out"),
                      ctx->GetInputDim(framework::GradVarName("Out")),
                      "Input(Out) and its gradients should have a same shape.");

    ctx->SetOutputDim(framework::GradVarName("X"),
                      ctx->GetInputDim(framework::GradVarName("Out")));
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    // choose cudnn kernel if the runtime supported.
    framework::LibraryType library_{framework::LibraryType::kPlain};
    std::string data_format = ctx.Attr<std::string>("data_format");
    framework::DataLayout layout_ = framework::StringToDataLayout(data_format);

#ifdef PADDLE_WITH_CUDA
    if (platform::CanCUDNNBeUsed(ctx)) {
      library_ = framework::LibraryType::kCUDNN;
    }
#endif
#ifdef PADDLE_WITH_MKLDNN
    if (library_ == framework::LibraryType::kPlain &&
        platform::CanMKLDNNBeUsed(ctx)) {
      library_ = framework::LibraryType::kMKLDNN;
      layout_ = framework::DataLayout::kMKLDNN;
    }
#endif
    auto input_data_type = framework::ToDataType(
        ctx.Input<Tensor>(framework::GradVarName("Out"))->type());
    if (input_data_type == framework::proto::VarType::FP16) {
      PADDLE_ENFORCE(platform::is_gpu_place(ctx.GetPlace()),
                     "float16 can only be used on GPU place");
    }

    return framework::OpKernelType(input_data_type, ctx.GetPlace(), layout_,
                                   library_);
  }
};

class SoftmaxOpGradMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
  std::unique_ptr<framework::OpDesc> Apply() const override {
    auto* op = new framework::OpDesc();
    op->SetType("softmax_grad");

    op->SetInput("Out", Output("Out"));
    op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));

    op->SetAttrMap(Attrs());

    op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
    return std::unique_ptr<framework::OpDesc>(op);
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OPERATOR(softmax, ops::SoftmaxOp, ops::SoftmaxOpMaker,
                  ops::SoftmaxOpGradMaker);
REGISTER_OPERATOR(softmax_grad, ops::SoftmaxOpGrad);
REGISTER_OP_CPU_KERNEL(
    softmax, ops::SoftmaxKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SoftmaxKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
    softmax_grad,
    ops::SoftmaxGradKernel<paddle::platform::CPUDeviceContext, float>,
    ops::SoftmaxGradKernel<paddle::platform::CPUDeviceContext, double>);


text:
package de.wicketxforms.formcontrols;

import java.util.Collection;

import org.apache.wicket.Component;
import org.w3c.dom.Element;
import org.w3c.dom.events.Event;

import de.betterform.xml.events.XFormsEventNames;
import de.wicketxforms.processor.ProcessorID;

/**
 * Adds additional functionality for FormControls listening to events that may effect the styling
 * of a FormControl through CSS classes.
 * (e.g. the {@code xforms-valid} and {@code xforms-invalid} events.)

 * When handling those events the CSS classes of the component with applied style attributes will be
 * updated accordingly. See also {@link #applyStyleAttributes(Component)}.
 *

 * If {@link #getWicketComponent()} retrieves a class implementing the
 * {@link IStyleUpdatingFormControlComponent}-Interface, it's hook methods will be called when
 * appropriate. See also {@link #callOnStateChangeHooks()}.
 *
 * @author Karl Scheel
 */
public abstract class AbstractStyleUpdatingFormControl extends AbstractFormControl {

  /**
   * Wicket-Model, das dynamisch CSS-Klassen je nach Status dieses FormControls liefert.
   */
  private final CssClassModel cssClassValueModel;

  /* -------------------------------------------------------------------------------------------- */

  /**
   * @see AbstractFormControl#AbstractFormControl(ProcessorID, Element)
   */
  protected AbstractStyleUpdatingFormControl(final ProcessorID processorID,
                                             final Element formControlNode) {

    super(processorID, formControlNode);

    cssClassValueModel = new CssClassModel(getFormControlNode());
  }

  /* -------------------------------------------------------------------------------------------- */

  /**
   * Executes the "onStateChange" hook methods of this controls
   * {@link IStyleUpdatingFormControlComponent}. Subclasses can use this to initialize their Wicket
   * component after creating it.
   *
   * @see IStyleUpdatingFormControlComponent
   * @see #getWicketComponent()
   */
  protected void callOnStateChangeHooks() {

    if (getWicketComponent() instanceof IStyleUpdatingFormControlComponent) {

      IStyleUpdatingFormControlComponent component = (IStyleUpdatingFormControlComponent) getWicketComponent();

      component.onReadOnlyStateChange(cssClassValueModel.isReadOnly);
      component.onRelevantStateChange(cssClassValueModel.isRelevant);
      component.onRequiredStateChange(cssClassValueModel.isRequired);
      component.onValidStateChange(cssClassValueModel.isValid);
    }
  }

  // adds additional CSS classes describing this FormControls state.
  @Override
  protected void modifyClassAttribute(Component component) {

    String staticClassValue = getCssClass().toString();
    Element formControl = getFormControlNode();

    if (formControl.hasAttributeNS(WICKETXFORMS_NAMESPACE, "class"))
       staticClassValue += " " + formControl.getAttributeNS(WICKETXFORMS_NAMESPACE, "class");

    component.add(new ClassAttributeModifier(staticClassValue, cssClassValueModel));
  }

  @Override
  protected Collection<String> getEventsToListenTo() {

    Collection<String> eventTypes = super.getEventsToListenTo();

    eventTypes.add(XFormsEventNames.VALID);
    eventTypes.add(XFormsEventNames.INVALID);
    eventTypes.add(XFormsEventNames.REQUIRED);
    eventTypes.add(XFormsEventNames.OPTIONAL);
    eventTypes.add(XFormsEventNames.READONLY);
    eventTypes.add(XFormsEventNames.READWRITE);
    eventTypes.add(XFormsEventNames.ENABLED);
    eventTypes.add(XFormsEventNames.DISABLED);

    return eventTypes;
  }

  @Override
  protected void onEventReceived(Event e) {

    super.onEventReceived(e);

    switch (e.getType()) {

      case XFormsEventNames.VALID:
        changeValidState(true);
        break;

      case XFormsEventNames.INVALID:
        changeValidState(false);
        break;

      case XFormsEventNames.REQUIRED:
        changeRequiredState(true);
        break;

      case XFormsEventNames.OPTIONAL:
        changeRequiredState(false);
        break;

      case XFormsEventNames.READONLY:
        changeReadOnlyState(true);
        break;

      case XFormsEventNames.READWRITE:
        changeReadOnlyState(false);
        break;

      case XFormsEventNames.ENABLED:
        changeRelevantState(true);
        break;

      case XFormsEventNames.DISABLED:
        changeRelevantState(false);
        break;
    }
  }

  private void changeValidState(boolean newValue) {

    if (cssClassValueModel.isValid != newValue) {

      cssClassValueModel.isValid = newValue;

      if (getWicketComponent() instanceof IStyleUpdatingFormControlComponent)
        ((IStyleUpdatingFormControlComponent) getWicketComponent()).onValidStateChange(newValue);
    }
  }

  private void changeReadOnlyState(boolean newValue) {

    if (cssClassValueModel.isReadOnly != newValue) {

      cssClassValueModel.isReadOnly = newValue;

      if (getWicketComponent() instanceof IStyleUpdatingFormControlComponent)
        ((IStyleUpdatingFormControlComponent) getWicketComponent()).onReadOnlyStateChange(newValue);
    }
  }

  private void changeRequiredState(boolean newValue) {

    if (cssClassValueModel.isRequired != newValue) {

      cssClassValueModel.isRequired = newValue;

      if (getWicketComponent() instanceof IStyleUpdatingFormControlComponent)
        ((IStyleUpdatingFormControlComponent) getWicketComponent()).onRequiredStateChange(newValue);
    }
  }

  private void changeRelevantState(boolean newValue) {

    if (cssClassValueModel.isRelevant != newValue) {

      cssClassValueModel.isRelevant = newValue;

      if (getWicketComponent() instanceof IStyleUpdatingFormControlComponent)
        ((IStyleUpdatingFormControlComponent) getWicketComponent()).onRelevantStateChange(newValue);
    }
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>

    <database id="DatabaseMapping">
        <schema>demoHotels</schema>
        <readOnly>false</readOnly>
        <dialect>org.ujorm.orm.dialect.H2Dialect</dialect>
        <jdbcUrl>jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1</jdbcUrl>
        <jdbcDriver>org.h2.Driver</jdbcDriver>
        <user>sa</user>
        <sequencer>org.ujorm.orm.UjoSequencer</sequencer>
        <orm2ddlPolicy>CREATE_OR_UPDATE_DDL</orm2ddlPolicy>

            <name>demo_hotel</name>
            <alias>demo_hotel</alias>
            <schema>demoHotels</schema>
            <orm2ddlPolicy>CREATE_OR_UPDATE_DDL</orm2ddlPolicy>
            <column id="ID">
                <name>ID</name>
                <primaryKey>true</primaryKey>
                <dbType>BIGINT</dbType>
                <comment>The Primary Key</comment>
            </column>
            <column id="NAME">
                <name>NAME</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>40</maxLength>
                <index>idx_hotel_name</index>
                <comment>Name of the Hotel</comment>
            </column>
            <column id="NOTE">
                <name>NOTE</name>
                <dbType>VARCHAR</dbType>
                <maxLength>256</maxLength>
                <comment>Description of the hotel</comment>
            </column>
            <column id="CITY">
                <name>CITY</name>
                <dbType>INT</dbType>
                <mandatory>true</mandatory>
                <comment>Relation to the City address</comment>
            </column>
            <column id="STREET">
                <name>STREET</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>128</maxLength>
                <comment>Street of address</comment>
            </column>
            <column id="PHONE">
                <name>PHONE</name>
                <dbType>VARCHAR</dbType>
                <maxLength>20</maxLength>
                <comment>Phone</comment>
            </column>
            <column id="STARS">
                <name>STARS</name>
                <dbType>REAL</dbType>
                <mandatory>true</mandatory>
                <comment>Stars</comment>
            </column>
            <column id="HOME_PAGE">
                <name>HOME_PAGE</name>
                <dbType>VARCHAR</dbType>
                <maxLength>100</maxLength>
                <comment>URL to the HomePage</comment>
            </column>
            <column id="PRICE">
                <name>PRICE</name>
                <dbType>DECIMAL</dbType>
                <mandatory>true</mandatory>
                <maxLength>8</maxLength>
                <precision>2</precision>
                <comment>Price per night in USD</comment>
            </column>
            <column id="CURRENCY">
                <name>CURRENCY</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>3</maxLength>
                <comment>Currency of the price</comment>
            </column>
            <column id="ACTIVE">
                <name>ACTIVE</name>
                <dbType>BOOLEAN</dbType>
                <mandatory>true</mandatory>
                <index>idx_hotel_name</index>
                <comment>Hotel state (the true or null is required)</comment>
            </column>

            <name>demo_customer</name>
            <alias>demo_customer</alias>
            <schema>demoHotels</schema>
            <orm2ddlPolicy>CREATE_OR_UPDATE_DDL</orm2ddlPolicy>
            <column id="ID">
                <name>ID</name>
                <primaryKey>true</primaryKey>
                <dbType>INT</dbType>
                <comment>The Primary Key</comment>
            </column>
            <column id="LOGIN">
                <name>LOGIN</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>6</maxLength>
                <uniqueIndex>idx_unique_login</uniqueIndex>
                <comment>Unique login</comment>
            </column>
            <column id="PASSWORD_HASH">
                <name>PASSWORD_HASH</name>
                <dbType>BIGINT</dbType>
                <mandatory>true</mandatory>
                <comment>Password hash</comment>
            </column>
            <column id="TITLE">
                <name>TITLE</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>2</maxLength>
                <comment>Title</comment>
            </column>
            <column id="FIRSTNAME">
                <name>FIRSTNAME</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>60</maxLength>
                <comment>Firstname</comment>
            </column>
            <column id="SURNAME">
                <name>SURNAME</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>60</maxLength>
                <comment>Lastname</comment>
            </column>
            <column id="EMAIL">
                <name>EMAIL</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>128</maxLength>
                <comment>Email</comment>
            </column>
            <column id="ADMIN">
                <name>ADMIN</name>
                <dbType>BOOLEAN</dbType>
                <comment>Administrator role sign</comment>
            </column>
            <column id="ACTIVE">
                <name>ACTIVE</name>
                <dbType>BOOLEAN</dbType>
                <uniqueIndex>idx_unique_login</uniqueIndex>
                <comment>Customer is allowed to login (the true or null values are required)</comment>
            </column>

            <name>demo_booking</name>
            <alias>demo_booking</alias>
            <schema>demoHotels</schema>
            <orm2ddlPolicy>CREATE_OR_UPDATE_DDL</orm2ddlPolicy>
            <column id="ID">
                <name>ID</name>
                <primaryKey>true</primaryKey>
                <dbType>BIGINT</dbType>
                <comment>The Primary Key</comment>
            </column>
            <column id="HOTEL">
                <name>HOTEL</name>
                <dbType>BIGINT</dbType>
                <mandatory>true</mandatory>
                <index>idx_booking</index>
                <comment>Relation to hotel</comment>
            </column>
            <column id="CUSTOMER">
                <name>CUSTOMER</name>
                <dbType>INT</dbType>
                <mandatory>true</mandatory>
                <index>idx_booking</index>
                <comment>Relation to customer</comment>
            </column>
            <column id="DATE_FROM">
                <name>DATE_FROM</name>
                <dbType>DATE</dbType>
                <mandatory>true</mandatory>
                <comment>Date from</comment>
            </column>
            <column id="NIGHTS">
                <name>NIGHTS</name>
                <dbType>SMALLINT</dbType>
                <comment>Number of nights</comment>
            </column>
            <column id="PERSONS">
                <name>PERSONS</name>
                <dbType>SMALLINT</dbType>
                <comment>Number of persons (limit from 1 to 50)</comment>
            </column>
            <column id="PRICE">
                <name>PRICE</name>
                <dbType>DECIMAL</dbType>
                <mandatory>true</mandatory>
                <maxLength>8</maxLength>
                <precision>2</precision>
                <comment>Total price</comment>
            </column>
            <column id="CURRENCY">
                <name>CURRENCY</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>3</maxLength>
                <comment>Currency of the total price</comment>
            </column>
            <column id="CREATION_DATE">
                <name>CREATION_DATE</name>
                <dbType>DATE</dbType>
                <mandatory>true</mandatory>
                <comment>Creation date of booking.</comment>
            </column>

            <name>demo_city</name>
            <alias>demo_city</alias>
            <schema>demoHotels</schema>
            <orm2ddlPolicy>CREATE_OR_UPDATE_DDL</orm2ddlPolicy>
            <column id="ID">
                <name>ID</name>
                <primaryKey>true</primaryKey>
                <dbType>INT</dbType>
                <comment>The Primary Key</comment>
            </column>
            <column id="NAME">
                <name>NAME</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>40</maxLength>
                <uniqueIndex>idx_unique_city</uniqueIndex>
                <comment>City name</comment>
            </column>
            <column id="COUNTRY">
                <name>COUNTRY</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>3</maxLength>
                <comment>Two characters country code along the ISO 3166</comment>
            </column>
            <column id="COUNTRY_NAME">
                <name>COUNTRY_NAME</name>
                <dbType>VARCHAR</dbType>
                <mandatory>true</mandatory>
                <maxLength>40</maxLength>
                <comment>Country name will be located in the another entity in a real application</comment>
            </column>
            <column id="LATITUDE">
                <name>LATITUDE</name>
                <dbType>REAL</dbType>
                <mandatory>true</mandatory>
                <comment>A geographic coordinate for north-south position on the Earth</comment>
            </column>
            <column id="LONGITUDE">
                <name>LONGITUDE</name>
                <dbType>REAL</dbType>
                <mandatory>true</mandatory>
                <comment>A geographic coordinate for east-west position on the Earth</comment>
            </column>

            <name>demoHotels</name>
            <alias>demoHotels</alias>
            <schema>demoHotels</schema>
            <orm2ddlPolicy>CREATE_OR_UPDATE_DDL</orm2ddlPolicy>
            <relation2m id="HOTEL">
                <name>HOTEL</name>
            </relation2m>
            <relation2m id="CUSTOMER">
                <name>CUSTOMER</name>
            </relation2m>
            <relation2m id="BOOKING">
                <name>BOOKING</name>
            </relation2m>
            <relation2m id="CITY">
                <name>CITY</name>
            </relation2m>

    </database>
    <parameters>
        <initializationBatch>org.ujorm.hotels.config.demoData.DataLoader</initializationBatch>
        <sequenceSchemaSymbol>true</sequenceSchemaSymbol>
        <moreParams></moreParams>
    </parameters>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 *
 * @author Júlio
 */
public class Controller implements ActionListener, ModelListener{
    private Model model;
    private View view;

    public void associaModel(Model m){
        model = m;
        model.addModelListener(this);
    }

    public void associaView(View v) {
        view = v;
    }

    public void inicializaModel(int v) {
        model.setValor(v);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        model.incrementaValor();
    }

    @Override
    public void valorAlterado(int v) {
        view.setCampoTexto(v);
    }

}


text:
<?php namespace Ordercloud\Requests\Orders;

use Ordercloud\Requests\Orders\Entities\NewOrderItem;
use Ordercloud\Support\CommandBus\Command;

/**
 * Class CreateOrderRequest
 *
 * @see Ordercloud\Requests\Orders\Handlers\CreateOrderRequestHandler
 */
class CreateOrderRequest implements Command
{
    /** @var int */
    private $userId;
    /** @var int */
    private $organisationId;
    /** @var array|NewOrderItem[] */
    private $items;
    /** @var string|float */
    private $amount;
    /** @var string */
    private $paymentStatus;
    /** @var string */
    private $deliveryType;
    /** @var int */
    private $deliveryAddressId;
    /** @var string */
    private $note;
    /**
     * @var int
     */
    private $tip;
    /**
     * @var int
     */
    private $deliveryServiceId;
    /**
     * @var int
     */
    private $orderSourceChannelId;
    /**
     * @var string
     */
    private $scheduledTime;
    /**
     * @var float
     */
    private $deliveryCost;

    public function __construct($userId, $organisationId, array $items, $amount, $paymentStatus, $deliveryType, $deliveryAddressId, $note, $tip, $deliveryServiceId, $orderSourceChannelId, $scheduledTime, $deliveryCost)
    {
        $this->userId = $userId;
        $this->organisationId = $organisationId;
        $this->items = $items;
        $this->amount = $amount;
        $this->paymentStatus = $paymentStatus;
        $this->deliveryType = $deliveryType;
        $this->deliveryAddressId = $deliveryAddressId;
        $this->note = $note;
        $this->tip = $tip;
        $this->deliveryServiceId = $deliveryServiceId;
        $this->orderSourceChannelId = $orderSourceChannelId;
        $this->scheduledTime = $scheduledTime;
        $this->deliveryCost = $deliveryCost;
    }

    /**
     * @return int
     */
    public function getUserId()
    {
        return $this->userId;
    }

    /**
     * @return int
     */
    public function getOrganisationId()
    {
        return $this->organisationId;
    }

    /**
     * @return array
     */
    public function getItems()
    {
        return $this->items;
    }

    /**
     * @return float|string
     */
    public function getAmount()
    {
        return $this->amount;
    }

    /**
     * @return string
     */
    public function getPaymentStatus()
    {
        return $this->paymentStatus;
    }

    /**
     * @return string
     */
    public function getDeliveryType()
    {
        return $this->deliveryType;
    }

    /**
     * @return int|null
     */
    public function getDeliveryAddressId()
    {
        return $this->deliveryAddressId;
    }

    /**
     * @return null|string
     */
    public function getNote()
    {
        return $this->note;
    }

    /**
     * @return int
     */
    public function getTip()
    {
        return $this->tip;
    }

    /**
     * @return int
     */
    public function getDeliveryServiceId()
    {
        return $this->deliveryServiceId;
    }

    /**
     * @return int
     */
    public function getOrderSourceChannelId()
    {
        return $this->orderSourceChannelId;
    }

    /**
     * @return string
     */
    public function getScheduledTime()
    {
        return $this->scheduledTime;
    }

    /**
     * @return float
     */
    public function getDeliveryCost()
    {
        return $this->deliveryCost;
    }
}


text:
PoolerAll::PoolerAll(const Options& iOptions, const Data& iData) :
      Pooler(iOptions, iData) {
   iOptions.check();
}

int PoolerAll::findCore(const Location& iLocation) const {
   return 0;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>study-parent</artifactId>
        <groupId>com.oschina</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>study-blog</artifactId>
    <packaging>pom</packaging>
    <modules>
        <module>study-blog-pojo</module>
        <module>study-blog-mapper</module>
        <module>study-blog-service</module>
        <module>study-blog-controller</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>

</project>


text:
const { MongoClient } = require("mongodb");
const { atlasURL } = require("../../ApiKeys");

const connection = MongoClient.connect(atlasURL);

connection
  .then((db) => {
    const collection = db.collection("randoms");

    const promise1 = collection.update(
      {
        name: "notRandom",
      },
      {
        name: "notRandom",
      },
      { upsert: true }
    );

    promise1
      .then((msg) => {
        console.log(msg.result);
      })
      .then(() => {
        collection
          .find()
          .toArray()
          .then(docs =>
            docs.forEach((element) => {
              console.log(element);
            }))
          .then(() => {
            db.close();
          });
      })
      .catch((err) => {
        console.error(err);
      });
  })
  .catch(err => console.error(err));


text:
<def-group>
  <!-- THIS FILE IS GENERATED by create_services_disabled.py.  DO NOT EDIT.  -->
  <definition class="compliance" id="service_saslauthd_disabled"
  version="1">
    <metadata>
      <title>Service saslauthd Disabled</title>
      <affected family="unix">
        <platform>Red Hat Enterprise Linux 6</platform>
      </affected>
      <description>The saslauthd service should be disabled if possible.</description>
    </metadata>
   <criteria comment="package cyrus-sasl removed or service saslauthd is not configured to start" operator="OR">
    <extend_definition comment="cyrus-sasl removed" definition_ref="package_cyrus-sasl_removed" />
    <criteria operator="AND" comment="service saslauthd is not configured to start">
      <criterion comment="saslauthd runlevel 0" test_ref="test_runlevel0_saslauthd" />
      <criterion comment="saslauthd runlevel 1" test_ref="test_runlevel1_saslauthd" />
      <criterion comment="saslauthd runlevel 2" test_ref="test_runlevel2_saslauthd" />
      <criterion comment="saslauthd runlevel 3" test_ref="test_runlevel3_saslauthd" />
      <criterion comment="saslauthd runlevel 4" test_ref="test_runlevel4_saslauthd" />
      <criterion comment="saslauthd runlevel 5" test_ref="test_runlevel5_saslauthd" />
      <criterion comment="saslauthd runlevel 6" test_ref="test_runlevel6_saslauthd" />
    </criteria>
    </criteria>
  </definition>
  <unix:runlevel_test check="all" check_existence="any_exist"
  comment="Runlevel test" id="test_runlevel0_saslauthd"
  version="2">
    <unix:object object_ref="obj_runlevel0_saslauthd" />
    <unix:state state_ref="state_service_saslauthd_off" />
  </unix:runlevel_test>
  <unix:runlevel_test check="all" check_existence="any_exist"
  comment="Runlevel test" id="test_runlevel1_saslauthd"
  version="2">
    <unix:object object_ref="obj_runlevel1_saslauthd" />
    <unix:state state_ref="state_service_saslauthd_off" />
  </unix:runlevel_test>
  <unix:runlevel_test check="all" check_existence="any_exist"
  comment="Runlevel test" id="test_runlevel2_saslauthd"
  version="2">
    <unix:object object_ref="obj_runlevel2_saslauthd" />
    <unix:state state_ref="state_service_saslauthd_off" />
  </unix:runlevel_test>
  <unix:runlevel_test check="all" check_existence="any_exist"
  comment="Runlevel test" id="test_runlevel3_saslauthd"
  version="2">
    <unix:object object_ref="obj_runlevel3_saslauthd" />
    <unix:state state_ref="state_service_saslauthd_off" />
  </unix:runlevel_test>
  <unix:runlevel_test check="all" check_existence="any_exist"
  comment="Runlevel test" id="test_runlevel4_saslauthd"
  version="2">
    <unix:object object_ref="obj_runlevel4_saslauthd" />
    <unix:state state_ref="state_service_saslauthd_off" />
  </unix:runlevel_test>
  <unix:runlevel_test check="all" check_existence="any_exist"
  comment="Runlevel test" id="test_runlevel5_saslauthd"
  version="2">
    <unix:object object_ref="obj_runlevel5_saslauthd" />
    <unix:state state_ref="state_service_saslauthd_off" />
  </unix:runlevel_test>
  <unix:runlevel_test check="all" check_existence="any_exist"
  comment="Runlevel test" id="test_runlevel6_saslauthd"
  version="2">
    <unix:object object_ref="obj_runlevel6_saslauthd" />
    <unix:state state_ref="state_service_saslauthd_off" />
  </unix:runlevel_test>
  <unix:runlevel_object id="obj_runlevel0_saslauthd" version="1">
    <unix:service_name>saslauthd</unix:service_name>
    <unix:runlevel operation="equals">0</unix:runlevel>
  </unix:runlevel_object>
  <unix:runlevel_object id="obj_runlevel1_saslauthd" version="1">
    <unix:service_name>saslauthd</unix:service_name>
    <unix:runlevel operation="equals">1</unix:runlevel>
  </unix:runlevel_object>
  <unix:runlevel_object id="obj_runlevel2_saslauthd" version="1">
    <unix:service_name>saslauthd</unix:service_name>
    <unix:runlevel operation="equals">2</unix:runlevel>
  </unix:runlevel_object>
  <unix:runlevel_object id="obj_runlevel3_saslauthd" version="1">
    <unix:service_name>saslauthd</unix:service_name>
    <unix:runlevel operation="equals">3</unix:runlevel>
  </unix:runlevel_object>
  <unix:runlevel_object id="obj_runlevel4_saslauthd" version="1">
    <unix:service_name>saslauthd</unix:service_name>
    <unix:runlevel operation="equals">4</unix:runlevel>
  </unix:runlevel_object>
  <unix:runlevel_object id="obj_runlevel5_saslauthd" version="1">
    <unix:service_name>saslauthd</unix:service_name>
    <unix:runlevel operation="equals">5</unix:runlevel>
  </unix:runlevel_object>
  <unix:runlevel_object id="obj_runlevel6_saslauthd" version="1">
    <unix:service_name>saslauthd</unix:service_name>
    <unix:runlevel operation="equals">6</unix:runlevel>
  </unix:runlevel_object>
  <unix:runlevel_state comment="not configured to start" id="state_service_saslauthd_off" version="1">
    <unix:start datatype="boolean">false</unix:start>
    <unix:kill datatype="boolean">true</unix:kill>
  </unix:runlevel_state>
</def-group>


text:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;

namespace SoapCore.Tests.Wsdl.Services
{
	[ServiceContract]
	public interface ICollectionDataContractService
	{
		[OperationContract]
		CollectionDataContractService.MyList<string> ListStrings();

		[OperationContract]
		CollectionDataContractService.MyList<CollectionDataContractService.MyType> ListMyTypes();
	}

	public class CollectionDataContractService : ICollectionDataContractService
	{
		public MyList<string> ListStrings() => throw new NotImplementedException();
		public MyList<MyType> ListMyTypes() => throw new NotImplementedException();

		[CollectionDataContract(Namespace = "http://testnamespace.org", Name = "My{0}List", ItemName = "MyItem")]
		public class MyList<T> : List<T>
		{
		}

		public class MyType
		{
			public string MyProperty { get; set; }
		}
	}
}


text:
'use strict';

require('../helper');

var server = require('../../lib/server')();
var assert = require('../support/assert');
var qs = require('querystring');
var MockDate = require('mockdate');

describe('last modified header', function () {
    var scenarios = [
        {
            tables: ['untitle_table_4'],
            desc: 'should use last updated time from public table',
            expectedLastModified: 'Wed, 01 Jan 2014 23:31:30 GMT'
        },
        {
            tables: ['private_table'],
            desc: 'should use last updated time from private table',
            expectedLastModified: 'Thu, 01 Jan 2015 23:31:30 GMT'
        },
        {
            tables: ['untitle_table_4', 'private_table'],
            desc: 'should use most recent last updated time from private and public table',
            expectedLastModified: 'Thu, 01 Jan 2015 23:31:30 GMT'
        },
        {
            tables: ['populated_places_simple_reduced', 'private_table'],
            desc: 'should use last updated time from table in cdb_tablemetadata instead of now() from unknown table',
            expectedLastModified: 'Thu, 01 Jan 2015 23:31:30 GMT'
        }
    ];

    scenarios.forEach(function (scenario) {
        it(scenario.desc, function (done) {
            var query = qs.stringify({
                q: scenario.tables.map(function (table) {
                    return 'select cartodb_id from ' + table;
                }).join(' UNION ALL '),
                api_key: 1234
            });
            assert.response(server,
                {
                    url: '/api/v1/sql?' + query,
                    headers: {
                        host: 'vizzuality.cartodb.com'
                    },
                    method: 'GET'
                },
                {
                    statusCode: 200
                },
                function (err, res) {
                    assert.ifError(err);
                    assert.strictEqual(res.headers['last-modified'], scenario.expectedLastModified);
                    done();
                }
            );
        });
    });

    it('should use Date.now() for tables not present in cdb_tablemetadata', function (done) {
        var query = qs.stringify({
            q: 'select cartodb_id from populated_places_simple_reduced limit 1',
            api_key: 1234
        });
        var fixedDateNow = Date.now();
        MockDate.set(fixedDateNow);
        assert.response(server,
            {
                url: '/api/v1/sql?' + query,
                headers: {
                    host: 'vizzuality.cartodb.com'
                },
                method: 'GET'
            },
            {
                statusCode: 200
            },
            function (err, res) {
                assert.ifError(err);
                MockDate.reset();
                assert.strictEqual(res.headers['last-modified'], new Date(fixedDateNow).toUTCString());
                done();
            }
        );
    });

    it('should use Date.now() for functions or results with no table associated', function (done) {
        var query = qs.stringify({
            q: 'select 1',
            api_key: 1234
        });
        var fixedDateNow = Date.now();
        MockDate.set(fixedDateNow);
        assert.response(server,
            {
                url: '/api/v1/sql?' + query,
                headers: {
                    host: 'vizzuality.cartodb.com'
                },
                method: 'GET'
            },
            {
                statusCode: 200
            },
            function (err, res) {
                assert.ifError(err);
                MockDate.reset();
                assert.strictEqual(res.headers['last-modified'], new Date(fixedDateNow).toUTCString());
                done();
            }
        );
    });
});


text:
/**
 * webkitRTCPeerConnection.js file
 */

webkitRTCPeerConnection = function(pc_config, con) {
	this.iceGatheringState = "";
	this.signalingState = "";
	this.iceConnectionState = "";

	this.pc_id = pcManagerJS.pc_new(this, pc_config, con);
};

webkitRTCPeerConnection.prototype.addStream = function(stream) {
	stream.pc_id = this.pc_id; // 本地流在这个时候才与某一个pc对象绑定

	return pcManagerJS.call_method('addStream', this.pc_id, stream);
};

webkitRTCPeerConnection.prototype.removeStream = function(stream) {
	return pcManagerJS.call_method('removeStream', this.pc_id, stream);
};

webkitRTCPeerConnection.prototype.close = function() {
	return pcManagerJS.call_method('close', this.pc_id, {});
};

webkitRTCPeerConnection.prototype.createAnswer = function(callback, obj, constraints) {
	this.cb_createAnswer = callback;

	return pcManagerJS.call_method('createAnswer', this.pc_id, constraints);
};

webkitRTCPeerConnection.prototype.createOffer = function(callback, obj, constraints) {
	this.cb_createOffer = callback;

	return pcManagerJS.call_method('createOffer', this.pc_id, constraints);
};

webkitRTCPeerConnection.prototype.createDataChannel = function(param) {
	return pcManagerJS.call_method('createDataChannel', this.pc_id, param);
};

webkitRTCPeerConnection.prototype.setLocalDescription = function(sd) {
	return pcManagerJS.call_method('setLocalDescription', this.pc_id, sd);
};

webkitRTCPeerConnection.prototype.setRemoteDescription = function(sd) {
	return pcManagerJS.call_method('setRemoteDescription', this.pc_id, sd);
};

webkitRTCPeerConnection.prototype.updateIce = function(param) {
	return pcManagerJS.call_method('updateIce', this.pc_id, param);
};

webkitRTCPeerConnection.prototype.addIceCandidate = function(ice) {
	return pcManagerJS.call_method('addIceCandidate', this.pc_id, ice);
};

webkitRTCPeerConnection.prototype.getStats = function() {
	return pcManagerJS.call_method('getStats', this.pc_id, {});
};


text:
require 'spec_helper'

RSpec.describe 'Projects > Members > User requests access', :js do
  let(:user) { create(:user) }
  let(:project) { create(:project, :public, :repository) }
  let(:maintainer) { project.owner }

  before do
    sign_in(user)
    visit project_path(project)
  end

  it 'request access feature is disabled' do
    project.update(request_access_enabled: false)
    visit project_path(project)

    expect(page).not_to have_content 'Request Access'
  end

  it 'user can request access to a project' do
    perform_enqueued_jobs { click_link 'Request Access' }

    expect(ActionMailer::Base.deliveries.last.to).to eq [maintainer.notification_email]
    expect(ActionMailer::Base.deliveries.last.subject).to eq "Request to join the #{project.full_name} project"

    expect(project.requesters.exists?(user_id: user)).to be_truthy

    expect(page).to have_content 'Withdraw Access Request'
    expect(page).not_to have_content 'Leave Project'
  end

  context 'code access is restricted' do
    it 'user can request access' do
      project.project_feature.update!(repository_access_level: ProjectFeature::PRIVATE,
                                      builds_access_level: ProjectFeature::PRIVATE,
                                      merge_requests_access_level: ProjectFeature::PRIVATE)
      visit project_path(project)

      expect(page).to have_content 'Request Access'
    end
  end

  it 'user is not listed in the project members page' do
    click_link 'Request Access'

    expect(project.requesters.exists?(user_id: user)).to be_truthy

    page.within('.nav-sidebar') do
      click_link('Members')
    end

    page.within('.content') do
      expect(page).not_to have_content(user.name)
    end
  end

  it 'user can withdraw its request for access' do
    click_link 'Request Access'

    expect(project.requesters.exists?(user_id: user)).to be_truthy

    accept_confirm { click_link 'Withdraw Access Request' }

    expect(page).not_to have_content 'Withdraw Access Request'
    expect(page).to have_content 'Request Access'
  end

  def open_project_settings_menu
    page.within('.layout-nav .nav-links') do
      click_link('Settings')
    end

    page.within('.sub-nav') do
      click_link('Members')
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
  "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

  <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />

  <title>RemoteApp</title>

  <link type="text/css" media="screen" href="rdoc.css" rel="stylesheet" />

RemoteApp

This is the API documentation for 'RemoteApp'.

Files

LICENSE

Rakefile

xbmc-client-LICENSE

IUI_LICENSE.txt

LICENSE

NOTICE

rhoconfig.txt

rholog.txt

Classes/Modules

ApiV4

ApiV4::Application

ApiV4::Input

ApiV4::Playback

ApiV4::Playlist

ApiV4::VideoLibrary

Api

Api::V2

Api::V4

ApiV2

ApiV2::Playback

ApiV2::VideoLibrary

XbmcConnect

XbmcConnect::Command

AppApplication

Application4

ApplicationHelper

BarcodeScanController

BrowserHelper

CommandsController

CommandsHelper

Control2

Control4

Controls

ControlsController

DownloadHelper

ErrorHelper

GeoController

GeoHelper

Input4

MethodHelper

MoreController

Movie

MovieController

MovieHelper

ObjHelper

Object

Playlist4

PlaylistController

PlaylistHelper

Product

ProductController

ProductHelper

SpecRunner

SpecRunnerController

TempClass

TvEpisodeHelper

TvSeasonHelper

TvShowHelper

Tvepisode

TvepisodeController

Tvseason

TvseasonController

Tvshow

TvshowController

VideoLibrary2

VideoLibrary4

XbmcAppHelper

XbmcConfig

XbmcConfigController

XbmcConfigHelper

XbmcController

Methods

::api_loaded? — XbmcConnect

::async_connect — XbmcConnect

::current_config — XbmcConfigHelper

::download_file — XbmcConnect

::load_api — XbmcConnect

::load_commands — XbmcConnect

::load_version — XbmcConnect

::new — XbmcConnect::Command

::new — SpecRunner

::new — AppApplication

::parse_commands_v2 — XbmcConnect

::parse_commands_v4 — XbmcConnect

::setup — XbmcConnect

::sync_connect — XbmcConnect

#add_all_to_playlist — TvEpisodeHelper

#add_episode — Playlist4

#add_episode_to_queue — TvepisodeController

#add_movie — Playlist4

#add_movie_to_queue — MovieHelper

#add_to_queue — MovieController

#api_callback — XbmcConfigController

#back — Input4

#big_skip_back — Control2

#big_skip_back — ControlsController

#big_skip_back — Control4

#big_skip_back_player — Controls

#big_skip_forward — ControlsController

#big_skip_forward — Control2

#big_skip_forward — Control4

#big_skip_forward_player — Controls

#blank? — ApplicationHelper

#both_items_present? — ApplicationHelper

#caller_request_hash_to_query — ApplicationHelper

#caller_request_query_to_hash — ApplicationHelper

#camera_callback — BarcodeScanController

#cancel_httpcall — XbmcConfigController

#change_vol_callback — CommandsController

#checked — BrowserHelper

#choose — BarcodeScanController

#clean — VideoLibrary4

#clean_video — CommandsController

#clean_video_lib — CommandsHelper

#clear_video — Playlist4

#cmd_callback — CommandsController

#commands — XbmcController

#control_callback — ControlsController

#create — ProductController

#create — XbmcConfigController

#create_sort_title — Tvshow

#create_sort_title — Movie

#decrease_volume — CommandsController

#decrease_volume — Application4

#delete — TvseasonController

#delete — TvepisodeController

#delete — XbmcConfigController

#delete — MovieController

#delete — ProductController

#delete_image — ObjHelper

#destroy_image — Tvepisode

#destroy_image — Tvseason

#destroy_image — Tvshow

#destroy_image — Movie

#destroy_thumb_image — ObjHelper

#display_blanks — ApplicationHelper

#display_blankstr — ApplicationHelper

#display_dollars — ApplicationHelper

#display_newline — ApplicationHelper

#display_number — ApplicationHelper

#display_space — ApplicationHelper

#down — Input4

#download_episodethumb — DownloadHelper

#download_moviethumb — DownloadHelper

#download_seasons — TvShowHelper

#download_seasonthumb — DownloadHelper

#download_thumb — DownloadHelper

#download_tvthumb — DownloadHelper

#edit — XbmcConfigController

#episode_queue_callback — TvepisodeController

#episode_thumb_callback — TvepisodeController

#episodes_callback — TvepisodeController

#error_handle — ErrorHelper

#fast_forward — Control2

#fast_forward — ControlsController

#fast_forward — Control4

#fast_forward_player — Controls

#filter_movies_xbmc — MovieHelper

#filter_products_xbmc — ProductHelper

#filter_tvshows_xbmc — TvShowHelper

#find_episode — TvEpisodeHelper

#find_episodes — TvEpisodeHelper

#find_movie — MovieHelper

#find_season — TvSeasonHelper

#find_seasons — TvSeasonHelper

#find_tvshow — TvShowHelper

#format_address_for_mapping — ApplicationHelper

#format_latlon_for_mapping — ApplicationHelper

#found — MovieController

#geo_callback — GeoController

#get_active_order — MovieController

#get_active_order — TvshowController

#get_country_code — GeoHelper

#get_episode_thumb — TvepisodeController

#get_episodes — VideoLibrary4

#get_geo — GeoHelper

#get_movie_thumb — VideoLibrary4

#get_movies — VideoLibrary4

#get_movies — VideoLibrary2

#get_movies_xbmc — MovieHelper

#get_order — MovieController

#get_order — TvshowController

#get_order_dir — MovieController

#get_order_dir — TvshowController

#get_player — Control4

#get_player — Control2

#get_product — ProductHelper

#get_season_thumb — TvseasonController

#get_seasons — VideoLibrary4

#get_thumb — MovieController

#get_tv_shows — VideoLibrary4

#get_tv_shows — TvshowController

#get_tv_thumb — TvshowController

#get_tvshows_xbmc — TvShowHelper

#get_video_items — Playlist4

#get_vol_callback — CommandsController

#get_volume — Application4

#get_watch_list_bool — MovieController

#get_youtube_videoid — MovieHelper

#handle_new_movies — MovieHelper

#handle_new_seasons — TvSeasonHelper

#handle_new_tvepisodes — TvEpisodeHelper

#handle_new_tvshows — TvShowHelper

#handle_product — BarcodeScanController

#handle_removed_movies — MovieHelper

#handle_removed_seasons — TvSeasonHelper

#handle_removed_tvepisodes — TvEpisodeHelper

#handle_removed_tvshows — TvShowHelper

#has_valid_mapping_address — ApplicationHelper

#home — Input4

#increase_volume — Application4

#increase_volume — CommandsController

#index — TvseasonController

#index — PlaylistController

#index — MoreController

#index — XbmcConfigController

#index — MovieController

#index — ProductController

#index — BarcodeScanController

#index — ControlsController

#index — TvshowController

#index — TvepisodeController

#index — SpecRunnerController

#index — CommandsController

#info — TvshowController

#input_back — CommandsController

#input_down — CommandsController

#input_home — CommandsController

#input_left — CommandsController

#input_right — CommandsController

#input_select — CommandsController

#input_up — CommandsController

#invoke — XbmcConnect::Command

#is_active? — XbmcConfig

#is_bb6 — BrowserHelper

#klass_name — XbmcConnect::Command

#left — Input4

#load_geo — BarcodeScanController

#load_thumb_cb — MovieController

#load_trailer — MovieController

#load_tv_shows — TvShowHelper

#load_tvepisodes — TvEpisodeHelper

#load_volume — CommandsController

#make_sort_title — ObjHelper

#make_sort_title_obj — ObjHelper

#metaclass — Object

#movies_callback — MovieController

#mute_callback — CommandsController

#new — ProductController

#new — BarcodeScanController

#new — XbmcConfigController

#open_imdb — MovieController

#options — MovieController

#pause_play — ControlsController

#placeholder — BrowserHelper

#platform — BrowserHelper

#play_all_episodes — TvepisodeController

#play_callback — MovieController

#play_episode — TvepisodeController

#play_episode — Playlist4

#play_episode_callback — TvepisodeController

#play_episode_helper — TvEpisodeHelper

#play_item — PlaylistController

#play_item_callback — PlaylistController

#play_movie — Playlist4

#play_movie — MovieController

#play_movie_helper — MovieHelper

#play_pause — Control4

#play_pause — Control2

#play_pause_player — Controls

#play_video — Playlist4

#play_video_position — Playlist4

#play_viedo_playlist_at_position — PlaylistHelper

#playlist_callback — PlaylistController

#queue_all_episodes — TvepisodeController

#queue_callback — MovieController

#queue_episode_helper — TvEpisodeHelper

#remove_item — PlaylistController

#remove_item_callback — PlaylistController

#remove_movie_cache — XbmcConfigController

#remove_video_playlist_at_position — PlaylistHelper

#remove_video_position — Playlist4

#render_transition — ApplicationHelper

#replace_newlines — ApplicationHelper

#rewind — ControlsController

#rewind — Control4

#rewind — Control2

#rewind_player — Controls

#right — Input4

#run — SpecRunner

#scan — VideoLibrary4

#scan — VideoLibrary2

#scan_video — CommandsController

#scan_video_lib — CommandsHelper

#search_by_title — MovieHelper

#search_title — BarcodeScanController

#season_callback — TvseasonController

#season_thumb_callback — TvseasonController

#select — Input4

#selected — BrowserHelper

#send_command — MethodHelper

#set_callbacks — CommandsHelper

#set_callbacks — MovieHelper

#set_country_code — GeoHelper

#set_mute — Application4

#set_volume — Application4

#show — XbmcConfigController

#show — ProductController

#show — TvseasonController

#show — TvepisodeController

#show — TvshowController

#show — MovieController

#skip_next — ControlsController

#skip_next — Control4

#skip_next — Control2

#skip_next_player — Controls

#skip_prev — ControlsController

#skip_prev — Control2

#skip_prev — Control4

#skip_prev_player — Controls

#sm_skip_back — Control4

#sm_skip_back — ControlsController

#sm_skip_back — Control2

#sm_skip_back_player — Controls

#sm_skip_forward — Control4

#sm_skip_forward — Control2

#sm_skip_forward — ControlsController

#sm_skip_forward_player — Controls

#sort — MovieController

#stop — Control2

#stop — ControlsController

#stop — Control4

#stop_player — Controls

#strike_if — ApplicationHelper

#strip_braces — ApplicationHelper

#sync_movies — MovieHelper

#sync_seasons — TvSeasonHelper

#sync_tv_shows — TvShowHelper

#sync_tvepisodes — TvEpisodeHelper

#take — BarcodeScanController

#take_callback — BarcodeScanController

#thumb_callback — TvshowController

#toggle_mute — CommandsController

#toggle_mute — Application4

#tv_shows_callback — TvshowController

#tvsort — TvshowController

#up — Input4

#update — XbmcConfigController

#update — ProductController

#update_callback — TvepisodeController

#update_episodes — TvSeasonHelper

#update_list — MovieController

#update_movie_list — MovieHelper

#update_playlist — PlaylistController

#update_playlist_helper — PlaylistHelper

#update_season_cb — TvseasonController

#update_season_list — TvseasonController

#update_seasons — TvShowHelper

#update_seasons_helper — TvSeasonHelper

#update_tvepisode_list — TvepisodeController

#version — XbmcController

#watch_later — MovieController

#watch_later? — Movie

#xbmc_decrease_volume — XbmcAppHelper

#xbmc_get_volume — XbmcAppHelper

#xbmc_increase_volume — XbmcAppHelper

#xbmc_input_back — CommandsHelper

#xbmc_input_down — CommandsHelper

#xbmc_input_home — CommandsHelper

#xbmc_input_left — CommandsHelper

#xbmc_input_right — CommandsHelper

#xbmc_input_select — CommandsHelper

#xbmc_input_up — CommandsHelper

#xbmc_set_mute — XbmcAppHelper

#xbmc_set_volume — XbmcAppHelper

#xbmc_toggle_mute — XbmcAppHelper

[Validate]

Generated with the Darkfish
      Rdoc Generator 2.


text:
package com.linkedin.intellij.dust;

import com.intellij.formatting.*;
import com.intellij.formatting.templateLanguages.DataLanguageBlockWrapper;
import com.intellij.formatting.templateLanguages.TemplateLanguageBlock;
import com.intellij.formatting.templateLanguages.TemplateLanguageFormattingModelBuilder;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.formatter.DocumentBasedFormattingModel;
import com.intellij.psi.templateLanguages.SimpleTemplateLanguageFormattingModelBuilder;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: yzhang
 * Date: 3/11/13
 * Time: 10:30 AM
 *
 * Based on the intellij mustache plugin
 */
public class DustFormattingModelBuilder extends TemplateLanguageFormattingModelBuilder {

  @Override
  public TemplateLanguageBlock createTemplateLanguageBlock(@Nonnull ASTNode node,
                                                           @Nullable Wrap wrap,
                                                           @Nullable Alignment alignment,
                                                           @Nullable List<DataLanguageBlockWrapper> foreignChildren,
                                                           @Nonnull CodeStyleSettings codeStyleSettings) {
    return new DustFormatterBlock(this, codeStyleSettings, node, foreignChildren);
  }

  /**
   * We have to override {@link com.intellij.formatting.templateLanguages.TemplateLanguageFormattingModelBuilder#createModel}
   * since after we delegate to some templated languages, those languages (xml/html for sure, potentially others)
   * delegate right back to us to format the DustTypes.OUTER_TYPE token we tell them to ignore,
   * causing an stack-overflowing loop.
   */
  @Nonnull
  public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) {

    final PsiFile file = element.getContainingFile();
    Block rootBlock;

    ASTNode node = element.getNode();

    if (node.getElementType() == DustFileViewProvider.OUTER_TYPE) {
      // If we're looking at a DustTypes.HTML element, then we've been invoked by our templated
      // language.  Make a dummy block to allow that formatter to continue
      return new SimpleTemplateLanguageFormattingModelBuilder().createModel(element, settings);
    } else {
      rootBlock = getRootBlock(file, file.getViewProvider(), settings);
    }

    return new DocumentBasedFormattingModel(rootBlock, element.getProject(), settings, file.getFileType(), file);
  }

  @Override
  public boolean dontFormatMyModel() {
    return false;
  }
}


text:
from django import forms
from django.conf import settings
from django.core.mail import mail_admins, send_mail

class ShowContributorContactForm(forms.Form):
    first_name = forms.CharField(
        max_length=50,
        widget=forms.TextInput(attrs={'class':'required'}),
        error_messages={'required': 'Please enter your first name.'}
    )
    last_name = forms.CharField(
        max_length=50,
        widget=forms.TextInput(attrs={'class':'required'}),
        error_messages={'required': 'Please enter your surname.'}
    )
    email = forms.CharField(
        max_length=150,
        widget=forms.TextInput(attrs={'class':'required'}),
        error_messages={'required': 'Please enter your email address.'}
    )
    message = forms.CharField(
        max_length=1500,
        widget=forms.Textarea(attrs={'class':'required'}),
        error_messages={'required': 'Please enter your message.'}
    )
    honeypot = forms.CharField(
        max_length=50,
        required=False,
    )

    def __init__(self, *args, **kwargs):
        super(ShowContributorContactForm, self).__init__(*args, **kwargs)
        self.contributor = kwargs.get('contributor', None)

    def is_valid(self, *args, **kwargs):
        is_valid = super(ShowContributorContactForm, self).is_valid(*args, **kwargs)
        if is_valid:
            if not self.cleaned_data['honeypot']:
                return True

    def handle_valid(self, contributor, *args, **kwargs):
        if not contributor.owner.email:
            mail_admins("Contact Error", "Message could not be sent to %s. No email address specified." % contributor.owner.email, fail_silently=True)
            return None
        else:
            subject = "Email from website."
            message = "%s sent you a message from the website:\r\n\r\n" % self.cleaned_data.get('first_name')
            for key, val in self.cleaned_data.iteritems():
                 if key != "honeypot":
                    message += "%s: %s\r\n" % (key.title().replace("_", " "), val)
            from_email = self.cleaned_data.get('email')
            to_email = [contributor.owner.email]

            send_mail(subject, message, from_email, to_email)

            return None


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

001// RobotBuilder Version: 0.0.2
002//
003// This file was generated by RobotBuilder. It contains sections of
004// code that are automatically generated and assigned by robotbuilder.
005// These sections will be updated in the future when you export to
006// Java from RobotBuilder. Do not put any code or make any change in
007// the blocks indicating autogenerated code or it will be lost on an
008// update. Deleting the comments indicating the section will prevent
009// it from being updated in th future.
010package org.usfirst.frc330.Beachbot2013Java.commands;
011import edu.wpi.first.wpilibj.command.AutoSpreadsheetCommand;
012import edu.wpi.first.wpilibj.command.Command;
013import org.usfirst.frc330.Beachbot2013Java.Robot;
014/*
015 * $Log: PickupFrisbeesOff.java,v $
016 * Revision 1.6  2013-03-15 02:58:07  echan
017 * robotbuilder update
018 *
019 * Revision 1.5  2013-03-15 02:51:09  echan
020 * added cvs log comments
021 *
022 */
023/**
024 *
025 */
026public class PickupFrisbeesOff extends Command implements AutoSpreadsheetCommand {
027    public PickupFrisbeesOff() {
028        // Use requires() here to declare subsystem dependencies
029        // eg. requires(chassis);
030
031        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
032        requires(Robot.frisbeePickup);
033    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
034    }
035    // Called just before this Command runs the first time
036    protected void initialize() {
037    }
038    // Called repeatedly when this Command is scheduled to run
039    protected void execute() {
040        Robot.frisbeePickup.setFrisbeePickupMotorStop();
041    }
042    // Make this return true when this Command no longer needs to run execute()
043    protected boolean isFinished() {
044        return true;
045    }
046    // Called once after isFinished returns true
047    protected void end() {
048    }
049    // Called when another command which requires one or more of the same
050    // subsystems is scheduled to run
051    protected void interrupted() {
052    }
053    public void setParam1(double param1) {
054    }
055    public void setParam2(double param2) {
056    }
057    public void setParam3(double param3) {
058    }
059    public void setStopAtEnd(boolean stopAtEnd) {
060    }
061    public Command copy() {
062        return new PickupFrisbeesOff();
063    }
064}


text:
import React from 'react';
import { settings } from 'carbon-components';

const { prefix } = settings;

export default class TagSkeleton extends React.Component {
  render() {
    return <span className={`${prefix}--tag ${prefix}--skeleton`} />;
  }
}


text:
'use strict';

// MODULES //

var tape = require( 'tape' );
var proxyquire = require( 'proxyquire' );
var Symbol = require( '@stdlib/symbol/ctor' );
var detect = require( './../lib' );

// VARIABLES //

var hasIteratorSymbol = ( typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.strictEqual( typeof detect, 'function', 'main export is a function' );
	t.end();
});

tape( 'feature detection result is a boolean', function test( t ) {
	t.strictEqual( typeof detect(), 'boolean', 'detection result is a boolean' );
	t.end();
});

tape( 'if `Symbol.iterator` is supported, detection result is `true`', function test( t ) {
	if ( hasIteratorSymbol ) {
		t.strictEqual( detect(), true, 'detection result is `true`' );
	} else {
		t.strictEqual( detect(), false, 'detection result is `false`' );
	}
	t.end();
});

tape( 'the function guards against a `Symbol` global variable which does not produce `symbols`', function test( t ) {
	var detect = proxyquire( './../lib/main.js', {
		'@stdlib/symbol/ctor': mock
	});
	t.strictEqual( detect(), false, 'detection result is `false`' );
	t.end();

	function mock() {
		return {};
	}
});