/*
One of those why doesn't Java ship with this functions
490638
public static void recursivelyDelete(File f) throws IOException {
        if (!f.exists()) {
            return;
        }
        if (f.isDirectory()) {
            for (File f1 : f.listFiles()) {
                recursivelyDelete(f1);
            }
            if (!f.delete()) {
                throw new IOException("Unable to delete directory " + f);
            }
        }
        else {
            if (!f.delete()) {
                throw new IOException("Unable to delete file " + f);
            }
        }
    }
909618
function(func,args) {
    var type = lib.type.typeOf(func);
    if (type === "string") {
      var fargs = [];
      if (args instanceof Array) {
        fargs.push.apply(fargs,args);
      }
      fargs.push(func);
      func = Function.constructor.apply(Function,fargs);
    } else if (type === "error") {
      func = function() { throw func };
    } else if (type === "object") {
      func = new Method(null,func).toFunction();
    } else if (type === "undefined") {
      func = function() {};
    }
    var index = this.functions.length;
    this.functions.push(func);
    return index;
  }
343551
function Math() {

    var self = this;

    // /**
    //  * init
    //  * @constructor
    //  * */
    // var init = function() {
    //     if ( typeof(Math.instance) != "undefined" ) {
    //         return Math.instance
    //     } else {
    //         Math.instance = self
    //     }
    // }

    /**
     * Operate from a string value
     *
     * e.g.:
     *
     *  var operate = require("gina").utils.math.operate;
     *  var calculation = "10*2";
     *  var result = operate(calculation);
     *      => 20
     *
     *  @param {string} calcultation
     *
     *  @return {number} result
     * */
    this.operate = function(calculation) {
        return new Function('return ' + calculation)()
    }

    /**
     * Checksum
     * e.g: checksum(data, 'sha1')
     *
     * @param {string} str - Data to analyse
     * @param {string} algorithm
     * @param {string} [ encoding ] - e.g.: hex
     *
     * @return {string} checksum
     * */
    var checkSum = function (str, algorithm, encoding) {
        try {
            return crypto
                .createHash(algorithm || 'md5')
                .update(str, 'utf8')
                .digest(encoding || 'hex')
        } catch (err) {
            return err
        }
    }

    /**
     * Checksum
     *
     * @param {string} filename|data
     * @param {string} algorithm
     * @param {string} encoding
     *
     * @callback cb
     *  @param {object|string} err
     *  @param {string} checksum
     * */
    this.checkSum = function(filename, algorithm, encoding, cb) {
        var err = false, sum = null;

        if ( /\./.test(filename) ) {
            fs.readFile(filename, function (err, data) {
                sum = checkSum(data, algorithm, encoding);
                if( sum instanceof Error) {
                    err = sum;
                    sum = undefined
                }

                cb(err, sum)
            })
        } else {
            sum = checkSum(filename, algorithm, encoding);
            if( sum instanceof Error) {
                err = sum;
                sum = undefined
            }

            cb(err, sum)
        }
    }

    /**
     * Check sum from file or form data
     *
     * @param {string} filename|data
     * @param {string} algorithm
     * @param {string} encoding
     *
     * @return {string} checksum
     * */
    this.checkSumSync = function(filename, algorithm, encoding) {
        var sum = null;
        try {
            if ( /(\.[a-z]{3})$/.test(filename) ) { // must be a string
                // from filename
                sum = checkSum( fs.readFileSync(filename), algorithm, encoding )
            } else {
                // from data
                sum = checkSum( filename, algorithm, encoding )
            }

            if (sum instanceof Error)
                throw sum;
            else
                return sum

        } catch (err) {
            //console.error(err.stack||err.message);
            //return undefined
            throw err
        }
    }

    // for big files only: > 1Mb
    //this.checkSumBig= function(filename, cb) {
    //    var hash = crypto.createHash('md5');
    //    var encryption = encryption || 'sha1';
    //
    //    var stream = fs.createReadStream(filename);
    //    stream.on('data', function (data) {
    //        hash.update(data, 'utf8')
    //    })
    //
    //    stream.on('end', function () {
    //        hash.digest('hex');
    //    })
    //}

    //init();
    return this
}
270720
function () {
	          var _this = this;
	          var args = [];
	          for (var _i = 0; _i < arguments.length; _i++) {
	              args[_i - 0] = arguments[_i];
	          }
	          var instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
	          _classStmt.fields.forEach(function (field) { _this[field.name] = undefined; });
	          _executeFunctionStatements(ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor);
	      }
1277281
static function mark_js_function(&$obj,&$marks=array())
    {
        foreach ($obj as $k=>&$v) {
            switch(gettype($v))
            {
            case "object":
            case "array":
                Utility::mark_js_function($v, $marks);
                break;
            case "string":
                $tsv = trim(strtolower($v));
                if (strpos($tsv, "function")===0  
                    && (strrpos($tsv, "}")===strlen($tsv)-1 
                    || strrpos($tsv, "()")===strlen($tsv)-2)
                ) {
                    $marks[] = trim($v);
                    $obj[$k] = "--js(".(count($marks)-1).")";
                }
                break;
            }
        }
        return $marks;
    }
794415
public static <T> DStreamJavaFunctions<T> javaFunctions(JavaDStream<T> dStream) {
        return new DStreamJavaFunctions<>(dStream.dstream());
    }
895805
function(json) {

    var resArray = [];

    var emitArrayOfObjects = function(json, res) {

        var printValue = function(v) {
            var result = null;
            if (typeof(v) === "function") {
                result = "<![CDATA[";
                result = result + v.toString();
                result = result + "]]>";
            } else {
                result = v;
                if (typeof(v) !== "string") {
                    if (v !== null && typeof(v) !== 'undefined') {
                        result = v.toString();
                    } else {
                        result = "";
                    }
                }
                result = result.replace(/[&]/g, "&amp;");
                result = result.replace(/[<]/g, "&lt;");
                result = result.replace(/[>]/g, "&gt;");
            }
            return result;
        };

        var emitSimple = function(elemName, value, res) {
            res.push(`<${elemName}>`);
            res.push(printValue(value));
            res.push(`</${elemName}>`);
        };

        var emitElement = function(elemName, subElemList, res) {
            if (Array.isArray(subElemList)) {
                subElemList.forEach(function(subElem) {
                    emitElement(elemName, subElem, res);
                });
            } else if (typeof subElemList === 'object' && subElemList !== null) {
                var attrs = [];
                var textValue = "";
                if (subElemList._attrs) {
                    for (var attrName in subElemList._attrs) {
                        if (subElemList._attrs.hasOwnProperty(attrName)) {
                            attrs.push(`${attrName}='${subElemList._attrs[attrName]}'`);
                        }
                    }
                }
                if (subElemList._text) {
                    textValue = subElemList._text;
                } else if (subElemList._cdata) {
                    textValue = `<![CDATA[${subElemList._cdata}]]>`;
                } else if (subElemList.text) {
                    textValue = subElemList.text;
                }
                var attrString = attrs.length > 0 ? attrs.join(" ") : "";
                res.push(attrs.length > 0 ? `<${elemName} ${attrString}>` : `<${elemName}>`);
                emitArrayOfObjects(subElemList, res);
                res.push(textValue);
                res.push(`</${elemName}>`);

            } else {
                emitSimple(elemName, subElemList, res);
            }
        };

        for (var key in json) {
            if (json.hasOwnProperty(key) && key !== '_attrs' && key !== '_cdata' && key !== '_text' && key !== 'text') {
                emitElement(key, json[key], res);
            }
        }
    };

    emitArrayOfObjects(json, resArray);
    return resArray.join("");
}
927592
function () {
        return {
            lineSeparator: '\n', // done
            maxLength: 120, // TODO
            wrapIfLong: false, // TODO
            indent: 4, // done
            useTabIndent: false, // done
            spaces: {
                around: {
                    unaryOperators: false, // TODO
                    binaryOperators: true, // done
                    ternaryOperators: true // done
                },
                before: {
                    functionDeclarationParentheses: false, // done function foo() {
                    functionExpressionParentheses: true, // done var foo = function () {
                    parentheses: true, // done if (), for (), while (), ...
                    leftBrace: true, // done function () {, if () {, do {, try { ...
                    keywords: true // done if {} else {}, do {} while (), try {} catch () {} finally
                },
                within: {
                    // function call, function declaration, if, for, while, switch, catch
                    parentheses: false // done
                },
                other: {
                    beforePropertyNameValueSeparator: false, // done {key: value} {key : value} {key:value}
                    afterPropertyNameValueSeparator: true // done
                }
            },
            bracesPlacement: { // 1. same line 2. next line
                functionDeclaration: 1, // TODO
                other: 1 // TODO
            },
            blankLines: {
                keepMaxBlankLines: 1, // done
                atEndOfFile: true // done
            },
            other: {
                keepArraySingleLine: false // TODO default formatted array multi line
            },
            fix: {
                prefixSpaceToLineComment: false, // done
                alterCommonBlockCommentToLineComment: false, // done
                singleVariableDeclarator: false, // done
                fixInvalidTypeof: false, // done
                removeEmptyStatement: false, // done
                autoSemicolon: false, // done
                singleQuotes: false, // done
                eqeqeq: false, // done
                invalidConstructor: false, // done
                addCurly: false, // done
                removeDebugger: false, // done
                noElseReturn: false
            }
        };
    }
172968
static int findFunction(Context cx,
                            MemberBox[] methodsOrCtors, Object[] args)
    {
        if (methodsOrCtors.length == 0) {
            return -1;
        } else if (methodsOrCtors.length == 1) {
            MemberBox member = methodsOrCtors[0];
            Class<?>[] argTypes = member.getParameterTypes();
            int alength = argTypes.length;

            if (member.isVarArgs()) {
                alength--;
                if ( alength > args.length) {
                    return -1;
                }
            } else {
                if (alength != args.length) {
                    return -1;
                }
            }
            for (int j = 0; j != alength; ++j) {
                if (!NativeJavaObject.canConvert(args[j], argTypes[j])) {
                    if (debug) printDebug("Rejecting (args can't convert) ",
                                          member, args);
                    return -1;
                }
            }
            if (debug) printDebug("Found ", member, args);
            return 0;
        }

        int firstBestFit = -1;
        int[] extraBestFits = null;
        int extraBestFitsCount = 0;

      search:
        for (int i = 0; i < methodsOrCtors.length; i++) {
            MemberBox member = methodsOrCtors[i];
            Class<?>[] argTypes = member.getParameterTypes();
            int alength = argTypes.length;
            if (member.isVarArgs()) {
                alength--;
                if ( alength > args.length) {
                    continue search;
                }
            } else {
                if (alength != args.length) {
                    continue search;
                }
            }
            for (int j = 0; j < alength; j++) {
                if (!NativeJavaObject.canConvert(args[j], argTypes[j])) {
                    if (debug) printDebug("Rejecting (args can't convert) ",
                                          member, args);
                    continue search;
                }
            }
            if (firstBestFit < 0) {
                if (debug) printDebug("Found first applicable ", member, args);
                firstBestFit = i;
            } else {
                // Compare with all currently fit methods.
                // The loop starts from -1 denoting firstBestFit and proceed
                // until extraBestFitsCount to avoid extraBestFits allocation
                // in the most common case of no ambiguity
                int betterCount = 0; // number of times member was prefered over
                                     // best fits
                int worseCount = 0;  // number of times best fits were prefered
                                     // over member
                for (int j = -1; j != extraBestFitsCount; ++j) {
                    int bestFitIndex;
                    if (j == -1) {
                        bestFitIndex = firstBestFit;
                    } else {
                        bestFitIndex = extraBestFits[j];
                    }
                    MemberBox bestFit = methodsOrCtors[bestFitIndex];
                    if (cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS) &&
                        bestFit.isPublic() != member.isPublic())
                    {
                        // When FEATURE_ENHANCED_JAVA_ACCESS gives us access
                        // to non-public members, continue to prefer public
                        // methods in overloading
                        if (bestFit.isPublic())
                            ++betterCount;
                        else
                            ++worseCount;
                    } else {
                        int preference = preferSignature(args, argTypes,
                                                         member.isVarArgs(),
                                                         bestFit.getParameterTypes(),
                                                         bestFit.isVarArgs() );
                        if (preference == PREFERENCE_AMBIGUOUS) {
                            break;
                        } else if (preference == PREFERENCE_FIRST_ARG) {
                            ++betterCount;
                        } else if (preference == PREFERENCE_SECOND_ARG) {
                            ++worseCount;
                        } else {
                            if (preference != PREFERENCE_EQUAL) Kit.codeBug();
                            // This should not happen in theory
                            // but on some JVMs, Class.getMethods will return all
                            // static methods of the class hierarchy, even if
                            // a derived class's parameters match exactly.
                            // We want to call the derived class's method.
                            if (bestFit.isStatic() &&
                                bestFit.getDeclaringClass().isAssignableFrom(
                                       member.getDeclaringClass()))
                            {
                                // On some JVMs, Class.getMethods will return all
                                // static methods of the class hierarchy, even if
                                // a derived class's parameters match exactly.
                                // We want to call the derived class's method.
                                if (debug) printDebug(
                                    "Substituting (overridden static)",
                                    member, args);
                                if (j == -1) {
                                    firstBestFit = i;
                                } else {
                                    extraBestFits[j] = i;
                                }
                            } else {
                                if (debug) printDebug(
                                    "Ignoring same signature member ",
                                    member, args);
                            }
                            continue search;
                        }
                    }
                }
                if (betterCount == 1 + extraBestFitsCount) {
                    // member was prefered over all best fits
                    if (debug) printDebug(
                        "New first applicable ", member, args);
                    firstBestFit = i;
                    extraBestFitsCount = 0;
                } else if (worseCount == 1 + extraBestFitsCount) {
                    // all best fits were prefered over member, ignore it
                    if (debug) printDebug(
                        "Rejecting (all current bests better) ", member, args);
                } else {
                    // some ambiguity was present, add member to best fit set
                    if (debug) printDebug(
                        "Added to best fit set ", member, args);
                    if (extraBestFits == null) {
                        // Allocate maximum possible array
                        extraBestFits = new int[methodsOrCtors.length - 1];
                    }
                    extraBestFits[extraBestFitsCount] = i;
                    ++extraBestFitsCount;
                }
            }
        }

        if (firstBestFit < 0) {
            // Nothing was found
            return -1;
        } else if (extraBestFitsCount == 0) {
            // single best fit
            return firstBestFit;
        }

        // report remaining ambiguity
        StringBuilder buf = new StringBuilder();
        for (int j = -1; j != extraBestFitsCount; ++j) {
            int bestFitIndex;
            if (j == -1) {
                bestFitIndex = firstBestFit;
            } else {
                bestFitIndex = extraBestFits[j];
            }
            buf.append("\n    ");
            buf.append(methodsOrCtors[bestFitIndex].toJavaDeclaration());
        }

        MemberBox firstFitMember = methodsOrCtors[firstBestFit];
        String memberName = firstFitMember.getName();
        String memberClass = firstFitMember.getDeclaringClass().getName();

        if (methodsOrCtors[0].isCtor()) {
            throw Context.reportRuntimeError3(
                "msg.constructor.ambiguous",
                memberName, scriptSignature(args), buf.toString());
        }
        throw Context.reportRuntimeError4(
            "msg.method.ambiguous", memberClass,
            memberName, scriptSignature(args), buf.toString());
    }
1277067
@Override
    public String visit(final JmesPathFunction function,
                        final Void aVoid) throws InvalidTypeException {
        final String prefix = "new " + function.getClass()
                .getSimpleName() + "( ";
        return function.getExpressions().stream()
                .map(a -> a.accept(this, aVoid))
                .collect(Collectors.joining(",", prefix, ")"));
    }
25036
protected Object invokeJavascript(String function, Object... args) {
        Object[] jsArgs = new Object[args.length];
        for (int i = 0; i < jsArgs.length; i++) {
            if (args[i] instanceof JavascriptObject) {
                jsArgs[i] = ((JavascriptObject) args[i]).getJSObject();
            } else if (args[i] instanceof JavascriptEnum) {
                jsArgs[i] = ((JavascriptEnum) args[i]).getEnumValue();
            } else {
                jsArgs[i] = args[i];
            }
        }
        return checkUndefined(jsObject.call(function, (Object[]) jsArgs));
    }
805065
function Buildit$run() {
		var externals, locals, define, out, patterns, walked, that = this;

		define = invert(this.define);
		externals = [];
		locals = {};
		patterns = [];

		each(this.exports, function(filepath, name) {
			var fullpath;

			fullpath = path.join(that.cwd, filepath + '.js');

			patterns.push(fullpath);
		});

		each(this.extensions, function(filepath) {
			var fullpath;

			fullpath = path.join(that.cwd, filepath + '.js');

			patterns.push(fullpath);
		});

		each(this.define, function(filepath, name) {
			var fullpath;

			fullpath = path.join(that.cwd, filepath + '.js');

			patterns.push(fullpath);
		});

		walked = walk(patterns, this.cwd);

		Array.prototype.push.apply(externals, walked.externals);
		unique(externals);

		each(walked.locals, function(file, name) {
			locals[name] = file;
		});

		each(this.define, function(filepath, name) {
			if (!locals.hasOwnProperty(filepath)) {
				throw new Error('Module "' + filepath + '" not found');
			}
		});

		each(this.exports, function(filepath, name) {
			if (!locals.hasOwnProperty(filepath)) {
				throw new Error('Module "' + filepath + '" not found');
			}
		});

		each(this.extensions, function(filepath) {
			if (!locals.hasOwnProperty(filepath)) {
				throw new Error('Module "' + filepath + '" not found');
			}
		});

		out = '';
		out += print.header(this.name, externals);
		out += print.library(externals);
		out += print.mappings(locals, this.cwd);
		out += print.machinery();

		each(locals, function(file, name) {
			out += print.file(name, file.source) + (define[name] ? print.define(define[name], name) : '');
		});

		each(this.extensions, function(filepath) {
			out += print.extension(filepath);
		});

		out += print.exports(this.exports);
		out += print.footer();

		return out;
	}
744789
function (fn, thisObject) {
    var ret = [];
    for (var i = 0, len = this.length; i < len; i++) {

      // Kael:
      // Some people might ask: "why we use a `i in this` here?".
      // ECMA:
      // > callback is invoked only for indexes of the array which have assigned values;
      // > it is not invoked for indexes which have been deleted or which have never been assigned values

      // Besides, `filter` method is not always used with real Arrays, invocations below might happen:

      //     var obj = {length: 4}; obj[3] = 1;
      //     Array.prototype.filter.call({length: 4});
      //     Array.prototype.filter.call($('body'));

      // as well as the lines below
      if ((i in this) && fn.call(thisObject, this[i], i, this)) {
        ret.push(this[i]);
      }
    }

    return ret;
  }
255182
function forIn(obj, fn, thisObj){
        var key, i = 0;
        // no need to check if argument is a real object that way we can use
        // it for arrays, functions, date, etc.

        //post-pone check till needed
        if (_hasDontEnumBug == null) { checkDontEnum(); }

        for (key in obj) {
            if (exec(fn, obj, key, thisObj) === false) {
                break;
            }
        }


        if (_hasDontEnumBug) {
            var ctor = obj.constructor,
                isProto = !!ctor && obj === ctor.prototype;

            while (key = _dontEnums[i++]) {
                // For constructor, if it is a prototype object the constructor
                // is always non-enumerable unless defined otherwise (and
                // enumerated above).  For non-prototype objects, it will have
                // to be defined on this object, since it cannot be defined on
                // any prototype objects.
                //
                // For other [[DontEnum]] properties, check if the value is
                // different than Object prototype value.
                if (
                    (key !== 'constructor' ||
                        (!isProto && hasOwn_1(obj, key))) &&
                    obj[key] !== Object.prototype[key]
                ) {
                    if (exec(fn, obj, key, thisObj) === false) {
                        break;
                    }
                }
            }
        }
    }
117083
final public void Function() throws ParseException {
 /*@bgen(jjtree) Function */
    AstFunction jjtn000 = new AstFunction(JJTFUNCTION);
    boolean jjtc000 = true;
    jjtree.openNodeScope(jjtn000);Token t0 = null;
    Token t1 = null;
    try {
      t0 = jj_consume_token(IDENTIFIER);
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case COLON:
        jj_consume_token(COLON);
        t1 = jj_consume_token(IDENTIFIER);
        break;
      default:
        jj_la1[48] = jj_gen;
        ;
      }
        if (t1 != null) {
            jjtn000.setPrefix(t0.image);
            jjtn000.setLocalName(t1.image);
        } else {
            jjtn000.setLocalName(t0.image);
        }
      label_19:
      while (true) {
        MethodParameters();
        switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
        case LPAREN:
          ;
          break;
        default:
          jj_la1[49] = jj_gen;
          break label_19;
        }
      }
    } catch (Throwable jjte000) {
      if (jjtc000) {
        jjtree.clearNodeScope(jjtn000);
        jjtc000 = false;
      } else {
        jjtree.popNode();
      }
      if (jjte000 instanceof RuntimeException) {
        {if (true) throw (RuntimeException)jjte000;}
      }
      if (jjte000 instanceof ParseException) {
        {if (true) throw (ParseException)jjte000;}
      }
      {if (true) throw (Error)jjte000;}
    } finally {
      if (jjtc000) {
        jjtree.closeNodeScope(jjtn000, true);
      }
    }
  }
395396
function(context: ParserContext): ?Token {
    if (
      !context.reader.match("<<") ||
      !/[\w'"`-]/.test(context.reader.peekWithOffset(2))
    )
      return null;

    // cannot be preceded by an a number or a string
    const walker = context.getTokenWalker();
    if (walker.hasPrev()) {
      const prevToken = walker.prev();
      if (util.contains(["number", "string"], prevToken.name)) return null;
    }

    // there are still cases where heredocs are falsely detected, because it
    // would require performingstatic analysis

    // e.g. foo <<a
    // if foo is an object that has the "<<" method defined, then it will perform a left shift
    // if foo is a function that takes a string argument, it will interpret it as a heredoc

    // so, we just force you to have whitespace between << and the rhs operand in these ambiguous cases

    // can be between quotes (double, single or back) or not, or preceded by a hyphen
    let value = context.reader.read(2);
    let ident = "";
    let current = context.reader.read();
    if (current === "-") {
      value += current;
      ident += current;
      current = context.reader.read();
    }

    let delimiter = "";
    if (util.contains(['"', "'", "`"], current)) delimiter = current;
    else ident += current;

    value += current;

    while (!context.reader.isEOF()) {
      const peek = context.reader.peek();
      if (peek === "\n" || (delimiter === "" && /\W/.test(peek))) break;
      value += context.reader.read();
      if (peek === delimiter) break;
      ident += peek;
    }

    if (Array.isArray(context.items.heredocQueue))
      context.items.heredocQueue.push(ident);
    else
      logger.errorInvalidValue(
        `context.items.heredocQueue is not an array.`,
        context.items.heredocQueue
      );

    return context.createToken("heredocDeclaration", value);
  }
957123
private boolean executeJavaScriptFunction(final String function) {
		List<WebView> webViews = viewFetcher.getCurrentViews(WebView.class, true);
		final WebView webView = viewFetcher.getFreshestView((ArrayList<WebView>) webViews);
		
		if(webView == null) {
			return false;
		}

		final String javaScript = setWebFrame(prepareForStartOfJavascriptExecution(webViews));
		
		inst.runOnMainSync(new Runnable() {
			public void run() {
				if(webView != null){
					webView.loadUrl("javascript:" + javaScript + function);
				}
			}
		});
		return true;
	}