text:
<?xml version="1.0"?>

<project name="build-test">

   <property name="initialcontext.factory.bea"
            value="weblogic.jndi.WLInitialContextFactory"/>

   <target name="check-database-settings"/>
   <target name="bea-set-properties"/>

    <path id="test.classpath">
        <pathelement path="${build.dir}/classes"/>
        <path refid="default.classpath"/>
    </path>

    <path id="test.runtime.classpath">
        <pathelement path="${build.dir}/instrumented-classes/classes"/>
        <pathelement path="${build.dir}/test-classes"/>
        <path refid="test.classpath"/>
    </path>

   <!-- =================================================================== -->
   <!-- TEST SECTION                                                        -->
   <!-- =================================================================== -->
    <!-- =================================================================== -->
    <!-- run Xdoclet for all Beans                                           -->
    <!-- =================================================================== -->
    <target name="test-ejbdoclet"
        depends="prepare, test-ejbdoclet-uptodatecheck, test-ejbdoclet-nodeps"/>
    <target name="test-ejbdoclet-uptodatecheck">
        <uptodate property="test-ejbdoclet.uptodate"
                  targetfile="${build.dir}/test-deploymentdescriptors/ejb-jar.xml" >
            <srcfiles dir="${base.dir}/test/java">
                <include name="**/*Bean.java" />
                <exclude name="**/*MBean.java" />
            </srcfiles>
            <srcfiles dir="${build.dir}/gen-test">
                <include name="**/*Bean.java" />
                <exclude name="**/*MBean.java" />
            </srcfiles>
        </uptodate>
    </target>
    <target name="test-ejbdoclet-nodeps" unless="test-ejbdoclet.uptodate">
        <xdoclet-ejb
            destdir="${build.dir}/gen-test"
            dd-dir="${build.dir}/test-deploymentdescriptors">
            <sources>
                <fileset dir="${base.dir}/test/java">
                    <include name="**/*Bean.java" />
                    <exclude name="**/*MBean.java" />
                </fileset>
                <!--fileset dir="${build.dir}/gen-test">
                    <include name="**/*Bean.java" />
                    <exclude name="**/*MBean.java" />
                </fileset-->
            </sources>
        </xdoclet-ejb>
    </target>

    <!-- =================================================================== -->
    <!-- run Xdoclet/Web for production Servlets                             -->
    <!-- =================================================================== -->
    <target name="test-webdoclet"
            depends="test-ejbdoclet, test-webdoclet-uptodatecheck,
                test-webdoclet-nodeps"/>
    <target name="test-webdoclet-uptodatecheck">
        <uptodate property="test-webdoclet.uptodate"
             targetfile="${build.dir}/test-deploymentdescriptors/web.xml" >
            <srcfiles dir="${base.dir}/test/java">
                <include name="**/*Servlet.java" />
            </srcfiles>
        </uptodate>
    </target>
    <target name="test-webdoclet-nodeps" unless="test-webdoclet.uptodate">
        <taskdef name="webdoclet"
             classname="xdoclet.modules.web.WebDocletTask">
            <classpath refid="default.classpath"/>
        </taskdef>
        <webdoclet destdir="${build.dir}" verbose="true">
            <fileset dir="${base.dir}/test/java">
                <include name="**/*Servlet.java" />
            </fileset>
            <deploymentdescriptor
             destdir="${build.dir}/test-deploymentdescriptors"
             validatexml="true"
             mergedir="${base.dir}/src/xml/xdoclet" />
        </webdoclet>
    </target>

    <target name="test-compile"
            depends="build, gen-test-classes, test-webdoclet, test-compile-nodeps"
            description="Compile JUnit tests"></target>
    <target name="test-compile-nodeps">
        <mkdir dir="${build.dir}/test-classes"/>
        <javac  destdir="${build.dir}/test-classes"
                deprecation="${build.debug}"
                debug="true"
                source="1.4">
            <src path="${base.dir}/test/java"/>
            <src path="${build.dir}/gen-test"/>
            <classpath>
                <pathelement path="${build.dir}/classes"/>
                <pathelement path="${build.dir}/test-classes"/>
                <path refid="test.classpath"/>
            </classpath>
        </javac>
    </target>

    <target name="instrument" depends="test-compile, instrument-nodeps"
            description="Add jcoverage instrumentation"></target>
    <target name="instrument-nodeps" if="build.coverage">
      <path id="emma.lib">
        <pathelement location="${base.dir}/lib/default/emma/emma.jar"/>
        <pathelement location="${base.dir}/lib/default/emma_ant/emma_ant.jar"/>
      </path>
      <taskdef resource="emma_ant.properties" classpathref="emma.lib"/>
      <emma>
        <instr destdir="${build.dir}/instrumented-classes"
               metadatafile="${build.dir}/metadata.em"
               merge="true" mode="fullcopy">
            <instrpath>
            	<path location="${build.dir}/classes"/>
                <path location="${build.dir}/test-classes"/>
            </instrpath>
      	</instr>
      </emma>

<!--    Switch back after cobertura 1.9.1 is available
        <taskdef resource="tasks.properties"
                 classpathref="default.classpath"/>
        <mkdir dir="${build.dir}/instrumented-classes" />
        <cobertura-instrument todir="${build.dir}/instrumented-classes">
            <ignore regex="org.apache.log4j.*"/>
            <fileset dir="${build.dir}">
                <include name="classes/**/*.class"/>
                <exclude name="classes/**/jaxb/**/*.class"/>
                <include name="test-classes/**/*.class"/>
                <exclude name="test-classes/**/jaxb/**/*.class"/>
                <exclude name="test-classes/**/org/jcoderz/commons/LogFormatterOutputTest.class"/>
            </fileset>
        </cobertura-instrument>
        <move file="${base.dir}/cobertura.ser"
            tofile="${build.dir}/instrumented-classes/cobertura.ser"/>
-->
    </target>

   <!-- insert test data into database -->
    <target name="test-insert-data"
            depends="check-database-settings, test-insert-data-sql"/>
    <target name="test-insert-data-sql">
        <sql driver="oracle.jdbc.driver.OracleDriver"
                autocommit="true"
                onError="continue"
                url="${db.url}"
                password="${db.passwd}"
                userid="${db.user}"
                encoding="UTF-8">
            <classpath>
                <pathelement location="${oracleclient.jar}" />
            </classpath>
            <fileset dir="${base.dir}/test/sql">
                <include name="*_insert_data.sql" />
            </fileset>
            <fileset dir="${build.dir}/gen-sql">
                <include name="*_insert_data.sql" />
            </fileset>
        </sql>
    </target>

    <target name="test" depends="test-local, test-server"
            description="Run all JUnit test suites"/>
    <target name="test-nodeps" depends="test-local-nodeps"/>
    <target name="test-local"
            depends="test-compile, instrument, test-local-nodeps"
            description="Run all local JUnit test suites"/>
    <target name="test-local-nodeps" if="junit.present">
        <mkdir dir="${build.dir}/report/junit"/>
        <junit printsummary="yes" haltonfailure="no"
                dir="${base.dir}/build" fork="true" timeout="60000"
                forkmode="perBatch"> <!-- should be forkmode="perBatch" after timeout fix -->
            <classpath refid="test.runtime.classpath"/>
            <sysproperty key="basedir" value="${base.dir}"/>
            <sysproperty key="java.util.logging.config.file"
                    value="${base.dir}/src/etc/fawkez-logging.properties"/>
            <sysproperty key="org.xml.sax.driver"
                    value="org.apache.xerces.parsers.SAXParser"/>
<!--                      value="org.apache.crimson.parser.XMLReaderImpl"/ -->
            <formatter type="brief" usefile="true"/>
            <formatter type="xml" usefile="true"/>
            <batchtest todir="${build.dir}/report/junit">
                <fileset dir="${base.dir}/test/java">
                    <include name="**/*Test.java"/>
                    <exclude name="**/HttpClientConnectionTest.java"/>
                    <exclude name="**/*ServerTest.java"/>
                    <exclude name="**/*BeanTest.java"/>
                </fileset>
                <fileset dir="${build.dir}/gen-test">
                    <include name="**/*Test.java"/>
                    <exclude name="**/*ServerTest.java"/>
                    <exclude name="**/*BeanTest.java"/>
                </fileset>
            </batchtest>
            <batchtest todir="${build.dir}/report/junit">
                <fileset dir="${base.dir}/test/java">
                    <include name="**/HttpClientConnectionTest.java"/>
                </fileset>
            </batchtest>
        </junit>
    </target>
    <target name="test-single-local"
            depends="test-compile, instrument, test-single-local-nodeps"
            description="Run a single JUnit test suite"/>
    <target name="test-single-local-nodeps" if="testcase">
        <mkdir dir="${build.dir}/report/junit"/>
        <junit printsummary="yes" haltonfailure="no"
                dir="${base.dir}/build" fork="true" timeout="60000"
                showoutput="true">
            <classpath refid="test.runtime.classpath"/>
            <sysproperty key="methods" value="${methods}"/>
            <sysproperty key="basedir" value="${base.dir}"/>
            <sysproperty key="java.util.logging.config.file"
                    file="${base.dir}/src/etc/fawkez-logging.properties"/>
            <sysproperty key="org.xml.sax.driver"
                    value="org.apache.xerces.parsers.SAXParser"/>
                    <!--value="org.apache.crimson.parser.XMLReaderImpl"/-->
            <formatter type="plain" usefile="false"/>
            <test name="${testcase}"/>
        </junit>
    </target>

   <!-- SERVER TESTS -->
    <target name="test-server"
            depends="test-compile, instrument, check-database-settings, test-insert-data, test-server-nodeps"
            description="Run all server JUnit test suites (w/ running server)"/>
    <target name="test-server-nodeps"
            depends="check-database-settings, bea-set-properties"
            if="junit.present">
        <mkdir dir="${build.dir}/report/junit"/>
        <junit printsummary="yes" haltonfailure="no"
                dir="${base.dir}" fork="true" timeout="1200000"
                forkmode="perBatch">
            <classpath refid="test.runtime.classpath"/>
            <sysproperty key="basedir" value="${base.dir}"/>
            <sysproperty key="java.util.logging.config.file"
                    value="${base.dir}/src/etc/fawkez-logging.properties"/>
            <sysproperty key="java.naming.factory.initial"
                    value="${initialcontext.factory.bea}"/>
            <sysproperty key="java.naming.provider.url" value="${bea.url}"/>
            <sysproperty key="DB_HOST" value="${db.host}"/>
            <sysproperty key="DB_DOMAIN" value="${db.domain}"/>
            <sysproperty key="DB_PORT" value="${db.port}"/>
            <sysproperty key="DB_USER" value="${db.user}"/>
            <sysproperty key="DB_PASSWD" value="${db.passwd}"/>
            <sysproperty key="DB_SID" value="${db.sid}"/>
            <sysproperty key="DB_URL_THICK" value="jdbc:oracle:oci8:@${db.connect_string}"/>
            <sysproperty key="SRV_HOSTNAME" value="${env.SRV_HOSTNAME}"/>
            <sysproperty key="SRV_HTTP_PORT" value="${env.SRV_HTTP_PORT}"/>
            <sysproperty key="java.security.auth.login.config"
                    value="jar:file:${build.dir}/fawkez.jar!/app_jaas.config"/>
            <formatter type="brief" usefile="true"/>
            <formatter type="xml" usefile="true"/>
            <batchtest todir="${build.dir}/report/junit">
                <fileset dir="${base.dir}/test/java">
                    <include name="**/*ServerTest.java"/>
                    <include name="**/*BeanTest.java"/>
                </fileset>
            </batchtest>
            <batchtest todir="${build.dir}/report/junit">
                <fileset dir="${base.dir}/build/gen-test">
                    <include name="**/*ServerTest.java"/>
                    <include name="**/*BeanTest.java"/>
                </fileset>
            </batchtest>
            <batchtest todir="${build.dir}/report/junit">
                <fileset dir="${base.dir}/test/java">
                </fileset>
            </batchtest>
        </junit>
        <echo message="Find detailed junit results at ${build.dir}/report/junit."
                level="info"/>
    </target>

   <!-- SINGLE SERVER TESTS -->
    <target name="test-single-server"
            depends="test-testcase-property-set, test-compile, instrument, test-single-server-nodeps"
            description="Run all single server JUnit test (w/ running server)"/>
    <target name="test-testcase-property-set" unless="testcase">
        <fail message="missing testcase property">
+-----------------------------------------------------------------+
! You must set the property 'testcase' for the requested target.  !
!                                                                 !
! For example:                                                    !
!    $ ant -Dtestcase=package.FooTest test-single-local           |
! or                                                              !
!    $ ant -Dtestcase=package.FooServerTest test-single-server    |
! or                                                              !
!    $ ant -Dtestcase=package.FooBeanTest test-single-server      !
+-----------------------------------------------------------------+
      </fail>
    </target>
    <target name="test-single-server-nodeps"
            depends="bea-set-properties" if="testcase, junit.present">
        <junit printsummary="yes" haltonfailure="yes"
                dir="${base.dir}" fork="true" timeout="1200000">
            <classpath refid="test.runtime.classpath"/>
            <sysproperty key="basedir" value="${base.dir}"/>
            <sysproperty key="java.naming.factory.initial"
                    value="${initialcontext.factory.bea}"/>
            <sysproperty key="java.naming.provider.url" value="${bea.url}"/>
            <sysproperty key="DB_HOST" value="${db.host}"/>
            <sysproperty key="DB_DOMAIN" value="${db.domain}"/>
            <sysproperty key="DB_PORT" value="${db.port}"/>
            <sysproperty key="DB_USER" value="${db.user}"/>
            <sysproperty key="DB_PASSWD" value="${db.passwd}"/>
            <sysproperty key="DB_SID" value="${db.sid}"/>
            <sysproperty key="DB_URL_THICK" value="jdbc:oracle:oci8:@${db.connect_string}"/>
            <sysproperty key="methods" value="${methods}"/>
            <formatter type="plain" usefile="false"/>
            <test name="${testcase}"/>
        </junit>
    </target>

   <!-- PUBLIC: JUnit HTML report -->
    <target name="test-report" depends="test, test-report-nodeps"/>
    <target name="test-report-nodeps">
        <mkdir dir="${build.dir}/doc/junit"/>
        <junitreport todir="${build.dir}/report/junit">
            <fileset dir="${build.dir}/report/junit">
                <include name="TEST-*.xml"/>
            </fileset>
            <report format="frames"
                    styledir="${base.dir}/config"
                    todir="${build.dir}/doc/junit"/>
        </junitreport>
      <!-- Remove properties from the report xml -->
        <xslt basedir="${base.dir}"
                in="${build.dir}/report/junit/TESTS-TestSuites.xml"
                out="${build.dir}/report/junit/TESTS-TestSuites.xml.tmp"
                style="${base.dir}/config/filter-test-properties.xsl"></xslt>
        <move file="${build.dir}/report/junit/TESTS-TestSuites.xml.tmp"
                toFile="${build.dir}/report/junit/TESTS-TestSuites.xml"/>
        <echo level="info"
            message="JUnit Report available at ${build.dir}/doc/junit"/>
    </target>

    <target name="gen-test-classes">
      <taskdef name="simple-type-generator"
        classname="org.jcoderz.commons.taskdefs.SimpleTypeGenerator">
        <classpath>
          <pathelement location="${build.dir}/classes"/>
          <path refid="default.classpath"/>
        </classpath>
      </taskdef>
      <simple-type-generator in="${base.dir}/test/xml/simple-types.xml"
              out="${build.dir}/simple-types.log"
              destDir="${build.dir}/gen-test"
              failonerror="true"
              force="true"/>
      <simple-type-generator in="${base.dir}/test/xml/simple-types.xml"
              out="${build.dir}/simple-types.log"
              destDir="${build.dir}/gen-test"
              failonerror="true"
              force="true"/>
      <taskdef name="log-message-generator"
               classname="org.jcoderz.commons.taskdefs.LogMessageGenerator">
          <classpath>
            <pathelement location="${build.dir}/classes"/>
            <path refid="default.classpath"/>
          </classpath>
      </taskdef>
      <log-message-generator
        in="${base.dir}/test/xml/app-info-test.xml"
        out="${build.dir}/app-info-test-log-message-info.out"
        destDir="${build.dir}/gen-test"
        application="TCS"
        failonerror="true"
        force="true"/>
    </target>

   <!-- Tests the execution of some ant tasks provided by this project -->
    <target name="test-ant-tasks">
        <taskdef name="log-message-generator"
                classname="org.jcoderz.commons.taskdefs.LogMessageGenerator">
            <classpath>
                <pathelement location="${build.dir}"/>
            </classpath>
        </taskdef>
        <taskdef name="simple-type-generator"
                classname="orz.jcoderz.commons.taskdefs.SimpleTypeGenerator">
            <classpath>
                <pathelement location="${build.dir}"/>
            </classpath>
        </taskdef>
        <taskdef name="jsf-converter-generator"
                classname="org.jcoderz.commons.taskdefs.JsfConverterGenerator">
            <classpath>
                <pathelement location="${build.dir}"/>
            </classpath>
        </taskdef>
        <log-message-generator in="${base.dir}/test/xml/log-message-info.xml"
                out="${build.dir}/test-log-message-info.log"
                destDir="${build.dir}/test"
                application="Fawkez"
                failonerror="true"
                force="true"/>
        <simple-type-generator in="${base.dir}/test/xml/simple-types.xml"
                out="${build.dir}/simple-types.log"
                destDir="${build.dir}/test"
                failonerror="true"
                force="true"/>
        <jsf-converter-generator in="${base.dir}/test/xml/jsf-converters.xml"
                out="${build.dir}/jsf-converters.log"
                destDir="${build.dir}/test"
                failonerror="true"
                force="true"/>
    </target>

  <!-- Test report encoding support -->
   <!-- The ruleset files -->
   <property name="pmd.rules" value="${base.dir}/config/jcoderz-pmd.xml"/>
   <property name="checkstyle.rules" value="${base.dir}/config/jcoderz-checkstyle.xml" />
   <property name="findbugs.rules" value="${base.dir}/config/jcoderz-findbugs.xml" />
   <property name="filter.rules" value="${base.dir}/config/jcoderz-report-filter.xsl" />

  <target name="report-test">
        <!-- This is the classpath used by the JcReportAntTask -->
        <path id="jcreport.classpath">
           <pathelement path="${base.dir}/build/classes"/>
           <fileset dir="${base.dir}/lib">
              <include name="default/jaxb/*.jar"/>
              <include name="default/chart2d/*.jar"/>
           </fileset>
        </path>
        <taskdef name="jcreport"
                 classname="org.jcoderz.phoenix.report.JcReportAntTask">
           <classpath refid="jcreport.classpath" />
        </taskdef>

        <!-- This classpath is used by the checkstyle process -->
        <path id="checkstyle.classpath">
           <fileset dir="${base.dir}/lib">
              <include name="default/antlr/*.jar"/>
              <include name="default/checkstyle/*.jar"/>
              <include name="default/commons-beanutils/*.jar"/>
              <include name="default/commons-beanutils-core/*.jar"/>
              <include name="default/commons-cli/*.jar"/>
              <include name="default/commons-logging/*.jar"/>
           </fileset>
        </path>
        <!-- This classpath is used by the pmd and cpd process -->
        <path id="pmd.classpath">
           <fileset dir="${base.dir}/lib">
              <include name="default/pmd/*.jar"/>
              <include name="default/asm*/*.jar"/>
              <include name="default/backport-util-concurrent/*.jar"/>
              <include name="default/jaxen/*.jar"/>
              <include name="default/oro/*.jar"/>
           </fileset>
        </path>
        <!-- This classpath is used by the findbugs process -->
        <path id="findbugs.classpath">
           <fileset dir="${base.dir}/lib">
              <include name="default/findbugs/*.jar"/>
              <include name="default/asm*/*.jar"/>
              <include name="default/jaxen/*.jar"/>
              <exclude name="**/fb-contrib.jar"/>
           </fileset>
        </path>
        <path id="findbugs.plugins">
            <path location="${base.dir}/lib/default/fb-contrib/fb-contrib.jar"/>
        </path>
        <!-- This is the auxiliary classpath used by findbugs -->
        <path id="findbugs.aux.classpath">
           <path location="${base.dir}/build/classes"/>
           <path location="${env.JAVA_HOME}/lib/tools.jar"/>
           <fileset dir="${base.dir}/lib">
              <include name="default/**/*.jar"/>
           </fileset>
        </path>

        <delete dir="${build.dir}/report-test"/>
          <property name="utf8-base.dir"
            location="${build.dir}/report-test/utf8"/>
      <property name="utf8-src.dir"
        location="${base.dir}/test/charset/java-utf8"/>
          <property name="utf8-class.dir"
            location="${utf8-base.dir}/classes"/>
      <mkdir dir="${utf8-class.dir}"/>
      <javac encoding="UTF-8"
           srcdir="${utf8-src.dir}"
           destdir="${utf8-class.dir}"/>
        <jcreport name="fawkez"
                  dest="${utf8-base.dir}/doc/findings-report"
                  wikibase="http://www.jcoderz.org/fawkez/wiki/jcreport:"
                  webrcsbase="http://www.jcoderz.org/fawkez/browser/trunk"
                  webrcssuffix=""
                  packagebase="org.jcoderz"
                  projectbase="${base.dir}"
                  tempfolder="${utf8-base.dir}/tmp"
                  debug="false"
                  encoding="utf-8"
                  cpus="0"> <!-- Increase to speed up -->
           <classpath refid="jcreport.classpath"/>
           <reports>
              <report name="fawkez-test"
                      level="prod"
                      sourcepath="${utf8-src.dir}"
                      classpath="${utf8-class.dir}">
              </report>
           </reports>
           <tools>
              <pmd config="${pmd.rules}"
                   targetjdk="1.4">
                 <classpath refid="pmd.classpath"/>
              </pmd>
              <cpd minimumtokens="100">
                 <classpath refid="pmd.classpath"/>
              </cpd>
             <!-- Could not disable UnreadFields cause further dependencies -->
             <findbugs maxheap="256" >
                 <classpath refid="findbugs.classpath"/>
                 <auxclasspath refid="findbugs.aux.classpath"/>
                 <pluginlist refid="findbugs.plugins"/>
              </findbugs>
              <checkstyle config="${checkstyle.rules}">
                 <classpath refid="checkstyle.classpath" />
              </checkstyle>
           </tools>
        </jcreport>

        <property name="cp500-base.dir"
          location="${build.dir}/report-test/cp500"/>
        <property name="cp500-src.dir"
          location="${base.dir}/test/charset/java-cp500"/>
        <property name="cp500-class.dir"
          location="${cp500-base.dir}/classes"/>
        <mkdir dir="${cp500-class.dir}"/>
        <javac encoding="cp500"
             srcdir="${cp500-src.dir}"
             destdir="${cp500-class.dir}"/>
        <jcreport name="fawkez"
                  dest="${cp500-base.dir}/doc/findings-report"
                  wikibase="http://www.jcoderz.org/fawkez/wiki/jcreport:"
                  webrcsbase="http://www.jcoderz.org/fawkez/browser/trunk"
                  webrcssuffix=""
                  packagebase="org.jcoderz"
                  projectbase="${base.dir}"
                  tempfolder="${cp500-base.dir}/tmp"
                  debug="false"
                  encoding="cp500"
                  cpus="0"> <!-- Increase to speed up -->
           <classpath refid="jcreport.classpath"/>
           <reports>
              <report name="fawkez-test"
                      level="prod"
                      sourcepath="${cp500-src.dir}"
                      classpath="${cp500-class.dir}">
              </report>
           </reports>
           <tools>
              <pmd config="${pmd.rules}" targetjdk="1.4">
                 <classpath refid="pmd.classpath"/>
              </pmd>
              <cpd minimumtokens="100">
                 <classpath refid="pmd.classpath"/>
              </cpd>
             <findbugs>
                 <classpath refid="findbugs.classpath"/>
                 <auxclasspath refid="findbugs.aux.classpath"/>
                 <pluginlist refid="findbugs.plugins"/>
              </findbugs>
              <checkstyle config="${checkstyle.rules}">
                 <classpath refid="checkstyle.classpath" />
              </checkstyle>
           </tools>
        </jcreport>

  </target>

</project>


text:
'use strict';

module.exports = function () {
  var _         = require('lodash'),
      path      = require('path'),
      Q         = require('q'),
      forever   = require('forever'),
      isRunning = require('is-running');

  /**
   * Start the mockify daemon.
   */
  var start = function () {
    var deferred = Q.defer();

    var daemonRootDir = path.resolve(__dirname, '../daemon'),
        binPath = path.join(daemonRootDir, 'mockify.js');

    forever.startDaemon(binPath, {
      silent          : false,
      max             : 10,
      watch           : true,
      watchDirectory  : daemonRootDir,
      cwd             : daemonRootDir,
      logFile         : path.join(daemonRootDir, 'log', 'mockify.log'),
      outFile         : path.join(daemonRootDir, 'log', 'mockify.out.log'),
      errFile         : path.join(daemonRootDir, 'log', 'mockify.err.log')
    });

    // @FIXME Handle forever errors
    deferred.resolve('mockify daemon has been started.');

    return deferred.promise;
  };

  /**
   * Stop the mockify daemon.
   * Loop over live processes and resolve the deferred once all processes are
   * killed.
   */
  var stop = function () {
    var deferred = Q.defer();

    var attempts = 0,
        message = 'Mockify is not running.',
        tryingToStop = false;

    var interval = setInterval(function () {
      process.stdout.write('.');

      forever.list(false, function (err, processes) {
        if (!tryingToStop && _.isArray(processes)) {
          // @FIXME Handle error if stopping when mockify is not started
          forever.stopAll().on('stopAll', function () {
            // @FIXME Handle forever errors
            deferred.resolve('Mockify daemon has been stopped.');
          });

          tryingToStop = true;
        }

        var allKilled = false;
        _.forEach(processes, function (process) {
          allKilled = allKilled && !isRunning(process.pid);
        });

        if (allKilled) {
          deferred.resolve(message);
        }
      });

      if (attempts > 5) {
        clearInterval(interval);
        deferred.resolve(message);
      }

      attempts++;
    }, 500);

    return deferred.promise;
  };

  return {
    start: start,
    stop: stop
  };
};

redpajama_set_name: RedPajamaGithub


text:
package org.knowm.xchange.okcoin;

import org.knowm.xchange.BaseExchange;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.okcoin.service.OkCoinAccountService;
import org.knowm.xchange.okcoin.service.OkCoinFuturesAccountService;
import org.knowm.xchange.okcoin.service.OkCoinFuturesMarketDataService;
import org.knowm.xchange.okcoin.service.OkCoinFuturesTradeService;
import org.knowm.xchange.okcoin.service.OkCoinMarketDataService;
import org.knowm.xchange.okcoin.service.OkCoinTradeService;

import si.mazi.rescu.SynchronizedValueFactory;

public class OkCoinExchange extends BaseExchange {

  @Override
  public void applySpecification(ExchangeSpecification exchangeSpecification) {

    super.applySpecification(exchangeSpecification);

    if (exchangeSpecification.getExchangeSpecificParametersItem("Use_Intl").equals(false)
        && exchangeSpecification.getExchangeSpecificParametersItem("Use_Futures").equals(true)) {
      throw new RuntimeException("Futures only available on international version. Set `Use_Intl` to true.");
    }

    concludeHostParams(exchangeSpecification);
  }

  @Override
  protected void initServices() {

    concludeHostParams(exchangeSpecification);

    if (exchangeSpecification.getExchangeSpecificParameters() != null
        && exchangeSpecification.getExchangeSpecificParametersItem("Use_Futures").equals(true)) {
      FuturesContract contract = futuresContractOfConfig(exchangeSpecification);

      this.marketDataService = new OkCoinFuturesMarketDataService(this, contract);
      if (exchangeSpecification.getApiKey() != null) {
        this.accountService = new OkCoinFuturesAccountService(this);
        this.tradeService = new OkCoinFuturesTradeService(this, contract, futuresLeverageOfConfig(exchangeSpecification));
      }
    } else {
      this.marketDataService = new OkCoinMarketDataService(this);
      if (exchangeSpecification.getApiKey() != null) {
        this.accountService = new OkCoinAccountService(this);
        this.tradeService = new OkCoinTradeService(this);
      }
    }
  }

  /**
   * Adjust host parameters depending on exchange specific parameters
   */
  private static void concludeHostParams(ExchangeSpecification exchangeSpecification) {

    if (exchangeSpecification.getExchangeSpecificParameters() != null) {
      if (exchangeSpecification.getExchangeSpecificParametersItem("Use_Intl").equals(true)
          && exchangeSpecification.getExchangeSpecificParametersItem("Use_Futures").equals(false)) {

        exchangeSpecification.setSslUri("https://www.okex.com/api");
        exchangeSpecification.setHost("www.okex.com");

      } else if (exchangeSpecification.getExchangeSpecificParametersItem("Use_Intl").equals(true)
          && exchangeSpecification.getExchangeSpecificParametersItem("Use_Futures").equals(true)) {

        exchangeSpecification.setSslUri("https://www.okex.com/api");
        exchangeSpecification.setHost("www.okex.com");

      }
    }
  }

  /**
   * Extract futures leverage used by spec
   */
  private static int futuresLeverageOfConfig(ExchangeSpecification exchangeSpecification) {

    if (exchangeSpecification.getExchangeSpecificParameters().containsKey("Futures_Leverage")) {
      return Integer.valueOf((String) exchangeSpecification.getExchangeSpecificParameters().get("Futures_Leverage"));
    } else {
      // default choice of 10x leverage is "safe" choice and default by OkCoin.
      return 10;
    }
  }

  /**
   * Extract contract used by spec
   */
  public static FuturesContract futuresContractOfConfig(ExchangeSpecification exchangeSpecification) {

    FuturesContract contract;

    if (exchangeSpecification.getExchangeSpecificParameters().containsKey("Futures_Contract")) {
      contract = (FuturesContract) exchangeSpecification.getExchangeSpecificParameters().get("Futures_Contract");
    } else if (exchangeSpecification.getExchangeSpecificParameters().containsKey("Futures_Contract_String")) {
      contract = FuturesContract.valueOfIgnoreCase(FuturesContract.class,
          (String) exchangeSpecification.getExchangeSpecificParameters().get("Futures_Contract_String"));
    } else {
      throw new RuntimeException("`Futures_Contract` or `Futures_Contract_String` not defined in exchange specific parameters.");
    }

    return contract;
  }

  @Override
  public ExchangeSpecification getDefaultExchangeSpecification() {

    ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass().getCanonicalName());
	exchangeSpecification.setSslUri("https://www.okex.com/api");
	exchangeSpecification.setHost("www.okex.com");
    exchangeSpecification.setExchangeName("OKCoin");
    exchangeSpecification.setExchangeDescription("OKCoin is a globally oriented crypto-currency trading platform.");

    // set to true to automatically use the Intl_ parameters for ssluri and host
    exchangeSpecification.setExchangeSpecificParametersItem("Use_Intl", false);
    exchangeSpecification.setExchangeSpecificParametersItem("Use_Futures", false);

    return exchangeSpecification;
  }

  @Override
  public SynchronizedValueFactory<Long> getNonceFactory() {

    // This exchange doesn't use a nonce for authentication
    return null;
  }

  @Override
  public String getMetaDataFileName(ExchangeSpecification exchangeSpecification) {

    if (exchangeSpecification.getExchangeSpecificParametersItem("Use_Intl").equals(false)) {
      return exchangeSpecification.getExchangeName().toLowerCase().replace(" ", "").replace("-", "").replace(".", "") + "_china";
    } else {
      if (exchangeSpecification.getExchangeSpecificParametersItem("Use_Futures").equals(true)) {
        return exchangeSpecification.getExchangeName().toLowerCase().replace(" ", "").replace("-", "").replace(".", "") + "_futures";
      } else {
        return exchangeSpecification.getExchangeName().toLowerCase().replace(" ", "").replace("-", "").replace(".", "") + "_intl";
      }

    }
  }
}


text:
package com.github.anba.es6draft.runtime.objects.binary;

import static com.github.anba.es6draft.runtime.AbstractOperations.ToNumber;
import static com.github.anba.es6draft.runtime.internal.Errors.newTypeError;
import static com.github.anba.es6draft.runtime.objects.binary.ArrayBufferConstructor.GetValueFromBuffer;
import static com.github.anba.es6draft.runtime.objects.binary.ArrayBufferConstructor.SetValueInBuffer;
import static com.github.anba.es6draft.runtime.types.Undefined.UNDEFINED;

import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.internal.Messages;
import com.github.anba.es6draft.runtime.types.builtins.ExoticIntegerIndexedObject;

/**
 *
22 Indexed Collections

 *
22.2 TypedArray Objects

 *

 *
22.2.7 Properties of TypedArray instances
 *

 */
public final class TypedArrayObject extends ExoticIntegerIndexedObject implements ArrayBufferView {
    /** [[ViewedArrayBuffer]] */
    private ArrayBufferObject buffer;

    /** [[ElementType]] */
    private ElementType elementType;

    /** [[ByteLength]] */
    private long byteLength;

    /** [[ByteOffset]] */
    private long byteOffset;

    /** [[ArrayLength]] */
    private long arrayLength;

    // FIXME: spec incomplete
    private boolean elementsWritable = true;

    public TypedArrayObject(Realm realm) {
        super(realm);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected long getLength() {
        return getArrayLength();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean getWritable() {
        return elementsWritable;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void setNonWritable() {
        assert elementsWritable;
        elementsWritable = false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Object elementGet(ExecutionContext cx, double index) {
        /* steps 1-2 (not applicable) */
        /* step 3 */
        ArrayBufferObject buffer = getBuffer();
        /* step 4 */
        if (buffer == null) {
            throw newTypeError(cx, Messages.Key.UninitialisedObject);
        }
        /* step 5 */
        long length = getArrayLength();
        /* step 6 */
        if (index < 0 || index >= length) {
            return UNDEFINED;
        }
        /* step 7 */
        long offset = getByteOffset();
        /* steps 8, 11 */
        ElementType elementType = getElementType();
        /* step 9 */
        int elementSize = elementType.size();
        /* step 10 */
        long indexedPosition = (long) ((index * elementSize) + offset);
        /* step 12 */
        return GetValueFromBuffer(cx, buffer, indexedPosition, elementType);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean elementSet(ExecutionContext cx, double index, Object value) {
        /* steps 1-2 (not applicable) */
        /* step 3 */
        ArrayBufferObject buffer = getBuffer();
        /* step 4 */
        if (buffer == null) {
            throw newTypeError(cx, Messages.Key.UninitialisedObject);
        }
        /* step 5 */
        long length = getArrayLength();
        /* steps 6-7 */
        double numValue = ToNumber(cx, value);
        /* step 8 */
        if (index < 0 || index >= length) {
            return false;
        }
        /* step 9 */
        long offset = getByteOffset();
        /* steps 10, 13 */
        ElementType elementType = getElementType();
        /* step 11 */
        int elementSize = elementType.size();
        /* step 12 */
        long indexedPosition = (long) ((index * elementSize) + offset);
        /* steps 14-15 */
        SetValueInBuffer(cx, buffer, indexedPosition, elementType, numValue);
        /* step 16 */
        return true;
    }

    /**
     * [[ViewedArrayBuffer]]
     */
    @Override
    public ArrayBufferObject getBuffer() {
        return buffer;
    }

    /**
     * [[ViewedArrayBuffer]]
     */
    public void setBuffer(ArrayBufferObject buffer) {
        assert buffer != null && buffer.getData() != null : "ArrayBufferObject not initialised";
        assert this.buffer == null : "TypedArrayObject already initialised";
        this.buffer = buffer;
    }

    /**
     * [[ElementType]]
     */
    public ElementType getElementType() {
        return elementType;
    }

    /**
     * [[ElementType]]
     */
    public void setElementType(ElementType elementType) {
        assert elementType != null;
        this.elementType = elementType;
    }

    /**
     * [[TypedArrayName]]
     */
    public String getTypedArrayName() {
        return elementType.getConstructorName();
    }

    /**
     * [[ByteLength]]
     */
    @Override
    public long getByteLength() {
        return byteLength;
    }

    /**
     * [[ByteLength]]
     */
    public void setByteLength(long byteLength) {
        assert byteLength >= 0 : "negative byte length: " + byteLength;
        this.byteLength = byteLength;
    }

    /**
     * [[ByteOffset]]
     */
    @Override
    public long getByteOffset() {
        return byteOffset;
    }

    /**
     * [[ByteOffset]]
     */
    public void setByteOffset(long byteOffset) {
        assert byteOffset >= 0 : "negative byte offset: " + byteOffset;
        this.byteOffset = byteOffset;
    }

    /**
     * [[ArrayLength]]
     */
    public long getArrayLength() {
        return arrayLength;
    }

    /**
     * [[ArrayLength]]
     */
    public void setArrayLength(long arrayLength) {
        assert arrayLength >= 0 : "negative array length: " + arrayLength;
        this.arrayLength = arrayLength;
    }
}


text:
var msg;
var level = 2;

// Determine message based on level
switch (level) {
	case 1:
		msg = 'Good luck on the first test';
		break;

	case 2:
		msg = 'Second of three - keep going!';
		break

	case 3:
		msg = 'Final round, almost there!';
		break;

	default:
		msg = 'Good luck!';
		break;
}

var el = document.getElementById('answer');
el.textContent = msg;


text:
namespace chrome {
namespace android {

// static
scoped_refptr<ToolbarLayer> ToolbarLayer::Create(
    ui::ResourceManager* resource_manager) {
  return make_scoped_refptr(new ToolbarLayer(resource_manager));
}

scoped_refptr<cc::Layer> ToolbarLayer::layer() {
  return layer_;
}

void ToolbarLayer::PushResource(
    int toolbar_resource_id,
    int toolbar_background_color,
    bool anonymize,
    int toolbar_textbox_background_color,
    int url_bar_background_resource_id,
    float url_bar_alpha,
    bool show_debug,
    float brightness,
    bool clip_shadow) {
  ui::ResourceManager::Resource* resource =
      resource_manager_->GetResource(ui::ANDROID_RESOURCE_TYPE_DYNAMIC,
                                     toolbar_resource_id);

  // Ensure the toolbar resource is available before making the layer visible.
  layer_->SetHideLayerAndSubtree(!resource);
  if (!resource)
    return;

  // This layer effectively draws over the space it takes for shadows.  Set the
  // bounds to the non-shadow size so that other things can properly line up.
  // Padding height does not include the height of the tabstrip, so we add
  // it explicitly by adding y offset.
  gfx::Size size = gfx::Size(
      resource->padding.width(),
      resource->padding.height() + resource->padding.y());
  layer_->SetBounds(size);

  toolbar_background_layer_->SetBounds(resource->padding.size());
  toolbar_background_layer_->SetPosition(
      gfx::PointF(resource->padding.origin()));
  toolbar_background_layer_->SetBackgroundColor(toolbar_background_color);

  bool url_bar_visible = (resource->aperture.width() != 0);
  url_bar_background_layer_->SetHideLayerAndSubtree(!url_bar_visible);
  if (url_bar_visible) {
    ui::ResourceManager::Resource* url_bar_background_resource =
        resource_manager_->GetResource(ui::ANDROID_RESOURCE_TYPE_STATIC,
                                       url_bar_background_resource_id);
    gfx::Size url_bar_size(
        resource->aperture.width() + url_bar_background_resource->size.width()
        - url_bar_background_resource->padding.width(),
        resource->aperture.height() + url_bar_background_resource->size.height()
        - url_bar_background_resource->padding.height());
    gfx::Rect url_bar_border(
        url_bar_background_resource->Border(url_bar_size));
    gfx::PointF url_bar_position = gfx::PointF(
        resource->aperture.x() - url_bar_background_resource->padding.x(),
        resource->aperture.y() - url_bar_background_resource->padding.y());

    url_bar_background_layer_->SetUIResourceId(
        url_bar_background_resource->ui_resource->id());
    url_bar_background_layer_->SetBorder(url_bar_border);
    url_bar_background_layer_->SetAperture(
        url_bar_background_resource->aperture);
    url_bar_background_layer_->SetBounds(url_bar_size);
    url_bar_background_layer_->SetPosition(url_bar_position);
    url_bar_background_layer_->SetOpacity(url_bar_alpha);
  }

  bitmap_layer_->SetUIResourceId(resource->ui_resource->id());
  bitmap_layer_->SetBounds(resource->size);

  layer_->SetMasksToBounds(clip_shadow);

  anonymize_layer_->SetHideLayerAndSubtree(!anonymize);
  if (anonymize) {
    anonymize_layer_->SetPosition(gfx::PointF(resource->aperture.origin()));
    anonymize_layer_->SetBounds(resource->aperture.size());
    anonymize_layer_->SetBackgroundColor(toolbar_textbox_background_color);
  }

  debug_layer_->SetBounds(resource->size);
  if (show_debug && !debug_layer_->parent())
    layer_->AddChild(debug_layer_);
  else if (!show_debug && debug_layer_->parent())
    debug_layer_->RemoveFromParent();

  if (brightness != brightness_) {
    brightness_ = brightness;
    cc::FilterOperations filters;
    if (brightness_ < 1.f)
      filters.Append(cc::FilterOperation::CreateBrightnessFilter(brightness_));
    layer_->SetFilters(filters);
  }
}

void ToolbarLayer::UpdateProgressBar(int progress_bar_x,
                                     int progress_bar_y,
                                     int progress_bar_width,
                                     int progress_bar_height,
                                     int progress_bar_color,
                                     int progress_bar_background_x,
                                     int progress_bar_background_y,
                                     int progress_bar_background_width,
                                     int progress_bar_background_height,
                                     int progress_bar_background_color) {
  bool is_progress_bar_background_visible = SkColorGetA(
      progress_bar_background_color);
  progress_bar_background_layer_->SetHideLayerAndSubtree(
      !is_progress_bar_background_visible);
  if (is_progress_bar_background_visible) {
    progress_bar_background_layer_->SetPosition(
        gfx::PointF(progress_bar_background_x, progress_bar_background_y));
    progress_bar_background_layer_->SetBounds(
        gfx::Size(progress_bar_background_width,
                  progress_bar_background_height));
    progress_bar_background_layer_->SetBackgroundColor(
        progress_bar_background_color);
  }

  bool is_progress_bar_visible = SkColorGetA(progress_bar_background_color);
  progress_bar_layer_->SetHideLayerAndSubtree(!is_progress_bar_visible);
  if (is_progress_bar_visible) {
    progress_bar_layer_->SetPosition(
        gfx::PointF(progress_bar_x, progress_bar_y));
    progress_bar_layer_->SetBounds(
        gfx::Size(progress_bar_width, progress_bar_height));
    progress_bar_layer_->SetBackgroundColor(progress_bar_color);
  }
}

ToolbarLayer::ToolbarLayer(ui::ResourceManager* resource_manager)
    : resource_manager_(resource_manager),
      layer_(cc::Layer::Create(content::Compositor::LayerSettings())),
      toolbar_background_layer_(
          cc::SolidColorLayer::Create(content::Compositor::LayerSettings())),
      url_bar_background_layer_(
          cc::NinePatchLayer::Create(content::Compositor::LayerSettings())),
      bitmap_layer_(
          cc::UIResourceLayer::Create(content::Compositor::LayerSettings())),
      progress_bar_layer_(
          cc::SolidColorLayer::Create(content::Compositor::LayerSettings())),
      progress_bar_background_layer_(
          cc::SolidColorLayer::Create(content::Compositor::LayerSettings())),
      anonymize_layer_(
          cc::SolidColorLayer::Create(content::Compositor::LayerSettings())),
      debug_layer_(
          cc::SolidColorLayer::Create(content::Compositor::LayerSettings())),
      brightness_(1.f) {
  toolbar_background_layer_->SetIsDrawable(true);
  layer_->AddChild(toolbar_background_layer_);

  url_bar_background_layer_->SetIsDrawable(true);
  url_bar_background_layer_->SetFillCenter(true);
  layer_->AddChild(url_bar_background_layer_);

  bitmap_layer_->SetIsDrawable(true);
  layer_->AddChild(bitmap_layer_);

  progress_bar_background_layer_->SetIsDrawable(true);
  progress_bar_background_layer_->SetHideLayerAndSubtree(true);
  layer_->AddChild(progress_bar_background_layer_);

  progress_bar_layer_->SetIsDrawable(true);
  progress_bar_layer_->SetHideLayerAndSubtree(true);
  layer_->AddChild(progress_bar_layer_);

  anonymize_layer_->SetIsDrawable(true);
  anonymize_layer_->SetBackgroundColor(SK_ColorWHITE);
  layer_->AddChild(anonymize_layer_);

  debug_layer_->SetIsDrawable(true);
  debug_layer_->SetBackgroundColor(SK_ColorGREEN);
  debug_layer_->SetOpacity(0.5f);
}

ToolbarLayer::~ToolbarLayer() {
}

}  //  namespace android
}  //  namespace chrome


text:
membrane-mu
===========

creep of membrane inside P matrix


text:
Converting the Heroes of Legend book into a simple python generator.

https://drive.google.com/file/d/0B2q3SyLsdffGV2NWSERMcTJtdlk/view


text:
This project is no longer in development. It is stored here for example and archive purposes.

# AEM Content Importer - Build

Maven Builds:

* Complete (content+bundle+saxon)
  Using profile `distribution` from either root or `aem-content-importer-content`.
  Assumes AEM 6.0 running on `localhost:4502`.

  For example:

  ```
  $ cd ~/my-code/aem-content-importer
  $ mvn -P distribution clean install
  ```

* Standard (only the selected project)
  With no profile specified maven installs only the selected project.
  Pay attention to aem-content-importer-bundle, the `/apps/${project.folder}/install` crx folder must exist

  *IMPORTANT: First install has to be done using profile `distribution`*

Maven tests:

* Unit-tests are executed by default.
* For launching integration-tests, it's necessary to use profile `integration-tests`.

# AEM Content Importer -  Upload Page
Go to the upload page: `http://<host>:<port>/content/resources/importer-tool.html`

You have two options:

* Fill out form parameters:
    * *Transformer*: Select from list (currently only one, `XMLTransformerDITA`). The value saved it'll be the whole package(`com.adobe.aem.importer.impl.DocImporterImpl`).
	* *Source folder*: Specify the source path in the repository. The folder must be already created and populated with
	  all the source files (including the `ditamap` file), for example, through dragging and dropping the files into
	  the repository using a WebDAV client. A typical location for the source directory is `/var/aem-importer/import`.
	* *Destination folder*: Specify the destination folder in the repository. Whether destination directory doesn't exist it will be created. i.e `content/dita-import`.
	* *Master File*: The name of the master file. For example, `mcloud.ditamap`.

* Upload a zip file containing all source files (contents+master+config) directly in the root or inside a folder. Note that the configuration file, which contains at least the same properties available in the form, must be the first file in the `zip` or `folder inside zip` package (alphabetical order).
  The upload can be performed either by dragging and dropping the `zip` file or by clicking the *Upload* button.
  Notice that config file values override the corresponding form parameters if they're filled them out.

  An example `config_param.xml`:

```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
 <entry key="xml-transformer">com.adobe.aem.importer.impl.DocImporterImpl</entry>
 <entry key="src">/var/aem-importer/import2</entry>
 <entry key="target">/content/pando</entry>
 <entry key="masterFile">mcloud.ditamap</entry>
 .....
 .....
</properties>
```

The result of upload page tool is to save a `.dita` file containing all configuration properties into path `/var/aem-importer/import`. This action fires the workflow model `aem-content-importer` in charge to process the importing

# Available Transformers

### XMLTransformerDITA

The XMLTransformerDITA transformer is currently the only one available and permits to import contents using an XSLT schema.
Here shown below the available parameters to set either in the form (custom properties input) or in zip (dita file):
* xslt-transformer: then class name of xslt transformer to use (i.e. net.sf.saxon.TransformerFactoryImpl). It's assume to be exported by an osgi bundle (it's available after first installation with `distribution` profile)
* xslt-file: the xslt file to use
* packageTpl: the path of package template to use by Jcr Archive Importer
* tempFolder: `optional, default '/var/aem-importer/tmp'` the temporary folder to use during processing
* graphicFolders: `optional, default 'images,graphics,Graphics'` the folder list separated by comma where to look up graphic resource to copy

An example of custom properties input in the form:
````
    xslt-transformer=net.sf.saxon.TransformerFactoryImpl
    xslt-file=/apps/aem-importer/resources/dita-to-content.xsl
    tempFolder=/var/aem-importer/tmp
    packageTpl=/apps/aem-importer/resources/package-tpl
    graphicFolders=images,graphics,Graphics
````

An example of `config_params.xml` containing XMLTransformerDITA properties also:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
 <entry key="xml-transformer">com.adobe.aem.importer.impl.DocImporterImpl</entry>
 <entry key="src">/var/aem-importer/import2</entry>
 <entry key="target">/content/pando</entry>
 <entry key="masterFile">mcloud.ditamap</entry>
 <entry key="xslt-transformer">net.sf.saxon.TransformerFactoryImpl</entry>
 <entry key="xslt-file">/apps/aem-importer/resources/dita-to-content.xsl</entry>
 <entry key="tempFolder">/var/aem-importer/tmp</entry>
 <entry key="packageTpl">/apps/aem-importer/resources/package-tpl</entry>
 <entry key="graphicFolders">images,graphics,Graphics</entry>
</properties>
```

### NoActionTransformer
Dummy transformer for testing service registration from external bundle

# Walkthrough test cases

### 1 - Zip File
*Manual steps*
* Go to page `http://<host>:<port>/content/resources/importer-tool.html`
* Zip folder `aem-content-importer-bundle/src/test/resources/exampleDITA`
* Drop in or load the zip file just created.
* Click Execute

*Automatic steps*
* find and read properties from the first file in the zip (in this case `0_config_params.xml`)
* all the files within zip are extracted into `/var/aem-importer/zip` (src param defined by `0_config_params.xml` file)
* a file `<id>.dita` is stored under `/var/aem-importer/import`
* workflow `aem-content-importer` is triggered and reads that configuration parameters
* check out if all parameters are set and invoke the selected transformer
* read and analyze master file `/var/aem-importer/zip/mcloud.ditamap`
* use the folder `/var/aem-importer/tmp` (creating an unique subfolder) as temporary repository (it will be deleted at the end)
* save final contents into `/content/dita-import`

### 2 - Input Form
*Manual steps*
* Go to page `http://<host>:<port>/content/resources/importer-tool.html`
* Fill in the **src** input the same folder used for previous test:
`/var/aem-importer/zip`
* Select from the **transformer** dropdown list:
`XMLTransformerDITA`
* Fill in the **master file** input:
`mcloud.ditamap`
* Fill in the **target** input a new destination path:
`/content/dita-import-2`
* Fill in the **custom properties** textarea all properties related to XSLT Transformer:
````
    xslt-transformer=net.sf.saxon.TransformerFactoryImpl
    xslt-file=/apps/aem-importer/resources/dita-to-content.xsl
    tempFolder=/var/aem-importer/tmp
    packageTpl=/apps/aem-importer/resources/package-tpl
    graphicFolders=images,graphics,Graphics
````
* Click Execute

*Automatic steps*
* save all parameters submitted in a file `<id>.dita` stored under `/var/aem-importer/import`
* workflow `aem-content-importer` is triggered and reads that configuration parameters
* check out if all parameters are set and invoke the selected transformer
* read and analyze master file `/var/aem-importer/zip/mcloud.ditamap`
* use the folder `/var/aem-importer/tmp` (creating an unique subfolder) as temporary repository (it will be deleted at the end)
* save final contents into `/content/dita-import-2`

### 3 - Workflow overriding
*Manual steps*
* Go to page `http://<host>:<port>/etc/workflow/models/aem-content-importer.html`
* Open edit dialog of `Content Transformer Process` step and select the tab `arguments`
* Insert into the input `target` the path `/content/dita-import-3`
* Click Save button on the top left corner
* Go to page `http://<host>:<port>/content/resources/importer-tool.html`
* Zip folder `aem-content-importer-bundle/src/test/resources/exampleDITA`
* Drop in or load the zip file just created.
* Click Execute

*Automatic steps*
* find and read properties from the first file in the zip (in this case `0_config_params.xml`)
* all the files within zip are extracted into `/var/aem-importer/zip` (src param defined by `0_config_params.xml` file)
* a file `<id>.dita` is stored under `/var/aem-importer/import`
* workflow `aem-content-importer` is triggered, reads that configuration parameters but gives the priority to those set inside
* check out if all parameters are set and invoke the selected transformer
* read and analyze master file `/var/aem-importer/zip/mcloud.ditamap`
* use the folder `/var/aem-importer/tmp` (creating an unique subfolder) as temporary repository (it will be deleted at the end)
* save final contents into `/content/dita-import-3`

# AEM Content Importer -  Command Line
* Maven install project aem-content-importer-cmd, that it's going to generate a lib folder with all necessary libraries and the runnable jar
file to execute inside project folder `aem-content-importer\tools-files`.
* There are two scripts in that project folder, one for linux (script.sh) and the other one for windows (script.bat) showing two examples: passing parameters, passing zip file that it's in that folder as well or a local folder with all source files for making the transformation.
* If it's necessary to pass custom properties, it's a mandatory to separate properties using the special character '#'. You can see it in script examples.
* If you have some doubts related to how to pass parameters execute the runnable jar without params. It'll be showed and explanation of each possible parameter.
An example:

````
java -jar aem-content-importer-cmd-0.0.1-SNAPSHOT.jar -src /var/aem-importer/import1 -transformer com.adobe.aem.importer.impl.DocImporterImpl -masterFile mcloud.ditamap -target /content/pando -customProps xslt-transformer=net.sf.saxon.TransformerFactoryImpl#xslt-file=/apps/aem-importer/resources/dita-to-content.xsl#tempFolder=/var/aem-importer/tmp#packageTpl=/apps/aem-importer/resources/package-tpl#graphicFolders=images,graphics,Graphics
````


text:
package fr.vidal.webservices.productservice;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for SafetyAlertStatus.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="SafetyAlertStatus">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="NO"/>
 *     <enumeration value="YES"/>
 *     <enumeration value="UNAVAILABLE"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "SafetyAlertStatus")
@XmlEnum
public enum SafetyAlertStatus {

    NO,
    YES,
    UNAVAILABLE;

    public String value() {
        return name();
    }

    public static SafetyAlertStatus fromValue(String v) {
        return valueOf(v);
    }

}


text:
package storage

import (
	"github.com/hyperledger/burrow/storage"
	dbm "github.com/tendermint/tm-db"
)

type CacheDB struct {
	cache   *KVCache
	backend storage.KVIterableReader
}

func NewCacheDB(backend storage.KVIterableReader) *CacheDB {
	return &CacheDB{
		cache:   NewKVCache(),
		backend: backend,
	}
}

// DB implementation
func (cdb *CacheDB) Get(key []byte) ([]byte, error) {
	value, deleted := cdb.cache.Info(key)
	if deleted {
		return nil, nil
	}
	if value != nil {
		return value, nil
	}
	return cdb.backend.Get(key)
}

func (cdb *CacheDB) Has(key []byte) (bool, error) {
	value, deleted := cdb.cache.Info(key)
	has, err := cdb.backend.Has(key)
	if err != nil {
		return false, err
	}
	return !deleted && (value != nil || has), nil
}

func (cdb *CacheDB) Iterator(low, high []byte) (storage.KVIterator, error) {
	// Keys from cache will sort first because of order in MultiIterator and Uniq will take the first KVs so KVs
	// appearing in cache will override values from backend.
	iterator, err := cdb.backend.Iterator(low, high)
	if err != nil {
		return nil, err
	}

	return Uniq(NewMultiIterator(false, cdb.cache.Iterator(low, high), iterator)), nil
}

func (cdb *CacheDB) ReverseIterator(low, high []byte) (storage.KVIterator, error) {
	iterator, err := cdb.backend.ReverseIterator(low, high)
	if err != nil {
		return nil, err
	}

	return Uniq(NewMultiIterator(true, cdb.cache.ReverseIterator(low, high), iterator)), nil
}

func (cdb *CacheDB) Set(key, value []byte) error {
	cdb.cache.Set(key, value)
	return nil
}

func (cdb *CacheDB) SetSync(key, value []byte) error {
	cdb.cache.Set(key, value)
	return nil
}

func (cdb *CacheDB) Delete(key []byte) error {
	cdb.cache.Delete(key)
	return nil
}

func (cdb *CacheDB) DeleteSync(key []byte) error {
	return cdb.Delete(key)
}

func (cdb *CacheDB) Close() error {
	return nil
}

func (cdb *CacheDB) NewBatch() dbm.Batch {
	return &cacheBatch{
		cache:   NewKVCache(),
		backend: cdb,
	}
}

func (cdb *CacheDB) Commit(writer storage.KVWriter) {
	cdb.cache.WriteTo(writer)
	cdb.cache.Reset()
}

type cacheBatch struct {
	cache   *KVCache
	backend *CacheDB
}

func (cb *cacheBatch) Set(key, value []byte) error {
	cb.cache.Set(key, value)
	return nil
}

func (cb *cacheBatch) Delete(key []byte) error {
	cb.cache.Delete(key)
	return nil
}

func (cb *cacheBatch) Write() error {
	cb.cache.WriteTo(cb.backend)
	return nil
}

func (cb *cacheBatch) Close() error {
	return nil
}

func (cb *cacheBatch) WriteSync() error {
	return cb.Write()
}

func (cdb *CacheDB) Print() error {
	return nil
}

func (cdb *CacheDB) Stats() map[string]string {
	return map[string]string{}
}


text:
* Added encode and decode commands
 * Encode files and unsaved tabs
 * Decode saved and unsaved hex dumps

##0.1.1 - Bug Fix
* Fixed issue with trying to run the package on non-TextEditor objects
* Changed menu to only show package options when a TextEditor was selected
* Clarified instructions in README.md


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package kr.co.bitnine.octopus.schema;

import kr.co.bitnine.octopus.meta.model.MetaColumn;
import kr.co.bitnine.octopus.meta.model.MetaTable;
import org.apache.calcite.adapter.java.AbstractQueryableTable;
import org.apache.calcite.linq4j.QueryProvider;
import org.apache.calcite.linq4j.Queryable;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rel.type.RelDataTypeImpl;
import org.apache.calcite.rel.type.RelDataTypeSystem;
import org.apache.calcite.rel.type.RelProtoDataType;
import org.apache.calcite.schema.Schema;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.sql.type.SqlTypeFactoryImpl;
import org.apache.calcite.sql.type.SqlTypeName;

public abstract class OctopusTable extends AbstractQueryableTable {
    private Schema.TableType tableType;
    private RelProtoDataType protoRowType;
    private final OctopusSchema schema;
    private final String name;

    public OctopusTable(MetaTable metaTable, OctopusSchema schema) {
        super(Object[].class);
        name = metaTable.getName();

        try {
            //tableType = Schema.TableType.valueOf(table.getType().name());
            tableType = Schema.TableType.TABLE; // FIXME
        } catch (IllegalArgumentException e) {
            tableType = Schema.TableType.TABLE;
        }

        RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(RelDataTypeSystem.DEFAULT);
        RelDataTypeFactory.FieldInfoBuilder fieldInfo = typeFactory.builder();
        for (MetaColumn metaColumn : metaTable.getColumns()) {
            String columnName = metaColumn.getName();

            //int jdbcType = metaColumn.getType().getJdbcType();
            int jdbcType = metaColumn.getType(); //FIXME
            SqlTypeName typeName = SqlTypeName.getNameForJdbcType(jdbcType);
            RelDataType sqlType = typeFactory.createSqlType(typeName);

            fieldInfo.add(columnName, sqlType);
        }
        protoRowType = RelDataTypeImpl.proto(fieldInfo.build());

        this.schema = schema;
    }

    public final String getName() {
        return name;
    }

    @Override
    public final RelDataType getRowType(RelDataTypeFactory relDataTypeFactory) {
        return protoRowType.apply(relDataTypeFactory);
    }

    @Override
    public final Schema.TableType getJdbcTableType() {
        return tableType;
    }

    public final OctopusSchema getSchema() {
        return schema;
    }

    public final RelProtoDataType getProtoRowType() {
        return protoRowType;
    }

    @Override
    public abstract <T> Queryable<T> asQueryable(QueryProvider queryProvider, SchemaPlus schemaPlus, String tableName);
}


text:
package nlp_automl

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// GetPredictResult invokes the nlp_automl.GetPredictResult API synchronously
// api document: https://help.aliyun.com/api/nlp-automl/getpredictresult.html
func (client *Client) GetPredictResult(request *GetPredictResultRequest) (response *GetPredictResultResponse, err error) {
	response = CreateGetPredictResultResponse()
	err = client.DoAction(request, response)
	return
}

// GetPredictResultWithChan invokes the nlp_automl.GetPredictResult API asynchronously
// api document: https://help.aliyun.com/api/nlp-automl/getpredictresult.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetPredictResultWithChan(request *GetPredictResultRequest) (<-chan *GetPredictResultResponse, <-chan error) {
	responseChan := make(chan *GetPredictResultResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.GetPredictResult(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// GetPredictResultWithCallback invokes the nlp_automl.GetPredictResult API asynchronously
// api document: https://help.aliyun.com/api/nlp-automl/getpredictresult.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetPredictResultWithCallback(request *GetPredictResultRequest, callback func(response *GetPredictResultResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *GetPredictResultResponse
		var err error
		defer close(result)
		response, err = client.GetPredictResult(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// GetPredictResultRequest is the request struct for api GetPredictResult
type GetPredictResultRequest struct {
	*requests.RpcRequest
	TopK         requests.Integer `position:"Body" name:"TopK"`
	ModelId      requests.Integer `position:"Body" name:"ModelId"`
	DetailTag    string           `position:"Body" name:"DetailTag"`
	Content      string           `position:"Body" name:"Content"`
	ModelVersion string           `position:"Body" name:"ModelVersion"`
}

// GetPredictResultResponse is the response struct for api GetPredictResult
type GetPredictResultResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
	Content   string `json:"Content" xml:"Content"`
}

// CreateGetPredictResultRequest creates a request to invoke GetPredictResult API
func CreateGetPredictResultRequest() (request *GetPredictResultRequest) {
	request = &GetPredictResultRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("nlp-automl", "2019-11-11", "GetPredictResult", "nlpautoml", "openAPI")
	return
}

// CreateGetPredictResultResponse creates a response to parse from GetPredictResult response
func CreateGetPredictResultResponse() (response *GetPredictResultResponse) {
	response = &GetPredictResultResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
from django.conf import settings

from .functions import get_images, sync_data

class Client(object):

    def __init__(self, api_token=None, api_url=None, media_url=None):
        self.api_token = api_token or settings.SYNCTOOL_CLIENT_TOKEN
        self.api_url = api_url or settings.SYNCTOOL_CLIENT_ENDPOINT
        self.media_url = media_url

    def get_url(self, url):
        return "%s%s/" % (self.api_url, url)

    def sync(self, url, **kwargs):
        sync_data(
            url=self.get_url(url),
            api_token=self.api_token,
            clean=kwargs.get("clean", False),
            reset=kwargs.get("reset", True),
            images=kwargs.get("images", False),
            media_url=self.media_url,
        )

    def images(self, queryset, field):
        get_images(
            base_url=self.media_url,
            queryset=queryset,
            field=field,
        )


text:
#ifndef _VARCHECK_H_
#define _VARCHECK_H_

#include "EfiShellLib.h"
//
// Shell command variable checking support
//
typedef enum {
  FlagTypeSingle      = 0,
  FlagTypeNeedVar,
  FlagTypeNeedSet,
  FlagTypeSkipUnknown
} SHELL_VAR_CHECK_FLAG_TYPE;

typedef enum {
  ARG_NO_ATTRIB         = 0x0,
  ARG_IS_QUOTED         = 0x1,
  ARG_PARTIALLY_QUOTED  = 0x2,
  ARG_FIRST_HALF_QUOTED = 0x4,
  ARG_FIRST_CHAR_IS_ESC = 0x8
};

typedef struct {
  CHAR16                    *FlagStr;
  UINT32                    FlagID;
  UINT32                    ConflictMask;
  SHELL_VAR_CHECK_FLAG_TYPE FlagType;
} SHELL_VAR_CHECK_ITEM;

typedef struct _SHELL_ARG_LIST {
  CHAR16                  *FlagStr;
  CHAR16                  *VarStr;
  UINTN                   Index;
  struct _SHELL_ARG_LIST  *Next;
} SHELL_ARG_LIST;

#define GetNextArg(a)   ((a)->Next)
#define GetFirstArg(a)  ((a)->VarList)
#define GetFirstFlag(a) ((a)->FlagList)

typedef struct {
  SHELL_ARG_LIST  *FlagList;
  SHELL_ARG_LIST  *VarList;
  UINTN           FlagCount;
  UINTN           ValueCount;
} SHELL_VAR_CHECK_PACKAGE;

typedef enum {
  VarCheckReserved      = -1,
  VarCheckOk            = 0,
  VarCheckDuplicate,
  VarCheckConflict,
  VarCheckUnknown,
  VarCheckLackValue,
  VarCheckOutOfMem
} SHELL_VAR_CHECK_CODE;

VOID
LibCheckVarFreeVarList (
  IN SHELL_VAR_CHECK_PACKAGE    *ChkPck
  );

SHELL_ARG_LIST  *
LibCheckVarGetFlag (
  IN SHELL_VAR_CHECK_PACKAGE   *ChkPck,
  IN CHAR16                    *FlagStr
  );

SHELL_VAR_CHECK_CODE
LibCheckVariables (
  IN VOID                             *ShellInt,
  IN SHELL_VAR_CHECK_ITEM             *CheckList,
  OUT SHELL_VAR_CHECK_PACKAGE         *ChkPck,
  OUT CHAR16                          **Useful
  );

SHELL_VAR_CHECK_CODE
LibCheckRedirVariables (
  IN VOID                             *si,
  IN SHELL_VAR_CHECK_ITEM             *CheckList,
  OUT SHELL_VAR_CHECK_PACKAGE         *ChkPck,
  OUT CHAR16                          **Useful
  );

EFI_STATUS
LibGetStdRedirFilename (
  OUT CHAR16             **FullFilename
  );

EFI_STATUS
LibGetErrRedirFilename (
  OUT CHAR16             **FullFilename
  );

#endif


text:
package camelinaction;

import org.apache.camel.Processor;
import org.apache.camel.util.component.AbstractApiConsumer;

import camelinaction.internal.HiWorldApiName;

/**
 * The HiWorld consumer.
 */
public class HiWorldConsumer extends AbstractApiConsumer<HiWorldApiName, HiWorldConfiguration> {

    public HiWorldConsumer(HiWorldEndpoint endpoint, Processor processor) {
        super(endpoint, processor);
    }

}


text:
var assert = require('assert'),
    path = require('path'),
    edgerc = require('../../src/edgerc');

describe('edgerc', function() {
  describe('the parsed edgrc file it returns', function() {
    describe('when it is not passed a second argument indicating config section', function() {
      beforeEach(function() {
        this.config = edgerc(path.resolve(__dirname, '../test_edgerc'));
      });

      it('reports the default host', function() {
        assert.equal(this.config.host, 'https://example.luna.akamaiapis.net');
      });

      it('reports the default client_token', function() {
        assert.equal(this.config.client_token, 'clientToken');
      });

      it('reports the default client_secret', function() {
        assert.equal(this.config.client_secret, 'clientSecret');
      });

      it('reports the default access_token', function() {
        assert.equal(this.config.access_token, 'accessToken');
      });
    });

    describe('when it is passed a second argument indicating config section', function() {
      beforeEach(function() {
        this.config = edgerc(path.resolve(__dirname, '../test_edgerc'), 'section');
      });

      it('reports the host associated with the section', function() {
        assert.equal(this.config.host, 'https://sectionexample.luna.akamaiapis.net');
      });

      it('reports the client_token associated with the section', function() {
        assert.equal(this.config.client_token, 'sectionClientToken');
      });

      it('reports the client_secret associated with the section', function() {
        assert.equal(this.config.client_secret, 'sectionClientSecret');
      });

      it('reports the access_token associated with the section', function() {
        assert.equal(this.config.access_token, 'sectionAccessToken');
      });
    });

    describe('when the section contains a host with the "https://" protocal specified', function() {
      beforeEach(function() {
        this.config = edgerc(path.resolve(__dirname, '../test_edgerc'), 'https');
      });

      it('reports a host with a valid URI string', function() {
        assert.equal(this.config.host, 'https://example.luna.akamaiapis.net');
      });
    });

    describe('when the section passed does not exist', function() {
      it('throws the proper error', function() {
        assert.throws(
          function() {
            return edgerc(path.resolve(__dirname, '../test_edgerc'), 'blah');
          },
          /An error occurred parsing the .edgerc file. You probably specified an invalid section name./
        );
      });
    });
  });
});


text:
#ifndef MODULES_DESKTOP_CAPTURE_DESKTOP_FRAME_WIN_H_
#define MODULES_DESKTOP_CAPTURE_DESKTOP_FRAME_WIN_H_

#include <memory>

#include <windows.h>

#include "modules/desktop_capture/desktop_frame.h"
#include "rtc_base/constructormagic.h"
#include "typedefs.h"  // NOLINT(build/include)

namespace webrtc {

// DesktopFrame implementation used by screen and window captures on Windows.
// Frame data is stored in a GDI bitmap.
class DesktopFrameWin : public DesktopFrame {
 public:
  ~DesktopFrameWin() override;

  static std::unique_ptr<DesktopFrameWin>
  Create(DesktopSize size, SharedMemoryFactory* shared_memory_factory, HDC hdc);

  HBITMAP bitmap() { return bitmap_; }

 private:
  DesktopFrameWin(DesktopSize size,
                  int stride,
                  uint8_t* data,
                  std::unique_ptr<SharedMemory> shared_memory,
                  HBITMAP bitmap);

  HBITMAP bitmap_;
  std::unique_ptr<SharedMemory> owned_shared_memory_;

  RTC_DISALLOW_COPY_AND_ASSIGN(DesktopFrameWin);
};

}  // namespace webrtc

#endif  // MODULES_DESKTOP_CAPTURE_DESKTOP_FRAME_WIN_H_


text:
var handleRedirection = function () {
    if (Ext.os.deviceType !== "Desktop") {
        var query = Ext.Object.fromQueryString(window.location.search),
            queryRedirect = query.redirect;

        if (!Ext.isEmpty(queryRedirect)) {
            queryRedirect = Ext.JSON.decode(queryRedirect);

            if (queryRedirect === false) {
                return;
            } else if (queryRedirect === true) {
                window.location = "https://mobile.ext.net";
                return;
            }
        }

        var cookieRedirect = Ext.util.Cookies.get("redirect");

        if (!Ext.isEmpty(cookieRedirect)) {
            cookieRedirect = Ext.JSON.decode(cookieRedirect);

            if (cookieRedirect === false) {
                return;
            } else if (cookieRedirect === true) {
                window.location = "https://mobile.ext.net";
                return;
            }
        }

        // Rich this code if neither query string nor Cookie directives
        // So, we should ask the user eiter redirect or stay
        Ext.onReady(function () {
            App.RedirectOverlay.show();
        });
    }
};

handleRedirection();

Ext.grid.NavigationModel.override({
    onKeyUp: function (keyEvent) {
        var newRecord = keyEvent.view.walkRecs(keyEvent.record, -1);

        if (newRecord && newRecord !== keyEvent.record) {
            this.setPosition(newRecord, this.columnIndex, keyEvent);
        } else {
            keyEvent.view.getSelectionModel().deselectAll();
            App.SearchField.focus(false, 100);
        }
    }
});

Ext.onReady(function () {
    var sidebarRight = document.getElementById('rightnav-body');
    Ps.initialize(sidebarRight);

    Ext.get("menu-button", true).on({
        click: function () {
            App.rightnav[App.rightnav.isHidden() ? "show" : "hide"]();
            Ps.update(sidebarRight);
        }
    });

    Ext.select("[data-toggle='collapse'", true).on({
        click: function (e) {
            e.preventDefault();

            this.toggleCls("expanded");
            Ext.get((this.getAttribute("data-target")).substring(1)).toggleCls("expanded");
        }
    });
});

var SEARCH_URL = "/search/",
    TAG_CLOUD_TOKEN = "/TagCloud",
    lockHistoryChange = false;

var tagLabelConfig = {
    trackOver: true,
    listeners: {
        beforetagadd: function (field, tag, o) {
            tag.overCls = "example-tag";
            o["data-qtip"] = "Click to filter examples by '" + tag.text + "'";
        },
        click: function (field, tag) {
            var searchField = App.SearchField;

            searchField.setValue(tag.text);
            changeFilterHash(tag.text.replace(" ", "+"));
            filter(searchField, true);
        }
    }
};

var createTagItems = function (tab, node) {
    var tb = tab.getDockedItems('toolbar[dock="top"]')[0];

    tb.insert(1, {
        xtype: "tbseparator"
    });

    if (node.data.tags.length > 0) {
        tb.insert(2, Ext.applyIf({
            xtype: "taglabel",
            tags: node.data.tags
        }, tagLabelConfig));
    }
};

var makeTab = function (id, url, title) {
    var win,
        tab,
        hostName,
        exampleName,
        node,
        tabTip;

    if (id === "-") {
        id = Ext.id(undefined, "extnet");
        lookup[url] = id;
    }

    tabTip = url.replace(/^\//g, "");
    tabTip = tabTip.replace(/\/$/g, "");
    tabTip = tabTip.replace(/\//g, " > ");
    tabTip = tabTip.replace(/_/g, " ");

    win = new Ext.window.Window({
        id: "w" + id,
        layout: "fit",
        title: "Source Code",
        iconCls: "fa fa-code",
        width: 925,
        height: 650,
        border: false,
        maximizable: true,
        constrain: true,
        closeAction: "hide",
        listeners: {
            show: {
                fn: function () {
                    var me = this,
                        height = Ext.getBody().getViewSize().height;

                    if (this.getSize().height > height) {
                        this.setHeight(height - 20)
                    }

                    App.direct.GetSourceTabs(id, url, this.nsId, {
                        eventMask: {
                            showMask: true,
                            customTarget: this.body
                        },
                        failure: function (msg, response) {
                            Ext.Msg.alert("Failure", "The error during example loading:\n" + response.responseText);
                        }
                    });
                },

                single: true
            }
        },
        buttons: [
            {
                id: "b" + id,
                text: "Download",
                iconCls: "fa fa-download",
                listeners: {
                    click: {
                        fn: function (el, e) {
                            App.direct.DownloadExample(url, {
                                isUpload: true,
                                formId: "downloadForm"
                            });
                        }
                    }
                }
            }
        ]
    });

    hostName = window.location.protocol + "//" + window.location.host;
    exampleName = url;

    tab = App.ExampleTabs.add(new Ext.panel.Panel({
        id: id,
        tbar: [{
            text: "Source Code",
            iconCls: "fa fa-code",
            listeners: {
                "click": function () {
                    Ext.getCmp("w" + id).show(null);
                }
            }
        },
        "->",
        {
            text: "Direct Link",
            iconCls: "fa fa-link",
            handler: function () {
                new Ext.window.Window({
                    modal: true,
                    iconCls: "fa fa-link",
                    layout: "absolute",
                    defaultButton: "dl" + id,
                    width: 400,
                    height: 140,
                    title: "Direct Link",
                    closable: false,
                    resizable: false,
                    items: [{
                        id: "dl" + id,
                        xtype: "textfield",
                        cls: "dlText",
                        width: 364,
                        x: 10,
                        y: 10,
                        selectOnFocus: true,
                        readOnly: true,
                        value: hostName + "/#" + exampleName
                    }],
                    buttons: [{
                        xtype: "button",
                        text: " Open",
                        iconCls: "fa fa-external-link",
                        tooltip: "Open Example in the separate window",
                        handler: function () {
                            window.open(hostName + "/#" + exampleName);
                        }
                    },
                    {
                        xtype: "button",
                        text: " Open (Direct)",
                        iconCls: "fa fa-external-link-square",
                        tooltip: "Open Example in the separate window using a direct link",
                        handler: function () {
                            window.open(hostName + url, "_blank");
                        }
                    },
                    {
                        xtype: "button",
                        text: "Close",
                        handler: function () {
                            this.findParentByType("window").hide(null);
                        }
                    }]
                }).show(null);
            }
        },
        "-",
        {
            text: "Refresh",
            handler: function () {
                Ext.getCmp(id).reload(true)
            },
            iconCls: "fa fa-refresh"
        }],
        title: title,
        tabTip: tabTip,
        hideMode: "offsets",

        loader: {
            renderer: "frame",
            url: hostName + url,
            listeners: {
                beforeload: function () {
                    this.target.body.mask('Loading...');
                },
                load: function (loader) {
                    this.target.body.unmask();
                }
            }
        },
        listeners: {
            deactivate: {
                fn: function (el) {
                    if (this.sWin && this.sWin.isVisible()) {
                        this.sWin.hide();
                    }
                }
            },

            destroy: function () {
                if (this.sWin) {
                    this.sWin.close();
                    this.sWin.destroy();
                }
            }
        },
        closable: true
    }));

    tab.sWin = win;
    setTimeout(function () {
        App.ExampleTabs.setActiveTab(tab);
    }, 250);

    var node = App.exampleTree.getStore().getNodeById(id),
        expandAndSelect = function (node) {
            var view = App.exampleTree.getView(),
                originalAnimate = view.animate;

            view.animate = false;
            node.bubble(function (node) {
                node.expand(false);
            });

            App.exampleTree.getSelectionModel().select(node);
            view.animate = originalAnimate;
        };

    if (node) {
        expandAndSelect(node);
        createTagItems(tab, node);
    } else {
        App.exampleTree.on("load", function (node) {
            node = App.exampleTree.getStore().getNodeById(id);
            if (node) {
                expandAndSelect(node);
                createTagItems(tab, node);
            }
        }, this, { delay: 10, single: true });
    }
};

var lookup = {};

var onTreeAfterRender = function (tree) {
    var sm = tree.getSelectionModel();

    Ext.create('Ext.util.KeyNav', {
        target: tree.view.el,
        enter: function (e) {
            if (sm.hasSelection()) {
                onTreeItemClick(sm.getSelection()[0], e);
            }
        }
    });
};

var onTreeItemClick = function (record, e) {
    if (record.isLeaf()) {
        e.stopEvent();
        loadExample(record.get('url'), record.getId(), record.get('text'));
    } else {
        record[record.isExpanded() ? 'collapse' : 'expand']();
    }
};

var treeRenderer = function (value, metadata, record) {
    if (record.data.flags) {
        if (record.data.flags == "n") {
            value += "New";
        } else if (record.data.flags == "u") {
            value += "Update";
        }
    }

    return value;
};

var loadExample = function (href, id, title) {
    var tab = App.ExampleTabs.getComponent(id),
        lObj = lookup[href];

    var slashFields = href.split("/");
    if (slashFields.length > 3) {
        href = "";
        for (var i in [0, 1, 2]) {
            href = href + slashFields[i] + "/"
        }
    } else if(href[href.length - 1] != "/") {
        href = href + "/";
    }

    if (id == "-") {
        App.direct.GetHashCode(href, {
            success: function (result) {
                loadExample(href, "e" + result, title);
            }
        });

        return;
    }

    lookup[href] = id;

    if (tab) {
        App.ExampleTabs.setActiveTab(tab);
    } else {
        if (Ext.isEmpty(title)) {
            var m = /(\w+)\/$/g.exec(href);
            title = m == null ? "[No name]" : m[1];
        }

        title = title.replace(/ <\/span>/g, "");
        title = title.replace(/_/g, " ");
        makeTab(id, href, title);
    }
};

var viewClick = function (dv, e) {
    var group = e.getTarget("h2", 3, true);

    if (group) {
        group.up("div").toggleClass("collapsed");
    }
};

var beforeSourceShow = function (el) {
    var height = Ext.getBody().getViewSize().height;

    if (el.getSize().height > height) {
        el.setHeight(height - 20);
    }
};

var change = function (token) {
    if (!lockHistoryChange) {
        if (token) {
            if (token.indexOf(SEARCH_URL) === 0) {
                filterByUrl(token);
            } else if (token === TAG_CLOUD_TOKEN) {
                showTagCloud();
            } else {
                loadExample(token, lookup[token] || "-");
            }
        } else {
            App.ExampleTabs.setActiveTab(0);
        }
    }
    lockHistoryChange = false;
};

var getToken = function (url) {
    var host = window.location.protocol + "//" + window.location.host;

    return url.substr(host.length);
};

var addToken = function (el, tab) {
    if (tab.loader && tab.loader.url) {
        var token = getToken(tab.loader.url);

        Ext.History.add(token);
    } else if (tab.historyToken) {
        Ext.History.add(tab.historyToken);
    } else {
        Ext.History.add("");
    }
};

var keyUp = function (field, e) {
    if (e.getKey() === 40) {
        return;
    }

    if (e.getKey() === Ext.event.Event.ESC) {
        clearFilter(field);
    } else {
        changeFilterHash(field.getRawValue().replace(" ", "+"));
        filter(field);
    }
};

/*
    field: the search field
    byTagsOnly: true means searcing by tags only and by full matching
*/
var filter = function (field, byTagsOnly) {
    var tree = App.exampleTree,
        text = field.getRawValue(),
        view = tree.getView(),
        originalAnimate = view.animate;

    if (Ext.isEmpty(text, false)) {
        clearFilter(field);
        return;
    }

    if (text.length < 2) {
        return;
    }

    field.getTrigger(0).show();

    var re = new RegExp(".*" + text + ".*", "i");

    tree.clearFilter(true);

    tree.filterBy(function (node) {
        var tags = node.data.tags,
            hasTags = Ext.isArray(node.data.tags) && node.data.tags.length > 0,
            match = false,
            pn = node.parentNode,
            pnIsFixed = false,
            i, len,
            tagMatch = false;

        if (App.SearchByTitles.checked && !byTagsOnly) {
            match = re.test(node.data.text);
        }

        if ((App.SearchByTags.checked || byTagsOnly) && hasTags) {
            if (byTagsOnly) {
                match = match || Ext.Array.contains(tags, text);
            } else {
                for (i = 0, len = tags.length; i < len; i++) {
                    if (re.test(tags[i])) {
                        match = true;
                        break;
                    }
                }
            }
        }

        if (match && node.isLeaf()) {
            pn.hasMatchNode = true;
        }

        if (pn) {
            node.bubble(function (n) {
                if (node != n) {
                    pnIsFixed = re.test(n.data.text);

                    return !pnIsFixed;
                }
            });
        }

        if (pn != null && pnIsFixed) {
            return true;
        }

        if (node.isLeaf() === false) {
            return match;
        }

        return pnIsFixed || match;
    }, { expandNodes: false });

    view.animate = false;
    tree.getRootNode().cascadeBy(function (node) {
        if (node.isRoot()) {
            return;
        }

        if ((node.getDepth() === 1) ||
            (node.getDepth() === 2 && node.hasMatchNode)) {
            node.expand(false);
        }

        delete node.hasMatchNode;
    }, tree);

    view.animate = originalAnimate;
};

var filterByUrl = function (url) {
    var field = App.SearchField,
        tree = App.exampleTree;

    if (!lockHistoryChange) {
        var tree = App.exampleTree,
            store = tree.getStore(),
            fn = function () {
                field.setValue(url.substr(SEARCH_URL.length).replace("+", " "));
                filter(field);
            };

        if (store.loading) {
            store.on("load", fn, null, { single: true, delay: 100 });
        } else {
            fn();
        }
    }
};

var clearFilter = function (field, trigger, index, e) {
    var tree = App.exampleTree;

    field.setValue("");
    changeFilterHash("");
    field.getTrigger(0).hide();
    tree.clearFilter(true);
    field.focus(false, 100);
};

var changeFilterHash = Ext.Function.createBuffered(
    function (text) {
        lockHistoryChange = true;
        if (text.length > 2) {
            window.location.hash = SEARCH_URL + text;
        } else {
            var tab = App.ExampleTabs.getActiveTab(),
                token = "";

            if (tab.loader && tab.loader.url) {
                token = getToken(tab.loader.url);
            }

            Ext.History.add(token);
        }
    },
    500);

var filterSpecialKey = function (field, e) {
    var tree = App.exampleTree,
        view = tree.getView();

    if (e.getKey() === e.DOWN) {
        var n = tree.getRootNode().findChildBy(function (node) {
            return node.isLeaf() && node.data.visible;
        }, tree, true);

        if (n) {
            tree.expandPath(n.getPath(), null, null, function () {
                tree.getSelectionModel().select(n);
            });
        }
    }
};

var filterNewExamples = function (checkItem, checked) {
    var tree = App.exampleTree;

    if (checked) {
        tree.clearFilter(true);
        tree.filterBy(function (node) {
            return node.data.isNew;
        });
    } else {
        tree.clearFilter(true);
    }
};

var swapThemeClass = function (frame, oldTheme, newTheme) {
    var html = Ext.fly(frame.document.body.parentNode);

    html.removeCls('x-theme-' + oldTheme);
    html.addCls('x-theme-' + newTheme);
};

var themeChange = function (menu, menuItem) {
    App.direct.SetTheme(menuItem.text, {
        success: function (result) {
            App.ExampleTabs.items.each(function(tab) {
                if (tab.id !== "tabHome") {
                    tab.getBody().location.reload();
                }
            });
        }
    });
};

var getAllTags = function () {
    var tags = [],
        root = App.exampleTree.getRootNode();

    root.cascadeBy(function (node) {
        if (Ext.isArray(node.data.tags)) {
            tags = tags.concat(node.data.tags)
        }
    });

    tags = Ext.Array.unique(tags);

    return Ext.Array.sort(tags);
};

var showTagCloud = function () {
    var tabPanel = App.ExampleTabs,
        tabId = "tagCloudTab",
        tab = tabPanel.getComponent(tabId);

    if (!tab) {
        tab = Ext.create("Ext.panel.Panel", {
            id: tabId,
            title: "Tag Cloud",
            icon: "#WeatherClouds",
            closable: true,
            url: "TagCloud",
            margin: 20,
            historyToken: TAG_CLOUD_TOKEN,
            items: [
                Ext.applyIf({
                    xtype: "taglabel",
                    tags: getAllTags()
                }, tagLabelConfig)
            ]
        });

        tabPanel.addTab(tab);
    }

    tabPanel.setActiveTab(tab);
};

if (window.location.href.indexOf("#") > 0) {
    var directLink = window.location.href.substr(window.location.href.indexOf("#") + 1)
                    .replace(/(\s|\<|<|%22|%3C|\"|\'|&quot|'|script)/gi, '');

    Ext.onReady(function () {
        Ext.Function.defer(function () {
            if (directLink.indexOf(SEARCH_URL) === 0) {
                filterByUrl(directLink);
            } else {
                if (!Ext.isEmpty(directLink, false)) {
                    if (directLink === TAG_CLOUD_TOKEN) {
                        if (App.exampleTree.store.loading) {
                            App.exampleTree.store.on("load", function () {
                                showTagCloud();
                            }, null, { single: true })
                        } else {
                            showTagCloud();
                        }
                    } else {
                        loadExample(directLink, "-");
                    }
                }
            }
        }, 100, window);
    }, window);
}

var onRedirect = function () {
    var remember = App.RememberCheckbox.getValue();

    if (remember) {
        Ext.util.Cookies.set("redirect", true);
    }

    window.location = "https://mvc.mobile.ext.net";
};

var onStay = function () {
    var remember = App.RememberCheckbox.getValue();

    if (remember) {
        Ext.util.Cookies.set("redirect", false);
    }

    this.up().hide();
};


text:
@ECHO OFF

echo  * Setting variables found in:
echo    %~f0

REM -------------------------------------------------------------------
REM   Change the following variables to reflect your desired settings
REM -------------------------------------------------------------------
set System=NYPD
set Source=Vehicle
set TargetDatabase=Traffic
set TargetSchema=dbo
set SourceDatabase=Stage
set SourceSchema=etl
set MetaDatabase=Traffic
REM -------------------------------------------------------------------


text:
class AddDeletedAtColumnToUsers < ActiveRecord::Migration
  def change
    add_column :users, :deleted_at, :datetime
  end
end


text:
console.log("[PhotoLibrary] installing...");

var exec = require("cordova/exec");

module.exports = {
	getRandomPhotos: function (howMany, callback) {
		console.log("[PhotoLibrary] getRandomPhotos");

		if (navigator.userAgent.indexOf("Android") !== -1) {
			// Android done in JS (TODO)
			callback(null, []);
		} else {
			exec(function success(result) {
				callback(null, _.map(result || [], function (path) {
					return {
						path: path,
						cdvfile: 'cdvfile://localhost/persistent/' + path.replace(/.*Documents\//, '')
					};
				}));
			}, function error(err) {
				callback(err, null);
			}, "PhotoLibrary", "getRandomPhotos", [howMany]);
		}
	}
};

console.log("[PhotoLibrary] installed.");