text:
package org.codehaus.gmaven.runtime.v2_0;

import groovyjarjarasm.asm.Opcodes;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.classgen.Verifier;
import org.codehaus.groovy.control.ResolveVisitor;
import org.codehaus.groovy.tools.Utilities;

import java.io.*;
import java.util.*;

public class JavaStubGenerator {
    private boolean java5 = false;
    private boolean requireSuperResolved = false;
    private File outputPath;
    private List<String> toCompile = new ArrayList<String>();
    private ArrayList<MethodNode> propertyMethods = new ArrayList<MethodNode>();
    private Map<String, MethodNode> propertyMethodsWithSigs = new HashMap<String, MethodNode>();
    private ArrayList<ConstructorNode> constructors = new ArrayList<ConstructorNode>();
    private ModuleNode currentModule;

    public JavaStubGenerator(final File outputPath, final boolean requireSuperResolved, final boolean java5) {
        this.outputPath = outputPath;
        this.requireSuperResolved = requireSuperResolved;
        this.java5 = java5;
        outputPath.mkdirs();
    }

    public JavaStubGenerator(final File outputPath) {
        this(outputPath, false, false);
    }

    private void mkdirs(File parent, String relativeFile) {
        int index = relativeFile.lastIndexOf('/');
        if (index == -1) return;
        File dir = new File(parent, relativeFile.substring(0, index));
        dir.mkdirs();
    }

    public void generateClass(ClassNode classNode) throws FileNotFoundException {
        // Only attempt to render our self if our super-class is resolved, else wait for it
        if (requireSuperResolved && !classNode.getSuperClass().isResolved()) {
            return;
        }

        // owner should take care for us
        if (classNode instanceof InnerClassNode)
            return;

        // don't generate stubs for private classes, as they are only visible in the same file
        if ((classNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return;

        String fileName = classNode.getName().replace('.', '/');
        mkdirs(outputPath, fileName);
        toCompile.add(fileName);

        File file = new File(outputPath, fileName + ".java");
        FileOutputStream fos = new FileOutputStream(file);
        PrintWriter out = new PrintWriter(fos);

        try {
            String packageName = classNode.getPackageName();
            if (packageName != null) {
                out.println("package " + packageName + ";\n");
            }

            printImports(out, classNode);
            printClassContents(out, classNode);

        } finally {
            try {
                out.close();
            } catch (Exception e) {
                // ignore
            }
            try {
                fos.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    private void printClassContents(PrintWriter out, ClassNode classNode) throws FileNotFoundException {
        if (classNode instanceof InnerClassNode && ((InnerClassNode) classNode).isAnonymous()) {
            // if it is an anonymous inner class, don't generate the stub code for it.
            return;
        }
        try {
            Verifier verifier = new Verifier() {
                public void addCovariantMethods(ClassNode cn) {}
                protected void addTimeStamp(ClassNode node) {}
                protected void addInitialization(ClassNode node) {}
                protected void addPropertyMethod(MethodNode method) {
                    doAddMethod(method);
                }
                protected void addReturnIfNeeded(MethodNode node) {}
                protected void addMethod(ClassNode node, boolean shouldBeSynthetic, String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) {
                    doAddMethod(new MethodNode(name, modifiers, returnType, parameters, exceptions, code));
                }

                protected void addConstructor(Parameter[] newParams, ConstructorNode ctor, Statement code, ClassNode node) {
                    if (code instanceof ExpressionStatement) {//GROOVY-4508
                        Statement temp = code;
                        code = new BlockStatement();
                        ((BlockStatement) code).addStatement(temp);
                    }
                    ConstructorNode ctrNode = new ConstructorNode(ctor.getModifiers(), newParams, ctor.getExceptions(), code);
                    ctrNode.setDeclaringClass(node);
                    constructors.add(ctrNode);
                }

                protected void addDefaultParameters(DefaultArgsAction action, MethodNode method) {
                    final Parameter[] parameters = method.getParameters();
                    final Expression[] saved = new Expression[parameters.length];
                    for (int i = 0; i < parameters.length; i++) {
                        if (parameters[i].hasInitialExpression())
                            saved[i] = parameters[i].getInitialExpression();
                    }
                    super.addDefaultParameters(action, method);
                    for (int i = 0; i < parameters.length; i++) {
                        if (saved[i] != null)
                            parameters[i].setInitialExpression(saved[i]);
                    }
                }

                private void doAddMethod(MethodNode method) {
                    String sig = method.getTypeDescriptor();

                    if (propertyMethodsWithSigs.containsKey(sig)) return;

                    propertyMethods.add(method);
                    propertyMethodsWithSigs.put(sig, method);
                }

                @Override
                protected void addDefaultConstructor(ClassNode node) {
                    // not required for stub generation
                }
            };
            verifier.visitClass(classNode);
            currentModule = classNode.getModule();

            boolean isInterface = classNode.isInterface();
            boolean isEnum = (classNode.getModifiers() & Opcodes.ACC_ENUM) != 0;
            boolean isAnnotationDefinition = classNode.isAnnotationDefinition();
            printAnnotations(out, classNode);
            printModifiers(out, classNode.getModifiers()
                    & ~(isInterface ? Opcodes.ACC_ABSTRACT : 0)
                    & ~(isEnum ? Opcodes.ACC_FINAL : 0));

            if (isInterface) {
                if (isAnnotationDefinition) {
                    out.print("@");
                }
                out.print("interface ");
            } else if (isEnum) {
                out.print("enum ");
            } else {
                out.print("class ");
            }

            String className = classNode.getNameWithoutPackage();
            if (classNode instanceof InnerClassNode)
                className = className.substring(className.lastIndexOf("$") + 1);
            out.println(className);
            printGenericsBounds(out, classNode, true);

            ClassNode superClass = classNode.getUnresolvedSuperClass(false);

            if (!isInterface && !isEnum) {
                out.print("  extends ");
                printType(out, superClass);
            }

            ClassNode[] interfaces = classNode.getInterfaces();
            if (interfaces != null && interfaces.length > 0 && !isAnnotationDefinition) {
                if (isInterface) {
                    out.println("  extends");
                } else {
                    out.println("  implements");
                }
                for (int i = 0; i < interfaces.length - 1; ++i) {
                    out.print("    ");
                    printType(out, interfaces[i]);
                    out.print(",");
                }
                out.print("    ");
                printType(out, interfaces[interfaces.length - 1]);
            }
            out.println(" {");

            printFields(out, classNode);
            printMethods(out, classNode, isEnum);

            for (Iterator<InnerClassNode> inner = classNode.getInnerClasses(); inner.hasNext(); ) {
                // GROOVY-4004: Clear the methods from the outer class so that they don't get duplicated in inner ones
                propertyMethods.clear();
                propertyMethodsWithSigs.clear();
                constructors.clear();
                printClassContents(out, inner.next());
            }

            out.println("}");
        } finally {
            propertyMethods.clear();
            propertyMethodsWithSigs.clear();
            constructors.clear();
            currentModule = null;
        }
    }

    private void printMethods(PrintWriter out, ClassNode classNode, boolean isEnum) {
        if (!isEnum) printConstructors(out, classNode);

        @SuppressWarnings("unchecked")
        List<MethodNode> methods = (List) propertyMethods.clone();
        methods.addAll(classNode.getMethods());
        for (MethodNode method : methods) {
            if (isEnum && method.isSynthetic()) {
                // skip values() method and valueOf(String)
                String name = method.getName();
                Parameter[] params = method.getParameters();
                if (name.equals("values") && params.length == 0) continue;
                if (name.equals("valueOf") &&
                        params.length == 1 &&
                        params[0].getType().equals(ClassHelper.STRING_TYPE)) {
                    continue;
                }
            }
            printMethod(out, classNode, method);
        }
    }

    private void printConstructors(PrintWriter out, ClassNode classNode) {
        @SuppressWarnings("unchecked")
        List<ConstructorNode> constrs = (List<ConstructorNode>) constructors.clone();
        if (constrs != null) {
            constrs.addAll(classNode.getDeclaredConstructors());
            for (ConstructorNode constr : constrs) {
                printConstructor(out, classNode, constr);
            }
        }
    }

    private void printFields(PrintWriter out, ClassNode classNode) {
        boolean isInterface = classNode.isInterface();
        List<FieldNode> fields = classNode.getFields();
        if (fields == null) return;
        List<FieldNode> enumFields = new ArrayList<FieldNode>(fields.size());
        List<FieldNode> normalFields = new ArrayList<FieldNode>(fields.size());
        for (FieldNode field : fields) {
            boolean isSynthetic = (field.getModifiers() & Opcodes.ACC_SYNTHETIC) != 0;
            if (field.isEnum()) {
                enumFields.add(field);
            } else if (!isSynthetic) {
                normalFields.add(field);
            }
        }
        printEnumFields(out, enumFields);
        for (FieldNode normalField : normalFields) {
            printField(out, normalField, isInterface);
        }
    }

    private void printEnumFields(PrintWriter out, List<FieldNode> fields) {
        if (fields.size() == 0) return;
        boolean first = true;
        for (FieldNode field : fields) {
            if (!first) {
                out.print(", ");
            } else {
                first = false;
            }
            out.print(field.getName());
        }
        out.println(";");
    }

    private void printField(PrintWriter out, FieldNode fieldNode, boolean isInterface) {
        if ((fieldNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return;
        printAnnotations(out, fieldNode);
        if (!isInterface) {
            printModifiers(out, fieldNode.getModifiers());
        }

        ClassNode type = fieldNode.getType();
        printType(out, type);

        out.print(" ");
        out.print(fieldNode.getName());
        if (isInterface || (fieldNode.getModifiers() & Opcodes.ACC_FINAL) != 0) {
            out.print(" = ");
            Expression valueExpr = fieldNode.getInitialValueExpression();
            if (valueExpr instanceof ConstantExpression) {
                valueExpr = Verifier.transformToPrimitiveConstantIfPossible((ConstantExpression) valueExpr);
            }
            if (valueExpr instanceof ConstantExpression
                    && fieldNode.isStatic() && fieldNode.isFinal()
                    && ClassHelper.isStaticConstantInitializerType(valueExpr.getType())
                    && valueExpr.getType().equals(fieldNode.getType())) {
                if (ClassHelper.STRING_TYPE.equals(valueExpr.getType())) {
                    // GROOVY-5150 : Initialize value with a dummy constant so that Java cross compiles correctly
                    // -- old methods --
//                    out.print("\"\"");
//                    out.print("\"" + escapeSpecialChars(valueExpr.getText()) + "\"");
                    // -- new method --
                    out.print("\"" + valueExpr.getText().replaceAll("\\\\", "\\\\\\\\")
                            .replaceAll("\\\"", "\\\\\"").replaceAll("\b", "\\\\b").replaceAll("\n", "\\\\n")
                            .replaceAll("\r", "\\\\r").replaceAll("\t", "\\\\t") + "\"");
                } else if (ClassHelper.char_TYPE.equals(valueExpr.getType())) {
                    out.print("'"+valueExpr.getText()+"'");
                } else {
                    ClassNode constantType = valueExpr.getType();
                    out.print('(');
                    printType(out, type);
                    out.print(") ");
                    out.print(valueExpr.getText());
                    if (ClassHelper.Long_TYPE.equals(ClassHelper.getWrapper(constantType))) out.print('L');
                }
            } else if (ClassHelper.isPrimitiveType(type)) {
                String val = type == ClassHelper.boolean_TYPE ? "false" : "0";
                out.print("new " + ClassHelper.getWrapper(type) + "((" + type + ")" + val + ")");
            } else {
                out.print("null");
            }
        }
        out.println(";");
    }

    private ConstructorCallExpression getConstructorCallExpression(ConstructorNode constructorNode) {
        Statement code = constructorNode.getCode();
        if (!(code instanceof BlockStatement))
            return null;

        BlockStatement block = (BlockStatement) code;
        List stats = block.getStatements();
        if (stats == null || stats.size() == 0)
            return null;

        Statement stat = (Statement) stats.get(0);
        if (!(stat instanceof ExpressionStatement))
            return null;

        Expression expr = ((ExpressionStatement) stat).getExpression();
        if (!(expr instanceof ConstructorCallExpression))
            return null;

        return (ConstructorCallExpression) expr;
    }

    private void printConstructor(PrintWriter out, ClassNode clazz, ConstructorNode constructorNode) {
        printAnnotations(out, constructorNode);
        // printModifiers(out, constructorNode.getModifiers());

        out.print("public "); // temporary hack
        String className = clazz.getNameWithoutPackage();
        if (clazz instanceof InnerClassNode)
            className = className.substring(className.lastIndexOf("$") + 1);
        out.println(className);

        printParams(out, constructorNode);

        ConstructorCallExpression constrCall = getConstructorCallExpression(constructorNode);
        if (constrCall == null || !constrCall.isSpecialCall()) {
            out.println(" {}");
        } else {
            out.println(" {");
            printSpecialConstructorArgs(out, constructorNode, constrCall);
            out.println("}");
        }
    }

    private Parameter[] selectAccessibleConstructorFromSuper(ConstructorNode node) {
        ClassNode type = node.getDeclaringClass();
        ClassNode superType = type.getSuperClass();

        for (ConstructorNode c : superType.getDeclaredConstructors()) {
            // Only look at things we can actually call
            if (c.isPublic() || c.isProtected()) {
                return c.getParameters();
            }
        }

        // fall back for parameterless constructor
        if (superType.isPrimaryClassNode()) {
            return Parameter.EMPTY_ARRAY;
        }

        return null;
    }

    private void printSpecialConstructorArgs(PrintWriter out, ConstructorNode node, ConstructorCallExpression constrCall) {
        // Select a constructor from our class, or super-class which is legal to call,
        // then write out an invoke w/nulls using casts to avoid ambiguous crapo

        Parameter[] params = selectAccessibleConstructorFromSuper(node);
        if (params != null) {
            out.print("super (");

            for (int i = 0; i < params.length; i++) {
                printDefaultValue(out, params[i].getType());
                if (i + 1 < params.length) {
                    out.print(", ");
                }
            }

            out.println(");");
            return;
        }

        // Otherwise try the older method based on the constructor's call expression
        Expression arguments = constrCall.getArguments();

        if (constrCall.isSuperCall()) {
            out.print("super(");
        } else {
            out.print("this(");
        }

        // Else try to render some arguments
        if (arguments instanceof ArgumentListExpression) {
            ArgumentListExpression argumentListExpression = (ArgumentListExpression) arguments;
            List<Expression> args = argumentListExpression.getExpressions();

            for (Expression arg : args) {
                if (arg instanceof ConstantExpression) {
                    ConstantExpression expression = (ConstantExpression) arg;
                    Object o = expression.getValue();

                    if (o instanceof String) {
                        out.print("(String)null");
                    } else {
                        out.print(expression.getText());
                    }
                } else {
                    ClassNode type = getConstructorArgumentType(arg, node);
                    printDefaultValue(out, type);
                }

                if (arg != args.get(args.size() - 1)) {
                    out.print(", ");
                }
            }
        }

        out.println(");");
    }

    private ClassNode getConstructorArgumentType(Expression arg, ConstructorNode node) {
        if (!(arg instanceof VariableExpression)) return arg.getType();
        VariableExpression vexp = (VariableExpression) arg;
        String name = vexp.getName();
        for (Parameter param : node.getParameters()) {
            if (param.getName().equals(name)) {
                return param.getType();
            }
        }
        return vexp.getType();
    }

    private void printMethod(PrintWriter out, ClassNode clazz, MethodNode methodNode) {
        if (methodNode.getName().equals("<clinit>")) return;
        if (methodNode.isPrivate() || !Utilities.isJavaIdentifier(methodNode.getName())) return;
        if (methodNode.isSynthetic() && methodNode.getName().equals("$getStaticMetaClass")) return;

        printAnnotations(out, methodNode);
        if (!clazz.isInterface()) printModifiers(out, methodNode.getModifiers());

        printGenericsBounds(out, methodNode.getGenericsTypes());
        out.print(" ");
        printType(out, methodNode.getReturnType());
        out.print(" ");
        out.print(methodNode.getName());

        printParams(out, methodNode);

        ClassNode[] exceptions = methodNode.getExceptions();
        for (int i = 0; i < exceptions.length; i++) {
            ClassNode exception = exceptions[i];
            if (i == 0) {
                out.print("throws ");
            } else {
                out.print(", ");
            }
            printType(out, exception);
        }

        if ((methodNode.getModifiers() & Opcodes.ACC_ABSTRACT) != 0) {
            out.println(";");
        } else {
            out.print(" { ");
            ClassNode retType = methodNode.getReturnType();
            printReturn(out, retType);
            out.println("}");
        }
    }

    private void printReturn(PrintWriter out, ClassNode retType) {
        String retName = retType.getName();
        if (!retName.equals("void")) {
            out.print("return ");

            printDefaultValue(out, retType);

            out.print(";");
        }
    }

    private void printDefaultValue(PrintWriter out, ClassNode type) {
        if (type.redirect() != ClassHelper.OBJECT_TYPE && type.redirect() != ClassHelper.boolean_TYPE) {
            out.print("(");
            printTypeWithoutBounds(out, type);
            out.print(")");
        }

        if (ClassHelper.isPrimitiveType(type)) {
            if (type == ClassHelper.boolean_TYPE) {
                out.print("false");
            } else {
                out.print("0");
            }
        } else {
            out.print("null");
        }
    }

    private void printType(PrintWriter out, ClassNode type) {
        if (type.isArray()) {
            printType(out, type.getComponentType());
            out.print("[]");
        } else if (java5 && type.isGenericsPlaceHolder()) {
            out.print(type.getGenericsTypes()[0].getName());
        } else {
            printGenericsBounds(out, type, false);
        }
    }

    private void printTypeWithoutBounds(PrintWriter out, ClassNode type) {
        if (type.isArray()) {
            printTypeWithoutBounds(out, type.getComponentType());
            out.print("[]");
        } else {
            printTypeName(out, type);
        }
    }

    private void printTypeName(PrintWriter out, ClassNode type) {
        if (ClassHelper.isPrimitiveType(type)) {
            if (type == ClassHelper.boolean_TYPE) {
                out.print("boolean");
            } else if (type == ClassHelper.char_TYPE) {
                out.print("char");
            } else if (type == ClassHelper.int_TYPE) {
                out.print("int");
            } else if (type == ClassHelper.short_TYPE) {
                out.print("short");
            } else if (type == ClassHelper.long_TYPE) {
                out.print("long");
            } else if (type == ClassHelper.float_TYPE) {
                out.print("float");
            } else if (type == ClassHelper.double_TYPE) {
                out.print("double");
            } else if (type == ClassHelper.byte_TYPE) {
                out.print("byte");
            } else {
                out.print("void");
            }
        } else {
            String name = type.getName();
            // check for an alias
            ClassNode alias = currentModule.getImportType(name);
            if (alias != null) name = alias.getName();
            out.print(name.replace('$', '.'));
        }
    }

    private void printGenericsBounds(PrintWriter out, ClassNode type, boolean skipName) {
        if (!skipName) printTypeName(out, type);
        if (!java5) return;
        if (!ClassHelper.isCachedType(type)) {
            printGenericsBounds(out, type.getGenericsTypes());
        }
    }

    private void printGenericsBounds(PrintWriter out, GenericsType[] genericsTypes) {
        if (genericsTypes == null || genericsTypes.length == 0) return;
        out.print('<');
        for (int i = 0; i < genericsTypes.length; i++) {
            if (i != 0) out.print(", ");
            out.print(genericsTypes[i].toString().replace("$","."));
        }
        out.print('>');
    }

    private void printParams(PrintWriter out, MethodNode methodNode) {
        out.print("(");
        Parameter[] parameters = methodNode.getParameters();
        if (parameters != null && parameters.length != 0) {
            int lastIndex = parameters.length - 1;
            boolean vararg = parameters[lastIndex].getType().isArray();
            for (int i = 0; i != parameters.length; ++i) {
                if (i == lastIndex && vararg) {
                    printType(out, parameters[i].getType().getComponentType());
                    out.print("...");
                } else {
                    printType(out, parameters[i].getType());
                }
                out.print(" ");
                out.print(parameters[i].getName());
                if (i + 1 < parameters.length) {
                    out.print(", ");
                }
            }
        }
        out.print(")");
    }

    private void printAnnotations(PrintWriter out, AnnotatedNode annotated) {
        if (!java5) return;
        for (AnnotationNode annotation : annotated.getAnnotations()) {
            printAnnotation(out, annotation);
        }
    }

    private void printAnnotation(PrintWriter out, AnnotationNode annotation) {
        out.print("@" + annotation.getClassNode().getName() + "(");
        boolean first = true;
        Map<String, Expression> members = annotation.getMembers();
        for (String key : members.keySet()) {
            if (first) first = false;
            else out.print(", ");
            out.print(key + "=" + getAnnotationValue(members.get(key)));
        }
        out.print(") ");
    }

    private String getAnnotationValue(Object memberValue) {
        String val = "null";
        if (memberValue instanceof ListExpression) {
            StringBuilder sb = new StringBuilder("{");
            boolean first = true;
            ListExpression le = (ListExpression) memberValue;
            for (Expression e : le.getExpressions()) {
                if (first) first = false;
                else sb.append(",");
                sb.append(getAnnotationValue(e));
            }
            sb.append("}");
            val = sb.toString();
        } else if (memberValue instanceof ConstantExpression) {
            ConstantExpression ce = (ConstantExpression) memberValue;
            Object constValue = ce.getValue();
            if (constValue instanceof AnnotationNode) {
                StringWriter writer = new StringWriter();
                PrintWriter out = new PrintWriter(writer);
                printAnnotation(out, (AnnotationNode) constValue);
                val = writer.toString();
            } else if (constValue instanceof Number || constValue instanceof Boolean)
                val = constValue.toString();
            else
                val = "\"" + escapeSpecialChars(constValue.toString()) + "\"";
        } else if (memberValue instanceof PropertyExpression || memberValue instanceof VariableExpression) {
            // assume must be static class field or enum value or class that Java can resolve
            val = ((Expression) memberValue).getText();
        } else if (memberValue instanceof ClosureExpression) {
            // annotation closure; replaced with this specific class literal to cover the
            // case where annotation type uses Class<? extends Closure> for the closure's type
            val = "groovy.lang.Closure.class";
        } else if (memberValue instanceof ClassExpression) {
            val = ((Expression) memberValue).getText() + ".class";
        }
        return val;
    }

    private void printModifiers(PrintWriter out, int modifiers) {
        if ((modifiers & Opcodes.ACC_PUBLIC) != 0)
            out.print("public ");

        if ((modifiers & Opcodes.ACC_PROTECTED) != 0)
            out.print("protected ");

        if ((modifiers & Opcodes.ACC_PRIVATE) != 0)
            out.print("private ");

        if ((modifiers & Opcodes.ACC_STATIC) != 0)
            out.print("static ");

        if ((modifiers & Opcodes.ACC_SYNCHRONIZED) != 0)
            out.print("synchronized ");

        if ((modifiers & Opcodes.ACC_FINAL) != 0)
            out.print("final ");

        if ((modifiers & Opcodes.ACC_ABSTRACT) != 0)
            out.print("abstract ");
    }

    private void printImports(PrintWriter out, ClassNode classNode) {
        List<String> imports = new ArrayList<String>();

        ModuleNode moduleNode = classNode.getModule();
        for (ImportNode importNode : moduleNode.getStarImports()) {
            imports.add(importNode.getPackageName());
        }

        for (ImportNode imp : moduleNode.getImports()) {
            if (imp.getAlias() == null)
                imports.add(imp.getType().getName());
        }

        imports.addAll(Arrays.asList(ResolveVisitor.DEFAULT_IMPORTS));

        for (String imp : imports) {
            String s = new StringBuilder()
                    .append("import ")
                    .append(imp)
                    .append((imp.charAt(imp.length() - 1) == '.') ? "*;" : ";")
                    .toString()
                    .replace('$', '.');
            out.println(s);
        }
        out.println();
    }

    public void clean() {
        for (String path : toCompile) {
            new File(outputPath, path + ".java").delete();
        }
    }

    private static String escapeSpecialChars(String value) {
        return value.replace("\n", "\\n").replace("\r", "\\r").replace("\"", "\\\"");
    }
}


text:
A JavaScript parser for
[Google Closure Compiler](https://developers.google.com/closure/compiler/docs/js-for-compiler#types)
and [JSDoc](https://github.com/jsdoc3/jsdoc) type expressions.

Catharsis is designed to be:

+ **Accurate**. Catharsis is based on a [PEG.js](http://pegjs.majda.cz/) grammar that's designed to
handle any valid type expression. It uses a [Mocha](http://visionmedia.github.com/mocha/) test suite
to verify the parser's accuracy.
+ **Fast**. Parse results are cached, so the parser is invoked only when necessary.
+ **Flexible**. Catharsis can convert a parse result back into a type expression, or into a
description of the type expression. In addition, Catharsis can parse
[JSDoc](https://github.com/jsdoc3/jsdoc)-style type expressions.

## Example ##

```js
var catharsis = require('catharsis');

// Google Closure Compiler parsing
var type = '!Object';
var parsedType;
try {
    parsedType = catharsis.parse(type); // {"type":"NameExpression,"name":"Object","nullable":false}
} catch(e) {
    console.error('unable to parse %s: %s', type, e);
}

// JSDoc-style type expressions enabled
var jsdocType = 'string[]';  // Closure Compiler expects Array.<string>
var parsedJsdocType;
try {
    parsedJsdocType = catharsis.parse(jsdocType, {jsdoc: true});
} catch (e) {
    console.error('unable to parse %s: %s', jsdocType, e);
}

// Converting parse results back to type expressions
catharsis.stringify(parsedType);                              // !Object
catharsis.stringify(parsedJsdocType);                         // string[]
catharsis.stringify(parsedJsdocType, {restringify: true});    // Array.<string>

// Converting parse results to descriptions of the type expression
catharsis.describe(parsedType).simple;                        // non-null Object
catharsis.describe(parsedJsdocType).simple;                   // Array of string
```

See the [test/specs directory](test/specs) for more examples of Catharsis' parse results.

## Methods ##

### parse(typeExpression, options) ###
Parse a type expression, and return the parse results. Throws an error if the type expression cannot
be parsed.

When called without options, Catharsis attempts to parse type expressions in the same way as
Closure Compiler. When the `jsdoc` option is enabled, Catharsis can also parse several kinds of
type expressions that are permitted in [JSDoc](https://github.com/jsdoc3/jsdoc):

+ The string `function` is treated as a function type with no parameters.
+ The period may be omitted from type applications. For example, `Array.<string>` and
`Array<string>` will be parsed in the same way.
+ You may append `[]` to a name expression (for example, `string[]`) to interpret it as a type
application with the expression `Array` (for example, `Array.<string>`).
+ Name expressions may contain the characters `#`, `~`, `:`, and `/`.
+ Name expressions may contain a suffix that is similar to a function signature (for example,
`MyClass(foo, bar)`).
+ Name expressions may contain a reserved word.
+ Record types may use types other than name expressions for keys.

#### Parameters ####
+ `type`: A string containing a Closure Compiler type expression.
+ `options`: Options for parsing the type expression.
    + `options.jsdoc`: Specifies whether to enable parsing of JSDoc-style type expressions. Defaults
    to `false`.
    + `options.useCache`: Specifies whether to use the cache of parsed types. Defaults to `true`.

#### Returns ####
An object containing the parse results. See the [test/specs directory](test/specs) for examples of
the parse results for different type expressions.

The object also includes two non-enumerable properties:

+ `jsdoc`: A boolean indicating whether the type expression was parsed with JSDoc support enabled.
+ `typeExpression`: A string containing the type expression that was parsed.

### stringify(parsedType, options) ###
Stringify `parsedType`, and return the type expression. If validation is enabled, throws an error if
the stringified type expression cannot be parsed.

#### Parameters ####
+ `parsedType`: An object containing a parsed Closure Compiler type expression.
+ `options`: Options for stringifying the parse results.
    + `options.cssClass`: Synonym for `options.linkClass`. Deprecated in version 0.8.0; will be
    removed in a future version.
    + `options.htmlSafe`: Specifies whether to return an HTML-safe string that replaces left angle
    brackets (`<`) with the corresponding entity (`<`). **Note**: Characters in name expressions
    are not escaped.
    + `options.linkClass`: A CSS class to add to HTML links. Used only if `options.links` is
    provided. By default, no CSS class is added.
    + `options.links`: An object whose keys are name expressions and whose values are URIs. If a
    name expression matches a key in `options.links`, the name expression will be wrapped in an
    HTML `<a>` tag that links to the URI. If `options.linkClass` is specified, the `<a>` tag will
    include a `class` attribute. **Note**: When using this option, parsed types are always
    restringified, and the resulting string is not cached.
    + `options.restringify`: Forces Catharsis to restringify the parsed type. If this option is not
    specified, and the parsed type object includes a `typeExpression` property, Catharsis will
    return the `typeExpression` property without modification when possible. Defaults to `false`.
    + `options.useCache`: Specifies whether to use the cache of stringified type expressions.
    Defaults to `true`.
    + `options.validate`: Specifies whether to validate the stringified parse results by attempting
    to parse them as a type expression. If the stringified results are not parsable by default, you
    must also provide the appropriate options to pass to the `parse()` method. Defaults to `false`.

#### Returns ####
A string containing the type expression.

### describe(parsedType, options) ###
Convert a parsed type to a description of the type expression. This method is especially useful if
your users are not familiar with the syntax for type expressions.

The `describe()` method returns the description in two formats:

+ **Simple format**. A string that provides a complete description of the type expression.
+ **Extended format**. An object that separates out some of the details about the outermost type
expression, such as whether the type is optional, nullable, or repeatable.

For example, if you call `describe('?function(new:MyObject, string)=')`, it returns the following
object:

```js
{
  simple: 'optional nullable function(constructs MyObject, string)',
  extended: {
    description: 'function(string)',
    modifiers: {
      functionNew: 'Returns MyObject when called with new.',
      functionThis: '',
      optional: 'Optional.',
      nullable: 'May be null.',
      repeatable: ''
    },
    returns: ''
  }
}
```

#### Parameters ####
+ `parsedType`: An object containing a parsed Closure Compiler type expression.
+ `options`: Options for creating the description.
    + `options.codeClass`: A CSS class to add to the tag that is wrapped around type names. Used
    only if `options.codeTag` is provided. By default, no CSS class is added.
    + `options.codeTag`: The name of an HTML tag (for example, `code`) to wrap around type names.
    For example, if this option is set to `code`, the type expression `Array.<string>` would have
    the simple description `<code>Array</code> of <code>string</code>`.
    + `options.language`: A string identifying the language in which to generate the description.
    The identifier should be an
    [ISO 639-1 language code](http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (for example,
    `en`). It can optionally be followed by a hyphen and an
    [ISO 3166-1 alpha-2 country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) (for example,
    `en-US`). If you use values other than `en`, you must provide translation resources in
    `options.resources`. Defaults to `en`.
    + `options.linkClass`: A CSS class to add to HTML links. Used only if `options.links` is
    provided. By default, no CSS class is added.
    + `options.links`: An object whose keys are name expressions and whose values are URIs. If a
    name expression matches a key in `options.links`, the name expression will be wrapped in an
    HTML `<a>` tag that links to the URI. If `options.linkClass` is specified, the `<a>` tag will
    include a `class` attribute. **Note**: When using this option, the description is not cached.
    + `options.resources`: An object that specifies how to describe type expressions for a given
    language. The object's property names should use the same format as `options.language`. Each
    property should contain an object in the same format as the translation resources in
    [res/en.json](res/en.json). If you specify a value for `options.resources.en`, it will override
    the defaults in [res/en.json](res/en.json).
    + `options.useCache`: Specifies whether to use the cache of descriptions. Defaults to `true`.

### Returns ###
An object with the following properties:

+ `simple`: A string that provides a complete description of the type expression.
+ `extended`: An object containing details about the outermost type expression.
    + `extended.description`: A string that provides a basic description of the type expression,
    excluding the information contained in other properties.
    + `extended.modifiers`: Information about modifiers that apply to the type expression.
        + `extended.modifiers.functionNew`: A string describing what a function returns when called
        with `new`. Used only for function types.
        + `extended.modifiers.functionThis`: A string describing what the keyword `this` refers to
        within a function. Used only for function types.
        + `extended.modifiers.nullable`: A string indicating whether the type is nullable or
        non-nullable.
        + `extended.modifiers.optional`: A string indicating whether the type is optional.
        + `extended.modifiers.repeatable`: A string indicating whether the type can be provided
    + `extended.returns`: A string describing the function's return value. Used only for function
    types.

## Installation ##

With [npm](http://npmjs.org):

    npm install catharsis

Or without:

    git clone git://github.com/hegemonic/catharsis.git
    cd catharsis
    npm install

## Roadmap and known issues ##

Take a look at the [issue tracker](https://github.com/hegemonic/catharsis/issues) to see what's in
store for Catharsis.

Bug reports, feature requests, and pull requests are always welcome! If you're working on a large
pull request, please contact me in advance so I can help things go smoothly.

**Note**: The parse tree's format should not be considered final until Catharsis reaches version
1.0. I'll do my best to provide release notes for any changes.

## Changelog ##

+ 0.8.7 (June 2015):
    + Record types that use numeric literals as property names (for example, `{0: string}`) are now
    parsed correctly.
    + Record types with a property that contains a function, with no space after the preceding colon
    (for example, `{foo:function()}`), are now parsed correctly.
    + Repeatable function parameters are no longer required to be enclosed in brackets, regardless
    of whether JSDoc-style type expressions are enabled. In addition, the brackets are omitted when
    stringifying a parsed type expression.
+ 0.8.6 (December 2014): Improved the description of the unknown type.
+ 0.8.5 (December 2014): Added support for postfix nullable/non-nullable operators combined with the
optional operator (for example, `foo?=`).
+ 0.8.4 (December 2014): JSDoc-style nested arrays (for example, `number[][]`) are now parsed
correctly when JSDoc-style type expressions are enabled.
+ 0.8.3 (October 2014):
    + Type applications are no longer required to include a period (`.`) as a separator, regardless
    of whether JSDoc-style type expressions are enabled.
    + Type unions that are not enclosed in parentheses can now include the repeatable (`...`)
    modifier when JSDoc-style type expressions are enabled.
    + Name expressions may now be enclosed in single or double quotation marks when JSDoc-style
    type expressions are enabled.
+ 0.8.2 (June 2014): Fixed a compatibility issue with the JSDoc fork of Mozilla Rhino.
+ 0.8.1 (June 2014): Added support for type unions that are not enclosed in parentheses, and that
contain nullable or non-nullable modifiers (for example, `!string|!number`).
+ 0.8.0 (May 2014):
    + Added a `describe()` method, which converts a parsed type to a description of the type.
    + Added a `linkClass` option to the `stringify()` method, and deprecated the existing `cssClass`
    option. The `cssClass` option will be removed in a future release.
    + Clarified and corrected several sections in the `README`.
+ 0.7.1 (April 2014): In record types, property names that begin with a keyword (for example,
`undefinedHTML`) are now parsed correctly when JSDoc-style type expressions are enabled.
+ 0.7.0 (October 2013):
    + Repeatable type expressions other than name expressions (for example, `...function()`) are now
    parsed and stringified correctly.
    + Type expressions that are both repeatable and either nullable or non-nullable (for example,
    `...!number`) are now parsed and stringified correctly.
    + Name expressions are now parsed correctly when they match a property name in an object
    instance (for example, `constructor`).
+ 0.6.0 (September 2013): Added support for the type expression `function[]` when JSDoc-style type
expressions are enabled.
+ 0.5.6 (April 2013):
    + For consistency with Google Closure Library, parentheses are no longer required around type
    unions. (In previous versions, the parentheses could be omitted when JSDoc support was enabled.)
    + For consistency with Google Closure Library, you can now use postfix notation for the `?`
    (nullable) and `!` (non-nullable) modifiers. For example, `?string` and `string?` are now
    treated as equivalent.
    + String literals and numeric literals are now allowed as property names within name
    expressions. For example, the name expression `Foo."bar"` is now parsed correctly.
+ 0.5.5 (April 2013): Corrected a parsing issue with name expressions that end with a value enclosed
in parentheses.
+ 0.5.4 (April 2013):
    + Repeatable literals (for example, `...*`) are now parsed correctly.
    + When JSDoc-style type expressions are enabled, a name expression can now contain a value
    enclosed in parentheses at the end of the name expression (for example, `MyClass(2)`).
+ 0.5.3 (March 2013): The `parse()` method now correctly parses name expressions that contain
hyphens.
+ 0.5.2 (March 2013): The `parse()` method now correctly parses function types when JSDoc-style type
expressions are enabled.
+ 0.5.1 (March 2013): Newlines and extra spaces are now removed from type expressions before they
are parsed.
+ 0.5.0 (March 2013):
    + The `parse()` method's `lenient` option has been renamed to `jsdoc`. **Note**: This change is
    not backwards-compatible with previous versions.
    + The `stringify()` method now accepts `cssClass` and `links` options, which you can use to
    add HTML links to a type expression.
+ 0.4.3 (March 2013):
    + The `stringify()` method no longer caches HTML-safe type expressions as if they were normal
    type expressions.
    + The `stringify()` method's options parameter may now include an `options.restringify`
    property, and the behavior of the `options.useCache` property has changed.
+ 0.4.2 (March 2013):
    + When lenient parsing is enabled, name expressions can now contain the characters `:` and `/`.
    + When lenient parsing is enabled, a name expression followed by `[]` (for example, `string[]`)
    will be interpreted as a type application with the expression `Array` (for example,
    `Array.<string>`).
+ 0.4.1 (March 2013):
    + The `parse()` and `stringify()` methods now honor all of the specified options.
    + When lenient parsing is enabled, name expressions can now contain a reserved word.
+ 0.4.0 (March 2013):
    + Catharsis now supports a lenient parsing option that can parse several kinds of malformed type
    expressions. See the documentation for details.
    + The objects containing parse results are now frozen.
    + The objects containing parse results now have two non-enumerable properties:
        + `lenient`: A boolean indicating whether the type expression was parsed in lenient mode.
        + `typeExpression`: A string containing the original type expression.
    + The `stringify()` method now honors the `useCache` option. If a parsed type includes a
    `typeExpression` property, and `useCache` is not set to `false`, the stringified type will be
    identical to the original type expression.
+ 0.3.1 (March 2013): Type expressions that begin with a reserved word, such as `integer`, are now
parsed correctly.
+ 0.3.0 (March 2013):
    + The `parse()` and `stringify()` methods are now synchronous, and the `parseSync()` and
    `stringifySync()` methods have been removed. **Note**: This change is not backwards-compatible
    with previous versions.
    + The parse results now use a significantly different format from previous versions. The new
    format is more expressive and is similar, but not identical, to the format used by the
    [doctrine](https://github.com/Constellation/doctrine) parser. **Note**: This change is not
    backwards-compatible with previous versions.
    + Name expressions that contain a reserved word now include a `reservedWord: true` property.
    + Union types that are optional or nullable, or that can be passed a variable number of times,
    are now parsed and stringified correctly.
    + Optional function types and record types are now parsed and stringified correctly.
    + Function types now longer include `new` or `this` properties unless the properties are defined
    in the type expression. In addition, the `new` and `this` properties can now use any type
    expression.
    + In record types, the key for a field type can now use any type expression.
    + Standalone single-character literals, such as ALL (`*`), are now parsed and stringified
    correctly.
    + `null` and `undefined` literals with additional properties, such as `repeatable`, are now
    stringified correctly.
+ 0.2.0 (November 2012):
    + Added `stringify()` and `stringifySync()` methods, which convert a parsed type to a type
    expression.
    + Simplified the parse results for function signatures. **Note**: This change is not
    backwards-compatible with previous versions.
    + Corrected minor errors in README.md.
+ 0.1.1 (November 2012): Added `opts` argument to `parse()` and `parseSync()` methods. **Note**: The
change to `parse()` is not backwards-compatible with previous versions.
+ 0.1.0 (November 2012): Initial release.

## License ##

[MIT license](https://github.com/hegemonic/catharsis/blob/master/LICENSE).

redpajama_set_name: RedPajamaGithub


text:
/*
Theme Name: Give Me A Name
Theme URI:
Description:
Version: 0.0.1
Author: Interglobal Vision
Author URI: http://interglobal.vision
*/


text:
import {assert} from 'chai';
import deepEqual from '../../src/3-Objects/4-Deep';

describe('3-Objects/4-DeepEqual', () => {
  it('should return equal for same values [10,10]', () => {
    assert(deepEqual(10,10));
  });
  it('should return equal for same values [-10,-10]', () => {
    assert(deepEqual(-10,-10));
  });
  it('should return equal for same values [bbb,bbb]', () => {
    assert(deepEqual('bbb','bbb'));
  });
  it('should return not equal for same values [alain,perkaz]', () => {
    assert(!deepEqual('alain','perkaz'));
  });
  it('should return equal for same values [true,true]', () => {
    assert(deepEqual(true,true));
  });
  it('should return not equal for same values [false,true]', () => {
    assert(!deepEqual(false,true));
  });
  it('should return not equal for different values [-10,10]', () => {
    assert(!deepEqual(-10,10));
  });
  it('should return equal for [null, null]', () => {
    assert(deepEqual(null, null));
  });
  it('should return not equal for [10, null]', () => {
    assert(!deepEqual(10, null));
  });
  it('should return not equal [null, object]', () => {
    assert(!deepEqual(null,{ a: 10}));
  });
  it('should return equal [object1, object1]', () => {
    assert(deepEqual({a:10}, {a:10}));
  });
  it('should return not equal [object1, object2]', () => {
    assert(!deepEqual({a: 10}, {b: 10}));
  });
  it('should return not equal [object1, object2]', () => {
    assert(!deepEqual({a: 10}, {a: 50}));
  });
});


text:
namespace Pizza.Contracts
{
    public interface IViewModelBase
    {
        int Id { get; set; }
    }
}


text:
using Org.Apache.REEF.Network.Group.Pipelining;
using Org.Apache.REEF.Tang.Formats;
using Org.Apache.REEF.Tang.Util;
using Org.Apache.REEF.Wake.Remote;
using Org.Apache.REEF.Wake.StreamingCodec;

namespace Org.Apache.REEF.Network.Group.Config
{
    public sealed class CodecToStreamingCodecConfiguration<T> : ConfigurationModuleBuilder
    {
        /// <summary>
        /// RequiredImpl for Codec. Client needs to set implementation for this paramter
        /// </summary>
        public static readonly RequiredImpl<ICodec<T>> Codec = new RequiredImpl<ICodec<T>>();

        /// <summary>
        /// Configuration Module for Codec
        /// </summary>
        public static ConfigurationModule Conf = new CodecToStreamingCodecConfiguration<T>()
            .BindImplementation(GenericType<ICodec<T>>.Class, Codec)
            .BindImplementation(GenericType<IStreamingCodec<T>>.Class, GenericType<CodecToStreamingCodec<T>>.Class)
            .BindImplementation(GenericType<IStreamingCodec<PipelineMessage<T>>>.Class, GenericType<StreamingPipelineMessageCodec<T>>.Class)
            .Build();
    }
}


text:
layout: data_model
title: ObfuscationTechniquesType
this_version: 1.0
---

  Heads up! These docs are for STIX 1.0, which is not the latest version (1.2). View the latest!

ObfuscationTechniquesTypeCybOX Core Schema

The ObfuscationTechniquesType enables the description of a set of potential techniques an attacker could leverage to obfuscate the observability of this Observable.

      <form id="nav-version">
        <select>

            <option value="1.2" >STIX 1.2</option>

            <option value="1.1.1" >STIX 1.1.1</option>

            <option value="1.1" >STIX 1.1</option>

            <option value="1.0.1" >STIX 1.0.1</option>

            <option value="1.0" selected="selected">STIX 1.0</option>

        </select>
      </form>

Fields

      Field Name
      Type
      Description

      Obfuscation_Technique1..n

          ObfuscationTechniqueType

The Obfuscation_Technique field is optional and enables the description of a single potential technique an attacker could leverage to obfuscate the observability of this Observable.


text:
from cython.cimports.libcpp.vector import vector

@cython.cclass
class Matrix:
    ncols: cython.unsigned
    v: vector[cython.float]

    def __cinit__(self, ncols: cython.unsigned):
        self.ncols = ncols

    def add_row(self):
        """Adds a row, initially zero-filled."""
        self.v.resize(self.v.size() + self.ncols)


text:
module MiqAeServiceVmSpec
  describe MiqAeMethodService::MiqAeServiceVm do
    let(:vm)         { FactoryGirl.create(:vm_vmware, :name => "template1", :location => "abc/abc.vmx") }
    let(:service_vm) { MiqAeMethodService::MiqAeServiceManageIQ_Providers_Vmware_InfraManager_Vm.find(vm.id) }

    before(:each) do
      @user = FactoryGirl.create(:user_with_group)
      Spec::Support::MiqAutomateHelper.create_service_model_method('SPEC_DOMAIN', 'EVM', 'AUTOMATE', 'test1', 'test')
      @ae_method     = ::MiqAeMethod.first
      @ae_result_key = 'foo'

      @vm   = FactoryGirl.create(:vm_vmware, :name => "template1", :location => "abc/abc.vmx")
      allow(MiqServer).to receive(:my_zone).and_return('default')
    end

    def invoke_ae
      MiqAeEngine.instantiate("/EVM/AUTOMATE/test1?Vm::vm=#{@vm.id}", @user)
    end

    it "#ems_custom_keys" do
      method   = "$evm.root['#{@ae_result_key}'] = $evm.root['vm'].ems_custom_keys"
      @ae_method.update_attributes(:data => method)
      ae_object = invoke_ae.root(@ae_result_key)
      expect(ae_object).to be_kind_of(Array)
      expect(ae_object).to be_empty

      key1   = 'key1'
      value1 = 'value1'
      c1 = FactoryGirl.create(:ems_custom_attribute, :resource => @vm, :name => key1, :value => value1)
      ae_object = invoke_ae.root(@ae_result_key)
      expect(ae_object).to be_kind_of(Array)
      expect(ae_object.length).to eq(1)
      expect(ae_object.first).to eq(key1)

      key2   = 'key2'
      value2 = 'value2'
      c1 = FactoryGirl.create(:ems_custom_attribute, :resource => @vm, :name => key2, :value => value2)
      ae_object = invoke_ae.root(@ae_result_key)
      expect(ae_object).to be_kind_of(Array)
      expect(ae_object.length).to eq(2)
      expect(ae_object.sort).to eq([key1, key2])
    end

    it "#ems_custom_get" do
      key    = 'key1'
      value  = 'value1'
      method = "$evm.root['#{@ae_result_key}'] = $evm.root['vm'].ems_custom_get('#{key}')"
      @ae_method.update_attributes(:data => method)
      ae_object = invoke_ae.root(@ae_result_key)
      expect(ae_object).to be_nil

      c1 = FactoryGirl.create(:ems_custom_attribute, :resource => @vm, :name => key, :value => value)
      ae_object = invoke_ae.root(@ae_result_key)
      expect(ae_object).to eq(value)
    end

    it "#remove_from_vmdb" do
      expect(VmOrTemplate.count).to eq(1)
      method = "$evm.root['#{@ae_result_key}'] = $evm.root['vm'].remove_from_vmdb"
      @ae_method.update_attributes(:data => method)
      ae_object = invoke_ae.root(@ae_result_key)
      expect(VmOrTemplate.count).to eq(0)
    end

    context "with a service" do
      before(:each) do
        @service = FactoryGirl.create(:service)
      end

      context "#add_to_service" do
        it "without a service relationship" do
          method = "$evm.root['#{@ae_result_key}'] = $evm.root['vm'].add_to_service($evm.vmdb('service').first)"
          @ae_method.update_attributes(:data => method)
          ae_object = invoke_ae.root(@ae_result_key)

          expect(ae_object).to be_kind_of(MiqAeMethodService::MiqAeServiceServiceResource)
          expect(@service.vms.count).to eq(1)
        end

        it "with an existing service relationship" do
          @service.add_resource!(@vm)
          method = "$evm.root['#{@ae_result_key}'] = $evm.root['vm'].add_to_service($evm.vmdb('service').first)"
          @ae_method.update_attributes(:data => method)

          expect { invoke_ae.root(@ae_result_key) }.to raise_error(MiqAeException::AbortInstantiation)
        end
      end

      context "#remove_from_service" do
        it "without a service relationship" do
          method = "$evm.root['#{@ae_result_key}'] = $evm.root['vm'].remove_from_service"
          @ae_method.update_attributes(:data => method)

          expect(invoke_ae.root(@ae_result_key)).to be_nil
        end

        it "with an existing service relationship" do
          @service.add_resource!(@vm)
          method = "$evm.root['#{@ae_result_key}'] = $evm.root['vm'].remove_from_service"
          @ae_method.update_attributes(:data => method)

          expect(invoke_ae.root(@ae_result_key)).to be_kind_of(MiqAeMethodService::MiqAeServiceServiceResource)
        end
      end
    end

    it "#start_retirement" do
      expect(service_vm.retirement_state).to be_nil
      service_vm.start_retirement
      expect(service_vm.retirement_state).to eq("retiring")
    end

    it "#retire_now" do
      expect(MiqEvent).to receive(:raise_evm_event).once

      service_vm.retire_now
    end

    it "#finish_retirement" do
      expect(service_vm.retired).to be_nil
      expect(service_vm.retirement_state).to be_nil
      expect(service_vm.retires_on).to be_nil

      service_vm.finish_retirement

      expect(service_vm.retired).to be_truthy
      expect(service_vm.retires_on).to be_between(Time.zone.now - 1.hour, Time.zone.now + 1.second)
      expect(service_vm.retirement_state).to eq("retired")
    end

    it "#retiring? - false" do
      expect(service_vm.retiring?).to be_falsey
    end

    it "#retiring - true" do
      service_vm.retirement_state = 'retiring'

      expect(service_vm.retiring?).to be_truthy
    end

    it "#error_retiring? - false" do
      expect(service_vm.error_retiring?).to be_falsey
    end

    it "#error_retiring - true" do
      service_vm.retirement_state = 'error'

      expect(service_vm.error_retiring?).to be_truthy
    end

    it "#retires_on - today" do
      vm.update_attributes(:retirement_last_warn => Time.zone.now)
      service_vm.retires_on = Time.zone.now

      vm.reload
      expect(vm.retirement_last_warn).to be_nil
      expect(vm.retirement_due?).to be_truthy
    end

    it "#retires_on - tomorrow" do
      vm.update_attributes(
        :retired              => true,
        :retirement_last_warn => Time.zone.now,
        :retirement_state     => "retiring"
      )
      service_vm.retires_on = Time.zone.now + 1.day
      vm.reload

      expect(vm).to have_attributes(
        :retirement_last_warn => nil,
        :retired              => false,
        :retirement_state     => nil,
        :retirement_due?      => false
      )
    end

    it "#extend_retires_on - no retirement date set" do
      Timecop.freeze(Time.zone.now) do
        extend_days = 7
        service_vm.extend_retires_on(extend_days)
        vm.reload
        new_retires_on = Time.zone.now + extend_days.days
        expect(vm.retires_on.day).to eq(new_retires_on.day)
      end
    end

    it "#extend_retires_on - future retirement date set" do
      Timecop.freeze(Time.zone.now) do
        vm.update_attributes(
          :retired              => true,
          :retirement_last_warn => Time.zone.now,
          :retirement_state     => "retiring"
        )
        future_retires_on = Time.zone.now + 30.days
        service_vm.retires_on = future_retires_on
        extend_days = 7
        service_vm.extend_retires_on(extend_days, future_retires_on)
        vm.reload

        expect(vm).to have_attributes(
          :retirement_last_warn => nil,
          :retired              => false,
          :retirement_state     => nil,
          :retires_on           => future_retires_on + extend_days.days
        )
      end
    end

    it "#extend_retires_on - invalid date" do
      error_msg = "Invalid Date specified: #{Time.zone.today}"
      expect { service_vm.extend_retires_on(7, Time.zone.today) }.to raise_error(RuntimeError, error_msg)
    end

    it "#retirement_warn" do
      expect(service_vm.retirement_warn).to be_nil
      vm.retirement_last_warn = Time.zone.now
      service_vm.retirement_warn = 60

      vm.reload

      expect(service_vm.retirement_warn).to eq(60)
      expect(vm.retirement_last_warn).to be_nil
    end

    context "#create_snapshot" do
      it "without memory" do
        service_vm.create_snapshot('snap', 'crackle & pop')

        expect(MiqQueue.first.args.first).to have_attributes(
          :task        => 'create_snapshot',
          :memory      => false,
          :name        => 'snap',
          :description => 'crackle & pop'
        )
      end

      it "with memory" do
        service_vm.create_snapshot('snap', 'crackle & pop', true)

        expect(MiqQueue.first.args.first).to have_attributes(
          :task        => 'create_snapshot',
          :memory      => true,
          :name        => 'snap',
          :description => 'crackle & pop'
        )
      end

      it "when not supported" do
        vm_amazon = FactoryGirl.create(:vm_amazon, :name => "template1")
        svc_vm = MiqAeMethodService::MiqAeServiceManageIQ_Providers_Amazon_CloudManager_Vm.find(vm_amazon.id)

        expect { svc_vm.create_snapshot('snap', 'crackle & pop') }.to raise_error(RuntimeError)
      end
    end
  end
end


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../広/index.html">
<meta http-equiv=refresh content="0; url='../広/index.html'">

Redirecting...

Click here if you are not redirected.


text:
/**
 * @author Anton Avtamonov
 */

package javax.swing.plaf;

public abstract class ScrollPaneUI extends ComponentUI {

}


text:
function elem=delendelem(elem,mask)
%
% elem=delendelem(elem,mask)
%
% delete elements whose nodes are all edge nodes
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% date: 2007/11/24
%
% input/output:
%      elem: input/output, surface/volumetric element list
%      mask: of length of node number, =0 for internal nodes, =1 for edge nodes
%
% -- this function is part of iso2mesh toolbox (http://iso2mesh.sf.net)
%

badidx=sum(mask(elem)');
elem(find(badidx==size(elem,2)),:)=[];


text:
make clean
make

# Build example with multiple curves and RSA security level
gcc -O2 -std=c99 ./examples/example_all.c -I./include/ -I./target/default/include/ -L./target/default/lib/ -lamcl_core -lamcl_curve_BLS381 -lamcl_curve_ED25519 -lamcl_curve_GOLDILOCKS -lamcl_curve_NIST256 -lamcl_mpin_BLS381 -lamcl_pairing_BLS381 -lamcl_rsa_2048 -lamcl_rsa_3072 -lamcl_wcc_BLS381 -lamcl_x509 -o testall

# Run code
export LD_LIBRARY_PATH=./target/default/lib
./testall


text:
/**********************************************
 * Namespace for file-related functions
 **********************************************/

import Util from './Util';
import { getMetadata } from './public';
import Properties from './Properties';
import Timer from './Timer';
import GDriveService from './GDriveService';
import API from './API';
import MimeType from './MimeType';
import Constants from './Constants';
import ErrorMessages from './ErrorMessages';
import FeatureFlag from './FeatureFlag';
import Logging from './Logging';

export default class FileService {
  gDriveService: GDriveService;
  timer: Timer;
  properties: Properties;
  nativeMimeTypes: string[];
  maxNumberOfAttempts: number;

  constructor(
    gDriveService: GDriveService,
    timer: Timer,
    properties: Properties
  ) {
    this.gDriveService = gDriveService;
    this.timer = timer;
    this.properties = properties;
    this.nativeMimeTypes = [
      MimeType.DOC,
      MimeType.DRAWING,
      MimeType.FOLDER,
      MimeType.FORM,
      MimeType.SCRIPT,
      MimeType.SHEET,
      MimeType.SLIDES
    ];
    this.maxNumberOfAttempts = 3; // this is arbitrary, could go up or down
    return this;
  }

  /**
   * Try to copy file to destination parent, or add new folder if it's a folder
   */
  copyFile(
    file: gapi.client.drive.FileResource
  ): gapi.client.drive.FileResource {
    // if folder, use insert, else use copy
    if (file.mimeType == MimeType.FOLDER) {
      var r = this.gDriveService.insertFolder(
        API.copyFileBody(
          this.properties.map[file.parents[0].id],
          file.title,
          MimeType.FOLDER,
          file.description
        )
      );

      // Update list of remaining folders
      this.properties.remaining.push(file.id);

      // map source to destination
      this.properties.map[file.id] = r.id;

      return r;
    } else {
      return this.gDriveService.copyFile(
        API.copyFileBody(this.properties.map[file.parents[0].id], file.title),
        file.id
      );
    }
  }

  /**
   * copy permissions from source to destination file/folder
   */
  copyPermissions(
    srcId: string,
    owners: { emailAddress: string }[],
    destId: string
  ): void {
    var permissions, destPermissions, i, j;

    try {
      permissions = this.gDriveService.getPermissions(srcId).items;
    } catch (e) {
      Logging.log({ status: Util.composeErrorMsg(e) });
    }

    // copy editors, viewers, and commenters from src file to dest file
    if (permissions && permissions.length > 0) {
      for (i = 0; i < permissions.length; i++) {
        // if there is no email address, it is only sharable by link.
        // These permissions will not include an email address, but they will include an ID
        // Permissions.insert requests must include either value or id,
        // thus the need to differentiate between permission types
        try {
          if (permissions[i].emailAddress) {
            if (permissions[i].role == 'owner') continue;

            this.gDriveService.insertPermission(
              API.permissionBodyValue(
                permissions[i].role,
                permissions[i].type,
                permissions[i].emailAddress
              ),
              destId,
              {
                sendNotificationEmails: 'false'
              }
            );
          } else {
            this.gDriveService.insertPermission(
              API.permissionBodyId(
                permissions[i].role,
                permissions[i].type,
                permissions[i].id,
                permissions[i].withLink
              ),
              destId,
              {
                sendNotificationEmails: 'false'
              }
            );
          }
        } catch (e) {}
      }
    }

    // convert old owners to editors
    if (owners && owners.length > 0) {
      for (i = 0; i < owners.length; i++) {
        try {
          this.gDriveService.insertPermission(
            API.permissionBodyValue('writer', 'user', owners[i].emailAddress),
            destId,
            {
              sendNotificationEmails: 'false'
            }
          );
        } catch (e) {}
      }
    }

    // remove permissions that exist in dest but not source
    // these were most likely inherited from parent

    try {
      destPermissions = this.gDriveService.getPermissions(destId).items;
    } catch (e) {
      Logging.log({ status: Util.composeErrorMsg(e) });
    }

    if (destPermissions && destPermissions.length > 0) {
      for (i = 0; i < destPermissions.length; i++) {
        for (j = 0; j < permissions.length; j++) {
          if (destPermissions[i].id == permissions[j].id) {
            break;
          }
          // if destPermissions does not exist in permissions, delete it
          if (
            j == permissions.length - 1 &&
            destPermissions[i].role != 'owner'
          ) {
            this.gDriveService.removePermission(destId, destPermissions[i].id);
          }
        }
      }
    }
  }

  /**
   * Process leftover files from prior query results
   * that weren't processed before script timed out.
   * Destination folder must be set to the parent of the first leftover item.
   * The list of leftover items is an equivalent array to fileList returned from the getFiles() query
   */
  handleLeftovers(
    userProperties: GoogleAppsScript.Properties.UserProperties,
    ss: GoogleAppsScript.Spreadsheet.Sheet
  ): void {
    if (Util.hasSome(this.properties.leftovers, 'items')) {
      this.properties.currFolderId = this.properties.leftovers.items[0].parents[0].id;
      this.processFileList(this.properties.leftovers.items, userProperties, ss);
    }
  }

  handleRetries(
    userProperties: GoogleAppsScript.Properties.UserProperties,
    ss: GoogleAppsScript.Spreadsheet.Sheet
  ): void {
    if (Util.hasSome(this.properties, 'retryQueue')) {
      this.properties.currFolderId = this.properties.retryQueue[0].parents[0].id;
      this.processFileList(this.properties.retryQueue, userProperties, ss);
    }
  }

  /**
   * Loops through array of files.items,
   * Applies Drive function to each (i.e. copy),
   * Logs result,
   * Copies permissions if selected and if file is a Drive document,
   * Get current runtime and decide if processing needs to stop.
   */
  processFileList(
    items: gapi.client.drive.FileResource[],
    userProperties: GoogleAppsScript.Properties.UserProperties,
    ss: GoogleAppsScript.Spreadsheet.Sheet
  ): void {
    while (items.length > 0 && this.timer.canContinue()) {
      // Get next file from passed file list.
      var item = items.pop();

      if (
        item.numberOfAttempts &&
        item.numberOfAttempts > this.maxNumberOfAttempts
      ) {
        Logging.logCopyError(ss, item.error, item, this.properties.timeZone);
        continue;
      }

      if (FeatureFlag.SKIP_DUPLICATE_ID) {
        // if item has already been completed, skip to avoid infinite loop bugs
        if (this.properties.completed[item.id]) {
          continue;
        }
      }

      // Copy each (files and folders are both represented the same in Google Drive)
      try {
        var newfile = this.copyFile(item);

        if (FeatureFlag.SKIP_DUPLICATE_ID) {
          // record that this file has been processed
          this.properties.completed[item.id] = true;
        }

        // log the new file as successful
        Logging.logCopySuccess(ss, newfile, this.properties.timeZone);
      } catch (e) {
        this.properties.retryQueue.unshift({
          id: item.id,
          title: item.title,
          description: item.description,
          parents: item.parents,
          mimeType: item.mimeType,
          error: e,
          owners: item.owners,
          numberOfAttempts: item.numberOfAttempts
            ? item.numberOfAttempts + 1
            : 1
        });
      }

      // Copy permissions if selected, and if permissions exist to copy
      try {
        if (
          this.properties.copyPermissions &&
          this.nativeMimeTypes.indexOf(item.mimeType) !== -1
        ) {
          this.copyPermissions(item.id, item.owners, newfile.id);
        }
      } catch (e) {
        // TODO: logging needed for failed permissions copying?
      }

      // Update current runtime and user stop flag
      this.timer.update(userProperties);
    }
  }

  /**
   * Create the root folder of the new copy.
   * Copy permissions from source folder to destination folder if copyPermissions == yes
   */
  initializeDestinationFolder(
    options: FrontEndOptions,
    today: string
  ): gapi.client.drive.FileResource {
    var destFolder;
    var destParentID;
    switch (options.copyTo) {
      case 'same':
        destParentID = options.srcParentID;
        break;
      case 'custom':
        destParentID = options.destParentID;
        break;
      default:
        destParentID = this.gDriveService.getRootID();
    }

    if (
      options.copyTo === 'custom' &&
      FileService.isDescendant([options.destParentID], options.srcFolderID)
    ) {
      throw new Error(ErrorMessages.Descendant);
    }

    destFolder = this.gDriveService.insertFolder(
      API.copyFileBody(
        destParentID,
        options.destFolderName,
        'application/vnd.google-apps.folder',
        `Copy of ${options.srcFolderName}, created ${today}`
      )
    );

    if (options.copyPermissions) {
      this.copyPermissions(options.srcFolderID, null, destFolder.id);
    }

    return destFolder;
  }

  /**
   * Create the spreadsheet used for logging progress of the copy
   * @return {File Resource} metadata for logger spreadsheet, or error on fail
   */
  createLoggerSpreadsheet(
    today: string,
    destId: string
  ): gapi.client.drive.FileResource {
    return this.gDriveService.copyFile(
      API.copyFileBody(destId, `Copy Folder Log ${today}`),
      Constants.BaseCopyLogId
    );
  }

  /**
   * Create document that is used to store temporary properties information when the app pauses.
   * Create document as plain text.
   * This will be deleted upon script completion.
   */
  createPropertiesDocument(destId: string): string {
    var propertiesDoc = this.gDriveService.insertBlankFile(destId);
    return propertiesDoc.id;
  }

  findPriorCopy(
    folderId: string
  ): { spreadsheetId: string; propertiesDocId: string } {
    // find DO NOT MODIFY OR DELETE file (e.g. propertiesDoc)
    var query = `'${folderId}' in parents and title contains 'DO NOT DELETE OR MODIFY' and mimeType = '${
      MimeType.PLAINTEXT
    }'`;
    var p = this.gDriveService.getFiles(
      query,
      null,
      'modifiedDate,createdDate'
    );

    // find copy log
    query = `'${folderId}' in parents and title contains 'Copy Folder Log' and mimeType = '${
      MimeType.SHEET
    }'`;
    var s = this.gDriveService.getFiles(query, null, 'title desc');

    try {
      return {
        spreadsheetId: s.items[0].id,
        propertiesDocId: p.items[0].id
      };
    } catch (e) {
      throw new Error(ErrorMessages.DataFilesNotFound);
    }
  }

  /**
   * Determines if maybeChildID is a descendant of maybeParentID
   */
  static isDescendant(maybeChildIDs: string[], maybeParentID: string): boolean {
    // cannot select same folder
    for (var i = 0; i < maybeChildIDs.length; i++) {
      if (maybeChildIDs[i] === maybeParentID) {
        return true;
      }
    }

    var results = [];

    for (i = 0; i < maybeChildIDs.length; i++) {
      // get parents of maybeChildID
      var currentParents = getMetadata(maybeChildIDs[i]).parents;

      // if at root or no parents, stop
      if (!currentParents || currentParents.length === 0) {
        continue;
      }

      // check all parents
      for (i = 0; i < currentParents.length; i++) {
        if (currentParents[i].id === maybeParentID) {
          return true;
        }
      }

      // recursively check the parents of the parents
      results.push(
        FileService.isDescendant(
          currentParents.map(function(f) {
            return f.id;
          }),
          maybeParentID
        )
      );
    }

    // check results array for any positives
    for (i = 0; i < results.length; i++) {
      if (results[i]) {
        return true;
      }
    }
    return false;
  }

  static getFileLinkForSheet(id: string, title?: string): string {
    if (id) {
      return 'https://drive.google.com/open?id=' + id;
    }
    return '';
    // 2018-12-01: different locales use different delimiters. Simplify link so it works everywhere
    // return (
    //   '=HYPERLINK("https://drive.google.com/open?id=' + id + '","' + title + '")'
    // );
  }
}


text:
using System;
using System.Threading;

class ThreadStartStruct
{
    int iRet = -1;

    public struct MyStruct
    {
        public int myInt;
        public string myStr;
        public long myLong;
        public double myDouble;
        public Mutex myMutex;
    }

    public static int Main()
    {
        ThreadStartStruct tss = new ThreadStartStruct();
        return tss.Run();
    }

    private int Run()
    {
        MyStruct m = new MyStruct();
        m.myInt = Int32.MinValue;
        m.myStr = "This is the string";
        m.myLong = Int64.MaxValue;
        m.myDouble = Double.MinValue;
        m.myMutex = new Mutex(true);

        Thread t = new Thread(new ParameterizedThreadStart(ThreadWorker));
        t.Start(m);
        // Test to see if it passing an owned mutex
        Thread.Sleep(1000);
        m.myMutex.ReleaseMutex();
        t.Join();

        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return (100 == iRet ? 100 : -1);
    }

    private void ThreadWorker(Object o)
    {
        if(Int32.MinValue == ((MyStruct)o).myInt &&
            "This is the string" == ((MyStruct)o).myStr &&
            Int64.MaxValue == ((MyStruct)o).myLong &&
            Double.MinValue == ((MyStruct)o).myDouble)
        {
            try
            {
                ((MyStruct)o).myMutex.WaitOne();
                ((MyStruct)o).myMutex.ReleaseMutex();
                iRet = 100;
            }
            catch(Exception e)
            {
                Console.WriteLine("Unexpected exception thrown: " +
                    e.ToString());
            }
        }
    }
}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit5129ad2ce156b3dcd34bcc0f8df88329::getLoader();


text:
<?php

use im\catalog\Module;
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model im\catalog\models\Category */

$this->title = Module::t('category', 'Categories');
$this->params['subtitle'] = Module::t('category', 'Category updating');
$this->params['breadcrumbs'] = [['label' => $this->title, 'url' => ['index']], $this->params['subtitle']];
?>

<?= $this->params['subtitle'] ?>

            <?= Html::a('', ['delete', 'id' => $model->id], ['class' => 'btn btn-sm btn-default', 'title' => Module::t('module', 'Delete'), 'data-confirm' => Module::t('module', 'Are you sure you want to delete this item?'), 'data-method' => 'delete']) ?>

        <?= $this->render('_form', [
            'model' => $model
        ]) ?>