text:
/* eslint indent: 0 */
/* eslint max-len: 0 */

// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser

import { types as tt } from "../tokenizer/types";
import Parser from "./index";
import { reservedWords } from "../util/identifier";

const pp = Parser.prototype;

// Check if property name clashes with already added.
// Object/class getters and setters are not allowed to clash —
// either with each other or with an init property — and in
// strict mode, init properties are also not allowed to be repeated.

pp.checkPropClash = function (prop, propHash) {
  if (prop.computed) return;

  let key = prop.key;
  let name;
  switch (key.type) {
    case "Identifier":
      name = key.name;
      break;

    case "StringLiteral":
    case "NumericLiteral":
      name = String(key.value);
      break;

    default:
      return;
  }

  if (name === "__proto__" && prop.kind === "init") {
    if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property");
    propHash.proto = true;
  }
};

// ### Expression parsing

// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function (s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.

// Parse a full expression. The optional arguments are used to
// forbid the `in` operator (in for loops initalization expressions)
// and provide reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).

pp.parseExpression = function (noIn, refShorthandDefaultPos) {
  let startPos = this.state.start, startLoc = this.state.startLoc;
  let expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos);
  if (this.match(tt.comma)) {
    let node = this.startNodeAt(startPos, startLoc);
    node.expressions = [expr];
    while (this.eat(tt.comma)) {
      node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos));
    }
    this.toReferencedList(node.expressions);
    return this.finishNode(node, "SequenceExpression");
  }
  return expr;
};

// Parse an assignment expression. This includes applications of
// operators like `+=`.

pp.parseMaybeAssign = function (noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) {
  if (this.match(tt._yield) && this.state.inGenerator) {
    return this.parseYield();
  }

  let failOnShorthandAssign;
  if (refShorthandDefaultPos) {
    failOnShorthandAssign = false;
  } else {
    refShorthandDefaultPos = { start: 0 };
    failOnShorthandAssign = true;
  }

  let startPos = this.state.start;
  let startLoc = this.state.startLoc;

  if (this.match(tt.parenL) || this.match(tt.name)) {
    this.state.potentialArrowAt = this.state.start;
  }

  let left = this.parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos);
  if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc);
  if (this.state.type.isAssign) {
    let node = this.startNodeAt(startPos, startLoc);
    node.operator = this.state.value;
    node.left = this.match(tt.eq) ? this.toAssignable(left) : left;
    refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly

    this.checkLVal(left);

    if (left.extra && left.extra.parenthesized) {
      let errorMsg;
      if (left.type === "ObjectPattern") {
        errorMsg = "`({a}) = 0` use `({a} = 0)`";
      } else if (left.type === "ArrayPattern") {
        errorMsg = "`([a]) = 0` use `([a] = 0)`";
      }
      if (errorMsg) {
        this.raise(left.start, `You're trying to assign to a parenthesized expression, eg. instead of ${errorMsg}`);
      }
    }

    this.next();
    node.right = this.parseMaybeAssign(noIn);
    return this.finishNode(node, "AssignmentExpression");
  } else if (failOnShorthandAssign && refShorthandDefaultPos.start) {
    this.unexpected(refShorthandDefaultPos.start);
  }

  return left;
};

// Parse a ternary conditional (`?:`) operator.

pp.parseMaybeConditional = function (noIn, refShorthandDefaultPos, refNeedsArrowPos) {
  let startPos = this.state.start, startLoc = this.state.startLoc;
  let expr = this.parseExprOps(noIn, refShorthandDefaultPos);
  if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;

  return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos);
};

pp.parseConditional = function (expr, noIn, startPos, startLoc) {
  if (this.eat(tt.question)) {
    let node = this.startNodeAt(startPos, startLoc);
    node.test = expr;
    node.consequent = this.parseMaybeAssign();
    this.expect(tt.colon);
    node.alternate = this.parseMaybeAssign(noIn);
    return this.finishNode(node, "ConditionalExpression");
  }
  return expr;
};

// Start the precedence parser.

pp.parseExprOps = function (noIn, refShorthandDefaultPos) {
  let startPos = this.state.start, startLoc = this.state.startLoc;
  let expr = this.parseMaybeUnary(refShorthandDefaultPos);
  if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
    return expr;
  } else {
    return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
  }
};

// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.

pp.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
  let prec = this.state.type.binop;
  if (prec != null && (!noIn || !this.match(tt._in))) {
    if (prec > minPrec) {
      let node = this.startNodeAt(leftStartPos, leftStartLoc);
      node.left = left;
      node.operator = this.state.value;

      if (
        node.operator === "**" &&
        left.type === "UnaryExpression" &&
        left.extra &&
        !left.extra.parenthesizedArgument &&
        !left.extra.parenthesized
      ) {
        this.raise(left.argument.start, "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.");
      }

      let op = this.state.type;
      this.next();

      let startPos = this.state.start;
      let startLoc = this.state.startLoc;
      node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn);

      this.finishNode(node, (op === tt.logicalOR || op === tt.logicalAND) ? "LogicalExpression" : "BinaryExpression");
      return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
    }
  }
  return left;
};

// Parse unary operators, both prefix and postfix.

pp.parseMaybeUnary = function (refShorthandDefaultPos) {
  if (this.state.type.prefix) {
    let node = this.startNode();
    let update = this.match(tt.incDec);
    node.operator = this.state.value;
    node.prefix = true;
    this.next();

    let argType = this.state.type;
    node.argument = this.parseMaybeUnary();

    this.addExtra(node, "parenthesizedArgument", argType === tt.parenL && (!node.argument.extra || !node.argument.extra.parenthesized));

    if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
      this.unexpected(refShorthandDefaultPos.start);
    }

    if (update) {
      this.checkLVal(node.argument);
    } else if (this.state.strict && node.operator === "delete" && node.argument.type === "Identifier") {
      this.raise(node.start, "Deleting local variable in strict mode");
    }

    return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  }

  let startPos = this.state.start, startLoc = this.state.startLoc;
  let expr = this.parseExprSubscripts(refShorthandDefaultPos);
  if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
  while (this.state.type.postfix && !this.canInsertSemicolon()) {
    let node = this.startNodeAt(startPos, startLoc);
    node.operator = this.state.value;
    node.prefix = false;
    node.argument = expr;
    this.checkLVal(expr);
    this.next();
    expr = this.finishNode(node, "UpdateExpression");
  }
  return expr;
};

// Parse call, dot, and `[]`-subscript expressions.

pp.parseExprSubscripts = function (refShorthandDefaultPos) {
  let startPos = this.state.start, startLoc = this.state.startLoc;
  let potentialArrowAt = this.state.potentialArrowAt;
  let expr = this.parseExprAtom(refShorthandDefaultPos);

  if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) {
    return expr;
  }

  if (refShorthandDefaultPos && refShorthandDefaultPos.start) {
    return expr;
  }

  return this.parseSubscripts(expr, startPos, startLoc);
};

pp.parseSubscripts = function (base, startPos, startLoc, noCalls) {
  for (;;) {
    if (!noCalls && this.eat(tt.doubleColon)) {
      let node = this.startNodeAt(startPos, startLoc);
      node.object = base;
      node.callee = this.parseNoCallExpr();
      return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
    } else if (this.eat(tt.dot)) {
      let node = this.startNodeAt(startPos, startLoc);
      node.object = base;
      node.property = this.parseIdentifier(true);
      node.computed = false;
      base = this.finishNode(node, "MemberExpression");
    } else if (this.eat(tt.bracketL)) {
      let node = this.startNodeAt(startPos, startLoc);
      node.object = base;
      node.property = this.parseExpression();
      node.computed = true;
      this.expect(tt.bracketR);
      base = this.finishNode(node, "MemberExpression");
    } else if (!noCalls && this.match(tt.parenL)) {
      let possibleAsync = this.state.potentialArrowAt === base.start && base.type === "Identifier" && base.name === "async" && !this.canInsertSemicolon();
      this.next();

      let node = this.startNodeAt(startPos, startLoc);
      node.callee = base;
      node.arguments = this.parseCallExpressionArguments(tt.parenR, possibleAsync);
      base = this.finishNode(node, "CallExpression");

      if (possibleAsync && this.shouldParseAsyncArrow()) {
        return this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
      } else {
        this.toReferencedList(node.arguments);
      }
    } else if (this.match(tt.backQuote)) {
      let node = this.startNodeAt(startPos, startLoc);
      node.tag = base;
      node.quasi = this.parseTemplate();
      base = this.finishNode(node, "TaggedTemplateExpression");
    } else {
      return base;
    }
  }
};

pp.parseCallExpressionArguments = function (close, possibleAsyncArrow) {
  let innerParenStart;

  let elts = [], first = true;
  while (!this.eat(close)) {
    if (first) {
      first = false;
    } else {
      this.expect(tt.comma);
      if (this.eat(close)) break;
    }

    // we need to make sure that if this is an async arrow functions, that we don't allow inner parens inside the params
    if (this.match(tt.parenL) && !innerParenStart) {
      innerParenStart = this.state.start;
    }

    elts.push(this.parseExprListItem(undefined, possibleAsyncArrow ? { start: 0 } : undefined));
  }

  // we found an async arrow function so let's not allow any inner parens
  if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) {
    this.unexpected();
  }

  return elts;
};

pp.shouldParseAsyncArrow = function () {
  return this.match(tt.arrow);
};

pp.parseAsyncArrowFromCallExpression = function (node, call) {
  this.expect(tt.arrow);
  return this.parseArrowExpression(node, call.arguments, true);
};

// Parse a no-call expression (like argument of `new` or `::` operators).

pp.parseNoCallExpr = function () {
  let startPos = this.state.start, startLoc = this.state.startLoc;
  return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
};

// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.

pp.parseExprAtom = function (refShorthandDefaultPos) {
  let node, canBeArrow = this.state.potentialArrowAt === this.state.start;
  switch (this.state.type) {
    case tt._super:
      if (!this.state.inMethod && !this.options.allowSuperOutsideMethod) {
        this.raise(this.state.start, "'super' outside of function or class");
      }

      node = this.startNode();
      this.next();
      if (!this.match(tt.parenL) && !this.match(tt.bracketL) && !this.match(tt.dot)) {
        this.unexpected();
      }
      if (this.match(tt.parenL) && this.state.inMethod !== "constructor" && !this.options.allowSuperOutsideMethod) {
        this.raise(node.start, "super() outside of class constructor");
      }
      return this.finishNode(node, "Super");

    case tt._this:
      node = this.startNode();
      this.next();
      return this.finishNode(node, "ThisExpression");

    case tt._yield:
      if (this.state.inGenerator) this.unexpected();

    case tt.name:
      node = this.startNode();
      let allowAwait = this.state.value === "await" && this.state.inAsync;
      let allowYield = this.shouldAllowYieldIdentifier();
      let id = this.parseIdentifier(allowAwait || allowYield);

      if (id.name === "await") {
        if (this.state.inAsync || this.inModule) {
          return this.parseAwait(node);
        }
      } else if (id.name === "async" && this.match(tt._function) && !this.canInsertSemicolon()) {
        this.next();
        return this.parseFunction(node, false, false, true);
      } else if (canBeArrow && id.name === "async" && this.match(tt.name)) {
        let params = [this.parseIdentifier()];
        this.expect(tt.arrow);
        // let foo = bar => {};
        return this.parseArrowExpression(node, params, true);
      }

      if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
        return this.parseArrowExpression(node, [id]);
      }

      return id;

    case tt._do:
      if (this.hasPlugin("doExpressions")) {
        let node = this.startNode();
        this.next();
        let oldInFunction = this.state.inFunction;
        let oldLabels = this.state.labels;
        this.state.labels = [];
        this.state.inFunction = false;
        node.body = this.parseBlock(false, true);
        this.state.inFunction = oldInFunction;
        this.state.labels = oldLabels;
        return this.finishNode(node, "DoExpression");
      }

    case tt.regexp:
      let value = this.state.value;
      node = this.parseLiteral(value.value, "RegExpLiteral");
      node.pattern = value.pattern;
      node.flags = value.flags;
      return node;

    case tt.num:
      return this.parseLiteral(this.state.value, "NumericLiteral");

    case tt.string:
      return this.parseLiteral(this.state.value, "StringLiteral");

    case tt._null:
      node = this.startNode();
      this.next();
      return this.finishNode(node, "NullLiteral");

    case tt._true: case tt._false:
      node = this.startNode();
      node.value = this.match(tt._true);
      this.next();
      return this.finishNode(node, "BooleanLiteral");

    case tt.parenL:
      return this.parseParenAndDistinguishExpression(null, null, canBeArrow);

    case tt.bracketL:
      node = this.startNode();
      this.next();
      node.elements = this.parseExprList(tt.bracketR, true, refShorthandDefaultPos);
      this.toReferencedList(node.elements);
      return this.finishNode(node, "ArrayExpression");

    case tt.braceL:
      return this.parseObj(false, refShorthandDefaultPos);

    case tt._function:
      return this.parseFunctionExpression();

    case tt.at:
      this.parseDecorators();

    case tt._class:
      node = this.startNode();
      this.takeDecorators(node);
      return this.parseClass(node, false);

    case tt._new:
      return this.parseNew();

    case tt.backQuote:
      return this.parseTemplate();

    case tt.doubleColon:
      node = this.startNode();
      this.next();
      node.object = null;
      let callee = node.callee = this.parseNoCallExpr();
      if (callee.type === "MemberExpression") {
        return this.finishNode(node, "BindExpression");
      } else {
        this.raise(callee.start, "Binding should be performed on object property.");
      }

    default:
      this.unexpected();
  }
};

pp.parseFunctionExpression = function () {
  let node = this.startNode();
  let meta = this.parseIdentifier(true);
  if (this.state.inGenerator && this.eat(tt.dot) && this.hasPlugin("functionSent")) {
    return this.parseMetaProperty(node, meta, "sent");
  } else {
    return this.parseFunction(node, false);
  }
};

pp.parseMetaProperty = function (node, meta, propertyName) {
  node.meta = meta;
  node.property = this.parseIdentifier(true);

  if (node.property.name !== propertyName) {
    this.raise(node.property.start, `The only valid meta property for new is ${meta.name}.${propertyName}`);
  }

  return this.finishNode(node, "MetaProperty");
};

pp.parseLiteral = function (value, type) {
  let node = this.startNode();
  this.addExtra(node, "rawValue", value);
  this.addExtra(node, "raw", this.input.slice(this.state.start, this.state.end));
  node.value = value;
  this.next();
  return this.finishNode(node, type);
};

pp.parseParenExpression = function () {
  this.expect(tt.parenL);
  let val = this.parseExpression();
  this.expect(tt.parenR);
  return val;
};

pp.parseParenAndDistinguishExpression = function (startPos, startLoc, canBeArrow, isAsync) {
  startPos = startPos || this.state.start;
  startLoc = startLoc || this.state.startLoc;

  let val;
  this.expect(tt.parenL);

  let innerStartPos = this.state.start, innerStartLoc = this.state.startLoc;
  let exprList = [], first = true;
  let refShorthandDefaultPos = { start: 0 }, spreadStart, optionalCommaStart;
  let refNeedsArrowPos = { start: 0 };
  while (!this.match(tt.parenR)) {
    if (first) {
      first = false;
    } else {
      this.expect(tt.comma, refNeedsArrowPos.start || null);
      if (this.match(tt.parenR)) {
        optionalCommaStart = this.state.start;
        break;
      }
    }

    if (this.match(tt.ellipsis)) {
      let spreadNodeStartPos = this.state.start, spreadNodeStartLoc = this.state.startLoc;
      spreadStart = this.state.start;
      exprList.push(this.parseParenItem(this.parseRest(), spreadNodeStartLoc, spreadNodeStartPos));
      break;
    } else {
      exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos));
    }
  }

  let innerEndPos = this.state.start;
  let innerEndLoc = this.state.startLoc;
  this.expect(tt.parenR);

  let arrowNode = this.startNodeAt(startPos, startLoc);
  if (canBeArrow && !this.canInsertSemicolon() && (arrowNode = this.parseArrow(arrowNode))) {
    for (let param of exprList) {
      if (param.extra && param.extra.parenthesized) this.unexpected(param.extra.parenStart);
    }

    return this.parseArrowExpression(arrowNode, exprList, isAsync);
  }

  if (!exprList.length) {
    if (isAsync) {
      return;
    } else {
      this.unexpected(this.state.lastTokStart);
    }
  }
  if (optionalCommaStart) this.unexpected(optionalCommaStart);
  if (spreadStart) this.unexpected(spreadStart);
  if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start);
  if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);

  if (exprList.length > 1) {
    val = this.startNodeAt(innerStartPos, innerStartLoc);
    val.expressions = exprList;
    this.toReferencedList(val.expressions);
    this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  } else {
    val = exprList[0];
  }

  this.addExtra(val, "parenthesized", true);
  this.addExtra(val, "parenStart", startPos);

  return val;
};

pp.parseArrow = function (node) {
  if (this.eat(tt.arrow)) {
    return node;
  }
};

pp.parseParenItem = function (node) {
  return node;
};

// New's precedence is slightly tricky. It must allow its argument
// to be a `[]` or dot subscript expression, but not a call — at
// least, not without wrapping it in parentheses. Thus, it uses the

pp.parseNew = function () {
  let node = this.startNode();
  let meta = this.parseIdentifier(true);

  if (this.eat(tt.dot)) {
    return this.parseMetaProperty(node, meta, "target");
  }

  node.callee = this.parseNoCallExpr();

  if (this.eat(tt.parenL)) {
    node.arguments = this.parseExprList(tt.parenR);
    this.toReferencedList(node.arguments);
  } else {
    node.arguments = [];
  }

  return this.finishNode(node, "NewExpression");
};

// Parse template expression.

pp.parseTemplateElement = function () {
  let elem = this.startNode();
  elem.value = {
    raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
    cooked: this.state.value
  };
  this.next();
  elem.tail = this.match(tt.backQuote);
  return this.finishNode(elem, "TemplateElement");
};

pp.parseTemplate = function () {
  let node = this.startNode();
  this.next();
  node.expressions = [];
  let curElt = this.parseTemplateElement();
  node.quasis = [curElt];
  while (!curElt.tail) {
    this.expect(tt.dollarBraceL);
    node.expressions.push(this.parseExpression());
    this.expect(tt.braceR);
    node.quasis.push(curElt = this.parseTemplateElement());
  }
  this.next();
  return this.finishNode(node, "TemplateLiteral");
};

// Parse an object literal or binding pattern.

pp.parseObj = function (isPattern, refShorthandDefaultPos) {
  let decorators = [];
  let propHash = Object.create(null);
  let first = true;
  let node = this.startNode();

  node.properties = [];
  this.next();

  while (!this.eat(tt.braceR)) {
    if (first) {
      first = false;
    } else {
      this.expect(tt.comma);
      if (this.eat(tt.braceR)) break;
    }

    while (this.match(tt.at)) {
      decorators.push(this.parseDecorator());
    }

    let prop = this.startNode(), isGenerator = false, isAsync = false, startPos, startLoc;
    if (decorators.length) {
      prop.decorators = decorators;
      decorators = [];
    }

    if (this.hasPlugin("objectRestSpread") && this.match(tt.ellipsis)) {
      prop = this.parseSpread();
      prop.type = isPattern ? "RestProperty" : "SpreadProperty";
      node.properties.push(prop);
      continue;
    }

    prop.method = false;
    prop.shorthand = false;

    if (isPattern || refShorthandDefaultPos) {
      startPos = this.state.start;
      startLoc = this.state.startLoc;
    }

    if (!isPattern) {
      isGenerator = this.eat(tt.star);
    }

    if (!isPattern && this.isContextual("async")) {
      if (isGenerator) this.unexpected();

      let asyncId = this.parseIdentifier();
      if (this.match(tt.colon) || this.match(tt.parenL) || this.match(tt.braceR)) {
        prop.key = asyncId;
      } else {
        isAsync = true;
        if (this.hasPlugin("asyncGenerators")) isGenerator = this.eat(tt.star);
        this.parsePropertyName(prop);
      }
    } else {
      this.parsePropertyName(prop);
    }

    this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos);
    this.checkPropClash(prop, propHash);

    if (prop.shorthand) {
      this.addExtra(prop, "shorthand", true);
    }

    node.properties.push(prop);
  }

  if (decorators.length) {
    this.raise(this.state.start, "You have trailing decorators with no property");
  }

  return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
};

pp.parseObjPropValue = function (prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos) {
  if (isAsync || isGenerator || this.match(tt.parenL)) {
    if (isPattern) this.unexpected();
    prop.kind = "method";
    prop.method = true;
    this.parseMethod(prop, isGenerator, isAsync);
    return this.finishNode(prop, "ObjectMethod");
  }

  if (this.eat(tt.colon)) {
    prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos);
    return this.finishNode(prop, "ObjectProperty");
  }

  if (!prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (!this.match(tt.comma) && !this.match(tt.braceR))) {
    if (isGenerator || isAsync || isPattern) this.unexpected();
    prop.kind = prop.key.name;
    this.parsePropertyName(prop);
    this.parseMethod(prop, false);
    let paramCount = prop.kind === "get" ? 0 : 1;
    if (prop.params.length !== paramCount) {
      let start = prop.start;
      if (prop.kind === "get") {
        this.raise(start, "getter should have no params");
      } else {
        this.raise(start, "setter should have exactly one param");
      }
    }
    return this.finishNode(prop, "ObjectMethod");
  }

  if (!prop.computed && prop.key.type === "Identifier") {
    if (isPattern) {
      let illegalBinding = this.isKeyword(prop.key.name);
      if (!illegalBinding && this.state.strict) {
        illegalBinding = reservedWords.strictBind(prop.key.name) || reservedWords.strict(prop.key.name);
      }
      if (illegalBinding) {
        this.raise(prop.key.start, "Binding " + prop.key.name);
      }
      prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
    } else if (this.match(tt.eq) && refShorthandDefaultPos) {
      if (!refShorthandDefaultPos.start) {
        refShorthandDefaultPos.start = this.state.start;
      }
      prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
    } else {
      prop.value = prop.key.__clone();
    }
    prop.shorthand = true;
    return this.finishNode(prop, "ObjectProperty");
  }

  this.unexpected();
};

pp.parsePropertyName = function (prop) {
  if (this.eat(tt.bracketL)) {
    prop.computed = true;
    prop.key = this.parseMaybeAssign();
    this.expect(tt.bracketR);
    return prop.key;
  } else {
    prop.computed = false;
    return prop.key = (this.match(tt.num) || this.match(tt.string)) ? this.parseExprAtom() : this.parseIdentifier(true);
  }
};

// Initialize empty function node.

pp.initFunction = function (node, isAsync) {
  node.id = null;
  node.generator = false;
  node.expression = false;
  node.async = !!isAsync;
};

// Parse object or class method.

pp.parseMethod = function (node, isGenerator, isAsync) {
  let oldInMethod = this.state.inMethod;
  this.state.inMethod = node.kind || true;
  this.initFunction(node, isAsync);
  this.expect(tt.parenL);
  node.params = this.parseBindingList(tt.parenR);
  node.generator = isGenerator;
  this.parseFunctionBody(node);
  this.state.inMethod = oldInMethod;
  return node;
};

// Parse arrow function expression with given parameters.

pp.parseArrowExpression = function (node, params, isAsync) {
  this.initFunction(node, isAsync);
  node.params = this.toAssignableList(params, true);
  this.parseFunctionBody(node, true);
  return this.finishNode(node, "ArrowFunctionExpression");
};

// Parse function body and check parameters.

pp.parseFunctionBody = function (node, allowExpression) {
  let isExpression = allowExpression && !this.match(tt.braceL);

  let oldInAsync = this.state.inAsync;
  this.state.inAsync = node.async;
  if (isExpression) {
    node.body = this.parseMaybeAssign();
    node.expression = true;
  } else {
    // Start a new scope with regard to labels and the `inFunction`
    // flag (restore them to their old value afterwards).
    let oldInFunc = this.state.inFunction, oldInGen = this.state.inGenerator, oldLabels = this.state.labels;
    this.state.inFunction = true; this.state.inGenerator = node.generator; this.state.labels = [];
    node.body = this.parseBlock(true);
    node.expression = false;
    this.state.inFunction = oldInFunc; this.state.inGenerator = oldInGen; this.state.labels = oldLabels;
  }
  this.state.inAsync = oldInAsync;

  // If this is a strict mode function, verify that argument names
  // are not repeated, and it does not try to bind the words `eval`
  // or `arguments`.
  let checkLVal = this.state.strict;
  let checkLValStrict = false;
  let isStrict = false;

  // arrow function
  if (allowExpression) checkLVal = true;

  // normal function
  if (!isExpression && node.body.directives.length) {
    for (let directive of (node.body.directives: Array<Object>)) {
      if (directive.value.value === "use strict") {
        isStrict = true;
        checkLVal = true;
        checkLValStrict = true;
        break;
      }
    }
  }

  //
  if (isStrict && node.id && node.id.type === "Identifier" && node.id.name === "yield") {
    this.raise(node.id.start, "Binding yield in strict mode");
  }

  if (checkLVal) {
    let nameHash = Object.create(null);
    let oldStrict = this.state.strict;
    if (checkLValStrict) this.state.strict = true;
    if (node.id) {
      this.checkLVal(node.id, true);
    }
    for (let param of (node.params: Array<Object>)) {
      this.checkLVal(param, true, nameHash);
    }
    this.state.strict = oldStrict;
  }
};

// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).

pp.parseExprList = function (close, allowEmpty, refShorthandDefaultPos) {
  let elts = [], first = true;
  while (!this.eat(close)) {
    if (first) {
      first = false;
    } else {
      this.expect(tt.comma);
      if (this.eat(close)) break;
    }

    elts.push(this.parseExprListItem(allowEmpty, refShorthandDefaultPos));
  }
  return elts;
};

pp.parseExprListItem = function (allowEmpty, refShorthandDefaultPos) {
  let elt;
  if (allowEmpty && this.match(tt.comma)) {
    elt = null;
  } else if (this.match(tt.ellipsis)) {
    elt = this.parseSpread(refShorthandDefaultPos);
  } else {
    elt = this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem);
  }
  return elt;
};

// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.

pp.parseIdentifier = function (liberal) {
  let node = this.startNode();

  if (this.match(tt.name)) {
    if (!liberal && this.state.strict && reservedWords.strict(this.state.value)) {
      this.raise(this.state.start, "The keyword '" + this.state.value + "' is reserved");
    }

    node.name = this.state.value;
  } else if (liberal && this.state.type.keyword) {
    node.name = this.state.type.keyword;
  } else {
    this.unexpected();
  }

  if (!liberal && node.name === "await" && this.state.inAsync) {
    this.raise(node.start, "invalid use of await inside of an async function");
  }

  node.loc.identifierName = node.name;

  this.next();
  return this.finishNode(node, "Identifier");
};

// Parses await expression inside async function.

pp.parseAwait = function (node) {
  if (!this.state.inAsync) {
    this.unexpected();
  }
  if (this.match(tt.star)) {
    this.raise(node.start, "await* has been removed from the async functions proposal. Use Promise.all() instead.");
  }
  node.argument = this.parseMaybeUnary();
  return this.finishNode(node, "AwaitExpression");
};

// Parses yield expression inside generator.

pp.parseYield = function () {
  let node = this.startNode();
  this.next();
  if (this.match(tt.semi) || this.canInsertSemicolon() || (!this.match(tt.star) && !this.state.type.startsExpr)) {
    node.delegate = false;
    node.argument = null;
  } else {
    node.delegate = this.eat(tt.star);
    node.argument = this.parseMaybeAssign();
  }
  return this.finishNode(node, "YieldExpression");
};


text:
function validateSchema (data) {
  try {
    // require validator.js
    var validator = require('validator');
    // reference this as self
    var self = this;

    // call a validator method depending on type
    function isValid (type, value) {
      switch (type) {
        case 'email':
          return validator.isEmail(value);
          break;
        case 'url':
          return validator.isURL(value);
          break;
        case 'domain':
          return validator.isFQDN(value);
          break;
        case 'ip':
          return validator.isIP(value);
          break;
        case 'alpha':
          return validator.isAlpha(value);
          break;
        case 'number':
          return validator.isNumeric(value);
          break;
        case 'alphanumeric':
          return validator.isAlphanumeric(value);
          break;
        case 'base64':
          return validator.isBase64(value);
          break;
        case 'hexadecimal':
          return validator.isHexadecimal(value);
          break;
        case 'hexcolor':
          return validator.isHexColor(value);
          break;
        case 'int':
          return validator.isInt(value);
          break;
        case 'float':
          return validator.isFloat(value);
          break;
        case 'null':
          return validator.isNull(value);
          break;
        case 'uuid':
          return validator.isUUID(value);
          break;
        case 'date':
          return validator.isDate(value);
          break;
        case 'creditcard':
          return validator.isCreditCard(value);
          break;
        case 'isbn':
          return validator.isISBN(value);
          break;
        case 'mobilephone':
          return validator.isMobilePhone(value);
          break;
        case 'json':
          return validator.isJSON(value);
          break;
        case 'ascii':
          return validator.isAscii(value);
          break;
        case 'mongoid':
          return validator.isMongoId(value);
          break;
        default:
          return false;
          break;
      }
    }

    // array of errors, by default is empty
    var errors = [];

    // walk for data and validate each property
    Object.keys(data).forEach(function (property) {
      // if the property doesn't exist in the schema
      if (!self.schema[property]) {
        var error = new Error(property + ' is invalid.');
        errors.push(error);
      }

      // if the property is invalid
      if (!isValid(self.schema[property], data[property])) {
        var error = new Error(property + ' must be ' + self.schema[property] + '.');
        errors.push(error);
      }
    });

    // return errors array or true if there are no errors
    return (errors.length) ? errors : true;
  } catch (err) {
    return err;
  }
}

var sukimajs = {
  register: function registerSchema (schema) {
    try {
      // return an object with the schema and a validate method
      return {
        schema: schema,
        validate: validateSchema
      }
    } catch (err) {
      return err;
    }
  }
}

module.exports = sukimajs;

redpajama_set_name: RedPajamaGithub


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe HomeHelper do

  #Delete this example and add some real ones or delete this file
  it "should include the HomeHelper" do
    included_modules = (class << helper; self; end).send :included_modules
    included_modules.should include(HomeHelper)
  end

end


text:
<!DOCTYPE html>

	<title>Loading</title>

	<button onclick="loading()">loading</button>


text:
libFolder = File.join(File.dirname(__FILE__),'lib')
$:.unshift(File.expand_path(libFolder)) unless $:.include?(File.expand_path(libFolder)) || $:.include?(libFolder)

require 'rspec/core/rake_task'
require 'rubygems/package_task'
require 'rdoc/task'

# Task to run RSpec tests
RSpec::Core::RakeTask.new(:spec)

# Task to package gem
gemspec = Gem::Specification.load('mtbuild.gemspec')
Gem::PackageTask.new(gemspec) do |pkg|
end

# Task to create docs
RDoc::Task.new do |rdoc|
  rdoc.main = "README.md"
  rdoc.rdoc_files.include(gemspec.files)
end

# Package only if tests pass and documentation generated
Rake::Task[:package].prerequisites.insert(0, :spec)
Rake::Task[:package].prerequisites.insert(1, :rdoc)

# Task to install gem
desc "Install the gem file #{gemspec.file_name}"
task :install => [:package] do
  sh "gem install pkg/#{gemspec.file_name}"
end

# Package by default
task :default => [:package]


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef _CONF_GPIO_PERIPHERAL_BUS_EXAMPLE_H
#define _CONF_GPIO_PERIPHERAL_BUS_EXAMPLE_H

#include "conf_board.h"

/*! \name Pin Configuration
 */
//! @{
#define GPIO_PIN_EXAMPLE_1  LED0_GPIO
#define GPIO_PIN_EXAMPLE_2  LED1_GPIO
#define GPIO_PIN_EXAMPLE_3  QT1081_TOUCH_SENSOR_ENTER
//! @}

#endif  // _CONF_GPIO_PERIPHERAL_BUS_EXAMPLE_H


text:
package com.orientechnologies.orient.core.storage.fs;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import com.orientechnologies.common.concur.lock.OLockException;
import com.orientechnologies.common.io.OFileUtils;
import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.serialization.OBinaryProtocol;

public class OFileClassic implements OFile {
  private static final boolean trackFileClose           = OGlobalConfiguration.TRACK_FILE_CLOSE.getValueAsBoolean();

  public final static String   NAME                     = "classic";
  public static final int      HEADER_SIZE              = 1024;
  private static final int     SOFTLY_CLOSED_OFFSET_V_0 = 8;
  private static final int     SOFTLY_CLOSED_OFFSET     = 16;
  private static final int     VERSION_OFFSET           = 48;
  private static final int     CURRENT_VERSION          = 1;
  private static final int     OPEN_RETRY_MAX           = 10;
  private static final int     OPEN_DELAY_RETRY         = 100;
  private static final long    LOCK_WAIT_TIME           = 300;
  private static final int     LOCK_MAX_RETRIES         = 10;
  private final ReadWriteLock  lock                     = new ReentrantReadWriteLock();
  private ByteBuffer           internalWriteBuffer      = ByteBuffer.allocate(OBinaryProtocol.SIZE_LONG);

  private volatile File        osFile;
  private final String         mode;

  private RandomAccessFile     accessFile;
  private FileChannel          channel;
  private volatile boolean     dirty                    = false;
  private volatile boolean     headerDirty              = false;
  private int                  version;

  private boolean              failCheck                = true;
  private volatile long        size;                                                                                // PART OF
                                                                                // HEADER (4
                                                                                // bytes)
  private FileLock             fileLock;
  private boolean              wasSoftlyClosed          = true;

  public OFileClassic(String osFile, String mode) {
    this.mode = mode;
    this.osFile = new File(osFile);
  }

  @Override
  public long allocateSpace(long size) {
    acquireWriteLock();
    try {
      final long currentSize = this.size;
      this.size += size;

      assert this.size >= size;

      return currentSize;
    } finally {
      releaseWriteLock();
    }
  }

  @Override
  public void shrink(long iSize) throws IOException {
    int attempts = 0;

    while (true) {
      try {
        acquireWriteLock();
        try {
          channel.truncate(HEADER_SIZE + iSize);
          size = iSize;

          assert size >= 0;
          break;

        } finally {
          releaseWriteLock();
          attempts++;
        }
      } catch (IOException e) {
        OLogManager.instance().error(this, "Error during file shrink for file " + getName() + " " + attempts + "-th attempt.", e);
        reopenFile(attempts, e);
      }
    }
  }

  @Override
  public long getFileSize() {
    return size;
  }

  public void read(long iOffset, byte[] iData, int iLength, int iArrayOffset) throws IOException {
    int attempts = 0;

    while (true) {
      try {
        acquireReadLock();
        try {
          iOffset = checkRegions(iOffset, iLength);

          ByteBuffer buffer = ByteBuffer.wrap(iData, iArrayOffset, iLength);
          channel.read(buffer, iOffset);
          break;

        } finally {
          releaseReadLock();
          attempts++;
        }
      } catch (IOException e) {
        OLogManager.instance().error(this, "Error during data read for file " + getName() + " " + attempts + "-th attempt.", e);
        reopenFile(attempts, e);
      }
    }
  }

  public void write(long iOffset, byte[] iData, int iSize, int iArrayOffset) throws IOException {
    int attempts = 0;

    while (true) {
      try {
        acquireWriteLock();
        try {
          writeInternal(iOffset, iData, iSize, iArrayOffset);
          break;
        } finally {
          releaseWriteLock();
          attempts++;
        }
      } catch (IOException e) {
        OLogManager.instance().error(this, "Error during data write for file  " + getName() + " " + attempts + "-th attempt.", e);
        reopenFile(attempts, e);
      }
    }
  }

  private void writeInternal(long iOffset, byte[] iData, int iSize, int iArrayOffset) throws IOException {
    if (iData != null) {
      iOffset += HEADER_SIZE;
      ByteBuffer byteBuffer = ByteBuffer.wrap(iData, iArrayOffset, iSize);
      channel.write(byteBuffer, iOffset);
      setDirty();
    }
  }

  @Override
  public void read(long iOffset, byte[] iDestBuffer, int iLenght) throws IOException {
    read(iOffset, iDestBuffer, iLenght, 0);
  }

  @Override
  public int readInt(long iOffset) throws IOException {
    int attempts = 0;
    while (true) {
      try {
        acquireReadLock();
        try {
          iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_INT);
          return readData(iOffset, OBinaryProtocol.SIZE_INT).getInt();
        } finally {
          releaseReadLock();
          attempts++;
        }
      } catch (IOException e) {
        OLogManager.instance().error(this, "Error during read of int data for file " + getName() + " " + attempts + "-th attempt.",
            e);
        reopenFile(attempts, e);
      }
    }
  }

  @Override
  public long readLong(long iOffset) throws IOException {
    int attempts = 0;

    while (true) {
      try {
        acquireReadLock();
        try {
          iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_LONG);
          return readData(iOffset, OBinaryProtocol.SIZE_LONG).getLong();
        } finally {
          releaseReadLock();
          attempts++;
        }
      } catch (IOException e) {
        OLogManager.instance().error(this,
            "Error during read of long data for file " + getName() + " " + attempts + "-th attempt.", e);
        reopenFile(attempts, e);
      }
    }
  }

  @Override
  public short readShort(long iOffset) throws IOException {
    int attempts = 0;

    while (true) {
      try {
        acquireReadLock();
        try {
          iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_SHORT);
          return readData(iOffset, OBinaryProtocol.SIZE_SHORT).getShort();
        } finally {
          releaseReadLock();
          attempts++;
        }
      } catch (IOException e) {
        OLogManager.instance().error(this,
            "Error during read of short data for file " + getName() + " " + attempts + "-th attempt.", e);
        reopenFile(attempts, e);
      }
    }
  }

  @Override
  public byte readByte(long iOffset) throws IOException {
    int attempts = 0;

    while (true) {
      try {
        acquireReadLock();
        try {
          iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_BYTE);
          return readData(iOffset, OBinaryProtocol.SIZE_BYTE).get();
        } finally {
          releaseReadLock();
          attempts++;
        }
      } catch (IOException e) {
        OLogManager.instance().error(this,
            "Error during read of byte data for file " + getName() + " " + attempts + "-th attempt.", e);
        reopenFile(attempts, e);
      }
    }
  }

  @Override
  public void writeInt(long iOffset, final int iValue) throws IOException {
    int attempts = 0;

    while (true) {
      try {
        acquireWriteLock();
        try {
          iOffset += HEADER_SIZE;

          final ByteBuffer buffer = getWriteBuffer(OBinaryProtocol.SIZE_INT);
          buffer.putInt(iValue);
          writeBuffer(buffer, iOffset);
          setDirty();

          break;
        } finally {
          releaseWriteLock();
          attempts++;
        }
      } catch (IOException e) {
        OLogManager.instance().error(this,
            "Error during write of int data for file " + getName() + " " + attempts + "-th attempt.", e);
        reopenFile(attempts, e);
      }
    }
  }

  @Override
  public void writeLong(long iOffset, final long iValue) throws IOException {
    int attempts = 0;

    while (true) {
      try {
        acquireWriteLock();
        try {
          iOffset += HEADER_SIZE;
          final ByteBuffer buffer = getWriteBuffer(OBinaryProtocol.SIZE_LONG);
          buffer.putLong(iValue);
          writeBuffer(buffer, iOffset);
          setDirty();
          break;
        } finally {
          releaseWriteLock();
          attempts++;
        }
      } catch (IOException e) {
        OLogManager.instance().error(this,
            "Error during write of long data for file " + getName() + " " + attempts + "-th attempt.", e);
        reopenFile(attempts, e);
      }
    }
  }

  @Override
  public void writeShort(long iOffset, final short iValue) throws IOException {
    int attempts = 0;

    while (true) {
      try {
        acquireWriteLock();
        try {
          iOffset += HEADER_SIZE;
          final ByteBuffer buffer = getWriteBuffer(OBinaryProtocol.SIZE_SHORT);
          buffer.putShort(iValue);
          writeBuffer(buffer, iOffset);
          setDirty();
          break;
        } finally {
          releaseWriteLock();
          attempts++;
        }
      } catch (IOException e) {
        OLogManager.instance().error(this,
            "Error during write of short data for file " + getName() + " " + attempts + "-th attempt.", e);
        reopenFile(attempts, e);
      }
    }
  }

  @Override
  public void writeByte(long iOffset, final byte iValue) throws IOException {
    int attempts = 0;
    while (true) {
      try {
        acquireWriteLock();
        try {
          iOffset += HEADER_SIZE;
          final ByteBuffer buffer = getWriteBuffer(OBinaryProtocol.SIZE_BYTE);
          buffer.put(iValue);
          writeBuffer(buffer, iOffset);
          setDirty();
          break;
        } finally {
          releaseWriteLock();
          attempts++;
        }
      } catch (IOException e) {
        OLogManager.instance().error(this,
            "Error during write of byte data for file " + getName() + " " + attempts + "-th attempt.", e);
        reopenFile(attempts, e);
      }
    }

  }

  @Override
  public long write(long iOffset, final byte[] iSourceBuffer) throws IOException {
    int attempts = 0;
    while (true) {
      try {
        long allocationDiff = 0;

        acquireWriteLock();
        try {
          if (iSourceBuffer != null) {
            final long start = accessFile.length();
            writeInternal(iOffset, iSourceBuffer, iSourceBuffer.length, 0);
            final long end = accessFile.length();
            allocationDiff = end - start;
          }
        } finally {
          releaseWriteLock();
          attempts++;
        }

        return allocationDiff;
      } catch (IOException e) {
        OLogManager.instance().error(this, "Error during write of data for file " + getName() + " " + attempts + "-th attempt.", e);
        reopenFile(attempts, e);
      }
    }
  }

  /**
   * Synchronizes the buffered changes to disk.
   *
   * @throws IOException
   *
   */
  @Override
  public boolean synch() throws IOException {
    acquireWriteLock();
    try {
      flushHeader();
      return true;
    } finally {
      releaseWriteLock();
    }
  }

  protected void flushHeader() throws IOException {
    acquireWriteLock();
    try {
      if (headerDirty || dirty) {
        headerDirty = dirty = false;
        try {
          channel.force(false);
        } catch (IOException e) {
          OLogManager.instance().warn(this, "Error during flush of file %s. Data may be lost in case of power failure.", getName(),
              e);
        }

      }
    } finally {
      releaseWriteLock();
    }
  }

  @Override
  public void create() throws IOException {
    acquireWriteLock();
    try {
      openChannel();
      init(HEADER_SIZE);

      setVersion(OFileClassic.CURRENT_VERSION);
      version = OFileClassic.CURRENT_VERSION;
      setSoftlyClosed(!failCheck);
    } finally {
      releaseWriteLock();
    }
  }

  @Override
  public boolean isSoftlyClosed() throws IOException {
    acquireReadLock();
    try {
      final ByteBuffer buffer;
      if (version == 0)
        buffer = readData(SOFTLY_CLOSED_OFFSET_V_0, 1);
      else
        buffer = readData(SOFTLY_CLOSED_OFFSET, 1);

      return buffer.get(0) > 0;
    } finally {
      releaseReadLock();
    }
  }

  public void setSoftlyClosed(final boolean value) throws IOException {
    acquireWriteLock();
    try {
      if (channel == null || mode.indexOf('w') < 0)
        return;

      final ByteBuffer buffer = getBuffer(1);
      buffer.put(0, (byte) (value ? 1 : 0));

      writeBuffer(buffer, SOFTLY_CLOSED_OFFSET);

      try {
        channel.force(true);
      } catch (IOException e) {
        OLogManager.instance()
            .warn(this, "Error during flush of file %s. Data may be lost in case of power failure.", getName(), e);
      }
    } finally {
      releaseWriteLock();
    }
  }

  /**
   * ALWAYS ADD THE HEADER SIZE BECAUSE ON THIS TYPE IS ALWAYS NEEDED
   */
  private long checkRegions(final long iOffset, final long iLength) {
    acquireReadLock();
    try {
      if (iOffset < 0 || iOffset + iLength > size)
        throw new OIOException("You cannot access outside the file size (" + size + " bytes). You have requested portion "
            + iOffset + "-" + (iOffset + iLength) + " bytes. File: " + toString());

      return iOffset + HEADER_SIZE;
    } finally {
      releaseReadLock();
    }

  }

  private ByteBuffer readData(final long iOffset, final int iSize) throws IOException {
    ByteBuffer buffer = getBuffer(iSize);
    channel.read(buffer, iOffset);
    buffer.rewind();
    return buffer;
  }

  private void writeBuffer(final ByteBuffer iBuffer, final long iOffset) throws IOException {
    iBuffer.rewind();
    channel.write(iBuffer, iOffset);
  }

  private ByteBuffer getBuffer(final int iLenght) {
    return ByteBuffer.allocate(iLenght);
  }

  private ByteBuffer getWriteBuffer(final int iLenght) {
    setDirty();
    if (iLenght <= OBinaryProtocol.SIZE_LONG)
      // RECYCLE WRITE BYTE BUFFER SINCE WRITES ARE SYNCHRONIZED
      return (ByteBuffer) internalWriteBuffer.rewind();

    return getBuffer(iLenght);
  }

  private void setVersion(int version) throws IOException {
    acquireWriteLock();
    try {
      final ByteBuffer buffer = getWriteBuffer(OBinaryProtocol.SIZE_BYTE);
      buffer.put((byte) version);
      writeBuffer(buffer, VERSION_OFFSET);
      setHeaderDirty();
    } finally {
      releaseWriteLock();
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.orient.core.storage.fs.OFileAAA#open()
   */
  public boolean open() throws IOException {
    acquireWriteLock();
    try {
      if (!osFile.exists())
        throw new FileNotFoundException("File: " + osFile.getAbsolutePath());

      openChannel();
      init(-1);

      OLogManager.instance().debug(this, "Checking file integrity of " + osFile.getName() + "...");

      if (failCheck) {
        wasSoftlyClosed = isSoftlyClosed();

        if (wasSoftlyClosed)
          setSoftlyClosed(false);
      }

      if (version < CURRENT_VERSION) {
        setVersion(CURRENT_VERSION);
        version = CURRENT_VERSION;
        setSoftlyClosed(!failCheck);
      }

      if (failCheck)
        return wasSoftlyClosed;

      return true;
    } finally {
      releaseWriteLock();
    }
  }

  public boolean wasSoftlyClosed() {
    acquireReadLock();
    try {
      return wasSoftlyClosed;
    } finally {
      releaseReadLock();
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.orient.core.storage.fs.OFileAAA#close()
   */
  public void close() throws IOException {
    acquireWriteLock();
    try {
      if (trackFileClose) {
        final Exception exception = new Exception();
        final StringWriter writer = new StringWriter();
        writer.append("File ").append(getName()).append(" was closed at : \r\n");

        final PrintWriter printWriter = new PrintWriter(writer);
        exception.printStackTrace(printWriter);
        printWriter.flush();

        OLogManager.instance().warn(this, writer.toString());
      }

      if (accessFile != null && (accessFile.length() - HEADER_SIZE) < getFileSize())
        accessFile.setLength(getFileSize() + HEADER_SIZE);

      setSoftlyClosed(true);

      if (OGlobalConfiguration.FILE_LOCK.getValueAsBoolean())
        unlock();

      if (channel != null && channel.isOpen()) {
        channel.close();
        channel = null;
      }

      if (accessFile != null) {
        accessFile.close();
        accessFile = null;
      }
    } catch (Exception e) {
      OLogManager.instance().error(this, "Error on closing file " + osFile.getAbsolutePath(), e, OIOException.class);
    } finally {
      releaseWriteLock();
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.orient.core.storage.fs.OFileAAA#delete()
   */
  public void delete() throws IOException {
    acquireWriteLock();
    try {
      close();
      if (osFile != null) {
        boolean deleted = OFileUtils.delete(osFile);
        int retryCount = 0;

        while (!deleted) {
          deleted = OFileUtils.delete(osFile);
          retryCount++;

          if (retryCount > 10)
            throw new IOException("Can not delete file. Retry limit exceeded.");
        }
      }
    } finally {
      releaseWriteLock();
    }
  }

  /*
   * Locks a portion of file.
   */
  public FileLock lock(final long iRangeFrom, final long iRangeSize, final boolean iShared) throws IOException {
    acquireWriteLock();
    try {
      return channel.lock(iRangeFrom, iRangeSize, iShared);
    } finally {
      releaseWriteLock();
    }
  }

  /*
   * Unlocks a portion of file.
   */
  public OFile unlock(final FileLock iLock) throws IOException {
    acquireWriteLock();
    try {
      if (iLock != null) {
        try {
          iLock.release();
        } catch (ClosedChannelException e) {
        }
      }
      return this;
    } finally {
      releaseWriteLock();
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.orient.core.storage.fs.OFileAAA#lock()
   */
  public void lock() throws IOException {
    if (channel == null)
      return;

    acquireWriteLock();
    try {
      for (int i = 0; i < LOCK_MAX_RETRIES; ++i) {
        try {
          fileLock = channel.tryLock();
          if (fileLock != null)
            break;
        } catch (OverlappingFileLockException e) {
          OLogManager.instance().debug(this,
              "Cannot open file '" + osFile.getAbsolutePath() + "' because it is locked. Waiting %d ms and retrying %d/%d...",
              LOCK_WAIT_TIME, i, LOCK_MAX_RETRIES);
        }

        if (fileLock == null)
          throw new OLockException(
              "File '"
                  + osFile.getPath()
                  + "' is locked by another process, maybe the database is in use by another process. Use the remote mode with a OrientDB server to allow multiple access to the same database.");
      }
    } finally {
      releaseWriteLock();
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.orient.core.storage.fs.OFileAAA#unlock()
   */
  public void unlock() throws IOException {
    acquireWriteLock();
    try {
      if (fileLock != null) {
        try {
          fileLock.release();
        } catch (ClosedChannelException e) {
        }
        fileLock = null;
      }
    } finally {
      releaseWriteLock();
    }
  }

  private void openChannel() throws IOException {
    acquireWriteLock();
    try {
      OLogManager.instance().debug(this, "[OFile.openChannel] opening channel for file '%s' of size: %d", osFile, osFile.length());

      for (int i = 0; i < OPEN_RETRY_MAX; ++i)
        try {
          accessFile = new RandomAccessFile(osFile, mode);
          break;
        } catch (FileNotFoundException e) {
          if (i == OPEN_RETRY_MAX - 1)
            throw e;

          // TRY TO RE-CREATE THE DIRECTORY (THIS HAPPENS ON WINDOWS AFTER A DELETE IS PENDING, USUALLY WHEN REOPEN THE DB VERY
          // FREQUENTLY)
          osFile.getParentFile().mkdirs();
          try {
            Thread.sleep(OPEN_DELAY_RETRY);
          } catch (InterruptedException e1) {
            Thread.currentThread().interrupt();
          }
        }

      if (accessFile == null)
        throw new FileNotFoundException(osFile.getAbsolutePath());

      channel = accessFile.getChannel();

      if (OGlobalConfiguration.FILE_LOCK.getValueAsBoolean())
        lock();
    } finally {
      releaseWriteLock();
    }
  }

  private void init(long newSize) throws IOException {
    if (newSize > -1 && accessFile.length() != newSize)
      accessFile.setLength(newSize);

    size = accessFile.length() - HEADER_SIZE;
    assert size >= 0;

    accessFile.seek(VERSION_OFFSET);
    version = accessFile.read();
  }

  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.orient.core.storage.fs.OFileAAA#isOpen()
   */
  public boolean isOpen() {
    acquireReadLock();
    try {
      return accessFile != null;
    } finally {
      releaseReadLock();
    }

  }

  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.orient.core.storage.fs.OFileAAA#exists()
   */
  public boolean exists() {
    acquireReadLock();
    try {
      return osFile != null && osFile.exists();
    } finally {
      releaseReadLock();
    }
  }

  private void setDirty() {
    acquireWriteLock();
    try {
      if (!dirty)
        dirty = true;
    } finally {
      releaseWriteLock();
    }
  }

  private void setHeaderDirty() {
    acquireWriteLock();
    try {
      if (!headerDirty)
        headerDirty = true;
    } finally {
      releaseWriteLock();
    }
  }

  public String getName() {
    acquireReadLock();
    try {
      if (osFile == null)
        return null;

      return osFile.getName();
    } finally {
      releaseReadLock();
    }
  }

  public String getPath() {
    acquireReadLock();
    try {
      return osFile.getPath();
    } finally {
      releaseReadLock();
    }
  }

  public String getAbsolutePath() {
    acquireReadLock();
    try {
      return osFile.getAbsolutePath();
    } finally {
      releaseReadLock();
    }
  }

  public boolean renameTo(final File newFile) throws IOException {
    acquireWriteLock();
    try {
      close();

      final boolean renamed = OFileUtils.renameFile(osFile, newFile);
      if (renamed)
        osFile = new File(newFile.getAbsolutePath());

      open();

      return renamed;
    } finally {
      releaseWriteLock();
    }
  }

  private void acquireWriteLock() {
    lock.writeLock().lock();
  }

  private void releaseWriteLock() {
    lock.writeLock().unlock();
  }

  private void acquireReadLock() {
    lock.readLock().lock();
  }

  private void releaseReadLock() {
    lock.readLock().unlock();
  }

  /*
   * (non-Javadoc)
   *
   * @see com.orientechnologies.orient.core.storage.fs.OFileAAA#toString()
   */
  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder(128);
    builder.append("File: ");
    builder.append(osFile.getName());
    if (accessFile != null) {
      builder.append(" os-size=");
      try {
        builder.append(accessFile.length());
      } catch (IOException e) {
        builder.append("?");
      }
    }
    builder.append(", stored=");
    builder.append(getFileSize());
    builder.append("");
    return builder.toString();
  }

  private void reopenFile(int attempt, IOException e) throws IOException {
    if (attempt > 1)
      throw e;

    acquireWriteLock();
    try {
      try {
        unlock();
      } catch (IOException ioe) {
        OLogManager.instance().error(this, "Error during unlock of file " + osFile.getName() + ", during IO exception handling.",
            ioe);
      }

      try {
        channel.close();
      } catch (IOException ioe) {
        OLogManager.instance().error(this,
            "Error during channel close for file " + osFile.getAbsolutePath() + ", during IO exception handling.", ioe);
      }

      try {
        accessFile.close();
      } catch (IOException ioe) {
        OLogManager.instance().error(this,
            "Error during close of file " + osFile.getAbsolutePath() + ", during IO exception handling.", ioe);
      }

      channel = null;
      accessFile = null;

      openChannel();
    } finally {
      releaseWriteLock();
    }
  }
}


text:
"""Base class for IKEA TRADFRI."""
import logging

from pytradfri.error import PytradfriError

from homeassistant.core import callback
from homeassistant.helpers.entity import Entity

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)

class TradfriBaseClass(Entity):
    """Base class for IKEA TRADFRI.

    All devices and groups should ultimately inherit from this class.
    """

    def __init__(self, device, api, gateway_id):
        """Initialize a device."""
        self._api = api
        self._device = None
        self._device_control = None
        self._device_data = None
        self._gateway_id = gateway_id
        self._name = None
        self._unique_id = None

        self._refresh(device)

    @callback
    def _async_start_observe(self, exc=None):
        """Start observation of device."""
        if exc:
            self.async_schedule_update_ha_state()
            _LOGGER.warning("Observation failed for %s", self._name, exc_info=exc)

        try:
            cmd = self._device.observe(
                callback=self._observe_update,
                err_callback=self._async_start_observe,
                duration=0,
            )
            self.hass.async_create_task(self._api(cmd))
        except PytradfriError as err:
            _LOGGER.warning("Observation failed, trying again", exc_info=err)
            self._async_start_observe()

    async def async_added_to_hass(self):
        """Start thread when added to hass."""
        self._async_start_observe()

    @property
    def name(self):
        """Return the display name of this device."""
        return self._name

    @property
    def should_poll(self):
        """No polling needed for tradfri device."""
        return False

    @property
    def unique_id(self):
        """Return unique ID for device."""
        return self._unique_id

    @callback
    def _observe_update(self, device):
        """Receive new state data for this device."""
        self._refresh(device)
        self.async_schedule_update_ha_state()

    def _refresh(self, device):
        """Refresh the device data."""
        self._device = device
        self._name = device.name

class TradfriBaseDevice(TradfriBaseClass):
    """Base class for a TRADFRI device.

    All devices should inherit from this class.
    """

    def __init__(self, device, api, gateway_id):
        """Initialize a device."""
        super().__init__(device, api, gateway_id)
        self._available = True

    @property
    def available(self):
        """Return True if entity is available."""
        return self._available

    @property
    def device_info(self):
        """Return the device info."""
        info = self._device.device_info

        return {
            "identifiers": {(DOMAIN, self._device.id)},
            "manufacturer": info.manufacturer,
            "model": info.model_number,
            "name": self._name,
            "sw_version": info.firmware_version,
            "via_device": (DOMAIN, self._gateway_id),
        }

    def _refresh(self, device):
        """Refresh the device data."""
        super()._refresh(device)
        self._available = device.reachable


text:
#pragma once
//------------------------------------------------------------------------------
/**
    @class Jobs::TPWorkerThread

    The worker thread class of the thread-pool job system.

    (C) 2009 Radon Labs GmbH
*/
#include "threading/thread.h"
#include "threading/safequeue.h"
#include "jobs/tp/tpjobcommand.h"
#include "debug/debugtimer.h"

//------------------------------------------------------------------------------
namespace Jobs
{
class TPWorkerThread : public Threading::Thread
{
    __DeclareClass(TPWorkerThread);
public:
    /// constructor
    TPWorkerThread();
    /// destructor
    virtual ~TPWorkerThread();

    /// called if thread needs a wakeup call before stopping
    virtual void EmitWakeupSignal();
    /// this method runs in the thread context
    virtual void DoWork();
    /// request threading code to stop, returns when thread has actually finished
    void Stop();

    /// push a job command onto the job queue
    void PushJobCommand(const TPJobCommand& cmd);

private:
    /// process a single job slice
    void ProcessJobSlices(TPJobSlice* firstSlice, ushort numSlices, ushort stride);

    static const SizeT MaxScratchSize = (64 * 1024);    // 64 kB max scratch size

    Threading::SafeQueue<TPJobCommand> jobQueue;
    ubyte* scratchBuffer;

#if NEBULA3_ENABLE_PROFILING
    _declare_timer(debugTimer);
#endif
};

} // namespace Jobs
//------------------------------------------------------------------------------


text:
export const appendOnLoadScript = jest.fn(({ callback, onLoadDone, overrideDomContentLoaded }) => {
  callback();
  if (typeof onLoadDone === "string") {
    eval(onLoadDone);
  } else if (typeof onLoadDone === "function") {
    onLoadDone();
  }
  if (overrideDomContentLoaded) {
    global.domContentLoaded();
  }
});


text:
import Board from '../../elements/boards/board';
import { RoundGenerator } from '../../elements/boards/generators/maps';
import Dice from '../../elements/dice/dice';
import { PlacementReferee, GameReferee } from '../referees/referee';
import { shuffle } from '../../util/arrays';

const logger = global.logger;

export default class Game {
	/**
	 * Constructor
	 * @param  {Object} id player's id
	 */
	constructor(id) {
		this._id = id;
		this._players = new Set();
		this._started = false;
	}

	/**
	 * Gets the id of the player
	 * @return {Integer} player's id
	 */
	get id() {
		return this._id;
	}

	/**
	 * Gets the list of players
	 * @return {Set} the game's player
	 */
	get players() {
		return this._players;
	}

	/**
	 * Adds a new player to the game.
	 * @param {Player} player the player to add
	 * @return {boolean} true if the player is added, false if it was already
	 *   present.
	 */
	add(player) {
		if (!this._players.has(player)) {
			this._players.add(player);
			player.game = this;
			return true;
		} else {
			return false;
		}
	}

	remove(player) {
		if (this._players.has(player)) {
			this._players.delete(player);
			player.game = undefined;
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Picks a city for a player.
	 * @param player the player wanting the location
	 * @param location the location of the desired city
	 * @return {City} the picked colony
	 * @throws if the rules prevent this operation
	 */
	pickColony(player, location) {
		this._referee.checkTurn(player);
		this._referee.pickColony(location);

		var pickedColony = this._board.getCity(location);
		pickedColony.owner = player;

		return pickedColony;
	}

	/**
	 * Picks a path for a player.
	 * @param player the player wanting the path
	 * @param path the path desired
	 * @return {Path} the picked path
	 * @throws if the rules prevent this operation
	 */
	pickPath(player, path) {
		this._referee.checkTurn(player);
		this._referee.pickPath(path);

		var pickedPath = this._board.getPath(path);
		pickedPath.owner = player;

		return pickedPath;
	}

	rollDice(player) {
		this._referee.checkTurn(player);
		if (this._referee.canRollDice(player)) {
			var values = [ this._dice.roll(), this._dice.roll() ];
			this._referee.rollDice(values[0] + values[1]);

			return values;
		} else {
			throw new Error('Dice already rolled');
		}
	}

	moveThieves(player) {
		this._referee.checkTurn(player);

		// TODO complete the implementation
		this._referee.moveThieves();
	}

	/**
	 * Makes the player end its turn.
	 * @param player the player ending its turn
	 * @returns the next player whose turn has started
	 */
	endTurn(player) {
		this._referee.checkTurn(player);
		this._referee.endTurn();
		if (this._prepared === false && this._referee.isPlacementComplete()) {
			this._prepared = true;
			this.initiateGame();
			this.emit('game:play');
		}

		return this._referee.currentPlayer;
	}

	/**
	 * Emits the message on the channel to all players of the game.
	 * @param  {String} channel name of the event
	 * @param  {Object=} message message to send
	 */
	emit(channel, message) {
		this._players.forEach(player => player.emit(channel, message));
	}

	start() {
		if (this._started) { throw new Error(`Game ${this._id} already started`); }
		if (this._players.size < 2) { throw new Error(`Not enough players in the game (${this._players.size})`); }

		this._started = true;
		logger.info(`Game ${this.id} starting ...`);

		var boardDescription = this.generatePlay();
		var playerOrder = this.prepareGame();

		this.emit('game:start', {
			_success: true,
			board: boardDescription,
			players: playerOrder
		});
		this.emit('game:prepare');
		this.emit('play:turn:new', { player: this._referee.currentPlayer.id });
	}

	/**
	 * Generates the play by creating all elements: dice,
	 * 	board, ...
	 * @return {Object} a description of the board
	 */
	generatePlay() {
		this._board = new Board();
		this._board.generate(new RoundGenerator(3));

		var description = { tiles: [], cities: [], paths: [] };
		for (let tile of this._board.tiles) {
			description.tiles.push({
				x: tile.location.x,
				y: tile.location.y,
				resource: tile.resource,
				diceValue: tile.diceValue
			});
		}
		for (let city of this._board.cities) {
			description.cities.push({
				x: city.location.x,
				y: city.location.y
			});
		}
		for (let path of this._board.paths) {
			description.paths.push({
				from: { x: path.from.x, y: path.from.y },
				to: { x: path.to.x, y: path.to.y }
			});
		}

		return description;
	}

	/**
	 * Prepares the game.
	 * This will create a referee monitoring the placement of the players, the
	 * distribution of the spots and roads.
	 * @return {Array} the ids of the players in order of play
	 */
	prepareGame() {
		this._referee = new PlacementReferee(this._board, shuffle(this._players));
		this._prepared = false;

		logger.info(`Preparing game ${this.id} ...`);
		return this._referee.players.map(player => player.id);
	}

	/**
	 * Initiates the game.
	 * It will create a referee to monitor the game and order the
	 * 	players.
	 */
	initiateGame() {
		this._dice = new Dice(6);
		var previousReferee = this._referee;
		this._referee = new GameReferee(previousReferee.board, previousReferee.players);

		// TODO send to each player their resources

		logger.info(`Game ${this.id} prepared and running !`);
	}
}


text:
namespace Microsoft.Xml.Schema
{
    using System;
    using Microsoft.Xml;

    using System.Collections;
    using System.Text;
    using System.Diagnostics;

    internal class BaseProcessor
    {
        private XmlNameTable _nameTable;
        private SchemaNames _schemaNames;
        private ValidationEventHandler _eventHandler;
        private XmlSchemaCompilationSettings _compilationSettings;
        private int _errorCount = 0;
        private string _nsXml;

        public BaseProcessor(XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler)
            : this(nameTable, schemaNames, eventHandler, new XmlSchemaCompilationSettings()) { } //Use the default for XmlSchemaCollection

        public BaseProcessor(XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler, XmlSchemaCompilationSettings compilationSettings)
        {
            Debug.Assert(nameTable != null);
            _nameTable = nameTable;
            _schemaNames = schemaNames;
            _eventHandler = eventHandler;
            _compilationSettings = compilationSettings;
            _nsXml = nameTable.Add(XmlReservedNs.NsXml);
        }

        protected XmlNameTable NameTable
        {
            get { return _nameTable; }
        }

        protected SchemaNames SchemaNames
        {
            get
            {
                if (_schemaNames == null)
                {
                    _schemaNames = new SchemaNames(_nameTable);
                }
                return _schemaNames;
            }
        }

        protected ValidationEventHandler EventHandler
        {
            get { return _eventHandler; }
        }

        protected XmlSchemaCompilationSettings CompilationSettings
        {
            get { return _compilationSettings; }
        }

        protected bool HasErrors
        {
            get { return _errorCount != 0; }
        }

        protected void AddToTable(XmlSchemaObjectTable table, XmlQualifiedName qname, XmlSchemaObject item)
        {
            if (qname.Name.Length == 0)
            {
                return;
            }
            XmlSchemaObject existingObject = (XmlSchemaObject)table[qname];

            if (existingObject != null)
            {
                if (existingObject == item)
                {
                    return;
                }
                string code = ResXml.Sch_DupGlobalElement;
                if (item is XmlSchemaAttributeGroup)
                {
                    string ns = _nameTable.Add(qname.Namespace);
                    if (Ref.Equal(ns, _nsXml))
                    { //Check for xml namespace
                        XmlSchema schemaForXmlNS = Preprocessor.GetBuildInSchema();
                        XmlSchemaObject builtInAttributeGroup = schemaForXmlNS.AttributeGroups[qname];
                        if ((object)existingObject == (object)builtInAttributeGroup)
                        {
                            table.Insert(qname, item);
                            return;
                        }
                        else if ((object)item == (object)builtInAttributeGroup)
                        { //trying to overwrite customer's component with built-in, ignore built-in
                            return;
                        }
                    }
                    else if (IsValidAttributeGroupRedefine(existingObject, item, table))
                    { //check for redefines
                        return;
                    }
                    code = ResXml.Sch_DupAttributeGroup;
                }
                else if (item is XmlSchemaAttribute)
                {
                    string ns = _nameTable.Add(qname.Namespace);
                    if (Ref.Equal(ns, _nsXml))
                    {
                        XmlSchema schemaForXmlNS = Preprocessor.GetBuildInSchema();
                        XmlSchemaObject builtInAttribute = schemaForXmlNS.Attributes[qname];
                        if ((object)existingObject == (object)builtInAttribute)
                        { //replace built-in one
                            table.Insert(qname, item);
                            return;
                        }
                        else if ((object)item == (object)builtInAttribute)
                        { //trying to overwrite customer's component with built-in, ignore built-in
                            return;
                        }
                    }
                    code = ResXml.Sch_DupGlobalAttribute;
                }
                else if (item is XmlSchemaSimpleType)
                {
                    if (IsValidTypeRedefine(existingObject, item, table))
                    {
                        return;
                    }
                    code = ResXml.Sch_DupSimpleType;
                }
                else if (item is XmlSchemaComplexType)
                {
                    if (IsValidTypeRedefine(existingObject, item, table))
                    {
                        return;
                    }
                    code = ResXml.Sch_DupComplexType;
                }
                else if (item is XmlSchemaGroup)
                {
                    if (IsValidGroupRedefine(existingObject, item, table))
                    { //check for redefines
                        return;
                    }
                    code = ResXml.Sch_DupGroup;
                }
                else if (item is XmlSchemaNotation)
                {
                    code = ResXml.Sch_DupNotation;
                }
                else if (item is XmlSchemaIdentityConstraint)
                {
                    code = ResXml.Sch_DupIdentityConstraint;
                }
                else
                {
                    Debug.Assert(item is XmlSchemaElement);
                }
                SendValidationEvent(code, qname.ToString(), item);
            }
            else
            {
                table.Add(qname, item);
            }
        }

        private bool IsValidAttributeGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table)
        {
            XmlSchemaAttributeGroup attGroup = item as XmlSchemaAttributeGroup;
            XmlSchemaAttributeGroup existingAttGroup = existingObject as XmlSchemaAttributeGroup;
            if (existingAttGroup == attGroup.Redefined)
            { //attribute group is the redefinition of existingObject
                if (existingAttGroup.AttributeUses.Count == 0)
                { //If the existing one is not already compiled, then replace.
                    table.Insert(attGroup.QualifiedName, attGroup); //Update with redefined entry
                    return true;
                }
            }
            else if (existingAttGroup.Redefined == attGroup)
            { //Redefined type already exists in the set, original type is added after redefined type, ignore the original type
                return true;
            }
            return false;
        }

        private bool IsValidGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table)
        {
            XmlSchemaGroup group = item as XmlSchemaGroup;
            XmlSchemaGroup existingGroup = existingObject as XmlSchemaGroup;
            if (existingGroup == group.Redefined)
            { //group is the redefinition of existingObject
                if (existingGroup.CanonicalParticle == null)
                { //If the existing one is not already compiled, then replace.
                    table.Insert(group.QualifiedName, group); //Update with redefined entry
                    return true;
                }
            }
            else if (existingGroup.Redefined == group)
            { //Redefined type already exists in the set, original type is added after redefined type, ignore the original type
                return true;
            }
            return false;
        }

        private bool IsValidTypeRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table)
        {
            XmlSchemaType schemaType = item as XmlSchemaType;
            XmlSchemaType existingType = existingObject as XmlSchemaType;
            if (existingType == schemaType.Redefined)
            { //schemaType is the redefinition of existingObject
                if (existingType.ElementDecl == null)
                { //If the existing one is not already compiled, then replace.
                    table.Insert(schemaType.QualifiedName, schemaType); //Update with redefined entry
                    return true;
                }
            }
            else if (existingType.Redefined == schemaType)
            { //Redefined type already exists in the set, original type is added after redefined type, ignore the original type
                return true;
            }
            return false;
        }

        protected void SendValidationEvent(string code, XmlSchemaObject source)
        {
            SendValidationEvent(new XmlSchemaException(code, source), XmlSeverityType.Error);
        }

        protected void SendValidationEvent(string code, string msg, XmlSchemaObject source)
        {
            SendValidationEvent(new XmlSchemaException(code, msg, source), XmlSeverityType.Error);
        }

        protected void SendValidationEvent(string code, string msg1, string msg2, XmlSchemaObject source)
        {
            SendValidationEvent(new XmlSchemaException(code, new string[] { msg1, msg2 }, source), XmlSeverityType.Error);
        }

        protected void SendValidationEvent(string code, string[] args, Exception innerException, XmlSchemaObject source)
        {
            SendValidationEvent(new XmlSchemaException(code, args, innerException, source.SourceUri, source.LineNumber, source.LinePosition, source), XmlSeverityType.Error);
        }

        protected void SendValidationEvent(string code, string msg1, string msg2, string sourceUri, int lineNumber, int linePosition)
        {
            SendValidationEvent(new XmlSchemaException(code, new string[] { msg1, msg2 }, sourceUri, lineNumber, linePosition), XmlSeverityType.Error);
        }

        protected void SendValidationEvent(string code, XmlSchemaObject source, XmlSeverityType severity)
        {
            SendValidationEvent(new XmlSchemaException(code, source), severity);
        }

        protected void SendValidationEvent(XmlSchemaException e)
        {
            SendValidationEvent(e, XmlSeverityType.Error);
        }

        protected void SendValidationEvent(string code, string msg, XmlSchemaObject source, XmlSeverityType severity)
        {
            SendValidationEvent(new XmlSchemaException(code, msg, source), severity);
        }

        protected void SendValidationEvent(XmlSchemaException e, XmlSeverityType severity)
        {
            if (severity == XmlSeverityType.Error)
            {
                _errorCount++;
            }
            if (_eventHandler != null)
            {
                _eventHandler(null, new ValidationEventArgs(e, severity));
            }
            else if (severity == XmlSeverityType.Error)
            {
                throw e;
            }
        }

        protected void SendValidationEventNoThrow(XmlSchemaException e, XmlSeverityType severity)
        {
            if (severity == XmlSeverityType.Error)
            {
                _errorCount++;
            }
            if (_eventHandler != null)
            {
                _eventHandler(null, new ValidationEventArgs(e, severity));
            }
        }
    };
} // namespace Microsoft.Xml


text:
{% extends "base.html" %}
{% load core_tags %}

{% block title %}{{ calendar.name }} Calendars {% endblock %}

{% block page_title %}{{ calendar.name}}{% endblock %}

{% block breadcrumbs %}

 Dashboard /

{{ 'Calendars' }}
       /

{{ calendar.name }}

{% endblock %}

{% block extracss %}
	<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/fullcalendar.css">
	<link rel="stylesheet" type="text/css" media="print" href="{{ STATIC_URL }}css/fullcalendar.print.css">
{% endblock %}

{% block extrajs %}

{% endblock %}

{% block content %}

Experiments

{% csrf_token %}

{% endblock %}


text:
from celery import Task

from socials.models import Keyword

class SocialsCrawlNaverTask(Task):

    def run(self, keyword_id):
        keyword = Keyword.objects.get(pk=keyword_id)
        keyword.crawl_all_providers()


text:
What about jQuery?

In build.sbt:

libraryDependencies += "be.doeraene" %%% "scalajs-jquery" % "0.8.0"

skip in packageJSDependencies := false

Include the generated javascript dependencies file:

<script type="text/javascript" src="./target/scala-2.11/demo-jsdeps.js"></script>


text:
/**
*
* IconButton
*
*/

import React from 'react';
import FontAwesome from 'react-fontawesome';
import classNames from 'classnames';
import styles from './styles.css';

function IconButton({ onClick, icon, iconClass, buttonClass }) {
  return (
    <div
      className={classNames(styles.iconButton, buttonClass)}
      onClick={onClick}
    >
      <FontAwesome
        className={iconClass}
        name={icon}
      />
    </div>
  );
}

IconButton.propTypes = {
  onClick: React.PropTypes.func.isRequired,
  icon: React.PropTypes.string.isRequired,
  iconClass: React.PropTypes.string,
  buttonClass: React.PropTypes.string,
};

export default IconButton;


text:
/*eslint-disable no-console */

// This file hooks up on require calls to transpile TypeScript.
const cli = require('ember-cli/lib/cli');
const UI = require('ember-cli/lib/ui');
const path = require('path');

Error.stackTraceLimit = Infinity;

module.exports = function(options) {

  // patch UI to not print Ember-CLI warnings (which don't apply to Angular-CLI)
  UI.prototype.writeWarnLine = function () { }

  const oldStdoutWrite = process.stdout.write;
  process.stdout.write = function (line) {
    line = line.toString();
    if (line.match(/ember-cli-(inject-)?live-reload/)) {
      // don't replace 'ember-cli-live-reload' on ng init diffs
      return oldStdoutWrite.apply(process.stdout, arguments);
    }
    line = line.replace(/ember-cli(?!.com)/g, 'angular-cli')
      .replace(/\bember\b(?!-cli.com)/g, 'ng');
    return oldStdoutWrite.apply(process.stdout, arguments);
  };

  const oldStderrWrite = process.stderr.write;
  process.stderr.write = function (line) {
    line = line.toString()
      .replace(/ember-cli(?!.com)/g, 'angular-cli')
      .replace(/\bember\b(?!-cli.com)/g, 'ng');
    return oldStderrWrite.apply(process.stdout, arguments);
  };

  options.cli = {
    name: 'ng',
    root: path.join(__dirname, '..', '..'),
    npmPackage: 'angular-cli'
  };

  // ensure the environemnt variable for dynamic paths
  process.env.PWD = process.env.PWD || process.cwd();
  process.env.CLI_ROOT = process.env.CLI_ROOT || path.resolve(__dirname, '..', '..');

  return cli(options);
};