text:
/*
 *  Regexp compilation.
 *
 *  See doc/regexp.rst for a discussion of the compilation approach and
 *  current limitations.
 *
 *  Regexp bytecode assumes jumps can be expressed with signed 32-bit
 *  integers.  Consequently the bytecode size must not exceed 0x7fffffffL.
 *  The implementation casts duk_size_t (buffer size) to duk_(u)int32_t
 *  in many places.  Although this could be changed, the bytecode format
 *  limit would still prevent regexps exceeding the signed 32-bit limit
 *  from working.
 *
 *  XXX: The implementation does not prevent bytecode from exceeding the
 *  maximum supported size.  This could be done by limiting the maximum
 *  input string size (assuming an upper bound can be computed for number
 *  of bytecode bytes emitted per input byte) or checking buffer maximum
 *  size when emitting bytecode (slower).
 */

#include "duk_internal.h"

#ifdef DUK_USE_REGEXP_SUPPORT

/*
 *  Helper macros
 */

#define DUK__RE_INITIAL_BUFSIZE 64

#undef DUK__RE_BUFLEN
#define DUK__RE_BUFLEN(re_ctx) \
	DUK_BW_GET_SIZE(re_ctx->thr, &re_ctx->bw)

/*
 *  Disjunction struct: result of parsing a disjunction
 */

typedef struct {
	/* Number of characters that the atom matches (e.g. 3 for 'abc'),
	 * -1 if atom is complex and number of matched characters either
	 * varies or is not known.
	 */
	duk_int32_t charlen;

#if 0
	/* These are not needed to implement quantifier capture handling,
	 * but might be needed at some point.
	 */

	/* re_ctx->captures at start and end of atom parsing.
	 * Since 'captures' indicates highest capture number emitted
	 * so far in a DUK_REOP_SAVE, the captures numbers saved by
	 * the atom are: ]start_captures,end_captures].
	 */
	duk_uint32_t start_captures;
	duk_uint32_t end_captures;
#endif
} duk__re_disjunction_info;

/*
 *  Encoding helpers
 *
 *  Some of the typing is bytecode based, e.g. slice sizes are unsigned 32-bit
 *  even though the buffer operations will use duk_size_t.
 */

/* XXX: the insert helpers should ensure that the bytecode result is not
 * larger than expected (or at least assert for it).  Many things in the
 * bytecode, like skip offsets, won't work correctly if the bytecode is
 * larger than say 2G.
 */

DUK_LOCAL duk_uint32_t duk__encode_i32(duk_int32_t x) {
	if (x < 0) {
		return ((duk_uint32_t) (-x)) * 2 + 1;
	} else {
		return ((duk_uint32_t) x) * 2;
	}
}

/* XXX: return type should probably be duk_size_t, or explicit checks are needed for
 * maximum size.
 */
DUK_LOCAL duk_uint32_t duk__insert_u32(duk_re_compiler_ctx *re_ctx, duk_uint32_t offset, duk_uint32_t x) {
	duk_uint8_t buf[DUK_UNICODE_MAX_XUTF8_LENGTH];
	duk_small_int_t len;

	len = duk_unicode_encode_xutf8((duk_ucodepoint_t) x, buf);
	DUK_BW_INSERT_ENSURE_BYTES(re_ctx->thr, &re_ctx->bw, offset, buf, len);
	return (duk_uint32_t) len;
}

DUK_LOCAL duk_uint32_t duk__append_u32(duk_re_compiler_ctx *re_ctx, duk_uint32_t x) {
	duk_uint8_t buf[DUK_UNICODE_MAX_XUTF8_LENGTH];
	duk_small_int_t len;

	len = duk_unicode_encode_xutf8((duk_ucodepoint_t) x, buf);
	DUK_BW_WRITE_ENSURE_BYTES(re_ctx->thr, &re_ctx->bw, buf, len);
	return (duk_uint32_t) len;
}

DUK_LOCAL duk_uint32_t duk__insert_i32(duk_re_compiler_ctx *re_ctx, duk_uint32_t offset, duk_int32_t x) {
	return duk__insert_u32(re_ctx, offset, duk__encode_i32(x));
}

#if 0  /* unused */
DUK_LOCAL duk_uint32_t duk__append_i32(duk_re_compiler_ctx *re_ctx, duk_int32_t x) {
	return duk__append_u32(re_ctx, duk__encode_i32(x));
}
#endif

/* special helper for emitting u16 lists (used for character ranges for built-in char classes) */
DUK_LOCAL void duk__append_u16_list(duk_re_compiler_ctx *re_ctx, duk_uint16_t *values, duk_uint32_t count) {
	/* Call sites don't need the result length so it's not accumulated. */
	while (count > 0) {
		(void) duk__append_u32(re_ctx, (duk_uint32_t) (*values++));
		count--;
	}
}

DUK_LOCAL void duk__insert_slice(duk_re_compiler_ctx *re_ctx, duk_uint32_t offset, duk_uint32_t data_offset, duk_uint32_t data_length) {
	DUK_BW_INSERT_ENSURE_SLICE(re_ctx->thr, &re_ctx->bw, offset, data_offset, data_length);
}

DUK_LOCAL void duk__append_slice(duk_re_compiler_ctx *re_ctx, duk_uint32_t data_offset, duk_uint32_t data_length) {
	DUK_BW_WRITE_ENSURE_SLICE(re_ctx->thr, &re_ctx->bw, data_offset, data_length);
}

DUK_LOCAL void duk__remove_slice(duk_re_compiler_ctx *re_ctx, duk_uint32_t data_offset, duk_uint32_t data_length) {
	DUK_BW_REMOVE_ENSURE_SLICE(re_ctx->thr, &re_ctx->bw, data_offset, data_length);
}

/*
 *  Insert a jump offset at 'offset' to complete an instruction
 *  (the jump offset is always the last component of an instruction).
 *  The 'skip' argument must be computed relative to 'offset',
 *  -without- taking into account the skip field being inserted.
 *
 *       ... A B C ins X Y Z ...   (ins may be a JUMP, SPLIT1/SPLIT2, etc)
 *   =>  ... A B C ins SKIP X Y Z
 *
 *  Computing the final (adjusted) skip value, which is relative to the
 *  first byte of the next instruction, is a bit tricky because of the
 *  variable length UTF-8 encoding.  See doc/regexp.rst for discussion.
 */
DUK_LOCAL duk_uint32_t duk__insert_jump_offset(duk_re_compiler_ctx *re_ctx, duk_uint32_t offset, duk_int32_t skip) {
	duk_small_int_t len;

	/* XXX: solve into closed form (smaller code) */

	if (skip < 0) {
		/* two encoding attempts suffices */
		len = duk_unicode_get_xutf8_length((duk_codepoint_t) duk__encode_i32(skip));
		len = duk_unicode_get_xutf8_length((duk_codepoint_t) duk__encode_i32(skip - (duk_int32_t) len));
		DUK_ASSERT(duk_unicode_get_xutf8_length(duk__encode_i32(skip - (duk_int32_t) len)) == len);  /* no change */
		skip -= (duk_int32_t) len;
	}
	return duk__insert_i32(re_ctx, offset, skip);
}

DUK_LOCAL duk_uint32_t duk__append_jump_offset(duk_re_compiler_ctx *re_ctx, duk_int32_t skip) {
	return (duk_uint32_t) duk__insert_jump_offset(re_ctx, (duk_uint32_t) DUK__RE_BUFLEN(re_ctx), skip);
}

/*
 *  duk_re_range_callback for generating character class ranges.
 *
 *  When ignoreCase is false, the range is simply emitted as is.
 *  We don't, for instance, eliminate duplicates or overlapping
 *  ranges in a character class.
 *
 *  When ignoreCase is true, the range needs to be normalized through
 *  canonicalization.  Unfortunately a canonicalized version of a
 *  continuous range is not necessarily continuous (e.g. [x-{] is
 *  continuous but [X-{] is not).  The current algorithm creates the
 *  canonicalized range(s) space efficiently at the cost of compile
 *  time execution time (see doc/regexp.rst for discussion).
 *
 *  Note that the ctx->nranges is a context-wide temporary value
 *  (this is OK because there cannot be multiple character classes
 *  being parsed simultaneously).
 */

DUK_LOCAL void duk__generate_ranges(void *userdata, duk_codepoint_t r1, duk_codepoint_t r2, duk_bool_t direct) {
	duk_re_compiler_ctx *re_ctx = (duk_re_compiler_ctx *) userdata;

	DUK_DD(DUK_DDPRINT("duk__generate_ranges(): re_ctx=%p, range=[%ld,%ld] direct=%ld",
	                   (void *) re_ctx, (long) r1, (long) r2, (long) direct));

	if (!direct && (re_ctx->re_flags & DUK_RE_FLAG_IGNORE_CASE)) {
		/*
		 *  Canonicalize a range, generating result ranges as necessary.
		 *  Needs to exhaustively scan the entire range (at most 65536
		 *  code points).  If 'direct' is set, caller (lexer) has ensured
		 *  that the range is already canonicalization compatible (this
		 *  is used to avoid unnecessary canonicalization of built-in
		 *  ranges like \W, which are not affected by canonicalization).
		 *
		 *  NOTE: here is one place where we don't want to support chars
		 *  outside the BMP, because the exhaustive search would be
		 *  massively larger.
		 */

		duk_codepoint_t i;
		duk_codepoint_t t;
		duk_codepoint_t r_start, r_end;

		r_start = duk_unicode_re_canonicalize_char(re_ctx->thr, r1);
		r_end = r_start;
		for (i = r1 + 1; i <= r2; i++) {
			t = duk_unicode_re_canonicalize_char(re_ctx->thr, i);
			if (t == r_end + 1) {
				r_end = t;
			} else {
				DUK_DD(DUK_DDPRINT("canonicalized, emit range: [%ld,%ld]", (long) r_start, (long) r_end));
				duk__append_u32(re_ctx, (duk_uint32_t) r_start);
				duk__append_u32(re_ctx, (duk_uint32_t) r_end);
				re_ctx->nranges++;
				r_start = t;
				r_end = t;
			}
		}
		DUK_DD(DUK_DDPRINT("canonicalized, emit range: [%ld,%ld]", (long) r_start, (long) r_end));
		duk__append_u32(re_ctx, (duk_uint32_t) r_start);
		duk__append_u32(re_ctx, (duk_uint32_t) r_end);
		re_ctx->nranges++;
	} else {
		DUK_DD(DUK_DDPRINT("direct, emit range: [%ld,%ld]", (long) r1, (long) r2));
		duk__append_u32(re_ctx, (duk_uint32_t) r1);
		duk__append_u32(re_ctx, (duk_uint32_t) r2);
		re_ctx->nranges++;
	}
}

/*
 *  Parse regexp Disjunction.  Most of regexp compilation happens here.
 *
 *  Handles Disjunction, Alternative, and Term productions directly without
 *  recursion.  The only constructs requiring recursion are positive/negative
 *  lookaheads, capturing parentheses, and non-capturing parentheses.
 *
 *  The function determines whether the entire disjunction is a 'simple atom'
 *  (see doc/regexp.rst discussion on 'simple quantifiers') and if so,
 *  returns the atom character length which is needed by the caller to keep
 *  track of its own atom character length.  A disjunction with more than one
 *  alternative is never considered a simple atom (although in some cases
 *  that might be the case).
 *
 *  Return value: simple atom character length or < 0 if not a simple atom.
 *  Appends the bytecode for the disjunction matcher to the end of the temp
 *  buffer.
 *
 *  Regexp top level structure is:
 *
 *    Disjunction = Term*
 *                | Term* | Disjunction
 *
 *    Term = Assertion
 *         | Atom
 *         | Atom Quantifier
 *
 *  An empty Term sequence is a valid disjunction alternative (e.g. /|||c||/).
 *
 *  Notes:
 *
 *    * Tracking of the 'simple-ness' of the current atom vs. the entire
 *      disjunction are separate matters.  For instance, the disjunction
 *      may be complex, but individual atoms may be simple.  Furthermore,
 *      simple quantifiers are used whenever possible, even if the
 *      disjunction as a whole is complex.
 *
 *    * The estimate of whether an atom is simple is conservative now,
 *      and it would be possible to expand it.  For instance, captures
 *      cause the disjunction to be marked complex, even though captures
 *      -can- be handled by simple quantifiers with some minor modifications.
 *
 *    * Disjunction 'tainting' as 'complex' is handled at the end of the
 *      main for loop collectively for atoms.  Assertions, quantifiers,
 *      and '|' tokens need to taint the result manually if necessary.
 *      Assertions cannot add to result char length, only atoms (and
 *      quantifiers) can; currently quantifiers will taint the result
 *      as complex though.
 */

DUK_LOCAL void duk__parse_disjunction(duk_re_compiler_ctx *re_ctx, duk_bool_t expect_eof, duk__re_disjunction_info *out_atom_info) {
	duk_int32_t atom_start_offset = -1;                   /* negative -> no atom matched on previous round */
	duk_int32_t atom_char_length = 0;                     /* negative -> complex atom */
	duk_uint32_t atom_start_captures = re_ctx->captures;  /* value of re_ctx->captures at start of atom */
	duk_int32_t unpatched_disjunction_split = -1;
	duk_int32_t unpatched_disjunction_jump = -1;
	duk_uint32_t entry_offset = (duk_uint32_t) DUK__RE_BUFLEN(re_ctx);
	duk_int32_t res_charlen = 0;  /* -1 if disjunction is complex, char length if simple */
	duk__re_disjunction_info tmp_disj;

	DUK_ASSERT(out_atom_info != NULL);

	if (re_ctx->recursion_depth >= re_ctx->recursion_limit) {
		DUK_ERROR(re_ctx->thr, DUK_ERR_RANGE_ERROR,
		          DUK_STR_REGEXP_COMPILER_RECURSION_LIMIT);
	}
	re_ctx->recursion_depth++;

#if 0
	out_atom_info->start_captures = re_ctx->captures;
#endif

	for (;;) {
		/* atom_char_length, atom_start_offset, atom_start_offset reflect the
		 * atom matched on the previous loop.  If a quantifier is encountered
		 * on this loop, these are needed to handle the quantifier correctly.
		 * new_atom_char_length etc are for the atom parsed on this round;
		 * they're written to atom_char_length etc at the end of the round.
		 */
		duk_int32_t new_atom_char_length;   /* char length of the atom parsed in this loop */
		duk_int32_t new_atom_start_offset;  /* bytecode start offset of the atom parsed in this loop
		                                     * (allows quantifiers to copy the atom bytecode)
		                                     */
		duk_uint32_t new_atom_start_captures;  /* re_ctx->captures at the start of the atom parsed in this loop */

		duk_lexer_parse_re_token(&re_ctx->lex, &re_ctx->curr_token);

		DUK_DD(DUK_DDPRINT("re token: %ld (num=%ld, char=%c)",
		                   (long) re_ctx->curr_token.t,
		                   (long) re_ctx->curr_token.num,
		                   (re_ctx->curr_token.num >= 0x20 && re_ctx->curr_token.num <= 0x7e) ?
		                   (int) re_ctx->curr_token.num : (int) '?'));

		/* set by atom case clauses */
		new_atom_start_offset = -1;
		new_atom_char_length = -1;
		new_atom_start_captures = re_ctx->captures;

		switch (re_ctx->curr_token.t) {
		case DUK_RETOK_DISJUNCTION: {
			/*
			 *  The handling here is a bit tricky.  If a previous '|' has been processed,
			 *  we have a pending split1 and a pending jump (for a previous match).  These
			 *  need to be back-patched carefully.  See docs for a detailed example.
			 */

			/* patch pending jump and split */
			if (unpatched_disjunction_jump >= 0) {
				duk_uint32_t offset;

				DUK_ASSERT(unpatched_disjunction_split >= 0);
				offset = unpatched_disjunction_jump;
				offset += duk__insert_jump_offset(re_ctx,
				                                  offset,
				                                  (duk_int32_t) (DUK__RE_BUFLEN(re_ctx) - offset));
				/* offset is now target of the pending split (right after jump) */
				duk__insert_jump_offset(re_ctx,
				                        unpatched_disjunction_split,
				                        offset - unpatched_disjunction_split);
			}

			/* add a new pending split to the beginning of the entire disjunction */
			(void) duk__insert_u32(re_ctx,
			                       entry_offset,
			                       DUK_REOP_SPLIT1);   /* prefer direct execution */
			unpatched_disjunction_split = entry_offset + 1;   /* +1 for opcode */

			/* add a new pending match jump for latest finished alternative */
			duk__append_u32(re_ctx, DUK_REOP_JUMP);
			unpatched_disjunction_jump = (duk_int32_t) DUK__RE_BUFLEN(re_ctx);

			/* 'taint' result as complex */
			res_charlen = -1;
			break;
		}
		case DUK_RETOK_QUANTIFIER: {
			if (atom_start_offset < 0) {
				DUK_ERROR(re_ctx->thr, DUK_ERR_SYNTAX_ERROR,
				          DUK_STR_INVALID_QUANTIFIER_NO_ATOM);
			}
			if (re_ctx->curr_token.qmin > re_ctx->curr_token.qmax) {
				DUK_ERROR(re_ctx->thr, DUK_ERR_SYNTAX_ERROR,
				          DUK_STR_INVALID_QUANTIFIER_VALUES);
			}
			if (atom_char_length >= 0) {
				/*
				 *  Simple atom
				 *
				 *  If atom_char_length is zero, we'll have unbounded execution time for e.g.
				 *  /()*x/.exec('x').  We can't just skip the match because it might have some
				 *  side effects (for instance, if we allowed captures in simple atoms, the
				 *  capture needs to happen).  The simple solution below is to force the
				 *  quantifier to match at most once, since the additional matches have no effect.
				 *
				 *  With a simple atom there can be no capture groups, so no captures need
				 *  to be reset.
				 */
				duk_int32_t atom_code_length;
				duk_uint32_t offset;
				duk_uint32_t qmin, qmax;

				qmin = re_ctx->curr_token.qmin;
				qmax = re_ctx->curr_token.qmax;
				if (atom_char_length == 0) {
					/* qmin and qmax will be 0 or 1 */
					if (qmin > 1) {
						qmin = 1;
					}
					if (qmax > 1) {
						qmax = 1;
					}
				}

				duk__append_u32(re_ctx, DUK_REOP_MATCH);   /* complete 'sub atom' */
				atom_code_length = (duk_int32_t) (DUK__RE_BUFLEN(re_ctx) - atom_start_offset);

				offset = atom_start_offset;
				if (re_ctx->curr_token.greedy) {
					offset += duk__insert_u32(re_ctx, offset, DUK_REOP_SQGREEDY);
					offset += duk__insert_u32(re_ctx, offset, qmin);
					offset += duk__insert_u32(re_ctx, offset, qmax);
					offset += duk__insert_u32(re_ctx, offset, atom_char_length);
					offset += duk__insert_jump_offset(re_ctx, offset, atom_code_length);
				} else {
					offset += duk__insert_u32(re_ctx, offset, DUK_REOP_SQMINIMAL);
					offset += duk__insert_u32(re_ctx, offset, qmin);
					offset += duk__insert_u32(re_ctx, offset, qmax);
					offset += duk__insert_jump_offset(re_ctx, offset, atom_code_length);
				}
				DUK_UNREF(offset);  /* silence scan-build warning */
			} else {
				/*
				 *  Complex atom
				 *
				 *  The original code is used as a template, and removed at the end
				 *  (this differs from the handling of simple quantifiers).
				 *
				 *  NOTE: there is no current solution for empty atoms in complex
				 *  quantifiers.  This would need some sort of a 'progress' instruction.
				 *
				 *  XXX: impose limit on maximum result size, i.e. atom_code_len * atom_copies?
				 */
				duk_int32_t atom_code_length;
				duk_uint32_t atom_copies;
				duk_uint32_t tmp_qmin, tmp_qmax;

				/* pre-check how many atom copies we're willing to make (atom_copies not needed below) */
				atom_copies = (re_ctx->curr_token.qmax == DUK_RE_QUANTIFIER_INFINITE) ?
				              re_ctx->curr_token.qmin : re_ctx->curr_token.qmax;
				if (atom_copies > DUK_RE_MAX_ATOM_COPIES) {
					DUK_ERROR(re_ctx->thr, DUK_ERR_RANGE_ERROR,
					          DUK_STR_QUANTIFIER_TOO_MANY_COPIES);
				}

				/* wipe the capture range made by the atom (if any) */
				DUK_ASSERT(atom_start_captures <= re_ctx->captures);
				if (atom_start_captures != re_ctx->captures) {
					DUK_ASSERT(atom_start_captures < re_ctx->captures);
					DUK_DDD(DUK_DDDPRINT("must wipe ]atom_start_captures,re_ctx->captures]: ]%ld,%ld]",
					                     (long) atom_start_captures, (long) re_ctx->captures));

					/* insert (DUK_REOP_WIPERANGE, start, count) in reverse order so the order ends up right */
					duk__insert_u32(re_ctx, atom_start_offset, (re_ctx->captures - atom_start_captures) * 2);
					duk__insert_u32(re_ctx, atom_start_offset, (atom_start_captures + 1) * 2);
					duk__insert_u32(re_ctx, atom_start_offset, DUK_REOP_WIPERANGE);
				} else {
					DUK_DDD(DUK_DDDPRINT("no need to wipe captures: atom_start_captures == re_ctx->captures == %ld",
					                     (long) atom_start_captures));
				}

				atom_code_length = (duk_int32_t) DUK__RE_BUFLEN(re_ctx) - atom_start_offset;

				/* insert the required matches (qmin) by copying the atom */
				tmp_qmin = re_ctx->curr_token.qmin;
				tmp_qmax = re_ctx->curr_token.qmax;
				while (tmp_qmin > 0) {
					duk__append_slice(re_ctx, atom_start_offset, atom_code_length);
					tmp_qmin--;
					if (tmp_qmax != DUK_RE_QUANTIFIER_INFINITE) {
						tmp_qmax--;
					}
				}
				DUK_ASSERT(tmp_qmin == 0);

				/* insert code for matching the remainder - infinite or finite */
				if (tmp_qmax == DUK_RE_QUANTIFIER_INFINITE) {
					/* reuse last emitted atom for remaining 'infinite' quantifier */

					if (re_ctx->curr_token.qmin == 0) {
						/* Special case: original qmin was zero so there is nothing
						 * to repeat.  Emit an atom copy but jump over it here.
						 */
						duk__append_u32(re_ctx, DUK_REOP_JUMP);
						duk__append_jump_offset(re_ctx, atom_code_length);
						duk__append_slice(re_ctx, atom_start_offset, atom_code_length);
					}
					if (re_ctx->curr_token.greedy) {
						duk__append_u32(re_ctx, DUK_REOP_SPLIT2);   /* prefer jump */
					} else {
						duk__append_u32(re_ctx, DUK_REOP_SPLIT1);   /* prefer direct */
					}
					duk__append_jump_offset(re_ctx, -atom_code_length - 1);  /* -1 for opcode */
				} else {
					/*
					 *  The remaining matches are emitted as sequence of SPLITs and atom
					 *  copies; the SPLITs skip the remaining copies and match the sequel.
					 *  This sequence needs to be emitted starting from the last copy
					 *  because the SPLITs are variable length due to the variable length
					 *  skip offset.  This causes a lot of memory copying now.
					 *
					 *  Example structure (greedy, match maximum # atoms):
					 *
					 *      SPLIT1 LSEQ
					 *      (atom)
					 *      SPLIT1 LSEQ    ; <- the byte length of this instruction is needed
					 *      (atom)         ; to encode the above SPLIT1 correctly
					 *      ...
					 *   LSEQ:
					 */
					duk_uint32_t offset = (duk_uint32_t) DUK__RE_BUFLEN(re_ctx);
					while (tmp_qmax > 0) {
						duk__insert_slice(re_ctx, offset, atom_start_offset, atom_code_length);
						if (re_ctx->curr_token.greedy) {
							duk__insert_u32(re_ctx, offset, DUK_REOP_SPLIT1);   /* prefer direct */
						} else {
							duk__insert_u32(re_ctx, offset, DUK_REOP_SPLIT2);   /* prefer jump */
						}
						duk__insert_jump_offset(re_ctx,
						                        offset + 1,   /* +1 for opcode */
						                        (duk_int32_t) (DUK__RE_BUFLEN(re_ctx) - (offset + 1)));
						tmp_qmax--;
					}
				}

				/* remove the original 'template' atom */
				duk__remove_slice(re_ctx, atom_start_offset, atom_code_length);
			}

			/* 'taint' result as complex */
			res_charlen = -1;
			break;
		}
		case DUK_RETOK_ASSERT_START: {
			duk__append_u32(re_ctx, DUK_REOP_ASSERT_START);
			break;
		}
		case DUK_RETOK_ASSERT_END: {
			duk__append_u32(re_ctx, DUK_REOP_ASSERT_END);
			break;
		}
		case DUK_RETOK_ASSERT_WORD_BOUNDARY: {
			duk__append_u32(re_ctx, DUK_REOP_ASSERT_WORD_BOUNDARY);
			break;
		}
		case DUK_RETOK_ASSERT_NOT_WORD_BOUNDARY: {
			duk__append_u32(re_ctx, DUK_REOP_ASSERT_NOT_WORD_BOUNDARY);
			break;
		}
		case DUK_RETOK_ASSERT_START_POS_LOOKAHEAD:
		case DUK_RETOK_ASSERT_START_NEG_LOOKAHEAD: {
			duk_uint32_t offset;
			duk_uint32_t opcode = (re_ctx->curr_token.t == DUK_RETOK_ASSERT_START_POS_LOOKAHEAD) ?
			                      DUK_REOP_LOOKPOS : DUK_REOP_LOOKNEG;

			offset = (duk_uint32_t) DUK__RE_BUFLEN(re_ctx);
			duk__parse_disjunction(re_ctx, 0, &tmp_disj);
			duk__append_u32(re_ctx, DUK_REOP_MATCH);

			(void) duk__insert_u32(re_ctx, offset, opcode);
			(void) duk__insert_jump_offset(re_ctx,
			                               offset + 1,   /* +1 for opcode */
			                               (duk_int32_t) (DUK__RE_BUFLEN(re_ctx) - (offset + 1)));

			/* 'taint' result as complex -- this is conservative,
			 * as lookaheads do not backtrack.
			 */
			res_charlen = -1;
			break;
		}
		case DUK_RETOK_ATOM_PERIOD: {
			new_atom_char_length = 1;
			new_atom_start_offset = (duk_int32_t) DUK__RE_BUFLEN(re_ctx);
			duk__append_u32(re_ctx, DUK_REOP_PERIOD);
			break;
		}
		case DUK_RETOK_ATOM_CHAR: {
			/* Note: successive characters could be joined into string matches
			 * but this is not trivial (consider e.g. '/xyz+/); see docs for
			 * more discussion.
			 */
			duk_uint32_t ch;

			new_atom_char_length = 1;
			new_atom_start_offset = (duk_int32_t) DUK__RE_BUFLEN(re_ctx);
			duk__append_u32(re_ctx, DUK_REOP_CHAR);
			ch = re_ctx->curr_token.num;
			if (re_ctx->re_flags & DUK_RE_FLAG_IGNORE_CASE) {
				ch = duk_unicode_re_canonicalize_char(re_ctx->thr, ch);
			}
			duk__append_u32(re_ctx, ch);
			break;
		}
		case DUK_RETOK_ATOM_DIGIT:
		case DUK_RETOK_ATOM_NOT_DIGIT: {
			new_atom_char_length = 1;
			new_atom_start_offset = (duk_int32_t) DUK__RE_BUFLEN(re_ctx);
			duk__append_u32(re_ctx,
			                (re_ctx->curr_token.t == DUK_RETOK_ATOM_DIGIT) ?
			                DUK_REOP_RANGES : DUK_REOP_INVRANGES);
			duk__append_u32(re_ctx, sizeof(duk_unicode_re_ranges_digit) / (2 * sizeof(duk_uint16_t)));
			duk__append_u16_list(re_ctx, duk_unicode_re_ranges_digit, sizeof(duk_unicode_re_ranges_digit) / sizeof(duk_uint16_t));
			break;
		}
		case DUK_RETOK_ATOM_WHITE:
		case DUK_RETOK_ATOM_NOT_WHITE: {
			new_atom_char_length = 1;
			new_atom_start_offset = (duk_int32_t) DUK__RE_BUFLEN(re_ctx);
			duk__append_u32(re_ctx,
			                (re_ctx->curr_token.t == DUK_RETOK_ATOM_WHITE) ?
			                DUK_REOP_RANGES : DUK_REOP_INVRANGES);
			duk__append_u32(re_ctx, sizeof(duk_unicode_re_ranges_white) / (2 * sizeof(duk_uint16_t)));
			duk__append_u16_list(re_ctx, duk_unicode_re_ranges_white, sizeof(duk_unicode_re_ranges_white) / sizeof(duk_uint16_t));
			break;
		}
		case DUK_RETOK_ATOM_WORD_CHAR:
		case DUK_RETOK_ATOM_NOT_WORD_CHAR: {
			new_atom_char_length = 1;
			new_atom_start_offset = (duk_int32_t) DUK__RE_BUFLEN(re_ctx);
			duk__append_u32(re_ctx,
			                (re_ctx->curr_token.t == DUK_RETOK_ATOM_WORD_CHAR) ?
			                DUK_REOP_RANGES : DUK_REOP_INVRANGES);
			duk__append_u32(re_ctx, sizeof(duk_unicode_re_ranges_wordchar) / (2 * sizeof(duk_uint16_t)));
			duk__append_u16_list(re_ctx, duk_unicode_re_ranges_wordchar, sizeof(duk_unicode_re_ranges_wordchar) / sizeof(duk_uint16_t));
			break;
		}
		case DUK_RETOK_ATOM_BACKREFERENCE: {
			duk_uint32_t backref = (duk_uint32_t) re_ctx->curr_token.num;
			if (backref > re_ctx->highest_backref) {
				re_ctx->highest_backref = backref;
			}
			new_atom_char_length = -1;   /* mark as complex */
			new_atom_start_offset = (duk_int32_t) DUK__RE_BUFLEN(re_ctx);
			duk__append_u32(re_ctx, DUK_REOP_BACKREFERENCE);
			duk__append_u32(re_ctx, backref);
			break;
		}
		case DUK_RETOK_ATOM_START_CAPTURE_GROUP: {
			duk_uint32_t cap;

			new_atom_char_length = -1;   /* mark as complex (capture handling) */
			new_atom_start_offset = (duk_int32_t) DUK__RE_BUFLEN(re_ctx);
			cap = ++re_ctx->captures;
			duk__append_u32(re_ctx, DUK_REOP_SAVE);
			duk__append_u32(re_ctx, cap * 2);
			duk__parse_disjunction(re_ctx, 0, &tmp_disj);  /* retval (sub-atom char length) unused, tainted as complex above */
			duk__append_u32(re_ctx, DUK_REOP_SAVE);
			duk__append_u32(re_ctx, cap * 2 + 1);
			break;
		}
		case DUK_RETOK_ATOM_START_NONCAPTURE_GROUP: {
			new_atom_start_offset = (duk_int32_t) DUK__RE_BUFLEN(re_ctx);
			duk__parse_disjunction(re_ctx, 0, &tmp_disj);
			new_atom_char_length = tmp_disj.charlen;
			break;
		}
		case DUK_RETOK_ATOM_START_CHARCLASS:
		case DUK_RETOK_ATOM_START_CHARCLASS_INVERTED: {
			/*
			 *  Range parsing is done with a special lexer function which calls
			 *  us for every range parsed.  This is different from how rest of
			 *  the parsing works, but avoids a heavy, arbitrary size intermediate
			 *  value type to hold the ranges.
			 *
			 *  Another complication is the handling of character ranges when
			 *  case insensitive matching is used (see docs for discussion).
			 *  The range handler callback given to the lexer takes care of this
			 *  as well.
			 *
			 *  Note that duplicate ranges are not eliminated when parsing character
			 *  classes, so that canonicalization of
			 *
			 *    [0-9a-fA-Fx-{]
			 *
			 *  creates the result (note the duplicate ranges):
			 *
			 *    [0-9A-FA-FX-Z{-{]
			 *
			 *  where [x-{] is split as a result of canonicalization.  The duplicate
			 *  ranges are not a semantics issue: they work correctly.
			 */

			duk_uint32_t offset;

			DUK_DD(DUK_DDPRINT("character class"));

			/* insert ranges instruction, range count patched in later */
			new_atom_char_length = 1;
			new_atom_start_offset = (duk_int32_t) DUK__RE_BUFLEN(re_ctx);
			duk__append_u32(re_ctx,
			                (re_ctx->curr_token.t == DUK_RETOK_ATOM_START_CHARCLASS) ?
			                DUK_REOP_RANGES : DUK_REOP_INVRANGES);
			offset = (duk_uint32_t) DUK__RE_BUFLEN(re_ctx);    /* patch in range count later */

			/* parse ranges until character class ends */
			re_ctx->nranges = 0;    /* note: ctx-wide temporary */
			duk_lexer_parse_re_ranges(&re_ctx->lex, duk__generate_ranges, (void *) re_ctx);

			/* insert range count */
			duk__insert_u32(re_ctx, offset, re_ctx->nranges);
			break;
		}
		case DUK_RETOK_ATOM_END_GROUP: {
			if (expect_eof) {
				DUK_ERROR(re_ctx->thr, DUK_ERR_SYNTAX_ERROR,
				          DUK_STR_UNEXPECTED_CLOSING_PAREN);
			}
			goto done;
		}
		case DUK_RETOK_EOF: {
			if (!expect_eof) {
				DUK_ERROR(re_ctx->thr, DUK_ERR_SYNTAX_ERROR,
				          DUK_STR_UNEXPECTED_END_OF_PATTERN);
			}
			goto done;
		}
		default: {
			DUK_ERROR(re_ctx->thr, DUK_ERR_SYNTAX_ERROR,
			          DUK_STR_UNEXPECTED_REGEXP_TOKEN);
		}
		}

		/* a complex (new) atom taints the result */
		if (new_atom_start_offset >= 0) {
			if (new_atom_char_length < 0) {
				res_charlen = -1;
			} else if (res_charlen >= 0) {
				/* only advance if not tainted */
				res_charlen += new_atom_char_length;
			}
		}

		/* record previous atom info in case next token is a quantifier */
		atom_start_offset = new_atom_start_offset;
		atom_char_length = new_atom_char_length;
		atom_start_captures = new_atom_start_captures;
	}

 done:

	/* finish up pending jump and split for last alternative */
	if (unpatched_disjunction_jump >= 0) {
		duk_uint32_t offset;

		DUK_ASSERT(unpatched_disjunction_split >= 0);
		offset = unpatched_disjunction_jump;
		offset += duk__insert_jump_offset(re_ctx,
		                                  offset,
		                                  (duk_int32_t) (DUK__RE_BUFLEN(re_ctx) - offset));
		/* offset is now target of the pending split (right after jump) */
		duk__insert_jump_offset(re_ctx,
		                        unpatched_disjunction_split,
		                        offset - unpatched_disjunction_split);
	}

#if 0
	out_atom_info->end_captures = re_ctx->captures;
#endif
	out_atom_info->charlen = res_charlen;
	DUK_DDD(DUK_DDDPRINT("parse disjunction finished: charlen=%ld",
	                     (long) out_atom_info->charlen));

	re_ctx->recursion_depth--;
}

/*
 *  Flags parsing (see E5 Section 15.10.4.1).
 */

DUK_LOCAL duk_uint32_t duk__parse_regexp_flags(duk_hthread *thr, duk_hstring *h) {
	const duk_uint8_t *p;
	const duk_uint8_t *p_end;
	duk_uint32_t flags = 0;

	p = DUK_HSTRING_GET_DATA(h);
	p_end = p + DUK_HSTRING_GET_BYTELEN(h);

	/* Note: can be safely scanned as bytes (undecoded) */

	while (p < p_end) {
		duk_uint8_t c = *p++;
		switch ((int) c) {
		case (int) 'g': {
			if (flags & DUK_RE_FLAG_GLOBAL) {
				goto error;
			}
			flags |= DUK_RE_FLAG_GLOBAL;
			break;
		}
		case (int) 'i': {
			if (flags & DUK_RE_FLAG_IGNORE_CASE) {
				goto error;
			}
			flags |= DUK_RE_FLAG_IGNORE_CASE;
			break;
		}
		case (int) 'm': {
			if (flags & DUK_RE_FLAG_MULTILINE) {
				goto error;
			}
			flags |= DUK_RE_FLAG_MULTILINE;
			break;
		}
		default: {
			goto error;
		}
		}
	}

	return flags;

 error:
	DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_REGEXP_FLAGS);
	return 0;  /* never here */
}

/*
 *  Create escaped RegExp source (E5 Section 15.10.3).
 *
 *  The current approach is to special case the empty RegExp
 *  ('' -> '(?:)') and otherwise replace unescaped '/' characters
 *  with '\/' regardless of where they occur in the regexp.
 *
 *  Note that normalization does not seem to be necessary for
 *  RegExp literals (e.g. '/foo/') because to be acceptable as
 *  a RegExp literal, the text between forward slashes must
 *  already match the escaping requirements (e.g. must not contain
 *  unescaped forward slashes or be empty).  Escaping IS needed
 *  for expressions like 'new Regexp("...", "")' however.
 *  Currently, we re-escape in either case.
 *
 *  Also note that we process the source here in UTF-8 encoded
 *  form.  This is correct, because any non-ASCII characters are
 *  passed through without change.
 */

DUK_LOCAL void duk__create_escaped_source(duk_hthread *thr, int idx_pattern) {
	duk_context *ctx = (duk_context *) thr;
	duk_hstring *h;
	const duk_uint8_t *p;
	duk_bufwriter_ctx bw_alloc;
	duk_bufwriter_ctx *bw;
	duk_uint8_t *q;
	duk_size_t i, n;
	duk_uint_fast8_t c_prev, c;

	h = duk_get_hstring(ctx, idx_pattern);
	DUK_ASSERT(h != NULL);
	p = (const duk_uint8_t *) DUK_HSTRING_GET_DATA(h);
	n = (duk_size_t) DUK_HSTRING_GET_BYTELEN(h);

	if (n == 0) {
		/* return '(?:)' */
		duk_push_hstring_stridx(ctx, DUK_STRIDX_ESCAPED_EMPTY_REGEXP);
		return;
	}

	bw = &bw_alloc;
	DUK_BW_INIT_PUSHBUF(thr, bw, n);
	q = DUK_BW_GET_PTR(thr, bw);

	c_prev = (duk_uint_fast8_t) 0;

	for (i = 0; i < n; i++) {
		c = p[i];

		q = DUK_BW_ENSURE_RAW(thr, bw, 2, q);

		if (c == (duk_uint_fast8_t) '/' && c_prev != (duk_uint_fast8_t) '\\') {
			/* Unescaped '/' ANYWHERE in the regexp (in disjunction,
			 * inside a character class, ...) => same escape works.
			 */
			*q++ = DUK_ASC_BACKSLASH;
		}
		*q++ = (duk_uint8_t) c;

		c_prev = c;
	}

	DUK_BW_SETPTR_AND_COMPACT(thr, bw, q);
	duk_to_string(ctx, -1);  /* -> [ ... escaped_source ] */
}

/*
 *  Exposed regexp compilation primitive.
 *
 *  Sets up a regexp compilation context, and calls duk__parse_disjunction() to do the
 *  actual parsing.  Handles generation of the compiled regexp header and the
 *  "boilerplate" capture of the matching substring (save 0 and 1).  Also does some
 *  global level regexp checks after recursive compilation has finished.
 *
 *  An escaped version of the regexp source, suitable for use as a RegExp instance
 *  'source' property (see E5 Section 15.10.3), is also left on the stack.
 *
 *  Input stack:  [ pattern flags ]
 *  Output stack: [ bytecode escaped_source ]  (both as strings)
 */

DUK_INTERNAL void duk_regexp_compile(duk_hthread *thr) {
	duk_context *ctx = (duk_context *) thr;
	duk_re_compiler_ctx re_ctx;
	duk_lexer_point lex_point;
	duk_hstring *h_pattern;
	duk_hstring *h_flags;
	duk__re_disjunction_info ign_disj;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(ctx != NULL);

	/*
	 *  Args validation
	 */

	/* TypeError if fails */
	h_pattern = duk_require_hstring(ctx, -2);
	h_flags = duk_require_hstring(ctx, -1);

	/*
	 *  Create normalized 'source' property (E5 Section 15.10.3).
	 */

	/* [ ... pattern flags ] */

	duk__create_escaped_source(thr, -2);

	/* [ ... pattern flags escaped_source ] */

	/*
	 *  Init compilation context
	 */

	/* [ ... pattern flags escaped_source buffer ] */

	DUK_MEMZERO(&re_ctx, sizeof(re_ctx));
	DUK_LEXER_INITCTX(&re_ctx.lex);  /* duplicate zeroing, expect for (possible) NULL inits */
	re_ctx.thr = thr;
	re_ctx.lex.thr = thr;
	re_ctx.lex.input = DUK_HSTRING_GET_DATA(h_pattern);
	re_ctx.lex.input_length = DUK_HSTRING_GET_BYTELEN(h_pattern);
	re_ctx.lex.token_limit = DUK_RE_COMPILE_TOKEN_LIMIT;
	re_ctx.recursion_limit = DUK_USE_REGEXP_COMPILER_RECLIMIT;
	re_ctx.re_flags = duk__parse_regexp_flags(thr, h_flags);

	DUK_BW_INIT_PUSHBUF(thr, &re_ctx.bw, DUK__RE_INITIAL_BUFSIZE);

	DUK_DD(DUK_DDPRINT("regexp compiler ctx initialized, flags=0x%08lx, recursion_limit=%ld",
	                   (unsigned long) re_ctx.re_flags, (long) re_ctx.recursion_limit));

	/*
	 *  Init lexer
	 */

	lex_point.offset = 0;  /* expensive init, just want to fill window */
	lex_point.line = 1;
	DUK_LEXER_SETPOINT(&re_ctx.lex, &lex_point);

	/*
	 *  Compilation
	 */

	DUK_D(DUK_DPRINT("starting regexp compilation"));

	duk__append_u32(&re_ctx, DUK_REOP_SAVE);
	duk__append_u32(&re_ctx, 0);
	duk__parse_disjunction(&re_ctx, 1 /*expect_eof*/, &ign_disj);
	duk__append_u32(&re_ctx, DUK_REOP_SAVE);
	duk__append_u32(&re_ctx, 1);
	duk__append_u32(&re_ctx, DUK_REOP_MATCH);

	/*
	 *  Check for invalid backreferences; note that it is NOT an error
	 *  to back-reference a capture group which has not yet been introduced
	 *  in the pattern (as in /\1(foo)/); in fact, the backreference will
	 *  always match!  It IS an error to back-reference a capture group
	 *  which will never be introduced in the pattern.  Thus, we can check
	 *  for such references only after parsing is complete.
	 */

	if (re_ctx.highest_backref > re_ctx.captures) {
		DUK_ERROR(thr, DUK_ERR_SYNTAX_ERROR, DUK_STR_INVALID_BACKREFS);
	}

	/*
	 *  Emit compiled regexp header: flags, ncaptures
	 *  (insertion order inverted on purpose)
	 */

	duk__insert_u32(&re_ctx, 0, (re_ctx.captures + 1) * 2);
	duk__insert_u32(&re_ctx, 0, re_ctx.re_flags);

	/* [ ... pattern flags escaped_source buffer ] */

	DUK_BW_COMPACT(thr, &re_ctx.bw);
	duk_to_string(ctx, -1);  /* coerce to string */

	/* [ ... pattern flags escaped_source bytecode ] */

	/*
	 *  Finalize stack
	 */

	duk_remove(ctx, -4);     /* -> [ ... flags escaped_source bytecode ] */
	duk_remove(ctx, -3);     /* -> [ ... escaped_source bytecode ] */

	DUK_D(DUK_DPRINT("regexp compilation successful, bytecode: %!T, escaped source: %!T",
	                 (duk_tval *) duk_get_tval(ctx, -1), (duk_tval *) duk_get_tval(ctx, -2)));
}

/*
 *  Create a RegExp instance (E5 Section 15.10.7).
 *
 *  Note: the output stack left by duk_regexp_compile() is directly compatible
 *  with the input here.
 *
 *  Input stack:  [ escaped_source bytecode ]  (both as strings)
 *  Output stack: [ RegExp ]
 */

DUK_INTERNAL void duk_regexp_create_instance(duk_hthread *thr) {
	duk_context *ctx = (duk_context *) thr;
	duk_hobject *h;
	duk_hstring *h_bc;
	duk_small_int_t re_flags;

	/* [ ... escape_source bytecode ] */

	h_bc = duk_get_hstring(ctx, -1);
	DUK_ASSERT(h_bc != NULL);
	DUK_ASSERT(DUK_HSTRING_GET_BYTELEN(h_bc) >= 1);          /* always at least the header */
	DUK_ASSERT(DUK_HSTRING_GET_CHARLEN(h_bc) >= 1);
	DUK_ASSERT((duk_small_int_t) DUK_HSTRING_GET_DATA(h_bc)[0] < 0x80);  /* flags always encodes to 1 byte */
	re_flags = (duk_small_int_t) DUK_HSTRING_GET_DATA(h_bc)[0];

	/* [ ... escaped_source bytecode ] */

	duk_push_object(ctx);
	h = duk_get_hobject(ctx, -1);
	DUK_ASSERT(h != NULL);
	duk_insert(ctx, -3);

	/* [ ... regexp_object escaped_source bytecode ] */

	DUK_HOBJECT_SET_CLASS_NUMBER(h, DUK_HOBJECT_CLASS_REGEXP);
	DUK_HOBJECT_SET_PROTOTYPE_UPDREF(thr, h, thr->builtins[DUK_BIDX_REGEXP_PROTOTYPE]);

	duk_xdef_prop_stridx(ctx, -3, DUK_STRIDX_INT_BYTECODE, DUK_PROPDESC_FLAGS_NONE);

	/* [ ... regexp_object escaped_source ] */

	duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_SOURCE, DUK_PROPDESC_FLAGS_NONE);

	/* [ ... regexp_object ] */

	duk_push_boolean(ctx, (re_flags & DUK_RE_FLAG_GLOBAL));
	duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_GLOBAL, DUK_PROPDESC_FLAGS_NONE);

	duk_push_boolean(ctx, (re_flags & DUK_RE_FLAG_IGNORE_CASE));
	duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_IGNORE_CASE, DUK_PROPDESC_FLAGS_NONE);

	duk_push_boolean(ctx, (re_flags & DUK_RE_FLAG_MULTILINE));
	duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_MULTILINE, DUK_PROPDESC_FLAGS_NONE);

	duk_push_int(ctx, 0);
	duk_xdef_prop_stridx(ctx, -2, DUK_STRIDX_LAST_INDEX, DUK_PROPDESC_FLAGS_W);

	/* [ ... regexp_object ] */
}

#undef DUK__RE_BUFLEN

#else  /* DUK_USE_REGEXP_SUPPORT */

/* regexp support disabled */

#endif  /* DUK_USE_REGEXP_SUPPORT */


text:
@implementation RNSpinkitManager

RCT_EXPORT_MODULE();

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

- (UIView *)view
{
    return [[RNSpinkit alloc] init];
}

RCT_EXPORT_VIEW_PROPERTY(type, NSString);
RCT_EXPORT_VIEW_PROPERTY(size, NSNumber);
RCT_EXPORT_VIEW_PROPERTY(color, NSString);

@end

redpajama_set_name: RedPajamaGithub


text:
var global_text = {
	header : {
		Server : "Serveur",
		New : "Nouveau",
		Hide : "Cacher",
		AddServer : "Ajouter un nouveau serveur",
		Connect : "Connexion",
		Index : "Index",
		AllIndex : "Tous les Index",
		Search : "Rechercher",
		AutoRefresh : "Rafraichissement auto.",
		Hits : "Résultats : ",
		Error : "Erreur",
		Status : "Statut",
		NoError : "OK",
		Customization : "Personnalisation",
		NewServerTitle : "Cacher / Montrer le formulaire d'ajout d'un nouveau serveur",
		ConnectTitle : "Etablir la connexion avec le nouveau serveur",
		navBar : {
			Request : "Requête",
			Keywords : "Mots Clés",
			Templates : "Templates",
		}
	},
	aggregation : {
		Aggregations : "Agregations",
		NewAggregation : "Nouvelle Agregations"
	},
	keyword : {
		Index : "Index",
		Save : "Sauvegarder",
		Add : "Ajouter"
	},
	request : {
		ShowAll : "Voir tout",
		Hide : "Cacher",
		SimplifiedRequest:"Requête simplifiée",
		ComplexeRequest:"Requête complexe",
		ResultPerPage:"Résultats par page",
		Search:"Rechercher",
		JsonQuery: "Requête Json",
		Keywords: "Mots Clés",
		Fields:"Champs",
		ShowAllFieldTitle : "Montrer / Cacher tous les champs",
		ShowAllKeywordTitle : "Montrer / Cacher tout les mots clés",
		KeywordFromQuery : "Mot clé depuis requête",
		Name : "Nom",
		Desc : "Desc",
		Save : "Sauvegarder",
		SortBy : "Trier par",
		Field : "Champ",
		AddSort : "Ajouter un tri"
	},
	result : {
		request_sub_tab : {
			Results : "Résultats",
			Aggregation :"Agrégation",
			Template : "Template",
			AdvancedRequest : "Requête avancée",
			ResultList : "Liste des résultats",
			JsonResult : "Résultats Json",
			First: "Début",
			Csv: "Export CSV",
			Prev: "Précédent",
			Next: "Suivant",
			Last: "Fin",
			Page: "Page",
			Go : "Aller à",
			AggregationFilter : "Filtres d'agrégation",
			Or:"Ou",
			And:"Et",
			Not:"Non",
		}
	},
	template : {
		ResultItems : "Objets Résultats",
		Aggregations : "Agrégations",
		aggregation_sub_tab :{
			Association : "Association",
			AggregationType : "Type d'agrégation",
			Template : "Template",
			Default : "Défaut",
			Update : "Mettre à jour",
			Edit: "Edition",
			New: "Nouveau",
			Save: "Sauvegarder",
			Delete: "Supprimer",
			TemplateName : "Nom du Template"
		},
		result_items_sub_tab :{
			Template : "Template",
			New: "Nouveau",
			Save: "Sauvegarder",
			Delete: "Supprimer",
			TemplateName : "Nom	du Template",
			Fields : "Champs"
		}
	},
	csvModal : {
		CsvExport : "Export CSV",
		Sep : "Séparateur de champs",
		TabSep : "Séparateur de multi-champs",
		Name : "Nom",
		Alias : "Alias",
		Show :  "Voir",
		Hide : "Cacher",
		CurrentResult : "Résultats actuels",
		CurrentResultTitle : "Exporter les résultas actuels au format csv",
		SomeResult : "Nombre de Résultats",
		SomeResultTitle : "Exporter une partie de tous les résultats au format csv",
		FullResultTitle : "Exporter tous les résultats au format csv !!! Attention l'export d'un grand nombre de résultats peut durer longtemps et avoir un impact sur les perfomances du serveur !!!",
		FullResult : "Tous les Résultats",
	},
	context : {
		Context : "Context",
		UpdateContext : "Mettre a jour le template courant",
		SaveContext :  "Sauvegarder le template courant",
		NewContext : "Nouveau context",
		SetAsDefaultContext : "Etablir comme context par défaut",
		ContextName : "Nom",
		Valider : "Valider",
		Remove : "Supprimer le context courant"
	},
	log : {
		Logs : "Logs",
		Hide : "Cacher/Montrer",
		Empty : "Vider les logs"
	},
	moduleManager : {
		ModulesManager : "Modules Manager",
		Add : "Ajouer",
		RestartInterface : "Réinitialiser l'interface",
		Lock : "Vérrouiller/Dévérouiller l'interface"
	}
}


text:
namespace content {

TEST(AccessibilityModeHelperTest, TestNoOpRemove) {
  EXPECT_EQ(AccessibilityModeComplete,
            RemoveAccessibilityModeFrom(AccessibilityModeComplete,
                                        AccessibilityModeOff));
}

TEST(AccessibilityModeHelperTest, TestRemoveSelf) {
  EXPECT_EQ(AccessibilityModeOff,
            RemoveAccessibilityModeFrom(AccessibilityModeComplete,
                                        AccessibilityModeComplete));

  EXPECT_EQ(
      AccessibilityModeOff,
      RemoveAccessibilityModeFrom(AccessibilityModeEditableTextOnly,
                                  AccessibilityModeEditableTextOnly));
}

TEST(AccessibilityModeHelperTest, TestAddMode) {
  EXPECT_EQ(
      AccessibilityModeComplete,
      AddAccessibilityModeTo(AccessibilityModeEditableTextOnly,
                             AccessibilityModeComplete));
  EXPECT_EQ(
      AccessibilityModeComplete,
      AddAccessibilityModeTo(AccessibilityModeEditableTextOnly,
                             AccessibilityModeTreeOnly));
}

}  // namespace content


text:
/* ---------------
 * Multigraph.java
 * ---------------
 * (C) Copyright 2003-2008, by Barak Naveh and Contributors.
 *
 * Original Author:  Barak Naveh
 * Contributor(s):   Christian Hammer
 *
 * $Id: Multigraph.java 645 2008-09-30 19:44:48Z perfecthash $
 *
 * Changes
 * -------
 * 05-Aug-2003 : Initial revision (BN);
 * 06-Aug-2005 : Made generic (CH);
 * 28-May-2006 : Moved connectivity info from edge to graph (JVS);
 *
 */
package org.jgrapht.graph;

import org.jgrapht.*;

/**
 * A multigraph. A multigraph is a non-simple undirected graph in which no loops
 * are permitted, but multiple edges between any two vertices are. If you're
 * unsure about multigraphs, see: <a
 * href="http://mathworld.wolfram.com/Multigraph.html">
 * http://mathworld.wolfram.com/Multigraph.html</a>.
 */
public class Multigraph<V, E>
    extends AbstractBaseGraph<V, E>
    implements UndirectedGraph<V, E>
{
    //~ Static fields/initializers ---------------------------------------------

    private static final long serialVersionUID = 3257001055819871795L;

    //~ Constructors -----------------------------------------------------------

    /**
     * Creates a new multigraph.
     *
     * @param edgeClass class on which to base factory for edges
     */
    public Multigraph(Class<? extends E> edgeClass)
    {
        this(new ClassBasedEdgeFactory<V, E>(edgeClass));
    }

    /**
     * Creates a new multigraph with the specified edge factory.
     *
     * @param ef the edge factory of the new graph.
     */
    public Multigraph(EdgeFactory<V, E> ef)
    {
        super(ef, true, false);
    }
}

// End Multigraph.java


text:
'use strict';

var path = require('path');
var fs = require('fs');
var ItemState = require('./item-state');

/**
 * @class GraphicsController
 * @param {Item} item
 * @constructor
 */
var ItemValidator = function (item) {
    this._item = item;
};

/**
 * @method isProcessingRequired
 * @return {Boolean}
 */
ItemValidator.prototype.isProcessingRequired = function () {
    return (
        !this.exists() ||
        this.isConfigDifferent() ||
        (this._item.conversion() !== null && this.isTimestampNewer())
    );
};

/**
 * @method isSrcNewer
 * @return {Boolean}
 */
ItemValidator.prototype.isTimestampNewer = function () {
    return new ItemState().isTimestampNewer(
        this._item,
        new Date(fs.statSync(this._item.src()).mtime)
    );
};

/**
 * @method exists
 * @return {Boolean}
 */
ItemValidator.prototype.exists = function () {
    return fs.existsSync(this._item.dest());
};

/**
 * @method exists
 * @return {Boolean}
 */
ItemValidator.prototype.isConfigDifferent = function () {
    return new ItemState().isConfigDifferent(this._item);
};

/* global module:false */
module.exports = ItemValidator;


text:
function [SPD, temperatures, stateTrackingData] = OLValidatePrimaryValues(primaryValues, calibration, oneLight, radiometer, varargin)
% Validates SPD that OneLight puts out for given primary values vector(s)
%
% Syntax:
%   SPD = OLValidatePrimaryValues(primaryValues, calibration, oneLight, radiometer)
%   SPD = OLValidatePrimaryValues(primaryValues, calibration, SimulatedOneLight,[])
%   [SPD, temperatures] = OLValidatePrimaryValues(...,'temperatureProbe',LJTemperatureProbe)
%   [SPD, temperatures, stateTrackingData] = OLValidatePrimaryValues(..., 'measureStateTracking',true)
%
% Description:
%    Sends a vector of primary values to a OneLight, measures the SPD and
%    compares that to the SPD that would be predicted from calibration
%    information. Can handle any number of vectors of primary values.
%
% Inputs:
%    primaryValues    - PxN array of primary values, where P is the number
%                       of primary values per spectrum, and N is the number
%                       of spectra to validate (i.e., a column vector per
%                       spectrum)
%    calibration      - struct containing calibration for oneLight
%    oneLight         - a oneLight device driver object to control a
%                       OneLight device, can be real or simulated
%    radiometer       - radiometer object to control a spectroradiometer.
%                       Can be passed empty when simulating
%
% Outputs:
%    results          - 1xN struct-array containing measurement information
%                       (as returned by radiometer), predictedSPD, error
%                       between the two, for all N spectra
%    temperatures     - array of structs, one struct per primary measurement,
%                       with each struct contaning temperature and time of
%                       measurement
%    stateStrackingData - struct with state tracking SPDs
%
% Optional key/value pairs:
%    nAverage         - number of measurements to average. Default 1.
%    temperatureProbe - LJTemperatureProbe object to drive a LabJack
%                       temperature probe
%    measureStateTrackingSPDs - boolean, indicating whether to collect
%                               state tracking data
%
% See also:
%    OLCorrectPrimary, OLValidateDirectionPrimary

% History:
%    11/29/17  jv  created. based on OLValidateCacheFileOOC
%    06/29/18  npc implemented temperature recording
%    06/30/18  npc implemented state tracking SPD recording
%    08/30/18  jv  radiometer as required argument (but can be empty)

%% Input validation
parser = inputParser;
parser.addRequired('primaryValues',@isnumeric);
parser.addRequired('calibration',@isstruct);
parser.addRequired('oneLight',@(x) isa(x,'OneLight'));
parser.addRequired('radiometer',@(x) isempty(x) || isa(x,'Radiometer'));
parser.addParameter('primaryTolerance',1e-5,@isnumeric);
parser.KeepUnmatched = true;
parser.parse(primaryValues,calibration,oneLight,radiometer,varargin{:});

radiometer = parser.Results.radiometer;

%% Predict SPD(s)
predictedSPDs = OLPrimaryToSpd(calibration,primaryValues,'primaryTolerance',parser.Results.primaryTolerance);

%% Measure SPD(s)
[measurement, temperatures, stateTrackingData] = OLMeasurePrimaryValues(primaryValues,calibration,oneLight,radiometer,...
                                                                        'primaryTolerance',parser.Results.primaryTolerance,parser.Unmatched);

%% Analyze and output
SPD = [];
for p = size(primaryValues,2):-1:1
    % Compare to prediction
    err = measurement(:,p) - predictedSPDs(:,p);

    % Add to results
    SPD(p).measuredSPD = measurement(:,p);
    SPD(p).predictedSPD = predictedSPDs(:,p);
    SPD(p).error = err;
end

end


text:
CREATE TABLE t4(a PRIMARY KEY, b);
INSERT INTO t4 VALUES(1, 'one');


text:
package jp.riken.kscope.exception;

import jp.riken.kscope.utils.Logger;

/**
 * 例外処理ハンドラ
 * @author RIKEN
 */
public class ExceptionHandler {

    /**
     * 例外メッセージをログ出力する
     * @param e			例外
     * @throws ApplicationException			アプリケーションエラー
     */
    public static void handleException(Exception e) throws ApplicationException {

        e.printStackTrace();

        // ログ出力
        Logger.error(e);

        // アプリケーション例外でラップしてthrow
        throw new ApplicationException(e);
    }
}


text:
@import 'part:@lyra/base/theme/variables-style';

.root {
  margin-top: 3rem;
}

.heading {
  color: var(--state-warning-color);
}

.inspectValue {
  border: 1px solid #aaa;
  max-height: 200px;
  overflow-y: scroll;
  background-color: white;
}

.content {
  border-top: 1px solid var(--state-warning-color);
  border-bottom: 1px solid var(--state-warning-color);
  padding: 1rem 0.5rem;
}


text:
'use strict';

var JS_DIRECTORY = "/js/";

var config = require('../../configs/build.conf.js');

var args = require('yargs').argv;
var gulp = require('gulp');

var concat = require('gulp-concat');
var connect = require('gulp-connect');
var gulpIf = require('gulp-if');
var plumber = require('gulp-plumber');
var uglify = require('gulp-uglify');

gulp.task('base-scripts', function () {
  var src = config.base.scripts;
  var dest = config.distDir + JS_DIRECTORY;
  var concatFile = 'base.js';
  var productionEnv = args.production; // ENV VARIABLE

  return gulp.src(src)
    .pipe(plumber())
    .pipe(concat(concatFile))
    .pipe(gulpIf(productionEnv, uglify()))
    .pipe(gulp.dest(dest))
    .pipe(connect.reload());
});


text:
<?php

namespace OpenConext\EngineBlockApiClientBundle\Value;

use OpenConext\Profile\Assert;
use OpenConext\Profile\Value\ContactPerson;
use OpenConext\Profile\Value\ContactPersonList;
use OpenConext\Profile\Value\ContactType;
use OpenConext\Profile\Value\ContactEmailAddress;

final class ContactPersonListFactory
{
    /**
     * @param mixed $data
     * @return ContactPersonList
     */
    public static function createListFromMetadata($data)
    {
        Assert::isArray($data, 'Metadata JSON structure must be an associative array, got %s');
        Assert::keyExists($data, 'contact_persons', 'Entity JSON structure must contain key "contact_persons"');
        Assert::isArray($data['contact_persons'], 'Contact persons JSON structure must be an associative array, got %s');

        // We cannot use self::class because translation extractions fails on that
        $contactPersons = array_map(
            ['\OpenConext\EngineBlockApiClientBundle\Value\ContactPersonListFactory', 'createContactPerson'],
            $data['contact_persons']
        );

        return new ContactPersonList($contactPersons);
    }

    /**
     * @param mixed $data
     * @return ContactPerson
     *
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
     */
    private static function createContactPerson($data)
    {
        Assert::isArray($data, 'Contact person JSON structure must be an associative array, got %s');
        Assert::keyExists($data, 'contact_type', 'Contact person JSON structure must contain key "contact_type"');

        if (!array_key_exists('email_address', $data)) {
            return new ContactPerson(new ContactType($data['contact_type']));
        }

        return new ContactPerson(
            new ContactType($data['contact_type']),
            new ContactEmailAddress($data['email_address'])
        );
    }
}


text:
package com.hazelcast.spi;

import com.hazelcast.nio.Address;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.util.Set;

import static org.junit.Assert.assertEquals;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class CallsPerMemberTest {

    private Address address;
    private Address anotherAddress;

    private CallsPerMember callsPerMember;

    @Before
    public void setUp() throws Exception {
        address = new Address("127.0.0.1", 5701);
        anotherAddress = new Address("127.0.0.1", 5702);

        callsPerMember = new CallsPerMember(address);
    }

    @Test
    public void testAdd() {
        callsPerMember.add(anotherAddress, 23);

        Set<Address> addresses = callsPerMember.addresses();
        assertEquals(1, addresses.size());
        assertEquals(anotherAddress, addresses.iterator().next());
    }

    @Test
    public void testAdd_whenAddressIsNull_thenAddsLocalAddress() {
        callsPerMember.add(null, 42);

        Set<Address> addresses = callsPerMember.addresses();
        assertEquals(1, addresses.size());
        assertEquals(address, addresses.iterator().next());
    }

    @Test
    public void testAdd_whenCallIdIsZero_thenNoAddressIsAdded() {
        callsPerMember.add(anotherAddress, 0);

        Set<Address> addresses = callsPerMember.addresses();
        assertEquals(0, addresses.size());
    }

    @Test
    public void testCallIds() {
        callsPerMember.add(anotherAddress, 23);

        long[] callIds = callsPerMember.toOpControl(anotherAddress).runningOperations();

        assertEquals(1, callIds.length);
        assertEquals(23, callIds[0]);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testCallIds_whenAddressIsUnknown_thenThrowException() {
        callsPerMember.toOpControl(address);
    }

    @Test
    public void testClearAndInitMember() {
        callsPerMember.add(address, 23);

        callsPerMember.clear();

        callsPerMember.getOrCreateCallIdsForMember(anotherAddress);

        long[] callIds = callsPerMember.toOpControl(anotherAddress).runningOperations();
        assertEquals(0, callIds.length);
    }
}


text:
export MONGO_URL="mongodb://localhost:27017/MedBook"

export settings_file="../config/travis/settings.json"
export port="3003"

if [ -z "$1" ]; then
    ~/.meteor/meteor --port $port --settings $settings_file
else
    ~/.meteor/meteor meteor $1 --port $port --settings $settings_file
fi


text:
<?php

namespace Oro\Bundle\LayoutBundle\Tests\Unit\Layout\Block\Extension\Stubs;

use Oro\Component\Layout\Block\Type\AbstractType;

class CustomType extends AbstractType
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @param string $name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

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


text:
namespace MahApps.Metro.Controls
{
    using System;
    using System.Collections;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Markup;
    using System.Windows.Media;
    using System.Windows.Shapes;

    /// <summary>
    ///     Represents a container with two views; one view for the main content and another view that is typically used for
    ///     navigation commands.
    /// </summary>
    [TemplatePart(Name = "PaneClipRectangle", Type = typeof(RectangleGeometry))]
    [TemplatePart(Name = "LightDismissLayer", Type = typeof(Rectangle))]
    [TemplateVisualState(Name = "Closed                 ", GroupName = "DisplayModeStates")]
    [TemplateVisualState(Name = "ClosedCompactLeft      ", GroupName = "DisplayModeStates")]
    [TemplateVisualState(Name = "ClosedCompactRight     ", GroupName = "DisplayModeStates")]
    [TemplateVisualState(Name = "OpenOverlayLeft        ", GroupName = "DisplayModeStates")]
    [TemplateVisualState(Name = "OpenOverlayRight       ", GroupName = "DisplayModeStates")]
    [TemplateVisualState(Name = "OpenInlineLeft         ", GroupName = "DisplayModeStates")]
    [TemplateVisualState(Name = "OpenInlineRight        ", GroupName = "DisplayModeStates")]
    [TemplateVisualState(Name = "OpenCompactOverlayLeft ", GroupName = "DisplayModeStates")]
    [TemplateVisualState(Name = "OpenCompactOverlayRight", GroupName = "DisplayModeStates")]
    [ContentProperty("Content")]
    public class SplitView : Control
    {
        /// <summary>
        ///     Identifies the <see cref="CompactPaneLength" /> dependency property.
        /// </summary>
        /// <returns>The identifier for the <see cref="CompactPaneLength" /> property.</returns>
        public static readonly DependencyProperty CompactPaneLengthProperty =
            DependencyProperty.Register("CompactPaneLength", typeof(double), typeof(SplitView), new PropertyMetadata(0d, OnMetricsChanged));

        private static void OnMetricsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var sender = d as SplitView;
            sender?.TemplateSettings?.Update();
            sender?.ChangeVisualState(true, true);
        }

        /// <summary>
        ///     Gets or sets the width of the <see cref="SplitView" /> pane in its compact display mode.
        /// </summary>
        /// <returns>
        ///     The width of the pane in it's compact display mode. The default is 48 device-independent pixel (DIP) (defined
        ///     by the SplitViewCompactPaneThemeLength resource).
        /// </returns>
        public double CompactPaneLength
        {
            get { return (double)this.GetValue(CompactPaneLengthProperty); }
            set { this.SetValue(CompactPaneLengthProperty, value); }
        }

        /// <summary>
        ///     Identifies the <see cref="Content" /> dependency property.
        /// </summary>
        /// <returns>The identifier for the <see cref="Content" /> dependency property.</returns>
        public static readonly DependencyProperty ContentProperty =
            DependencyProperty.Register("Content", typeof(UIElement), typeof(SplitView), new PropertyMetadata(null));

        /// <summary>
        ///     Gets or sets the contents of the main panel of a <see cref="SplitView" />.
        /// </summary>
        /// <returns>The contents of the main panel of a <see cref="SplitView" />. The default is null.</returns>
        public UIElement Content
        {
            get { return (UIElement)this.GetValue(ContentProperty); }
            set { this.SetValue(ContentProperty, value); }
        }

        /// <summary>
        ///     Identifies the <see cref="DisplayMode" /> dependency property.
        /// </summary>
        /// <returns>The identifier for the <see cref="DisplayMode" /> dependency property.</returns>
        public static readonly DependencyProperty DisplayModeProperty =
            DependencyProperty.Register("DisplayMode", typeof(SplitViewDisplayMode), typeof(SplitView), new PropertyMetadata(SplitViewDisplayMode.Overlay, OnStateChanged));

        private static void OnStateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var sender = d as SplitView;
            sender?.ChangeVisualState();
        }

        /// <summary>
        ///     Gets of sets a value that specifies how the pane and content areas of a <see cref="SplitView" /> are shown.
        /// </summary>
        /// <returns>
        ///     A value of the enumeration that specifies how the pane and content areas of a <see cref="SplitView" /> are
        ///     shown. The default is <see cref="SplitViewDisplayMode.Overlay" />.
        /// </returns>
        public SplitViewDisplayMode DisplayMode
        {
            get { return (SplitViewDisplayMode)this.GetValue(DisplayModeProperty); }
            set { this.SetValue(DisplayModeProperty, value); }
        }

        /// <summary>
        ///     Identifies the <see cref="IsPaneOpen" /> dependency property.
        /// </summary>
        /// <returns>The identifier for the <see cref="IsPaneOpen" /> dependency property.</returns>
        public static readonly DependencyProperty IsPaneOpenProperty =
            DependencyProperty.Register("IsPaneOpen", typeof(bool), typeof(SplitView), new PropertyMetadata(false, OnIsPaneOpenChanged));

        private static void OnIsPaneOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var sender = d as SplitView;
            var newValue = (bool)e.NewValue;
            var oldValue = (bool)e.OldValue;

            if (sender == null
                || newValue == oldValue)
                return;

            if (newValue)
                sender.ChangeVisualState(); // Open pane
            else
                sender.OnIsPaneOpenChanged(); // Close pane
        }

        /// <summary>
        ///     Gets or sets a value that specifies whether the <see cref="SplitView" /> pane is expanded to its full width.
        /// </summary>
        /// <returns>true if the pane is expanded to its full width; otherwise, false. The default is true.</returns>
        public bool IsPaneOpen
        {
            get { return (bool)this.GetValue(IsPaneOpenProperty); }
            set { this.SetValue(IsPaneOpenProperty, value); }
        }

        /// <summary>
        ///     Identifies the <see cref="OpenPaneLength" /> dependency property.
        /// </summary>
        /// <returns>The identifier for the <see cref="OpenPaneLength" /> dependency property.</returns>
        public static readonly DependencyProperty OpenPaneLengthProperty =
            DependencyProperty.Register("OpenPaneLength", typeof(double), typeof(SplitView), new PropertyMetadata(0d, OnMetricsChanged));

        /// <summary>
        ///     Gets or sets the width of the <see cref="SplitView" /> pane when it's fully expanded.
        /// </summary>
        /// <returns>
        ///     The width of the <see cref="SplitView" /> pane when it's fully expanded. The default is 320 device-independent
        ///     pixel (DIP).
        /// </returns>
        public double OpenPaneLength
        {
            get { return (double)this.GetValue(OpenPaneLengthProperty); }
            set { this.SetValue(OpenPaneLengthProperty, value); }
        }

        /// <summary>
        ///     Identifies the <see cref="Pane" /> dependency property.
        /// </summary>
        /// <returns>The identifier for the <see cref="Pane" /> dependency property.</returns>
        public static readonly DependencyProperty PaneProperty =
            DependencyProperty.Register("Pane", typeof(UIElement), typeof(SplitView), new PropertyMetadata(null, UpdateLogicalChild));

        /// <summary>
        ///     Gets or sets the contents of the pane of a <see cref="SplitView" />.
        /// </summary>
        /// <returns>The contents of the pane of a <see cref="SplitView" />. The default is null.</returns>
        public UIElement Pane
        {
            get { return (UIElement)this.GetValue(PaneProperty); }
            set { this.SetValue(PaneProperty, value); }
        }

        /// <summary>
        ///     Identifies the <see cref="PaneBackground" /> dependency property.
        /// </summary>
        /// <returns>The identifier for the <see cref="PaneBackground" /> dependency property.</returns>
        public static readonly DependencyProperty PaneBackgroundProperty =
            DependencyProperty.Register("PaneBackground", typeof(Brush), typeof(SplitView), new PropertyMetadata(null));

        /// <summary>
        ///     Gets or sets the Brush to apply to the background of the <see cref="Pane" /> area of the control.
        /// </summary>
        /// <returns>The Brush to apply to the background of the <see cref="Pane" /> area of the control.</returns>
        public Brush PaneBackground
        {
            get { return (Brush)this.GetValue(PaneBackgroundProperty); }
            set { this.SetValue(PaneBackgroundProperty, value); }
        }

        /// <summary>
        ///     Identifies the <see cref="PaneForeground" /> dependency property.
        /// </summary>
        /// <returns>The identifier for the <see cref="PaneForeground" /> dependency property.</returns>
        public static readonly DependencyProperty PaneForegroundProperty =
            DependencyProperty.Register("PaneForeground", typeof(Brush), typeof(SplitView), new PropertyMetadata(null));

        /// <summary>
        ///     Gets or sets the Brush to apply to the foreground of the <see cref="Pane" /> area of the control.
        /// </summary>
        /// <returns>The Brush to apply to the background of the <see cref="Pane" /> area of the control.</returns>
        public Brush PaneForeground
        {
            get { return (Brush)this.GetValue(PaneForegroundProperty); }
            set { this.SetValue(PaneForegroundProperty, value); }
        }

        /// <summary>
        ///     Identifies the PanePlacement dependency property.
        /// </summary>
        /// <returns>The identifier for the PanePlacement dependency property.</returns>
        public static readonly DependencyProperty PanePlacementProperty =
            DependencyProperty.Register("PanePlacement", typeof(SplitViewPanePlacement), typeof(SplitView), new PropertyMetadata(SplitViewPanePlacement.Left, OnStateChanged));

        /// <summary>
        ///     Gets or sets a value that specifies whether the pane is shown on the right or left side of the
        ///     <see cref="SplitView" />.
        /// </summary>
        /// <returns>
        ///     A value of the enumeration that specifies whether the pane is shown on the right or left side of the
        ///     <see cref="SplitView" />. The default is <see cref="SplitViewPanePlacement.Left" />.
        /// </returns>
        public SplitViewPanePlacement PanePlacement
        {
            get { return (SplitViewPanePlacement)this.GetValue(PanePlacementProperty); }
            set { this.SetValue(PanePlacementProperty, value); }
        }

        /// <summary>
        ///     Identifies the <see cref="TemplateSettings" /> dependency property.
        /// </summary>
        /// <returns>The identifier for the <see cref="TemplateSettings" /> dependency property.</returns>
        public static readonly DependencyProperty TemplateSettingsProperty =
            DependencyProperty.Register("TemplateSettings", typeof(SplitViewTemplateSettings), typeof(SplitView), new PropertyMetadata(null));

        /// <summary>
        ///     Gets an object that provides calculated values that can be referenced as TemplateBinding sources when defining
        ///     templates for a <see cref="SplitView" /> control.
        /// </summary>
        /// <returns>An object that provides calculated values for templates.</returns>
        public SplitViewTemplateSettings TemplateSettings
        {
            get { return (SplitViewTemplateSettings)this.GetValue(TemplateSettingsProperty); }
            private set { this.SetValue(TemplateSettingsProperty, value); }
        }

        private Rectangle lightDismissLayer;
        private RectangleGeometry paneClipRectangle;

        /// <summary>
        ///     Initializes a new instance of the <see cref="SplitView" /> class.
        /// </summary>
        public SplitView()
        {
            this.DefaultStyleKey = typeof(SplitView);
            this.TemplateSettings = new SplitViewTemplateSettings(this);
        }

        /// <summary>
        ///     Occurs when the <see cref="SplitView" /> pane is closed.
        /// </summary>
        public event EventHandler PaneClosed;

        /// <summary>
        ///     Occurs when the <see cref="SplitView" /> pane is closing.
        /// </summary>
        public event EventHandler<SplitViewPaneClosingEventArgs> PaneClosing;

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            this.paneClipRectangle = this.GetTemplateChild("PaneClipRectangle") as RectangleGeometry;

            this.lightDismissLayer = this.GetTemplateChild("LightDismissLayer") as Rectangle;
            if (this.lightDismissLayer != null)
            {
                this.lightDismissLayer.MouseDown += this.OnLightDismiss;
            }

            this.ExecuteWhenLoaded(() =>
                {
                    this.TemplateSettings.Update();
                    this.ChangeVisualState(false);
                });
        }

        private static void UpdateLogicalChild(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            if (!(dependencyObject is SplitView splitView))
            {
                return;
            }

            if (e.OldValue is FrameworkElement oldChild)
            {
                splitView.RemoveLogicalChild(oldChild);
            }

            if (e.NewValue is FrameworkElement newChild)
            {
                splitView.AddLogicalChild(newChild);
                newChild.DataContext = splitView.DataContext;
            }
        }

        /// <inheritdoc />
        protected override IEnumerator LogicalChildren
        {
            get
            {
                // cheat, make a list with all logical content and return the enumerator
                ArrayList children = new ArrayList();
                if (this.Pane != null)
                {
                    children.Add(this.Pane);
                }

                if (this.Content != null)
                {
                    children.Add(this.Content);
                }

                return children.GetEnumerator();
            }
        }

        protected override void OnRenderSizeChanged(SizeChangedInfo info)
        {
            base.OnRenderSizeChanged(info);
            if (this.paneClipRectangle != null)
            {
                this.paneClipRectangle.Rect = new Rect(0, 0, this.OpenPaneLength, (double)this.ActualHeight);
            }
        }

        protected virtual void ChangeVisualState(bool animated = true, bool reset = false)
        {
            if (this.paneClipRectangle != null)
            {
                this.paneClipRectangle.Rect = new Rect(0, 0, this.OpenPaneLength, (double)this.ActualHeight); // We could also use ActualHeight and subscribe to the SizeChanged property
            }

            var state = string.Empty;
            if (this.IsPaneOpen)
            {
                state += "Open";
                switch (this.DisplayMode)
                {
                    case SplitViewDisplayMode.CompactInline:
                        state += "Inline";
                        break;
                    default:
                        state += this.DisplayMode.ToString();
                        break;
                }

                state += this.PanePlacement.ToString();
            }
            else
            {
                state += "Closed";
                if (this.DisplayMode == SplitViewDisplayMode.CompactInline
                    || this.DisplayMode == SplitViewDisplayMode.CompactOverlay)
                {
                    state += "Compact";
                    state += this.PanePlacement.ToString();
                }
            }

            if (reset)
            {
                VisualStateManager.GoToState(this, "None", animated);
            }

            VisualStateManager.GoToState(this, state, animated);
        }

        protected virtual void OnIsPaneOpenChanged()
        {
            var cancel = false;
            if (this.PaneClosing != null)
            {
                var args = new SplitViewPaneClosingEventArgs();
                foreach (var paneClosingDelegates in this.PaneClosing.GetInvocationList())
                {
                    var eventHandler = paneClosingDelegates as EventHandler<SplitViewPaneClosingEventArgs>;
                    if (eventHandler == null)
                        continue;

                    eventHandler(this, args);
                    if (args.Cancel)
                    {
                        cancel = true;
                        break;
                    }
                }
            }
            if (!cancel)
            {
                this.ChangeVisualState();
                this.PaneClosed?.Invoke(this, EventArgs.Empty);
            }
            else
            {
                this.SetCurrentValue(IsPaneOpenProperty, false);
            }
        }

        private void OnLightDismiss(object sender, MouseButtonEventArgs e)
        {
            this.SetCurrentValue(IsPaneOpenProperty, false);
        }
    }
}


text:
class Chart < Canvas

  attr_accessor :chart_left, :chart_right, :chart_bottom, :chart_top
  attr_accessor :chart_width, :chart_height

  # num horiz lines used to figure out true height of chart so the top line matches max data values
  def initialize(num_horiz_lines)
    super()

    @chart_top_offset = 5               # title/subtitle
    @chart_bottom_offset = 5            # legend
    @chart_side_offset = 6              # labels
    @num_horiz_lines = num_horiz_lines  # number of background horiz lines in chart

    # height/width of inset chart
    @max_chart_height = @window_height - @chart_top_offset - @chart_bottom_offset + 2
    @chart_height = ((@max_chart_height / num_horiz_lines).floor) * num_horiz_lines
    @chart_width = @window_width - ( 2 * @chart_side_offset )  # left and right side

    # helpers
    @chart_left = @chart_side_offset
    @chart_right = @chart_width - @chart_side_offset
    @chart_bottom = @chart_bottom_offset
    @chart_top = @chart_height + @chart_bottom_offset

    draw_axes
  end

  protected

  def draw_axes

    axis_left_col = @chart_side_offset
    axis_right_col = axis_left_col + @chart_width

    horiz_line(@chart_bottom_offset, @chart_width, axis_left_col, '_') # bottom axis
    vert_line(axis_left_col, 0, @chart_height, @chart_bottom_offset, '|') # left axis
    vert_line(axis_right_col, 0, @chart_height, @chart_bottom_offset, '|') # right axis

  end

  # Draw horizontal axes labels
  def chart_horiz_labels(label_left, label_middle, label_right)
    left_position_start = @chart_side_offset
    middle_position_start = @chart_side_offset + (@chart_width / 2.0).to_i - (label_middle.to_s.length / 2.0).to_i
    right_position_start = @canvas_width - @chart_side_offset - label_right.to_s.length
    text(left_position_start, @chart_bottom_offset - 1, label_left)
    text(middle_position_start, @chart_bottom_offset - 1, label_middle)
    text(right_position_start, @chart_bottom_offset - 1, label_right)
  end

  # Draw horizontal visual lines with % calculated labels on vertical axes
  def chart_horiz_lines(char, left_max_value, left_suffix, right_max_value, right_suffix)

    left_position_start = @chart_side_offset
    right_position_start = @canvas_width - @chart_side_offset

    height_incr_percent = 1.0 / @num_horiz_lines
    lines_per_increment = (@chart_height * height_incr_percent).floor
    line_width = @chart_width - 2  # inset within left/right axes
    side_offset = @chart_side_offset + 1  # account for left axis
    for line_num in 1..@num_horiz_lines do
      horiz_line( (@chart_bottom_offset - 1 + (line_num * lines_per_increment)), line_width, side_offset, char)
      if !left_max_value.nil?
        left_label = "[#{line_num * (left_max_value.to_f / @num_horiz_lines).floor}#{left_suffix}]"
        text((left_position_start - (left_label.size / 2)), ((line_num * lines_per_increment)+ @chart_bottom_offset - 1), left_label)
      end
      if !right_max_value.nil?
        right_label = "[#{line_num * (right_max_value.to_f / @num_horiz_lines).floor}#{right_suffix}]"
        text((right_position_start - (right_label.size / 2)), ((line_num * lines_per_increment)+ @chart_bottom_offset - 1), right_label)
      end
    end
  end

  # -------------------------------------------------
  # PRIMITIVES
  # -------------------------------------------------
  def vert_line(x, y, height, offset, char)
    return if height < 0.5
    for i in y..height - 1 do
      point(x, (i + offset), char) if i < @chart_height   # prevent drawing above the chart due to rounding
    end
  end

  def horiz_line(y, width, offset, char)
    return if width == 0
    for i in 0..width do
      point((i + offset), y, char)
    end
  end

  def point(x, y, char)
    @window.cursor = translate(x, y)
    write(char)
  end

  def text(x, y, text)
    @window.cursor = translate(x, y)
    write(text)
  end

  def cursor(x, y)
    @window.cursor = translate(x, y)
  end

  def write(text)
    VIM::command("normal R#{text}")
  end

  def reset_cursor
    # hack to re-orient the screen; it just works
    # - otherwise if you shrink the window, the cursor set may be shifted to the right
    text(0,@window.height,'')
    cursor(0,@window.height)   # upper left
  end

  def draw_title(title)
    x = (@window_width - title.size) / 2
    y = (@window_height - 1)
    text(x, y, title)
  end

  def draw_subtitle(subtitle)
    x = (@window_width - subtitle.size) / 2
    y = (@window_height - 2)
    text(x, y, subtitle)
  end

  def draw_legend(legend)
    text(((@window_width - legend.length) / 2).floor, 2, legend)
  end

  def debug(*args)
    args.each_index do |i|
    point(0,i+1,args[i])
    end
  end

  private

  # Translate 1-based points to vim's row/col based coord system
  def translate(x, y)
    # lines are top-to-bottom so flip vertical to be 0,0 lower left
    return @canvas_height - y + 1, x - 1
  end

end


text:
package mock

import (
	"fmt"

	"github.com/cilium/cilium/pkg/lock"
	"github.com/cilium/cilium/pkg/trigger"
)

type mockMetrics struct {
	mutex                 lock.RWMutex
	allocationAttempts    map[string]histogram
	releaseAttempts       map[string]histogram
	ipAllocations         map[string]int64
	ipReleases            map[string]int64
	interfaceAllocations  map[string]int64
	allocatedIPs          map[string]int
	availableInterfaces   int
	interfaceCandidates   int
	emptyInterfaceSlots   int
	availableIPsPerSubnet map[string]int
	nodes                 map[string]int
	resyncCount           int64
}

type histogram struct {
	count int64
	sum   float64
}

// NewMockMetrics returns a new metrics implementation with a mocked backend
func NewMockMetrics() *mockMetrics {
	return &mockMetrics{
		allocationAttempts:    map[string]histogram{},
		releaseAttempts:       map[string]histogram{},
		interfaceAllocations:  map[string]int64{},
		ipAllocations:         map[string]int64{},
		ipReleases:            map[string]int64{},
		allocatedIPs:          map[string]int{},
		nodes:                 map[string]int{},
		availableIPsPerSubnet: map[string]int{},
	}
}

func (m *mockMetrics) GetAllocationAttempts(typ, status, subnetID string) int64 {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	return m.allocationAttempts[fmt.Sprintf("type=%s, status=%s, subnetId=%s", typ, status, subnetID)].count
}

func (m *mockMetrics) AllocationAttempt(typ, status, subnetID string, observer float64) {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	key := fmt.Sprintf("type=%s, status=%s, subnetId=%s", typ, status, subnetID)
	value := m.allocationAttempts[key]
	value.count++
	value.sum += observer
	m.allocationAttempts[key] = value
}

func (m *mockMetrics) ReleaseAttempt(typ, status, subnetID string, observer float64) {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	key := fmt.Sprintf("type=%s, status=%s, subnetId=%s", typ, status, subnetID)
	value := m.releaseAttempts[key]
	value.count++
	value.sum += observer
	m.releaseAttempts[key] = value
}

func (m *mockMetrics) IncInterfaceAllocation(subnetID string) {
	m.mutex.Lock()
	m.interfaceAllocations[fmt.Sprintf("subnetId=%s", subnetID)]++
	m.mutex.Unlock()
}

func (m *mockMetrics) IPAllocations(subnetID string) int64 {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	return m.ipAllocations["subnetId="+subnetID]
}

func (m *mockMetrics) AddIPAllocation(subnetID string, allocated int64) {
	m.mutex.Lock()
	m.ipAllocations["subnetId="+subnetID] += allocated
	m.mutex.Unlock()
}

func (m *mockMetrics) AddIPRelease(subnetID string, released int64) {
	m.mutex.Lock()
	m.ipReleases["subnetId="+subnetID] += released
	m.mutex.Unlock()
}

func (m *mockMetrics) AllocatedIPs(typ string) int {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	return m.allocatedIPs[typ]
}

func (m *mockMetrics) SetAllocatedIPs(typ string, allocated int) {
	m.mutex.Lock()
	m.allocatedIPs[typ] = allocated
	m.mutex.Unlock()
}

func (m *mockMetrics) AvailableInterfaces() int {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	return m.availableInterfaces
}

func (m *mockMetrics) SetAvailableInterfaces(available int) {
	m.mutex.Lock()
	m.availableInterfaces = available
	m.mutex.Unlock()
}

func (m *mockMetrics) InterfaceCandidates() int {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	return m.interfaceCandidates
}

func (m *mockMetrics) SetInterfaceCandidates(interfaceCandidates int) {
	m.mutex.Lock()
	m.interfaceCandidates = interfaceCandidates
	m.mutex.Unlock()
}

func (m *mockMetrics) EmptyInterfaceSlots() int {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	return m.emptyInterfaceSlots
}

func (m *mockMetrics) SetEmptyInterfaceSlots(emptyInterfaceSlots int) {
	m.mutex.Lock()
	m.emptyInterfaceSlots = emptyInterfaceSlots
	m.mutex.Unlock()
}

func (m *mockMetrics) Nodes(category string) int {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	return m.nodes[category]
}

func (m *mockMetrics) SetNodes(category string, nodes int) {
	m.mutex.Lock()
	m.nodes[category] = nodes
	m.mutex.Unlock()
}

func (m *mockMetrics) SetAvailableIPsPerSubnet(subnetID, availabilityZone string, available int) {
	m.mutex.Lock()
	m.availableIPsPerSubnet[fmt.Sprintf("subnetId=%s, availabilityZone=%s", subnetID, availabilityZone)] = available
	m.mutex.Unlock()
}

func (m *mockMetrics) ResyncCount() int64 {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	return m.resyncCount
}

func (m *mockMetrics) IncResyncCount() {
	m.mutex.Lock()
	m.resyncCount++
	m.mutex.Unlock()
}

func (m *mockMetrics) PoolMaintainerTrigger() trigger.MetricsObserver {
	return nil
}

func (m *mockMetrics) K8sSyncTrigger() trigger.MetricsObserver {
	return nil
}

func (m *mockMetrics) ResyncTrigger() trigger.MetricsObserver {
	return nil
}


text:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once('../vendor/autoload.php');

use DataBase\Conexao;
use App\TarefaAPI as Tarefa;
$method = $_SERVER['REQUEST_METHOD'];
$tarefa = new Tarefa($_REQUEST['request'], $_SERVER['REQUEST_METHOD']);

//print_r($_REQUEST);


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>establishment</type>
  <type>local_government_office</type>
  <type>point_of_interest</type>
  <formatted_address>1 Staffordshire Place, Stafford ST16 2LP, UK</formatted_address>
  <address_component>
   <long_name>1</long_name>
   <short_name>1</short_name>
   <type>street_number</type>
  </address_component>
  <address_component>
   <long_name>Staffordshire Place</long_name>
   <short_name>Staffordshire Place</short_name>
   <type>route</type>
  </address_component>
  <address_component>
   <long_name>Stafford</long_name>
   <short_name>Stafford</short_name>
   <type>postal_town</type>
  </address_component>
  <address_component>
   <long_name>Staffordshire</long_name>
   <short_name>Staffordshire</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>England</long_name>
   <short_name>England</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>United Kingdom</long_name>
   <short_name>GB</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>ST16 2LP</long_name>
   <short_name>ST16 2LP</short_name>
   <type>postal_code</type>
  </address_component>
  <geometry>
   <location>
    <lat>52.8057348</lat>
    <lng>-2.1149929</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>52.8043858</lat>
     <lng>-2.1163419</lng>
    </southwest>
    <northeast>
     <lat>52.8070838</lat>
     <lng>-2.1136439</lng>
    </northeast>
   </viewport>
  </geometry>
  <place_id>ChIJQbw5ZIJxekgR0Entt8lWJbI</place_id>
 </result>
</GeocodeResponse>


text:
"""
A static dictionary with SAML testusers that can be used as response.
"""
USERS = {
    "testuser1": {
        "sn": ["Testsson 1"],
        "givenName": ["Test 1"],
        "eduPersonAffiliation": ["student"],
        "eduPersonScopedAffiliation": ["student@example.com"],
        "eduPersonPrincipalName": ["test@example.com"],
        "uid": ["testuser1"],
        "eduPersonTargetedID": ["one!for!all"],
        "c": ["SE"],
        "o": ["Example Co."],
        "ou": ["IT"],
        "initials": ["P"],
        "schacHomeOrganization": ["example.com"],
        "email": ["test@example.com"],
        "displayName": ["Test Testsson"],
        "norEduPersonNIN": ["SE199012315555"]
    }
}