text:
package org.codehaus.groovy.ant;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyResourceLoader;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GroovyInternalPosixParser;
import org.apache.commons.cli.Options;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.RuntimeConfigurable;
import org.apache.tools.ant.taskdefs.Execute;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.util.GlobPatternMapper;
import org.apache.tools.ant.util.SourceFileScanner;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.SourceExtensionHandler;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.codehaus.groovy.runtime.DefaultGroovyStaticMethods;
import org.codehaus.groovy.tools.ErrorReporter;
import org.codehaus.groovy.tools.FileSystemCompiler;
import org.codehaus.groovy.tools.RootLoader;
import org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit;

/**
 * Compiles Groovy source files using Ant.
 *

 * Typically involves using Ant from the command-line and an Ant build file such as:
 *

 * <?xml version="1.0"?>
 * <project name="MyGroovyBuild" default="compile">
 *   <property name="groovy.home" value="/Path/To/Groovy"/>
 *   <property name="groovy.version" value="X.Y.Z"/>
 *   <path id="groovy.classpath">
 *     <fileset dir="${groovy.home}/embeddable">
 *       <include name="groovy-all-${groovy.version}.jar" />
 *     </fileset>
 *   </path>
 *   <taskdef name="groovyc" classname="org.codehaus.groovy.ant.Groovyc" classpathref="groovy.classpath"/>
 *
 *   <target name="compile" description="compile groovy sources">
 *     <groovyc srcdir="src" listfiles="true" classpathref="groovy.classpath"/>
 *   </target>
 * </project>
 *

 *

 * This task can take the following arguments:
 *

 *
srcdir

 *
scriptExtension

 *
targetBytecode

 *
destdir

 *
sourcepath

 *
sourcepathRef

 *
classpath

 *
classpathRef

 *
listfiles

 *
failonerror

 *
proceed

 *
memoryInitialSize

 *
memoryMaximumSize

 *
encoding

 *
verbose

 *
includeantruntime

 *
includejavaruntime

 *
fork

 *
javaHome

 *
executable

 *
updatedProperty

 *
errorProperty

 *
includeDestClasses

 *
jointCompilationOptions

 *
stacktrace

 *
indy

 *
scriptBaseClass

 *
stubdir

 *
keepStubs

 *
forceLookupUnnamedFiles

 *
configscript

 *

 * And these nested tasks:
 *

 *
javac

 *

 * Of these arguments, the srcdir and destdir are required.
 *

 *
When this task executes, it will recursively scan srcdir and destdir looking for Groovy source files
 * to compile. This task makes its compile decision based on timestamp.
 *

 * A more elaborate build file showing joint compilation:
 *

 * <?xml version="1.0"?>
 * <project name="MyJointBuild" default="compile">
 *   <property name="groovy.home" value="/Path/To/Groovy"/>
 *   <property name="groovy.version" value="X.Y.Z"/>
 *
 *   <path id="groovy.classpath">
 *     <fileset dir="${groovy.home}/embeddable">
 *       <include name="groovy-all-${groovy.version}.jar" />
 *     </fileset>
 *   </path>
 *
 *   <target name="clean" description="remove all built files">
 *     <delete dir="classes" />
 *   </target>
 *
 *   <target name="compile" depends="init" description="compile java and groovy sources">
 *     <mkdir dir="classes" />
 *     <groovyc destdir="classes" srcdir="src" listfiles="true" keepStubs="true" stubdir="stubs">
 *       <javac debug="on" deprecation="true"/>
 *       <classpath>
 *         <fileset dir="classes"/>
 *         <path refid="groovy.classpath"/>
 *       </classpath>
 *     </groovyc>
 *   </target>
 *
 *   <target name="init">
 *     <taskdef name="groovyc" classname="org.codehaus.groovy.ant.Groovyc" classpathref="groovy.classpath"/>
 *   </target>
 * </project>
 *

 *

 * Based heavily on the Javac implementation in Ant.
 *

 * Can also be used from {@link groovy.util.AntBuilder} to allow the build file to be scripted in Groovy.
 *
 * @author James Strachan
 * @author Hein Meling
 * @author Russel Winder
 * @author Danno Ferrin
 * @author Paul King
 */
public class Groovyc extends MatchingTask {
    private static final URL[] EMPTY_URL_ARRAY = new URL[0];
    private final LoggingHelper log = new LoggingHelper(this);

    private Path src;
    private File destDir;
    private Path compileClasspath;
    private Path compileSourcepath;
    private String encoding;
    private boolean stacktrace = false;
    private boolean verbose = false;
    private boolean includeAntRuntime = true;
    private boolean includeJavaRuntime = false;
    private boolean fork = false;
    private File forkJavaHome;
    private String forkedExecutable = null;
    private String memoryInitialSize;
    private String memoryMaximumSize;
    private String scriptExtension = "*.groovy";
    private String targetBytecode = null;

    protected boolean failOnError = true;
    protected boolean listFiles = false;
    protected File[] compileList = new File[0];

    private String updatedProperty;
    private String errorProperty;
    private boolean taskSuccess = true;
    private boolean includeDestClasses = true;

    protected CompilerConfiguration configuration;
    private Javac javac;
    private boolean jointCompilation;

    private List<File> temporaryFiles = new ArrayList<File>(2);
    private File stubDir;
    private boolean keepStubs;
    private boolean forceLookupUnnamedFiles;
    private boolean useIndy;
    private String scriptBaseClass;
    private String configscript;

    private Set<String> scriptExtensions = new LinkedHashSet<String>();

    /**
     * Adds a path for source compilation.
     *
     * @return a nested src element.
     */
    public Path createSrc() {
        if (src == null) {
            src = new Path(getProject());
        }
        return src.createPath();
    }

    /**
     * Recreate src.
     *
     * @return a nested src element.
     */
    protected Path recreateSrc() {
        src = null;
        return createSrc();
    }

    /**
     * Set the source directories to find the source Java files.
     *
     * @param srcDir the source directories as a path
     */
    public void setSrcdir(Path srcDir) {
        if (src == null) {
            src = srcDir;
        } else {
            src.append(srcDir);
        }
    }

    /**
     * Gets the source dirs to find the source java files.
     *
     * @return the source directories as a path
     */
    public Path getSrcdir() {
        return src;
    }

    /**
     * Set the extension to use when searching for Groovy source files.
     * Accepts extensions in the form *.groovy, .groovy or groovy
     *
     * @param scriptExtension the extension of Groovy source files
     */
    public void setScriptExtension(String scriptExtension) {
        if (scriptExtension.startsWith("*.")) {
            this.scriptExtension = scriptExtension;
        } else if (scriptExtension.startsWith(".")) {
            this.scriptExtension = "*" + scriptExtension;
        } else {
            this.scriptExtension = "*." + scriptExtension;
        }
    }

    /**
     * Get the extension to use when searching for Groovy source files.
     *
     * @return the extension of Groovy source files
     */
    public String getScriptExtension() {
        return scriptExtension;
    }

    /**
     * Sets the bytecode compatibility mode
     *
     * @param version the bytecode compatibility mode
     */
    public void setTargetBytecode(String version) {
        if (CompilerConfiguration.PRE_JDK5.equals(version) || CompilerConfiguration.POST_JDK5.equals(version)) {
            this.targetBytecode = version;
        }
    }

    /**
     * Retrieves the compiler bytecode compatibility mode.
     *
     * @return bytecode compatibility mode. Can be either <tt>1.5</tt> or <tt>1.4</tt>.
     */
    public String getTargetBytecode() {
        return this.targetBytecode;
    }

    /**
     * Set the destination directory into which the Java source
     * files should be compiled.
     *
     * @param destDir the destination director
     */
    public void setDestdir(File destDir) {
        this.destDir = destDir;
    }

    /**
     * Gets the destination directory into which the java source files
     * should be compiled.
     *
     * @return the destination directory
     */
    public File getDestdir() {
        return destDir;
    }

    /**
     * Set the sourcepath to be used for this compilation.
     *
     * @param sourcepath the source path
     */
    public void setSourcepath(Path sourcepath) {
        if (compileSourcepath == null) {
            compileSourcepath = sourcepath;
        } else {
            compileSourcepath.append(sourcepath);
        }
    }

    /**
     * Gets the sourcepath to be used for this compilation.
     *
     * @return the source path
     */
    public Path getSourcepath() {
        return compileSourcepath;
    }

    /**
     * Adds a path to sourcepath.
     *
     * @return a sourcepath to be configured
     */
    public Path createSourcepath() {
        if (compileSourcepath == null) {
            compileSourcepath = new Path(getProject());
        }
        return compileSourcepath.createPath();
    }

    /**
     * Adds a reference to a source path defined elsewhere.
     *
     * @param r a reference to a source path
     */
    public void setSourcepathRef(Reference r) {
        createSourcepath().setRefid(r);
    }

    /**
     * Set the classpath to be used for this compilation.
     *
     * @param classpath an Ant Path object containing the compilation classpath.
     */
    public void setClasspath(Path classpath) {
        if (compileClasspath == null) {
            compileClasspath = classpath;
        } else {
            compileClasspath.append(classpath);
        }
    }

    /**
     * Gets the classpath to be used for this compilation.
     *
     * @return the class path
     */
    public Path getClasspath() {
        return compileClasspath;
    }

    /**
     * Adds a path to the classpath.
     *
     * @return a class path to be configured
     */
    public Path createClasspath() {
        if (compileClasspath == null) {
            compileClasspath = new Path(getProject());
        }
        return compileClasspath.createPath();
    }

    /**
     * Adds a reference to a classpath defined elsewhere.
     *
     * @param r a reference to a classpath
     */
    public void setClasspathRef(Reference r) {
        createClasspath().setRefid(r);
    }

    /**
     * If true, list the source files being handed off to the compiler.
     * Default is false.
     *
     * @param list if true list the source files
     */
    public void setListfiles(boolean list) {
        listFiles = list;
    }

    /**
     * Get the listfiles flag.
     *
     * @return the listfiles flag
     */
    public boolean getListfiles() {
        return listFiles;
    }

    /**
     * Indicates whether the build will continue
     * even if there are compilation errors; defaults to true.
     *
     * @param fail if true halt the build on failure
     */
    public void setFailonerror(boolean fail) {
        failOnError = fail;
    }

    /**
     * @param proceed inverse of failonerror
     */
    public void setProceed(boolean proceed) {
        failOnError = !proceed;
    }

    /**
     * Gets the failonerror flag.
     *
     * @return the failonerror flag
     */
    public boolean getFailonerror() {
        return failOnError;
    }

    /**
     * The initial size of the memory for the underlying VM
     * if javac is run externally; ignored otherwise.
     * Defaults to the standard VM memory setting.
     * (Examples: 83886080, 81920k, or 80m)
     *
     * @param memoryInitialSize string to pass to VM
     */
    public void setMemoryInitialSize(String memoryInitialSize) {
        this.memoryInitialSize = memoryInitialSize;
    }

    /**
     * Gets the memoryInitialSize flag.
     *
     * @return the memoryInitialSize flag
     */
    public String getMemoryInitialSize() {
        return memoryInitialSize;
    }

    /**
     * The maximum size of the memory for the underlying VM
     * if javac is run externally; ignored otherwise.
     * Defaults to the standard VM memory setting.
     * (Examples: 83886080, 81920k, or 80m)
     *
     * @param memoryMaximumSize string to pass to VM
     */
    public void setMemoryMaximumSize(String memoryMaximumSize) {
        this.memoryMaximumSize = memoryMaximumSize;
    }

    /**
     * Gets the memoryMaximumSize flag.
     *
     * @return the memoryMaximumSize flag
     */
    public String getMemoryMaximumSize() {
        return memoryMaximumSize;
    }

    /**
     * Sets the file encoding for generated files.
     *
     * @param encoding the file encoding to be used
     */
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    /**
     * Returns the encoding to be used when creating files.
     *
     * @return the file encoding to use
     */
    public String getEncoding() {
        return encoding;
    }

    /**
     * Enable verbose compiling which will display which files
     * are being compiled. Default is false.
     */
    public void setVerbose(boolean verbose) {
        this.verbose = verbose;
    }

    /**
     * Gets the verbose flag.
     *
     * @return the verbose flag
     */
    public boolean getVerbose() {
        return verbose;
    }

    /**
     * If true, includes Ant's own classpath in the classpath. Default is true.
     * If setting to false and using groovyc in conjunction with AntBuilder
     * you might need to explicitly add the Groovy jar(s) to the groovyc
     * classpath using a nested classpath task.
     *
     * @param include if true, includes Ant's own classpath in the classpath
     */
    public void setIncludeantruntime(boolean include) {
        includeAntRuntime = include;
    }

    /**
     * Gets whether or not the ant classpath is to be included in the classpath.
     *
     * @return whether or not the ant classpath is to be included in the classpath
     */
    public boolean getIncludeantruntime() {
        return includeAntRuntime;
    }

    /**
     * If true, includes the Java runtime libraries in the classpath. Default is false.
     *
     * @param include if true, includes the Java runtime libraries in the classpath
     */
    public void setIncludejavaruntime(boolean include) {
        includeJavaRuntime = include;
    }

    /**
     * Gets whether or not the java runtime should be included in this
     * task's classpath.
     *
     * @return the includejavaruntime attribute
     */
    public boolean getIncludejavaruntime() {
        return includeJavaRuntime;
    }

    /**
     * If true forks the Groovy compiler. Default is false.
     *
     * @param f "true|false|on|off|yes|no"
     */
    public void setFork(boolean f) {
        fork = f;
    }

    /**
     * The JDK Home to use when forked.
     * Ignored if "executable" is specified.
     *
     * @param home the java.home value to use, default is the current JDK's home
     */
    public void setJavaHome(File home) {
        forkJavaHome = home;
    }

    /**
     * Sets the name of the java executable to use when
     * invoking the compiler in forked mode, ignored otherwise.
     *
     * @param forkExecPath the name of the executable
     * @since Groovy 1.8.7
     */
    public void setExecutable(String forkExecPath) {
        forkedExecutable = forkExecPath;
    }

    /**
     * The value of the executable attribute, if any.
     *
     * @return the name of the java executable
     * @since Groovy 1.8.7
     */
    public String getExecutable() {
        return forkedExecutable;
    }

    /**
     * The property to set on compilation success.
     * This property will not be set if the compilation
     * fails, or if there are no files to compile.
     *
     * @param updatedProperty the property name to use.
     */
    public void setUpdatedProperty(String updatedProperty) {
        this.updatedProperty = updatedProperty;
    }

    /**
     * The property to set on compilation failure.
     * This property will be set if the compilation
     * fails.
     *
     * @param errorProperty the property name to use.
     */
    public void setErrorProperty(String errorProperty) {
        this.errorProperty = errorProperty;
    }

    /**
     * This property controls whether to include the
     * destination classes directory in the classpath
     * given to the compiler.
     * The default value is "true".
     *
     * @param includeDestClasses the value to use.
     */
    public void setIncludeDestClasses(boolean includeDestClasses) {
        this.includeDestClasses = includeDestClasses;
    }

    /**
     * Get the value of the includeDestClasses property.
     *
     * @return the value.
     */
    public boolean isIncludeDestClasses() {
        return includeDestClasses;
    }

    /**
     * Get the result of the groovyc task (success or failure).
     *
     * @return true if compilation succeeded, or
     *         was not necessary, false if the compilation failed.
     */
    public boolean getTaskSuccess() {
        return taskSuccess;
    }

    /**
     * Add the configured nested javac task if present to initiate joint compilation.
     */
    public void addConfiguredJavac(final Javac javac) {
        this.javac = javac;
        jointCompilation = true;
    }

    /**
     * Enable compiler to report stack trace information if a problem occurs
     * during compilation. Default is false.
     */
    public void setStacktrace(boolean stacktrace) {
        this.stacktrace = stacktrace;
    }

    /**
     * Set the indy flag.
     *
     * @param useIndy the indy flag
     */
    public void setIndy(boolean useIndy) {
        this.useIndy = useIndy;
    }

    /**
     * Get the value of the indy flag.
     *
     * @return if to use indy
     */
    public boolean getIndy() {
        return this.useIndy;
    }

    /**
     * Set the base script class name for the scripts (must derive from Script)
     *
     * @param scriptBaseClass Base class name for scripts (must derive from Script)
     */
    public void setScriptBaseClass(String scriptBaseClass) {
        this.scriptBaseClass = scriptBaseClass;
    }

    /**
     * Get the base script class name for the scripts (must derive from Script)
     *
     * @return Base class name for scripts (must derive from Script)
     */
    public String getScriptBaseClass() {
        return this.scriptBaseClass;
    }

    /**
     * Get the configuration file used to customize the compilation configuration.
     *
     * @return a path to a configuration script
     */
    public String getConfigscript() {
        return configscript;
    }

    /**
     * Set the configuration file used to customize the compilation configuration.
     *
     * @param configscript a path to a configuration script
     */
    public void setConfigscript(final String configscript) {
        this.configscript = configscript;
    }

    /**
     * Set the stub directory into which the Java source stub
     * files should be generated. The directory need not exist
     * and will not be deleted automatically - though its contents
     * will be cleared unless 'keepStubs' is true. Ignored when forked.
     *
     * @param stubDir the stub directory
     */
    public void setStubdir(File stubDir) {
        jointCompilation = true;
        this.stubDir = stubDir;
    }

    /**
     * Gets the stub directory into which the Java source stub
     * files should be generated
     *
     * @return the stub directory
     */
    public File getStubdir() {
        return stubDir;
    }

    /**
     * Set the keepStubs flag. Defaults to false. Set to true for debugging.
     * Ignored when forked.
     *
     * @param keepStubs should stubs be retained
     */
    public void setKeepStubs(boolean keepStubs) {
        this.keepStubs = keepStubs;
    }

    /**
     * Gets the keepStubs flag.
     *
     * @return the keepStubs flag
     */
    public boolean getKeepStubs() {
        return keepStubs;
    }

    /**
     * Set the forceLookupUnnamedFiles flag. Defaults to false.
     *
     * The Groovyc Ant task is frequently used in the context of a build system
     * that knows the complete list of source files to be compiled. In such a
     * context, it is wasteful for the Groovy compiler to go searching the
     * classpath when looking for source files and hence by default the
     * Groovyc Ant task calls the compiler in a special mode with such searching
     * turned off. If you wish the compiler to search for source files then
     * you need to set this flag to {@code true}.
     *
     * @param forceLookupUnnamedFiles should unnamed source files be searched for on the classpath
     */
    public void setForceLookupUnnamedFiles(boolean forceLookupUnnamedFiles) {
        this.forceLookupUnnamedFiles = forceLookupUnnamedFiles;
    }

    /**
     * Gets the forceLookupUnnamedFiles flag.
     *
     * @return the forceLookupUnnamedFiles flag
     */
    public boolean getForceLookupUnnamedFiles() {
        return forceLookupUnnamedFiles;
    }

    /**
     * Executes the task.
     *
     * @throws BuildException if an error occurs
     */
    public void execute() throws BuildException {
        checkParameters();
        resetFileLists();
        loadRegisteredScriptExtensions();

        if (javac != null) jointCompilation = true;

        // scan source directories and dest directory to build up
        // compile lists
        String[] list = src.list();
        for (String filename : list) {
            File file = getProject().resolveFile(filename);
            if (!file.exists()) {
                throw new BuildException("srcdir \"" + file.getPath() + "\" does not exist!", getLocation());
            }
            DirectoryScanner ds = this.getDirectoryScanner(file);
            String[] files = ds.getIncludedFiles();
            scanDir(file, destDir != null ? destDir : file, files);
        }

        compile();
        if (updatedProperty != null
                && taskSuccess
                && compileList.length != 0) {
            getProject().setNewProperty(updatedProperty, "true");
        }
    }

    /**
     * Clear the list of files to be compiled and copied.
     */
    protected void resetFileLists() {
        compileList = new File[0];
        scriptExtensions = new LinkedHashSet<String>();
    }

    /**
     * Scans the directory looking for source files to be compiled.
     * The results are returned in the class variable compileList
     *
     * @param srcDir  The source directory
     * @param destDir The destination directory
     * @param files   An array of filenames
     */
    protected void scanDir(File srcDir, File destDir, String[] files) {
        GlobPatternMapper m = new GlobPatternMapper();
        SourceFileScanner sfs = new SourceFileScanner(this);
        File[] newFiles;
        for (String extension : getScriptExtensions()) {
            m.setFrom("*." + extension);
            m.setTo("*.class");
            newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m);
            addToCompileList(newFiles);
        }

        if (jointCompilation) {
            m.setFrom("*.java");
            m.setTo("*.class");
            newFiles = sfs.restrictAsFiles(files, srcDir, destDir, m);
            addToCompileList(newFiles);
        }
    }

    protected void addToCompileList(File[] newFiles) {
        if (newFiles.length > 0) {
            File[] newCompileList = new File[compileList.length + newFiles.length];
            System.arraycopy(compileList, 0, newCompileList, 0, compileList.length);
            System.arraycopy(newFiles, 0, newCompileList, compileList.length, newFiles.length);
            compileList = newCompileList;
        }
    }

    /**
     * Gets the list of files to be compiled.
     *
     * @return the list of files as an array
     */
    public File[] getFileList() {
        return compileList;
    }

    protected void checkParameters() throws BuildException {
        if (src == null) {
            throw new BuildException("srcdir attribute must be set!", getLocation());
        }
        if (src.size() == 0) {
            throw new BuildException("srcdir attribute must be set!", getLocation());
        }

        if (destDir != null && !destDir.isDirectory()) {
            throw new BuildException("destination directory \""
                    + destDir
                    + "\" does not exist or is not a directory",
                    getLocation());
        }

        if (encoding != null && !Charset.isSupported(encoding)) {
            throw new BuildException("encoding \"" + encoding + "\" not supported.");
        }
    }

    private void listFiles() {
        if (listFiles) {
            for (File srcFile : compileList) {
                log.info(srcFile.getAbsolutePath());
            }
        }
    }

    private List<String> extractJointOptions(Path classpath) {
        List<String> jointOptions = new ArrayList<String>();
        if (!jointCompilation) return jointOptions;

        // extract joint options, some get pushed up...
        RuntimeConfigurable rc = javac.getRuntimeConfigurableWrapper();
        for (Object o1 : rc.getAttributeMap().entrySet()) {
            final Map.Entry e = (Map.Entry) o1;
            final String key = e.getKey().toString();
            final String value = getProject().replaceProperties(e.getValue().toString());
            if (key.contains("debug")) {
                String level = "";
                if (javac.getDebugLevel() != null) {
                    level = ":" + javac.getDebugLevel();
                }
                jointOptions.add("-Fg" + level);
            } else if (key.contains("debugLevel")) {
                // ignore, taken care of in debug
            } else if ((key.contains("nowarn"))
                    || (key.contains("verbose"))
                    || (key.contains("deprecation"))) {
                // false is default, so something to do only in true case
                if ("on".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value))
                    jointOptions.add("-F" + key);
            } else if (key.contains("classpath")) {
                classpath.add(javac.getClasspath());
            } else if ((key.contains("depend"))
                    || (key.contains("extdirs"))
                    || (key.contains("encoding"))
                    || (key.contains("source"))
                    || (key.contains("target"))
                    || (key.contains("verbose"))) { // already handling verbose but pass on too
                jointOptions.add("-J" + key + "=" + value);
            } else {
                log.warn("The option " + key + " cannot be set on the contained <javac> element. The option will be ignored");
            }
            // TODO includes? excludes?
        }

        // ant's <javac> supports nested <compilerarg value=""> elements (there can be multiple of them)
        // for additional options to be passed to javac.
        Enumeration children = rc.getChildren();
        while (children.hasMoreElements()) {
            RuntimeConfigurable childrc = (RuntimeConfigurable) children.nextElement();
            if (childrc.getElementTag().equals("compilerarg")) {
                for (Object o : childrc.getAttributeMap().entrySet()) {
                    final Map.Entry e = (Map.Entry) o;
                    final String key = e.getKey().toString();
                    if (key.equals("value")) {
                        final String value = getProject().replaceProperties(e.getValue().toString());
                        StringTokenizer st = new StringTokenizer(value, " ");
                        while (st.hasMoreTokens()) {
                            String optionStr = st.nextToken();
                            String replaced = optionStr.replace("-X", "-FX");
                            if (optionStr.equals(replaced)) {
                                replaced = optionStr.replace("-W", "-FW"); // GROOVY-5063
                            }
                            jointOptions.add(replaced);
                        }
                    }
                }
            }
        }

        return jointOptions;
    }

    private void doForkCommandLineList(List<String> commandLineList, Path classpath, String separator) {
        if (!fork) return;

        if (includeAntRuntime) {
            classpath.addExisting((new Path(getProject())).concatSystemClasspath("last"));
        }
        if (includeJavaRuntime) {
            classpath.addJavaRuntime();
        }

        if (forkedExecutable != null && !forkedExecutable.equals("")) {
            commandLineList.add(forkedExecutable);
        } else {
            String javaHome;
            if (forkJavaHome != null) {
                javaHome = forkJavaHome.getPath();
            } else {
                javaHome = System.getProperty("java.home");
            }
            commandLineList.add(javaHome + separator + "bin" + separator + "java");
        }
        commandLineList.add("-classpath");
        commandLineList.add(classpath.toString());

        final String fileEncodingProp = System.getProperty("file.encoding");
        if ((fileEncodingProp != null) && !fileEncodingProp.equals("")) {
            commandLineList.add("-Dfile.encoding=" + fileEncodingProp);
        }
        if (targetBytecode != null) {
            commandLineList.add("-Dgroovy.target.bytecode=" + targetBytecode);
        }

        if ((memoryInitialSize != null) && !memoryInitialSize.equals("")) {
            commandLineList.add("-Xms" + memoryInitialSize);
        }
        if ((memoryMaximumSize != null) && !memoryMaximumSize.equals("")) {
            commandLineList.add("-Xmx" + memoryMaximumSize);
        }
        if (!"*.groovy".equals(getScriptExtension())) {
            String tmpExtension = getScriptExtension();
            if (tmpExtension.startsWith("*."))
                tmpExtension = tmpExtension.substring(1);
            commandLineList.add("-Dgroovy.default.scriptExtension=" + tmpExtension);
        }
        commandLineList.add(FileSystemCompilerFacade.class.getName());
        if (forceLookupUnnamedFiles) {
            commandLineList.add("--forceLookupUnnamedFiles");
        }
    }

    private void doNormalCommandLineList(List<String> commandLineList, List<String> jointOptions, Path classpath) {
        commandLineList.add("--classpath");
        commandLineList.add(classpath.toString());
        if (jointCompilation) {
            commandLineList.add("-j");
            commandLineList.addAll(jointOptions);
        }
        if (destDir != null) {
            commandLineList.add("-d");
            commandLineList.add(destDir.getPath());
        }
        if (encoding != null) {
            commandLineList.add("--encoding");
            commandLineList.add(encoding);
        }
        if (stacktrace) {
            commandLineList.add("-e");
        }
        if (useIndy) {
            commandLineList.add("--indy");
        }
        if (scriptBaseClass != null) {
            commandLineList.add("-b");
            commandLineList.add(scriptBaseClass);
        }
        if (configscript != null) {
            commandLineList.add("--configscript");
            commandLineList.add(configscript);
        }
    }

    private void addSourceFiles(List<String> commandLineList) {
        // check to see if an external file is needed
        int count = 0;
        if (fork) {
            for (File srcFile : compileList) {
                count += srcFile.getPath().length();
            }
            for (Object commandLineArg : commandLineList) {
                count += commandLineArg.toString().length();
            }
            count += compileList.length;
            count += commandLineList.size();
        }
        // 32767 is the command line length limit on Windows
        if (fork && (count > 32767)) {
            try {
                File tempFile = File.createTempFile("groovyc-files-", ".txt");
                temporaryFiles.add(tempFile);
                PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
                for (File srcFile : compileList) {
                    pw.println(srcFile.getPath());
                }
                pw.close();
                commandLineList.add("@" + tempFile.getPath());
            } catch (IOException e) {
                log.error("Error creating file list", e);
            }
        } else {
            for (File srcFile : compileList) {
                commandLineList.add(srcFile.getPath());
            }
        }
    }

    private String[] makeCommandLine(List<String> commandLineList) {
        final String[] commandLine = new String[commandLineList.size()];
        for (int i = 0; i < commandLine.length; ++i) {
            commandLine[i] = commandLineList.get(i);
        }
        log.verbose("Compilation arguments:");
        log.verbose(DefaultGroovyMethods.join(commandLine, "\n"));
        return commandLine;
    }

    private void runForked(String[] commandLine) {
        // use the main method in FileSystemCompiler
        final Execute executor = new Execute(); // new LogStreamHandler ( attributes , Project.MSG_INFO , Project.MSG_WARN ) ) ;
        executor.setAntRun(getProject());
        executor.setWorkingDirectory(getProject().getBaseDir());
        executor.setCommandline(commandLine);
        try {
            executor.execute();
        } catch (final IOException ioe) {
            throw new BuildException("Error running forked groovyc.", ioe);
        }
        final int returnCode = executor.getExitValue();
        if (returnCode != 0) {
            taskSuccess = false;
            if (errorProperty != null) {
                getProject().setNewProperty(errorProperty, "true");
            }
            if (failOnError) {
                throw new BuildException("Forked groovyc returned error code: " + returnCode);
            } else {
                log.error("Forked groovyc returned error code: " + returnCode);
            }
        }
    }

    private void runCompiler(String[] commandLine) {
        // hand crank it so we can add our own compiler configuration
        try {
            Options options = FileSystemCompiler.createCompilationOptions();

            CommandLineParser cliParser = new GroovyInternalPosixParser();

            CommandLine cli;
            cli = cliParser.parse(options, commandLine);

            configuration = FileSystemCompiler.generateCompilerConfigurationFromOptions(cli);
            configuration.setScriptExtensions(getScriptExtensions());
            String tmpExtension = getScriptExtension();
            if (tmpExtension.startsWith("*."))
                tmpExtension = tmpExtension.substring(1);
            configuration.setDefaultScriptExtension(tmpExtension);

            // Load the file name list
            String[] filenames = FileSystemCompiler.generateFileNamesFromOptions(cli);
            boolean fileNameErrors = filenames == null;

            fileNameErrors = fileNameErrors && !FileSystemCompiler.validateFiles(filenames);

            if (targetBytecode != null) {
                configuration.setTargetBytecode(targetBytecode);
            }

            if (!fileNameErrors) {
                FileSystemCompiler.doCompilation(configuration, makeCompileUnit(), filenames, forceLookupUnnamedFiles);
            }

        } catch (Exception re) {
            Throwable t = re;
            if ((re.getClass() == RuntimeException.class) && (re.getCause() != null)) {
                // unwrap to the real exception
                t = re.getCause();
            }
            StringWriter writer = new StringWriter();
            new ErrorReporter(t, false).write(new PrintWriter(writer));
            String message = writer.toString();

            taskSuccess = false;
            if (errorProperty != null) {
                getProject().setNewProperty(errorProperty, "true");
            }

            if (failOnError) {
                log.error(message);
                throw new BuildException("Compilation Failed", t, getLocation());
            } else {
                log.error(message);
            }
        }
    }

    protected void compile() {
        if (compileList.length == 0) return;

        try {
            log.info("Compiling " + compileList.length + " source file"
                    + (compileList.length == 1 ? "" : "s")
                    + (destDir != null ? " to " + destDir : ""));

            listFiles();
            Path classpath = getClasspath() != null ? getClasspath() : new Path(getProject());
            List<String> jointOptions = extractJointOptions(classpath);

            String separator = System.getProperty("file.separator");
            List<String> commandLineList = new ArrayList<String>();

            doForkCommandLineList(commandLineList, classpath, separator);
            doNormalCommandLineList(commandLineList, jointOptions, classpath);
            addSourceFiles(commandLineList);

            String[] commandLine = makeCommandLine(commandLineList);

            if (fork) {
                runForked(commandLine);
            } else {
                runCompiler(commandLine);
            }
        } finally {
            for (File temporaryFile : temporaryFiles) {
                try {
                    FileSystemCompiler.deleteRecursive(temporaryFile);
                } catch (Throwable t) {
                    System.err.println("error: could not delete temp files - " + temporaryFile.getPath());
                }
            }
        }
    }

    protected CompilationUnit makeCompileUnit() {
        Map<String, Object> options = configuration.getJointCompilationOptions();
        if (options != null) {
            if (keepStubs) {
                options.put("keepStubs", Boolean.TRUE);
            }
            if (stubDir != null) {
                options.put("stubDir", stubDir);
            } else {
                try {
                    File tempStubDir = DefaultGroovyStaticMethods.createTempDir(null, "groovy-generated-", "-java-source");
                    temporaryFiles.add(tempStubDir);
                    options.put("stubDir", tempStubDir);
                } catch (IOException ioe) {
                    throw new BuildException(ioe);
                }
            }
            return new JavaAwareCompilationUnit(configuration, buildClassLoaderFor());
        } else {
            return new CompilationUnit(configuration, null, buildClassLoaderFor());
        }
    }

    protected GroovyClassLoader buildClassLoaderFor() {
        // GROOVY-5044
        if (!fork && !getIncludeantruntime()) {
            throw new IllegalArgumentException("The includeAntRuntime=false option is not compatible with fork=false");
        }
        ClassLoader parent = getIncludeantruntime()
                ? getClass().getClassLoader()
                : new AntClassLoader(new RootLoader(EMPTY_URL_ARRAY, null), getProject(), getClasspath());
        if (parent instanceof AntClassLoader) {
            AntClassLoader antLoader = (AntClassLoader) parent;
            String[] pathElm = antLoader.getClasspath().split(File.pathSeparator);
            List<String> classpath = configuration.getClasspath();
            /*
             * Iterate over the classpath provided to groovyc, and add any missing path
             * entries to the AntClassLoader.  This is a workaround, since for some reason
             * 'directory' classpath entries were not added to the AntClassLoader' classpath.
             */
            for (String cpEntry : classpath) {
                boolean found = false;
                for (String path : pathElm) {
                    if (cpEntry.equals(path)) {
                        found = true;
                        break;
                    }
                }
                /*
                 * fix for GROOVY-2284
                 * seems like AntClassLoader doesn't check if the file
                 * may not exist in the classpath yet
                 */
                if (!found && new File(cpEntry).exists()) {
                	try {
                		antLoader.addPathElement(cpEntry);
                	}
                	catch(BuildException e) {
                		log.warn("The classpath entry " + cpEntry + " is not a valid Java resource");
                	}
                }
            }
        }

        GroovyClassLoader loader = new GroovyClassLoader(parent, configuration);
        if (!forceLookupUnnamedFiles) {
            // in normal case we don't need to do script lookups
            loader.setResourceLoader(new GroovyResourceLoader() {
                public URL loadGroovySource(String filename) throws MalformedURLException {
                    return null;
                }
            });
        }
        return loader;
    }

    private Set<String> getScriptExtensions() {
        return scriptExtensions;
    }

    private void loadRegisteredScriptExtensions() {
        if (scriptExtensions.isEmpty()) {

            scriptExtensions.add(getScriptExtension().substring(2)); // first extension will be the one set explicitly on <groovyc>

            Path classpath = getClasspath() != null ? getClasspath() : new Path(getProject());
            final String[] pe = classpath.list();
            final GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader());
            for (String file : pe) {
                loader.addClasspath(file);
            }
            scriptExtensions.addAll(SourceExtensionHandler.getRegisteredExtensions(loader));
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Shop.Web.Model
{
    public interface IModel
    {
    }
}

redpajama_set_name: RedPajamaGithub


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

    <groupId>WebMoneyBanking</groupId>
    <artifactId>WebMoney</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>


text:
package org.elasticsearch.search.facet.terms.index;

import com.google.common.collect.Sets;
import org.apache.lucene.index.AtomicReaderContext;
import org.elasticsearch.search.facet.FacetExecutor;
import org.elasticsearch.search.facet.InternalFacet;
import org.elasticsearch.search.facet.terms.TermsFacet;
import org.elasticsearch.search.facet.terms.strings.InternalStringTermsFacet;

import java.io.IOException;

/**
 *
 */
public class IndexNameFacetExecutor extends FacetExecutor {

    private final String indexName;
    private final InternalStringTermsFacet.ComparatorType comparatorType;
    private final int size;

    private int count = 0;

    public IndexNameFacetExecutor(String indexName, TermsFacet.ComparatorType comparatorType, int size) {
        this.indexName = indexName;
        this.comparatorType = comparatorType;
        this.size = size;
    }

    @Override
    public Collector collector() {
        return new Collector();
    }

    @Override
    public InternalFacet buildFacet(String facetName) {
        return new InternalStringTermsFacet(facetName, comparatorType, size, Sets.newHashSet(new InternalStringTermsFacet.TermEntry(indexName, count)), 0, count);
    }

    class Collector extends FacetExecutor.Collector {

        private int count;

        @Override
        public void setNextReader(AtomicReaderContext context) throws IOException {
        }

        @Override
        public void collect(int doc) throws IOException {
            count++;
        }

        @Override
        public void postCollection() {
            IndexNameFacetExecutor.this.count = count;
        }
    }
}


text:
u"""RCSCON execution template.

:copyright: Copyright (c) 2019 RadiaSoft LLC.  All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkcompat
from pykern import pkio
from pykern.pkcollections import PKDict
from pykern.pkdebug import pkdp, pkdc, pkdlog
from sirepo import simulation_db
from sirepo.template import template_common
import numpy
import os
import re
import sirepo.sim_data

_SIM_DATA, SIM_TYPE, _SCHEMA = sirepo.sim_data.template_globals()

_OUTPUT_FILE = PKDict(
    fitOutputFile='fit.csv',
    predictOutputFile='predict.csv',
    testOutputFile='test.csv',
)

def background_percent_complete(report, run_dir, is_running):
    res = PKDict(
        percentComplete=0,
        frameCount=0,
    )
    if report == 'partitionAnimation':
        if not is_running and run_dir.join('x-train.csv').exists():
            res.percentComplete = 100
            res.frameCount = 1;
        return res
    if report == 'elegantAnimation':
        if not is_running and run_dir.join('inputs.csv').exists():
            _compute_elegant_result_columns(run_dir, res)
        return res
    csv_file = run_dir.join(_OUTPUT_FILE.fitOutputFile)
    if csv_file.exists():
        line = _read_last_line(csv_file)
        m = re.search(r'^(\d+)', line)
        if m and int(m.group(1)) > 0:
            data = simulation_db.read_json(run_dir.join(template_common.INPUT_BASE_NAME))
            max_frame = data.models.neuralNet.epochs
            res.frameCount = int(m.group(1)) + 1
            res.percentComplete = float(res.frameCount) * 100 / max_frame
    return res

def extract_report_data(run_dir, sim_in):
    if 'mlModelGraph' in sim_in.report:
        svg = pkio.read_text('modelGraph.svg')
        template_common.write_sequential_result(
            PKDict(svg=svg),
            run_dir=run_dir,
        )
        return
    if sim_in.report == 'partitionSelectionReport':
        template_common.write_sequential_result(
            _extract_partition_selection(run_dir, sim_in),
            run_dir=run_dir,
        )
        return
    assert 'fileColumnReport' in sim_in.report
    idx = sim_in.models[sim_in.report].columnNumber
    x, y, col_name, source_name = _extract_column(run_dir, sim_in, idx)
    template_common.write_sequential_result(
        _plot_info(
            x,
            [
                PKDict(
                    points=y.tolist(),
                    label='',
                ),
            ],
            col_name,
        ),
        run_dir=run_dir,
    )

def get_application_data(data, **kwargs):
    if data.method == 'compute_column_count':
        return _compute_file_column_count(data.files)
    assert False, 'unknown get_application_data: {}'.format(data)

def get_data_file(run_dir, model, frame, options=None, **kwargs):
    sim_in = simulation_db.read_json(run_dir.join(template_common.INPUT_BASE_NAME))
    f = sim_in.models.files
    if 'fileColumnReport' in model:
        source = _input_or_output(
            sim_in,
            int(re.search(r'(\d+)$', model).group(1)),
            'inputs',
            'outputs',
        )[0]
        return _SIM_DATA.lib_file_name_with_model_field(
            'files',
            source,
            sim_in.models.files[source],
        )
    if model == 'partitionSelectionReport' or 'partitionAnimation' in model:
        return _SIM_DATA.lib_file_name_with_model_field(
            'files',
            'inputs',
            sim_in.models.files.inputs,
        )
    if model == 'epochAnimation':
        return _OUTPUT_FILE.fitOutputFile
    if 'fitAnimation' in model:
        return PKDict(
            content=run_dir.join(_OUTPUT_FILE.testOutputFile).read_text() \
                + run_dir.join(_OUTPUT_FILE.predictOutputFile).read_text(),
            uri='test-and-predict.csv',
        )
    raise AssertionError('unknown model: {}'.format(model))

def prepare_sequential_output_file(run_dir, sim_in):
    if 'fileColumnReport' not in sim_in.report:
        return
    fn = simulation_db.json_filename(template_common.OUTPUT_BASE_NAME, run_dir)
    if fn.exists():
        fn.remove()
        extract_report_data(run_dir, sim_in)

def python_source_for_model(data, model):
    return _generate_parameters_file(data)

def sim_frame(frame_args):
    if frame_args.frameReport == 'epochAnimation':
        return _epoch_animation(frame_args)
    if 'partitionAnimation' in frame_args.frameReport:
        return _partition_animation(frame_args)
    return _fit_animation(frame_args)

def write_parameters(data, run_dir, is_parallel):
    pkio.write_text(
        run_dir.join(template_common.PARAMETERS_PYTHON_FILE),
        _generate_parameters_file(data),
    )

def _compute_column_count(file_dir, input_filename, output_filename, res):
    count = 0
    for info in (['inputs', input_filename], ['outputs', output_filename]):
        header = _read_csv_header_columns(file_dir.join(info[1]))
        count += len(header)
        res['{}Count'.format(info[0])] = len(header)
    res.columnCount = count
    return res

def _compute_elegant_result_columns(run_dir, res):
    return _compute_column_count(run_dir, 'inputs.csv', 'outputs.csv', res)

def _compute_file_column_count(files):
    return _compute_column_count(
        simulation_db.simulation_lib_dir(SIM_TYPE),
        _SIM_DATA.lib_file_name_with_model_field('files', 'inputs', files.inputs),
        _SIM_DATA.lib_file_name_with_model_field('files', 'outputs', files.outputs),
        files,
    )

def _epoch_animation(frame_args):
    header, v = _read_file(frame_args.run_dir, _OUTPUT_FILE.fitOutputFile)
    return _plot_info(
        v[:, 0],
        [PKDict(
            points=v[:, i].tolist(),
            label=header[i],
        ) for i in (1, 2)],
    ).pkupdate(x_label=header[0])

def _extract_column(run_dir, sim_in, idx):
    source, idx = _input_or_output(sim_in, idx, 'inputs', 'outputs')
    header, v = _read_file(run_dir, _SIM_DATA.rcscon_filename(sim_in, 'files', source))
    y = v[:, idx]
    x = numpy.arange(0, len(y))
    return x, y, header[idx], source

def _extract_partition_selection(run_dir, sim_in):
    # return report with input0 and output0
    x, in0, in_col, _ = _extract_column(run_dir, sim_in, 0)
    _, out0, out_col, _ = _extract_column(run_dir, sim_in, sim_in.models.files.inputsCount)
    return _plot_info(
        x,
        [
            PKDict(
                points=in0.tolist(),
                label=in_col,
            ),
            PKDict(
                points=out0.tolist(),
                label=out_col,
            ),
        ],
    )

def _fit_animation(frame_args):
    idx = int(frame_args.columnNumber)
    header, v = _read_file(frame_args.run_dir, _OUTPUT_FILE.predictOutputFile)
    _, y = _read_file(frame_args.run_dir, _OUTPUT_FILE.testOutputFile)
    frame_args.histogramBins = 30
    return template_common.heatmap(
        [v[:, idx], y[:, idx]],
        frame_args,
        PKDict(
            x_label='',
            y_label='',
            title=header[idx],
            hideColorBar=True,
        ),
    )

def _generate_elegant_simulation(data):
    vars_by_name = PKDict({x.name : x.value for x in data.models.rpnVariables})
    for m in ('elegantAnimation', 'latticeSettings', 'rfcSettings'):
        for f in data.models[m]:
            vars_by_name[f] = data.models[m][f]
    data.models.rpnVariables = [PKDict(name=n, value=v) for n,v in vars_by_name.items()]
    data.models.simulation.update(
        simulationMode='serial',
    )
    from sirepo.template import elegant
    return elegant.rcscon_generate_lattice(data)

def _generate_parameters_file(data):
    report = data.get('report', '')
    if report == 'elegantAnimation':
        return _generate_elegant_simulation(data)
    res, v = template_common.generate_parameters_file(data)
    res += 'from __future__ import absolute_import, division, print_function\n'
    infile = _SIM_DATA.rcscon_filename(data, 'files', 'inputs')
    outfile = _SIM_DATA.rcscon_filename(data, 'files', 'outputs')
    v.pkupdate(
        inputsFileName=infile,
        outputsFileName=outfile,
        layerImplementationNames=_layer_implementation_list(data),
        neuralNetLayers=data.models.neuralNet.layers,
        inputDim=data.models.files.inputsCount,
    ).pkupdate(_OUTPUT_FILE)
    if 'mlModelGraph' in report:
        res += template_common.render_jinja(SIM_TYPE, v, 'build-model.py')
        res += template_common.render_jinja(SIM_TYPE, v, 'graph.py')
        return res
    res += template_common.render_jinja(SIM_TYPE, v, 'scale.py')
    if 'fileColumnReport' in report or report == 'partitionSelectionReport':
        return res
    v.hasTrainingAndTesting = v.partition_section0 == 'train_and_test' \
        or v.partition_section1 == 'train_and_test' \
        or v.partition_section2 == 'train_and_test'
    res += template_common.render_jinja(SIM_TYPE, v, 'partition.py')
    if 'partitionAnimation' in report:
        res += template_common.render_jinja(SIM_TYPE, v, 'save-partition.py')
        return res
    res += template_common.render_jinja(SIM_TYPE, v, 'build-model.py')
    res += template_common.render_jinja(SIM_TYPE, v, 'train.py')
    return res

def _input_or_output(sim_in, idx, input_field, output_field):
    res = input_field
    if idx >= sim_in.models.files.inputsCount:
        res = output_field
        idx -= sim_in.models.files.inputsCount
    return res, idx

def _layer_implementation_list(data):
    res = {}
    for layer in data.models.neuralNet.layers:
        res[layer.layer] = 1
    return res.keys()

def _histogram_plot(values, vrange):
    hist = numpy.histogram(values, bins=20, range=vrange)
    x = []
    y = []
    for i in range(len(hist[0])):
        x.append(hist[1][i])
        x.append(hist[1][i + 1])
        y.append(hist[0][i])
        y.append(hist[0][i])
    x.insert(0, x[0])
    y.insert(0, 0)
    return x, y

def _update_range(vrange, values):
    minv = min(values)
    maxv = max(values)
    if not vrange:
        vrange.append(minv)
        vrange.append(maxv)
        return
    if vrange[0] > minv:
        vrange[0] = minv
    if vrange[1] < maxv:
        vrange[1] = maxv

def _partition_animation(frame_args):
    sim_in = frame_args.sim_in
    idx = int(frame_args.columnNumber)
    source, idx = _input_or_output(sim_in, idx, 'x', 'y')
    header, train = _read_file(frame_args.run_dir, '{}-train.csv'.format(source))
    _, test = _read_file(frame_args.run_dir, '{}-test.csv'.format(source))
    _, validate = _read_file(frame_args.run_dir, '{}-validate.csv'.format(source))
    d = PKDict(
        train=train[:, idx],
        test=test[:, idx],
        validate=validate[:, idx],
    )
    plots = []
    r = []
    for name in ('train', 'test', 'validate'):
        _update_range(r, d[name])
    for name in ('train', 'test', 'validate'):
        x, y = _histogram_plot(d[name], r)
        plots.append(
            PKDict(
                points=y,
                label=name,
            ),
        )
    return _plot_info(numpy.array(x), plots, title=header[idx])

def _plot_info(x, plots, title=''):
    return PKDict(
        title=title,
        x_range=[float(min(x)), float(max(x))],
        y_label='',
        x_label='',
        x_points=x.tolist(),
        plots=plots,
        y_range=template_common.compute_plot_color_and_range(plots),
    )

def _read_csv_header_columns(path):
    import csv

    with open(str(path)) as f:
        for row in csv.reader(f):
            return row
    return None

def _read_file(run_dir, filename):
    path = str(run_dir.join(filename))
    v = numpy.genfromtxt(path, delimiter=',', skip_header=1)
    if len(v.shape) == 1:
        v.shape = (v.shape[0], 1)
    return _read_csv_header_columns(path), v

def _read_last_line(path):
    # for performance, don't read whole file if only last line is needed
    try:
        with open(str(path), 'rb') as f:
            f.readline()
            f.seek(-2, os.SEEK_END)
            while f.read(1) != b'\n':
                f.seek(-2, os.SEEK_CUR)
            return pkcompat.from_bytes(f.readline())
    except IOError:
        return ''


text:
{% extends "base.html" %}{% load i18n %}
{% block title %}{% trans "Login" %}{% endblock %}
{% block content %}
{% if form.errors %}

{% trans "Your username and password didn't match. Please try again." %}

{% endif %}

{% trans "Log in" %}

<form method="post" action="{% url django.contrib.auth.views.login %}">
    {% csrf_token %}
    {% for field in form %}
    {% include "forms/form_field.html" %}
    {% endfor %}
    <input type="submit" value="{% trans "Log in" %}" />
    <input type="hidden" name="next" value="{{ next }}" />
</form>

{% trans "Do you need an account" %}?

{% trans "Don't you remember your password" %}?

{% endblock %}


text:
NS_ASSUME_NONNULL_BEGIN

void LNKPrintVector(const char *name, LNKFloat *vector, LNKSize n);
void LNKPrintMatrix(const char *name, LNKFloat *matrix, LNKSize m, LNKSize n);

/// The matrix data is loaded in column-major order.
NSData *__nullable LNKLoadBinaryMatrixFromFileAtURL(NSURL *url, LNKSize expectedLength);

NS_ASSUME_NONNULL_END


text:
package test;
public class Wibble {
  public void foo() {
    System.out.println("Wibble.foo() running, version 1");
  }
}


text:
/**
 * Factory for CRUD model routes
 *
 * Example usage (without auth middleware)
 *
 * exports.get = modelRoute.get(User);
 * exports.put = modelRoute.put(User);
 * exports.post = modelRoute.post(User, function(req, res, instance) {
 *     instance.joined = new Date();
 * });
 * exports.delete = modelRoute.delete(User);
 */

exports.get = function(model) {
    return function(req, res) {
        model.findOne({ _id: req.params.id }, function(err, instance) {
            if (err) return res.json(500, {"error": err});
            if (!instance) return res.json(404, {"error": "Who?"});
            res.json(instance);
        });
    };
};

exports.put = function(model, pre) {
    return function(req, res){
        model.findOne({ _id: req.params.id }, function(err, instance) {
            if (err) return res.json(500, {"error": err});
            if (!instance) return res.json(404, {"error": "Who?"});
            // todo validation, etc.
            model.schema.eachPath(function(path, details) {
                if (req.body[path] === undefined) return;
                instance[path] = req.body[path];
            });
            if (pre) pre(req, res, instance);
            instance.save(function (err) {
                if (err) return res.json(500, {"error": err});
                res.json(instance);
            });
        });
    };
};

exports.post = function(model, pre) {
    return function(req, res){
        // todo validation, etc.
        var instance = new model();
        model.schema.eachPath(function(path, details) {
            if (req.body[path] === undefined) return;
            instance[path] = req.body[path];
        });
        if (pre) pre(req, res, instance);
        instance.save(function (err) {
            if (err) return res.json(500, {"error": err});
            res.json(201, instance);
        });
    };
};

exports.delete = function(model) {
    return function(req, res){
        model.remove({ _id: req.params.id }, function(err) {
            if (err) return res.json(500, {"error": err});
            res.json({"success": 1});
        });
    };
};


text:
{
    'name': 'Customer Profiling',
    'version': '1.3',
    'category': 'Marketing',
    'description': """
This module allows users to perform segmentation within partners.
=================================================================

It uses the profiles criteria from the earlier segmentation module and improve it.
Thanks to the new concept of questionnaire. You can now regroup questions into a
questionnaire and directly use it on a partner.

It also has been merged with the earlier CRM & SRM segmentation tool because they
were overlapping.

    **Note:** this module is not compatible with the module segmentation, since it's the same which has been renamed.
    """,
    'author': 'OpenERP SA',
    'website': 'https://www.odoo.com/page/crm',
    'depends': ['base', 'crm'],
    'data': ['security/ir.model.access.csv', 'wizard/open_questionnaire_view.xml', 'crm_profiling_view.xml'],
    'demo': ['crm_profiling_demo.xml'],
    'test': [
        #'test/process/profiling.yml', #TODO:It's not debuging because problem to write data for open.questionnaire from partner section.
    ],
    'installable': True,
    'auto_install': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
package io.techcode.streamy.kafka.util

import akka.kafka.testkit.scaladsl.{ScalatestKafkaSpec, TestcontainersKafkaLike}
import org.scalatest.concurrent.{Eventually, ScalaFutures}
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

/**
  * Helper for kafka spec.
  */
abstract class KafkaSpec(kafkaPort: Int) extends ScalatestKafkaSpec(kafkaPort) with TestcontainersKafkaLike
  with AnyWordSpecLike with Matchers with ScalaFutures with Eventually {

  protected def this() = this(kafkaPort = -1)

  def sleep(): Unit = Thread.sleep(KafkaSpec.TestSleep)

}

object KafkaSpec {
  val TestSleep: Long = 10000L
}


text:
namespace gfx {
class Canvas;
class ImageSkia;
class Rect;
class Size;
}

namespace ui {

// Theme support for non-Windows toolkits.
class NATIVE_THEME_EXPORT NativeThemeBase : public NativeTheme {
 public:
  // NativeTheme implementation:
  gfx::Size GetPartSize(Part part,
                        State state,
                        const ExtraParams& extra) const override;
  void Paint(SkCanvas* canvas,
             Part part,
             State state,
             const gfx::Rect& rect,
             const ExtraParams& extra) const override;

  void PaintStateTransition(SkCanvas* canvas,
                            Part part,
                            State startState,
                            State endState,
                            double progress,
                            const gfx::Rect& rect) const override;

 protected:
  NativeThemeBase();
  ~NativeThemeBase() override;

  // Draw the arrow. Used by scrollbar and inner spin button.
  virtual void PaintArrowButton(
      SkCanvas* gc,
      const gfx::Rect& rect,
      Part direction,
      State state) const;
  // Paint the scrollbar track. Done before the thumb so that it can contain
  // alpha.
  virtual void PaintScrollbarTrack(
      SkCanvas* canvas,
      Part part,
      State state,
      const ScrollbarTrackExtraParams& extra_params,
      const gfx::Rect& rect) const;
  // Draw the scrollbar thumb over the track.
  virtual void PaintScrollbarThumb(
      SkCanvas* canvas,
      Part part,
      State state,
      const gfx::Rect& rect) const;

  virtual void PaintScrollbarCorner(SkCanvas* canvas,
                                    State state,
                                    const gfx::Rect& rect) const;

  virtual void PaintCheckbox(
      SkCanvas* canvas,
      State state,
      const gfx::Rect& rect,
      const ButtonExtraParams& button) const;

  virtual void PaintRadio(
      SkCanvas* canvas,
      State state,
      const gfx::Rect& rect,
      const ButtonExtraParams& button) const;

  virtual void PaintButton(
      SkCanvas* canvas,
      State state,
      const gfx::Rect& rect,
      const ButtonExtraParams& button) const;

  virtual void PaintTextField(
      SkCanvas* canvas,
      State state,
      const gfx::Rect& rect,
      const TextFieldExtraParams& text) const;

  virtual void PaintMenuList(
      SkCanvas* canvas,
      State state,
      const gfx::Rect& rect,
      const MenuListExtraParams& menu_list) const;

  virtual void PaintMenuPopupBackground(
      SkCanvas* canvas,
      const gfx::Size& size,
      const MenuBackgroundExtraParams& menu_background) const;

  virtual void PaintMenuItemBackground(
      SkCanvas* canvas,
      State state,
      const gfx::Rect& rect,
      const MenuItemExtraParams& menu_item) const;

  virtual void PaintSliderTrack(
      SkCanvas* canvas,
      State state,
      const gfx::Rect& rect,
      const SliderExtraParams& slider) const;

  virtual void PaintSliderThumb(
      SkCanvas* canvas,
      State state,
      const gfx::Rect& rect,
      const SliderExtraParams& slider) const;

  virtual void PaintInnerSpinButton(
      SkCanvas* canvas,
      State state,
      const gfx::Rect& rect,
      const InnerSpinButtonExtraParams& spin_button) const;

  virtual void PaintProgressBar(
      SkCanvas* canvas,
      State state,
      const gfx::Rect& rect,
      const ProgressBarExtraParams& progress_bar) const;

  virtual void PaintScrollbarThumbStateTransition(SkCanvas* canvas,
                                                  Part part,
                                                  State startState,
                                                  State endState,
                                                  double progress,
                                                  const gfx::Rect& rect) const {
  }

  // Shrinks checkbox/radio button rect, if necessary, to make room for padding
  // and drop shadow.
  // TODO(mohsen): This is needed because checkboxes/radio buttons on Android
  // have different padding from those on desktop Chrome. Get rid of this when
  // crbug.com/530746 is resolved.
  virtual void AdjustCheckboxRadioRectForPadding(SkRect* rect) const;

  void set_scrollbar_button_length(unsigned int length) {
    scrollbar_button_length_ = length;
  }
  int scrollbar_button_length() const { return scrollbar_button_length_; }

  void DrawImageInt(SkCanvas* canvas, const gfx::ImageSkia& image,
                    int src_x, int src_y, int src_w, int src_h,
                    int dest_x, int dest_y, int dest_w, int dest_h) const;

  void DrawTiledImage(SkCanvas* canvas,
                      const gfx::ImageSkia& image,
                      int src_x, int src_y,
                      float tile_scale_x, float tile_scale_y,
                      int dest_x, int dest_y, int w, int h) const;

  SkColor SaturateAndBrighten(SkScalar* hsv,
                              SkScalar saturate_amount,
                              SkScalar brighten_amount) const;

  // Paints the arrow used on the scrollbar and spinner.
  void PaintArrow(SkCanvas* canvas,
                  const gfx::Rect& rect,
                  Part direction,
                  SkColor color) const;

  // Returns the color used to draw the arrow.
  SkColor GetArrowColor(State state) const;

 private:
  void DrawVertLine(SkCanvas* canvas,
                    int x,
                    int y1,
                    int y2,
                    const SkPaint& paint) const;
  void DrawHorizLine(SkCanvas* canvas,
                     int x1,
                     int x2,
                     int y,
                     const SkPaint& paint) const;
  void DrawBox(SkCanvas* canvas,
               const gfx::Rect& rect,
               const SkPaint& paint) const;
  SkScalar Clamp(SkScalar value,
                 SkScalar min,
                 SkScalar max) const;
  SkColor OutlineColor(SkScalar* hsv1, SkScalar* hsv2) const;

  // Paint the common parts of the checkboxes and radio buttons.
  // borderRadius specifies how rounded the corners should be.
  SkRect PaintCheckboxRadioCommon(
      SkCanvas* canvas,
      State state,
      const gfx::Rect& rect,
      const SkScalar borderRadius) const;

  unsigned int scrollbar_width_;

  // The length of the arrow buttons, 0 means no buttons are drawn.
  unsigned int scrollbar_button_length_;

  DISALLOW_COPY_AND_ASSIGN(NativeThemeBase);
};

}  // namespace ui

#endif  // UI_NATIVE_THEME_NATIVE_THEME_BASE_H_


text:
    <button class="delete u-cf" ng-click="$ctrl.finishVote($ctrl.runningVote.vote)" ng-show="$ctrl.currentUser._id==$ctrl.runningVote.vote.owner"> ×</button>

{{$ctrl.runningVote.vote.username}} wants to order at {{$ctrl.runningVote.restaurant.name}}

    <form ng-if="!$ctrl.voteOwner && !$ctrl.voteAnswered"
        ng-submit="$ctrl.respondVote($ctrl.responseVal, $ctrl.runningVote)">

You too?

                <input type="radio" ng-model="$ctrl.responseVal" ng-value="$ctrl.positive"/>
                Yes

                <input type="radio" ng-model="$ctrl.responseVal" ng-value="$ctrl.negative" />
                No

                <input type="radio" ng-model="$ctrl.responseVal" ng-value="$ctrl.other"/>

                    Other <input type="text" ng-model="$ctrl.responseVal.restaurant"
                                ng-disabled="$ctrl.responseVal!==$ctrl.other"
                                ng-required="$ctrl.responseVal===$ctrl.other" />

        <input type="submit" class="button-primary" value="Vote"/>
    </form>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>space dodge game</title>
    <link rel="stylesheet" href="base.css">

Score

          <canvas id="play-area" width="600" height="450"></canvas>

        <button id="restart">Restart</button>


text:
package org.redisson;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.redisson.api.RLongAdder;

public class RedissonLongAdderTest extends BaseTest {

    @Test
    public void testSum() {
        RLongAdder adder1 = redisson.getLongAdder("test1");
        RLongAdder adder2 = redisson.getLongAdder("test1");
        RLongAdder adder3 = redisson.getLongAdder("test1");

        adder1.add(2);
        adder2.add(4);
        adder3.add(1);

        Assertions.assertThat(adder1.sum()).isEqualTo(7);
        Assertions.assertThat(adder2.sum()).isEqualTo(7);
        Assertions.assertThat(adder3.sum()).isEqualTo(7);
    }

    @Test
    public void testReset() {
        RLongAdder adder1 = redisson.getLongAdder("test1");
        RLongAdder adder2 = redisson.getLongAdder("test1");
        RLongAdder adder3 = redisson.getLongAdder("test1");

        adder1.add(2);
        adder2.add(4);
        adder3.add(1);

        adder1.reset();

        Assertions.assertThat(adder1.sum()).isZero();
        Assertions.assertThat(adder2.sum()).isZero();
        Assertions.assertThat(adder3.sum()).isZero();
    }

}


text:
module VCloudClient
  class Connection
    ##
    # Fetch details about a given network
    def get_network(networkId)
      response = get_base_network(networkId)

      name = response.css('OrgVdcNetwork').attribute('name').text

      description = response.css("Description").first
      description = description.text unless description.nil?

      gateway = response.css('Gateway')
      gateway = gateway.text unless gateway.nil?

      netmask = response.css('Netmask')
      netmask = netmask.text unless netmask.nil?

      fence_mode = response.css('FenceMode')
      fence_mode = fence_mode.text unless fence_mode.nil?

      start_address = response.css('StartAddress')
      start_address = start_address.text unless start_address.nil?

      end_address = response.css('EndAddress')
      end_address = end_address.text unless end_address.nil?

      { :id => networkId, :name => name, :description => description,
        :gateway => gateway, :netmask => netmask, :fence_mode => fence_mode,
        :start_address => start_address, :end_address => end_address }
    end

    ##
    # Friendly helper method to fetch an network id by name
    # - organization hash (from get_organization/get_organization_by_name)
    # - network name
    def get_network_id_by_name(organization, networkName)
      result = nil

      organization[:networks].each do |network|
        if network[0].downcase == networkName.downcase
          result = network[1]
        end
      end

      result
    end

    ##
    # Friendly helper method to fetch an network by name
    # - organization hash (from get_organization/get_organization_by_name)
    # - network name
    def get_network_by_name(organization, networkName)
      result = nil

      organization[:networks].each do |network|
        if network[0].downcase == networkName.downcase
          result = get_network(network[1])
        end
      end

      result
    end

    private
      # Get a network configuration
      def get_base_network(networkId)
        params = {
          'method' => :get,
          'command' => "/network/#{networkId}"
        }

        base_network, headers = send_request(params)
        base_network
      end
  end
end


text:
iOS-SliderMenuBar
=================

A completely customizable alternative to the UITabBarController.

##Capabilities
- Can make the items in the bar look any way you want
- Can make bar height any size
- Animates the selected item in bar

##Todo
- Make Images fit with text if item is large enough to hold both
- Smooth animations for showing text or image
- Allow to instantiate with option of vertical or horizontal bar
- Add UIScrollView to the bar (So that you can put more than 5 items on the bar)

![alt tag](http://i877.photobucket.com/albums/ab335/whitehead1415/iOSSimulatorScreenshotOct72013125404PM_zps8bbeade2.png)


text:
package com.github.tjake.rbm.minst;

import com.github.tjake.rbm.*;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BinaryMinstDBN {
    static MinstDatasetReader dr;
    StackedRBM rbm;
    final StackedRBMTrainer trainer;
    final LayerFactory layerFactory = new LayerFactory();

    public BinaryMinstDBN(File labels, File images) {
        dr = new MinstDatasetReader(labels, images);

        rbm = new StackedRBM();
        trainer = new StackedRBMTrainer(rbm, 0.5f, 0.001f, 0.2f, 0.2f, layerFactory);
    }

    void learn(int iterations, boolean addLabels, int stopAt) {

        for (int p = 0; p < iterations; p++) {

            // Get random input
            List<Layer> inputBatch = new ArrayList<Layer>();
            List<Layer> labelBatch = addLabels ? new ArrayList<Layer>() : null;

            for (int j = 0; j < 30; j++) {
                MinstItem trainItem = dr.getTrainingItem();
                Layer input = layerFactory.create(trainItem.data.length);

                for (int i = 0; i < trainItem.data.length; i++)
                    input.set(i, trainItem.data[i]);

                inputBatch.add(new BinaryLayer(input));

                if (addLabels) {
                    float[] labelInput = new float[10];
                    labelInput[Integer.valueOf(trainItem.label)] = 1.0f;
                    labelBatch.add(layerFactory.create(labelInput));
                }
            }

            double error = trainer.learn(inputBatch, labelBatch, stopAt);

            if (p % 100 == 0)
                System.err.println("Iteration " + p + ", Error = " + error+", Energy = "+rbm.freeEnergy());
        }
    }

    Iterator<Tuple> evaluate(MinstItem test) {

        Layer input = layerFactory.create(test.data.length);

        for (int i = 0; i < test.data.length; i++)
            input.set(i, test.data[i]);

        input = new BinaryLayer(input);

        int stackNum = rbm.getInnerRBMs().size();

        for (int i = 0; i < stackNum; i++) {

            SimpleRBM iRBM = rbm.getInnerRBMs().get(i);

            if (iRBM.biasVisible.size() > input.size()) {
                Layer newInput = new Layer(iRBM.biasVisible.size());

                System.arraycopy(input.get(), 0, newInput.get(), 0, input.size());
                for (int j = input.size(); j < newInput.size(); j++)
                    newInput.set(j, 0.1f);

                input = newInput;
            }

            if (i == (stackNum - 1)) {
                return iRBM.iterator(input);
            }

            input = iRBM.activateHidden(input, null);
        }

        return null;
    }

    public static void start(File labels, File images, File saveto) {

        BinaryMinstDBN m = new BinaryMinstDBN(labels,images);

        boolean prevStateLoaded = false;

        if (saveto.exists()){
            try {
                DataInput input = new DataInputStream(new BufferedInputStream(new FileInputStream(saveto)));
                m.rbm.load(input, m.layerFactory);
                prevStateLoaded = true;

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (!prevStateLoaded) {
            int numIterations = 1000;

            m.rbm.setLayerFactory(m.layerFactory).addLayer(dr.rows * dr.cols, false).addLayer(500, false).addLayer(500, false).addLayer(2000, false).withCustomInput(510).build();

            System.err.println("Training level 1");
            m.learn(numIterations, false, 1);
            System.err.println("Training level 2");
            m.learn(numIterations, false, 2);
            System.err.println("Training level 3");
            m.learn(numIterations, true, 3);

            try {
                DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(saveto)));
                m.rbm.save(out);

                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        double numCorrect = 0;
        double numWrong = 0;
        double numAlmost = 0.0;

        while (true) {
            MinstItem testCase = m.dr.getTestItem();

            Iterator<Tuple> it = m.evaluate(testCase);

            float[] labeld = new float[10];

            for (int i = 0; i < 2; i++) {
                Tuple t = it.next();

                for (int j = (t.visible.size() - 10), k = 0; j < t.visible.size() && k < 10; j++, k++) {
                    labeld[k] += t.visible.get(j);
                }
            }

            float max1 = 0.0f;
            float max2 = 0.0f;
            int p1 = -1;
            int p2 = -1;

            System.err.print("Label is: " + testCase.label);

            for (int i = 0; i < labeld.length; i++) {
                labeld[i] /= 2;
                if (labeld[i] > max1) {
                    max2 = max1;
                    max1 = labeld[i];

                    p2 = p1;
                    p1 = i;
                }
            }

            System.err.print(", Winner is " + p1 + "(" + max1 + ") second is " + p2 + "(" + max2 + ")");
            if (p1 == Integer.valueOf(testCase.label)) {
                System.err.println(" CORRECT!");
                numCorrect++;

            } else if (p2 == Integer.valueOf(testCase.label)) {
                System.err.println(" Almost!");
                numAlmost++;
            } else {
                System.err.println(" wrong :(");
                numWrong++;
            }

            System.err.println("Error Rate = " + ((numWrong / (numAlmost + numCorrect + numWrong)) * 100));

        }
    }
}


text:
import {
  CLICK_START_MENU_ITEM,
  CLOSE_START_MENU_WINDOW
} from "../actions/constants";

export default function(state = [], action){
  switch (action.type) {
    case CLICK_START_MENU_ITEM:
      return action.payload;
    case CLOSE_START_MENU_WINDOW:
      return action.payload;
  }
  return state;
}


text:
require 'rails_helper'

describe UsersController do
  user = User.create(username: "TestymcTesterson", email: "test@test.com", password_digest: 123)
  it 'should add a new user to the databse' do
    # put :update, params
    expect(User.last.username).to eq('TestymcTesterson')
  end
end


text:
package faker

import "reflect"

type Phone struct {
	Number string
	Format string
}

func (phone *Phone) Numberʹ(params ...interface{}) string {
	format := phone.Formatʹ()

	types := kindOf(params...)
	if len(types) >= 1 && types[0] == reflect.String {
		format = params[0].(string)
	}

	phone.Number = replaceSymbolWithNumber(format, '#')
	phone.Format = format
	return phone.Number
}

func (phone *Phone) Formatʹ() string {
	format := getData("Phone", "PhoneFormat")
	phone.Format = sample(format)
	return phone.Format
}

// Fake Generate random data for all field
func (phone *Phone) Fake() {
	phone.Formatʹ()
	phone.Numberʹ()
}

// ToJSON Encode name and its fields to JSON.
func (phone *Phone) ToJSON() (string, error) {
	return ToJSON(phone)
}

// ToXML Encode name and its fields to XML.
func (phone *Phone) ToXML() (string, error) {
	return ToXML(phone)
}


text:
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace EventSource
{

    [Serializable]
	public class AggregateNotFoundException : Exception
	{
		private readonly Guid entityId;
		private readonly string entityType;

		public AggregateNotFoundException()
		{
		}

		public AggregateNotFoundException(Guid entityId) : base(entityId.ToString())
		{
			this.entityId = entityId;
		}

		public AggregateNotFoundException(Guid entityId, string entityType)
			: base(entityType + ": " + entityId)
		{
			this.entityId = entityId;
			this.entityType = entityType;
		}

		public AggregateNotFoundException(Guid entityId, string entityType, string message, Exception inner)
			: base(message, inner)
		{
			this.entityId = entityId;
			this.entityType = entityType;
		}

		protected AggregateNotFoundException(
			SerializationInfo info,
			StreamingContext context) : base(info, context)
		{
			if (info == null)
				throw new ArgumentNullException(nameof(info));

			entityId = Guid.Parse(info.GetString("entityId"));
			entityType = info.GetString("entityType");
		}

		public Guid EntityId
		{
			get { return entityId; }
		}

		public string EntityType
		{
			get { return entityType; }
		}

		[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			base.GetObjectData(info, context);
			info.AddValue("entityId", entityId.ToString());
			info.AddValue("entityType", entityType);
		}
	}
}


text:
"""Code Wars Kata.

https://www.codewars.com/kata/permutation-average
"""

from itertools import permutations

def permutation_average(n):
    total = 0
    list_nums = map(''.join, permutations(str(n)))
    for num in list_nums:
        total += float(num)
    return int((total / len(list_nums)) + .5)


text:
namespace Browser
{
    partial class BrowserForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.webBrowser = new System.Windows.Forms.WebBrowser();
            this.SuspendLayout();
            //
            // webBrowser
            //
            this.webBrowser.Dock = System.Windows.Forms.DockStyle.Fill;
            this.webBrowser.Location = new System.Drawing.Point(0, 0);
            this.webBrowser.MinimumSize = new System.Drawing.Size(20, 20);
            this.webBrowser.Name = "webBrowser";
            this.webBrowser.Size = new System.Drawing.Size(416, 356);
            this.webBrowser.TabIndex = 0;
            this.webBrowser.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.webBrowser_Navigated);
            //
            // BrowserForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(416, 356);
            this.Controls.Add(this.webBrowser);
            this.Name = "BrowserForm";
            this.Text = "Browser";
            this.Load += new System.EventHandler(this.BrowserForm_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.WebBrowser webBrowser;
    }
}


text:
package org.apache.ignite.internal.processors.cache.distributed.replicated;

import org.apache.ignite.configuration.*;
import org.apache.ignite.internal.processors.cache.*;

import static org.apache.ignite.cache.CacheMode.*;

/**
 * Replicated cache metrics test.
 */
public class GridCacheReplicatedMetricsSelfTest extends GridCacheTransactionalAbstractMetricsSelfTest {
    /** */
    private static final int GRID_CNT = 2;

    @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception {
        IgniteConfiguration c = super.getConfiguration(gridName);

        c.getTransactionConfiguration().setTxSerializableEnabled(true);

        return c;
    }

    /** {@inheritDoc} */
    @Override protected CacheConfiguration cacheConfiguration(String gridName) throws Exception {
        CacheConfiguration cfg = super.cacheConfiguration(gridName);

        cfg.setCacheMode(REPLICATED);

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected int gridCount() {
        return GRID_CNT;
    }
}


text:
package com.amazonaws.services.elasticsearch.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.elasticsearch.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * AddTagsRequest Marshaller
 */
public class AddTagsRequestMarshaller implements
        Marshaller<Request<AddTagsRequest>, AddTagsRequest> {

    private static final String DEFAULT_CONTENT_TYPE = "";

    public Request<AddTagsRequest> marshall(AddTagsRequest addTagsRequest) {

        if (addTagsRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<AddTagsRequest> request = new DefaultRequest<AddTagsRequest>(
                addTagsRequest, "AWSElasticsearch");

        request.setHttpMethod(HttpMethodName.POST);

        String uriResourcePath = "/2015-01-01/tags";
        request.setResourcePath(uriResourcePath);

        try {
            StringWriter stringWriter = new StringWriter();
            JSONWriter jsonWriter = new JSONWriter(stringWriter);

            jsonWriter.object();

            if (addTagsRequest.getARN() != null) {
                jsonWriter.key("ARN").value(addTagsRequest.getARN());
            }

            java.util.List<Tag> tagListList = addTagsRequest.getTagList();
            if (tagListList != null) {
                jsonWriter.key("TagList");
                jsonWriter.array();
                for (Tag tagListListValue : tagListList) {
                    if (tagListListValue != null) {

                        TagJsonMarshaller.getInstance().marshall(
                                tagListListValue, jsonWriter);
                    }
                }
                jsonWriter.endArray();
            }

            jsonWriter.endObject();

            String snippet = stringWriter.toString();
            byte[] content = snippet.getBytes(UTF8);
            request.setContent(new StringInputStream(snippet));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            if (!request.getHeaders().containsKey("Content-Type")) {
                request.addHeader("Content-Type", DEFAULT_CONTENT_TYPE);
            }
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

function get_body($ss, $vardef)
{
	$edit_mod_strings = return_module_language($GLOBALS['current_language'], 'EditCustomFields');
	$ss->assign('MOD', $edit_mod_strings);

	$edValue = '';
    if(!empty($vardef['default_value'])) {
        $edValue = $vardef['default_value'];
        $edValue = str_replace(array("\r\n", "\n"), " ",$edValue);
    }
    $ss->assign('HTML_EDITOR', $edValue);
    $ss->assign('preSave', 'document.popup_form.presave();');
	///////////////////////////////////
	return $ss->fetch('modules/DynamicFields/templates/Fields/Forms/html.tpl');
}
?>


text:
// main saga
export default function* mainSaga () {
  //yield [fork(getProjectInfo)];

};