text:
package org.fcrepo.test.api;

import static junit.framework.Assert.fail;

import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;

import junit.framework.JUnit4TestAdapter;

import org.fcrepo.client.FedoraClient;

import org.fcrepo.common.Constants;
import org.fcrepo.common.Models;
import org.fcrepo.common.PID;

import org.fcrepo.server.management.FedoraAPIMMTOM;
import org.fcrepo.server.utilities.TypeUtility;

import org.fcrepo.test.FedoraServerTestCase;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Tests a series of many dissemination requests. NOTE: This test requies API-A
 * to be open (non-authenticating)
 *
 * @author Chris Wilper
 */
public class TestManyDisseminations
        extends FedoraServerTestCase {

    private static final Logger LOGGER =
        LoggerFactory.getLogger(TestManyDisseminations.class);

    private static final String DATA_OBJECT_PID = "test:ManyDiss";

    private static final String SDEF_OBJECT_PID = "test:ManyDiss-SDef";

    private static final String SDEP_OBJECT_PID = "test:ManyDiss-SDep";

    private static final String CMODEL_OBJECT_PID = "test:ManyDiss-CModel";

    private static final String X_DS = "DC";

    private static final String E_DS = "DC_REF_E";

    private static final String R_DS = "DC_REF_R";

    private static FedoraAPIMMTOM APIM;

    private static final String BASE_URL = FedoraServerTestCase.getBaseURL();

    private static FedoraClient s_client;

    @BeforeClass
    public static void bootstrap() throws Exception {
        s_client = getFedoraClient();
        APIM = s_client.getAPIMMTOM();

        APIM.ingest(TypeUtility.convertBytesToDataHandler(getCModelObject()), FOXML_FORMAT, "");
        APIM.ingest(TypeUtility.convertBytesToDataHandler(getSDefObject()), FOXML_FORMAT, "");
        APIM.ingest(TypeUtility.convertBytesToDataHandler(getSDepObject()), FOXML_FORMAT, "");
        APIM.ingest(TypeUtility.convertBytesToDataHandler(getDataObject()), FOXML_FORMAT, "");
    }

    @AfterClass
    public static void cleanUp() throws Exception {
        APIM.purgeObject(DATA_OBJECT_PID, "", false);
        APIM.purgeObject(SDEP_OBJECT_PID, "", false);
        APIM.purgeObject(SDEF_OBJECT_PID, "", false);
        APIM.purgeObject(CMODEL_OBJECT_PID, "", false);
        s_client.shutdown();
    }

    @After
    public void tearDown() throws Exception {
    }

    //---
    // Tests
    //---

    /**
     * Tests a rapid series of requests for an inline XML datastream.
     */
    @Test
    public void testManyDatastreamDisseminationsX() throws Exception {
        doDissemTest(DATA_OBJECT_PID + "/" + X_DS, false);
    }

    /**
     * Tests a rapid series of requests for an External datastream.
     */
    @Test
    public void testManyDatastreamDisseminationsE() throws Exception {
        doDissemTest(DATA_OBJECT_PID + "/" + E_DS, false);
    }

    /**
     * Tests a rapid series of requests for a Redirect datastream.
     */
    @Test
    public void testManyDatastreamDisseminationsR() throws Exception {
        doDissemTest(DATA_OBJECT_PID + "/" + R_DS, true);
    }

    /**
     * Tests a rapid series of requests for a Saxon dissemination that uses an
     * inline XML datastream.
     */
    @Test
    public void testManySaxonDisseminationsX() throws Exception {
        doDissemTest(DATA_OBJECT_PID + "/" + SDEF_OBJECT_PID + "/getIDFrom"
                     + X_DS, false);
    }

    /**
     * Tests a rapid series of requests for a Saxon dissemination that uses an
     * External datastream.
     */
    @Test
    public void testManySaxonDisseminationsE() throws Exception {
        doDissemTest(DATA_OBJECT_PID + "/" + SDEF_OBJECT_PID + "/getIDFrom"
                     + E_DS, false);
    }

    /**
     * Tests a rapid series of requests for a Saxon dissemination that uses a
     * Redirect datastream.
     */
    @Test
    public void testManySaxonDisseminationsR() throws Exception {
        doDissemTest(DATA_OBJECT_PID + "/" + SDEF_OBJECT_PID + "/getIDFrom"
                     + R_DS, false);
    }

    /**
     * Starts getting a dissemination, then aborts the connection (forcibly
     * closes the socket on the client side) 30 times in a row.
     */
    private void doDissemTest(String what, boolean redirectOK) throws Exception {
        final int num = 30;
        LOGGER.debug("Getting {} {} times...", what, num);
        int i = 0;
        try {
            URL url = new URL(BASE_URL + "/get/" + what);
            for (i = 0; i < num; i++) {
                HttpURLConnection conn =
                        (HttpURLConnection) url.openConnection();
                InputStream in = conn.getInputStream();
                in.read();
                in.close();
                conn.disconnect();
            }
        } catch (Exception e) {
            fail("Dissemination of " + what + " failed on iter " + i + ": "
                 + e.getMessage());
        }
    }

    public static junit.framework.Test suite() {
        return new JUnit4TestAdapter(TestManyDisseminations.class);
    }

    public static void main(String[] args) {
        JUnitCore.runClasses(TestManyDisseminations.class);
    }

    // static bootstrap helpers

        private static final String CR = System.getProperty("line.separator");

        private static final String FOXML_FORMAT = FOXML1_1.uri;

        private static final String FOXML_NAMESPACE =
                "info:fedora/fedora-system:def/foxml#";

        private static byte[] getCModelObject() throws Exception {
            StringBuilder buf = new StringBuilder();
            openFOXML(buf, CMODEL_OBJECT_PID);

            StringBuilder rdf = new StringBuilder();
            openRDF(rdf, CMODEL_OBJECT_PID);
            appendRel(rdf, MODEL.HAS_MODEL.localName, PID
                    .getInstance(Models.CONTENT_MODEL_3_0.uri).toString());
            appendRel(rdf, MODEL.HAS_SERVICE.localName, SDEF_OBJECT_PID);
            closeRDF(rdf);
            appendInlineDatastream(buf,
                                   "RELS-EXT",
                                   "application/rdf+xml",
                                   Constants.RELS_EXT1_0.uri,
                                   rdf.toString());

            closeFOXML(buf);
            return buf.toString().getBytes("UTF-8");
        }

        private static byte[] getSDefObject() throws Exception {
            StringBuilder buf = new StringBuilder();
            openFOXML(buf, SDEF_OBJECT_PID);
            StringBuilder rdf = new StringBuilder();
            openRDF(rdf, SDEF_OBJECT_PID);
            appendRel(rdf, MODEL.HAS_MODEL.localName, PID
                    .getInstance(Models.SERVICE_DEFINITION_3_0.uri).toString());
            closeRDF(rdf);
            appendInlineDatastream(buf,
                                   "RELS-EXT",
                                   "application/rdf+xml",
                                   Constants.RELS_EXT1_0.uri,
                                   rdf.toString());
            appendInlineDatastream(buf,
                                   "METHODMAP",
                                   "text/xml",
                                   Constants.SDEF_METHOD_MAP1_0.uri,
                                   getSDefMethodMap());
            closeFOXML(buf);
            return buf.toString().getBytes("UTF-8");
        }

        private static byte[] getSDepObject() throws Exception {
            StringBuilder buf = new StringBuilder();
            openFOXML(buf, SDEP_OBJECT_PID);
            appendInlineDatastream(buf,
                                   "METHODMAP",
                                   "text/xml",
                                   Constants.SDEP_METHOD_MAP1_1.uri,
                                   getSDepMethodMap());
            appendInlineDatastream(buf,
                                   "DSINPUTSPEC",
                                   "text/xml",
                                   Constants.DS_INPUT_SPEC1_1.uri,
                                   getDSInputSpec());
            appendInlineDatastream(buf,
                                   "WSDL",
                                   "text/xml",
                                   Constants.WSDL.uri,
                                   getWSDL());

            StringBuilder rdf = new StringBuilder();
            openRDF(rdf, SDEP_OBJECT_PID);
            appendRel(rdf, MODEL.HAS_MODEL.localName, PID
                    .getInstance(Models.SERVICE_DEPLOYMENT_3_0.uri).toString());
            appendRel(rdf, MODEL.IS_DEPLOYMENT_OF.localName, SDEF_OBJECT_PID);
            appendRel(rdf, MODEL.IS_CONTRACTOR_OF.localName, CMODEL_OBJECT_PID);
            closeRDF(rdf);
            appendInlineDatastream(buf,
                                   "RELS-EXT",
                                   "application/rdf+xml",
                                   Constants.RELS_EXT1_0.uri,
                                   rdf.toString());

            closeFOXML(buf);
            return buf.toString().getBytes("UTF-8");
        }

        private static void openRDF(StringBuilder buf, String sPID) {
            buf.append("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-"
                       + "rdf-syntax-ns#\" xmlns:fedora-model=\"info:fedora/"
                       + "fedora-system:def/model#\">\n  <rdf:Description "
                       + "rdf:about=\"info:fedora/" + sPID + "\">\n");
        }

        private static void closeRDF(StringBuilder buf) {
            buf.append("  </rdf:Description>\n</rdf:RDF>");
        }

        private static void appendRel(StringBuilder buf,
                                      String pName,
                                      String oPID) {
            buf.append("    <fedora-model:" + pName
                       + " rdf:resource=\"info:fedora/" + oPID + "\"/>\n");
        }

        private static String getWSDL() {
            return "<wsdl:definitions name=\"ManyDissSDep\" targetNamespace=\"bmech\""
                   + CR
                   +
                   "    xmlns:http=\"http://schemas.xmlsoap.org/wsdl/http/\" xmlns:mime=\"http://schemas.xmlsoap.org/wsdl/mime/\""
                   + CR
                   + "    xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap\""
                   + CR
                   + "    xmlns:soapenc=\"http://schemas.xmlsoap.org/wsdl/soap/encoding\" xmlns:this=\"bmech\""
                   + CR
                   +
                   "    xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
                   + CR
                   + "  <wsdl:types>"
                   + CR
                   + "    <xsd:schema targetNamespace=\"bmech\">"
                   + CR
                   + "      <xsd:simpleType name=\"XSLTType\">"
                   + CR
                   + "        <xsd:restriction base=\"xsd:string\"/>"
                   + CR
                   + "      </xsd:simpleType>"
                   + CR
                   + "      <xsd:simpleType name=\"DCType\">"
                   + CR
                   + "        <xsd:restriction base=\"xsd:string\"/>"
                   + CR
                   + "      </xsd:simpleType>"
                   + CR
                   + "      <xsd:simpleType name=\"DC_REF_EType\">"
                   + CR
                   + "        <xsd:restriction base=\"xsd:string\"/>"
                   + CR
                   + "      </xsd:simpleType>"
                   + CR
                   + "      <xsd:simpleType name=\"DC_REF_RType\">"
                   + CR
                   + "        <xsd:restriction base=\"xsd:string\"/>"
                   + CR
                   + "      </xsd:simpleType>"
                   + CR
                   + "    </xsd:schema>"
                   + CR
                   + "  </wsdl:types>"
                   + CR
                   + "  <wsdl:message name=\"getIDFromDCRequest\">"
                   + CR
                   + "    <wsdl:part name=\"XSLT\" type=\"this:XSLTType\"/>"
                   + CR
                   + "    <wsdl:part name=\"DC\" type=\"this:DCType\"/>"
                   + CR
                   + "  </wsdl:message>"
                   + CR
                   + "  <wsdl:message name=\"getIDFromDC_REF_ERequest\">"
                   + CR
                   + "    <wsdl:part name=\"XSLT\" type=\"this:XSLTType\"/>"
                   + CR
                   + "    <wsdl:part name=\"DC_REF_E\" type=\"this:DC_REF_EType\"/>"
                   + CR
                   + "  </wsdl:message>"
                   + CR
                   + "  <wsdl:message name=\"getIDFromDC_REF_RRequest\">"
                   + CR
                   + "    <wsdl:part name=\"XSLT\" type=\"this:XSLTType\"/>"
                   + CR
                   + "    <wsdl:part name=\"DC_REF_R\" type=\"this:DC_REF_RType\"/>"
                   + CR
                   + "  </wsdl:message>"
                   + CR
                   + "  <wsdl:message name=\"dissemResponse\">"
                   + CR
                   + "    <wsdl:part name=\"dissem\" type=\"xsd:base64Binary\"/>"
                   + CR
                   + "  </wsdl:message>"
                   + CR
                   + "  <wsdl:portType name=\"ManyDissSDepPortType\">"
                   + CR
                   + "    <wsdl:operation name=\"getIDFromDC\">"
                   + CR
                   + "      <wsdl:input message=\"this:getIDFromDCRequest\"/>"
                   + CR
                   + "      <wsdl:output message=\"this:dissemResponse\"/>"
                   + CR
                   + "    </wsdl:operation>"
                   + CR
                   + "    <wsdl:operation name=\"getIDFromDC_REF_E\">"
                   + CR
                   + "      <wsdl:input message=\"this:getIDFromDC_REF_ERequest\"/>"
                   + CR
                   + "      <wsdl:output message=\"this:dissemResponse\"/>"
                   + CR
                   + "    </wsdl:operation>"
                   + CR
                   + "    <wsdl:operation name=\"getIDFromDC_REF_R\">"
                   + CR
                   + "      <wsdl:input message=\"this:getIDFromDC_REF_RRequest\"/>"
                   + CR
                   + "      <wsdl:output message=\"this:dissemResponse\"/>"
                   + CR
                   + "    </wsdl:operation>"
                   + CR
                   + "  </wsdl:portType>"
                   + CR
                   + "  <wsdl:service name=\"ManyDissSDep\">"
                   + CR
                   + "    <wsdl:port binding=\"this:ManyDissSDep_http\" name=\"ManyDissSDep_port\">"
                   + CR
                   + "      <http:address location=\"http://local.fedora.server/saxon/\"/>"
                   + CR
                   + "    </wsdl:port>"
                   + CR
                   + "  </wsdl:service>"
                   + CR
                   + "  <wsdl:binding name=\"ManyDissSDep_http\" type=\"this:ManyDissSDepPortType\">"
                   + CR
                   + "    <http:binding verb=\"GET\"/>"
                   + CR
                   + "    <wsdl:operation name=\"getIDFromDC\">"
                   + CR
                   +
                   "      <http:operation location=\"SaxonServlet?clear-stylesheet-cache=true&source=(DC)&style=(XSLT)\"/>"
                   + CR
                   + "      <wsdl:input>"
                   + CR
                   + "        <http:urlReplacement/>"
                   + CR
                   + "      </wsdl:input>"
                   + CR
                   + "      <wsdl:output>"
                   + CR
                   + "        <mime:content type=\"text/xml\"/>"
                   + CR
                   + "      </wsdl:output>"
                   + CR
                   + "    </wsdl:operation>"
                   + CR
                   + "    <wsdl:operation name=\"getIDFromDC_REF_E\">"
                   + CR
                   +
                   "      <http:operation location=\"SaxonServlet?clear-stylesheet-cache=true&source=(DC_REF_E)&style=(XSLT)\"/>"
                   + CR
                   + "      <wsdl:input>"
                   + CR
                   + "        <http:urlReplacement/>"
                   + CR
                   + "      </wsdl:input>"
                   + CR
                   + "      <wsdl:output>"
                   + CR
                   + "        <mime:content type=\"text/xml\"/>"
                   + CR
                   + "      </wsdl:output>"
                   + CR
                   + "    </wsdl:operation>"
                   + CR
                   + "    <wsdl:operation name=\"getIDFromDC_REF_R\">"
                   + CR
                   +
                   "      <http:operation location=\"SaxonServlet?clear-stylesheet-cache=true&source=(DC_REF_R)&style=(XSLT)\"/>"
                   + CR
                   + "      <wsdl:input>"
                   + CR
                   + "        <http:urlReplacement/>"
                   + CR
                   + "      </wsdl:input>"
                   + CR
                   + "      <wsdl:output>"
                   + CR
                   + "        <mime:content type=\"text/xml\"/>"
                   + CR
                   + "      </wsdl:output>"
                   + CR
                   + "    </wsdl:operation>"
                   + CR + "  </wsdl:binding>" + CR + "</wsdl:definitions>";
        }

        private static String getDSInputSpec() {
            return "<fbs:DSInputSpec "
                   + "  label=\"label\" xmlns:fbs=\"http://fedora.comm.nsdlib.org/service/bindspec\">"
                   + CR
                   + "  <fbs:DSInput DSMax=\"1\" DSMin=\"1\" DSOrdinality=\"false\" wsdlMsgPartName=\"XSLT\">"
                   + CR
                   + "    <fbs:DSInputLabel>XSLT Binding</fbs:DSInputLabel>"
                   + CR
                   + "    <fbs:DSMIME>text/xml</fbs:DSMIME>"
                   + CR
                   + "    <fbs:DSInputInstruction/>"
                   + CR
                   + "  </fbs:DSInput>"
                   + CR
                   + "  <fbs:DSInput DSMax=\"1\" DSMin=\"1\" DSOrdinality=\"false\" wsdlMsgPartName=\"DC\">"
                   + CR
                   + "    <fbs:DSInputLabel>DC Binding</fbs:DSInputLabel>"
                   + CR
                   + "    <fbs:DSMIME>text/xml</fbs:DSMIME>"
                   + CR
                   + "    <fbs:DSInputInstruction/>"
                   + CR
                   + "  </fbs:DSInput>"
                   + CR
                   + "  <fbs:DSInput DSMax=\"1\" DSMin=\"1\" DSOrdinality=\"false\" wsdlMsgPartName=\"DC_REF_E\">"
                   + CR
                   + "    <fbs:DSInputLabel>DC_REF_E Binding</fbs:DSInputLabel>"
                   + CR
                   + "    <fbs:DSMIME>text/xml</fbs:DSMIME>"
                   + CR
                   + "    <fbs:DSInputInstruction/>"
                   + CR
                   + "  </fbs:DSInput>"
                   + CR
                   + "  <fbs:DSInput DSMax=\"1\" DSMin=\"1\" DSOrdinality=\"false\" wsdlMsgPartName=\"DC_REF_R\">"
                   + CR
                   + "    <fbs:DSInputLabel>DC_REF_R Binding</fbs:DSInputLabel>"
                   + CR
                   + "    <fbs:DSMIME>text/xml</fbs:DSMIME>"
                   + CR
                   + "    <fbs:DSInputInstruction/>"
                   + CR
                   + "  </fbs:DSInput>"
                   + CR + "</fbs:DSInputSpec>";
        }

        private static String getSDepMethodMap() {
            return "<fmm:MethodMap bDefPID=\""
                   + SDEF_OBJECT_PID
                   + "\" name=\"name\" xmlns:fmm=\"http://fedora.comm.nsdlib.org/service/methodmap\">"
                   + CR
                   +
                   "  <fmm:Method operationLabel=\"label\" operationName=\"getIDFromDC\" wsdlMsgName=\"getIDFromDCRequest\" wsdlMsgOutput=\"dissemResponse\">"
                   + CR
                   +
                   "    <fmm:DatastreamInputParm defaultValue=\"\" label=\"\" parmName=\"XSLT\" passBy=\"URL_REF\" required=\"true\"/>"
                   + CR
                   +
                   "    <fmm:DatastreamInputParm defaultValue=\"\" label=\"\" parmName=\"DC\" passBy=\"URL_REF\" required=\"true\"/>"
                   + CR
                   + "    <fmm:MethodReturnType wsdlMsgName=\"dissemResponse\" wsdlMsgTOMIME=\"text/xml\"/>"
                   + CR
                   + "  </fmm:Method>"
                   + CR
                   +
                   "  <fmm:Method operationLabel=\"label\" operationName=\"getIDFromDC_REF_E\" wsdlMsgName=\"getIDFromDC_REF_ERequest\" wsdlMsgOutput=\"dissemResponse\">"
                   + CR
                   +
                   "    <fmm:DatastreamInputParm defaultValue=\"\" label=\"\" parmName=\"XSLT\" passBy=\"URL_REF\" required=\"true\"/>"
                   + CR
                   +
                   "    <fmm:DatastreamInputParm defaultValue=\"\" label=\"\" parmName=\"DC_REF_E\" passBy=\"URL_REF\" required=\"true\"/>"
                   + CR
                   + "    <fmm:MethodReturnType wsdlMsgName=\"dissemResponse\" wsdlMsgTOMIME=\"text/xml\"/>"
                   + CR
                   + "  </fmm:Method>"
                   + CR
                   +
                   "  <fmm:Method operationLabel=\"label\" operationName=\"getIDFromDC_REF_R\" wsdlMsgName=\"getIDFromDC_REF_RRequest\" wsdlMsgOutput=\"dissemResponse\">"
                   + CR
                   +
                   "    <fmm:DatastreamInputParm defaultValue=\"\" label=\"\" parmName=\"XSLT\" passBy=\"URL_REF\" required=\"true\"/>"
                   + CR
                   +
                   "    <fmm:DatastreamInputParm defaultValue=\"\" label=\"\" parmName=\"DC_REF_R\" passBy=\"URL_REF\" required=\"true\"/>"
                   + CR
                   + "    <fmm:MethodReturnType wsdlMsgName=\"dissemResponse\" wsdlMsgTOMIME=\"text/xml\"/>"
                   + CR + "  </fmm:Method>" + CR + "</fmm:MethodMap>";
        }

        private static String getSDefMethodMap() {
            return "<fmm:MethodMap name=\"name\" xmlns:fmm=\"http://fedora.comm.nsdlib.org/service/methodmap\">"
                   + CR
                   + "  <fmm:Method label=\"label\" operationName=\"getIDFromDC\"/>"
                   + CR
                   + "  <fmm:Method label=\"label\" operationName=\"getIDFromDC_REF_E\"/>"
                   + CR
                   + "  <fmm:Method label=\"label\" operationName=\"getIDFromDC_REF_R\"/>"
                   + CR + "</fmm:MethodMap>" + CR;
        }

        private static byte[] getDataObject() throws Exception {
            StringBuilder buf = new StringBuilder();
            openFOXML(buf, DATA_OBJECT_PID);
            final String mimeType = "text/xml";
            InetAddress addr = InetAddress.getLocalHost();
            final String url =
                    "http://" + addr.getHostAddress() + ":"
                    + FedoraServerTestCase.getPort() + "/"
                    + FedoraServerTestCase.getFedoraAppServerContext()
                    + "/get/" + DATA_OBJECT_PID + "/" + X_DS;
            appendInlineDatastream(buf,
                                   X_DS,
                                   "text/xml",
                                   Constants.OAI_DC2_0.uri,
                                   getDC());
            appendInlineDatastream(buf, "XSLT", "text/xml", null, getXSLT());
            appendRemoteDatastream(buf, E_DS, "E", mimeType, url);
            appendRemoteDatastream(buf, R_DS, "R", mimeType, url);

            StringBuilder rdf = new StringBuilder();
            openRDF(rdf, DATA_OBJECT_PID);
            appendRel(rdf, MODEL.HAS_MODEL.localName, PID
                    .getInstance(Models.FEDORA_OBJECT_3_0.uri).toString());
            appendRel(rdf, MODEL.HAS_MODEL.localName, CMODEL_OBJECT_PID);
            closeRDF(rdf);
            appendInlineDatastream(buf,
                                   "RELS-EXT",
                                   "application/rdf+xml",
                                   Constants.RELS_EXT1_0.uri,
                                   rdf.toString());

            closeFOXML(buf);
            return buf.toString().getBytes("UTF-8");
        }

        private static String getDC() {
            return "<oai_dc:dc xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:oai_dc=\"http://www.openarchives.org/OAI/2.0/oai_dc/\">"
                   + CR
                   + "  <dc:identifier>test:ManyDiss</dc:identifier>"
                   + CR + "</oai_dc:dc>";
        }

        private static String getXSLT() {
            StringBuilder buf = new StringBuilder();
            buf
                    .append("<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"
                            + CR
                            + "  <xsl:output encoding=\"UTF-8\" indent=\"yes\" method=\"xml\"/>"
                            + CR
                            + "  <xsl:template match=\"dc:identifier\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
                            + CR);
            for (int i = 0; i < 5000; i++) {
                buf.append("    <identifier>" + CR);
                buf.append("      <xsl:value-of select=\"text()\"/>" + CR);
                buf.append("    </identifier>" + CR);
            }
            buf.append("  </xsl:template>" + CR + "</xsl:stylesheet>");
            return buf.toString();
        }

        private static void openFOXML(StringBuilder buf, String pid) {
            buf.append("<foxml:digitalObject");
            buf.append(" VERSION=\"1.1\"");
            buf.append(" PID=\"" + pid + "\"");
            buf.append(" xmlns:foxml=\"" + FOXML_NAMESPACE + "\"");
            buf.append(">" + CR + "<foxml:objectProperties>" + CR);
            buf.append("<foxml:property NAME=\"info:fedora/fedora-system:def/model#state\" VALUE=\"Active\"/>");
            buf.append(CR + "</foxml:objectProperties>" + CR);
        }

        private static void appendInlineDatastream(StringBuilder buf,
                                                   String dsID,
                                                   String mimeType,
                                                   String formatURI,
                                                   String xml) {
            openDatastream(buf, dsID, "X");
            openDatastreamVersion(buf, dsID + ".0", mimeType, formatURI);
            buf.append("      <foxml:xmlContent>" + CR);
            buf.append(xml);
            buf.append(CR + "      </foxml:xmlContent>" + CR);
            closeDatastreamVersion(buf);
            closeDatastream(buf);
        }

        private static void appendRemoteDatastream(StringBuilder buf,
                                                   String dsID,
                                                   String controlGroup,
                                                   String mimeType,
                                                   String location) {
            openDatastream(buf, dsID, controlGroup);
            openDatastreamVersion(buf, dsID + ".0", mimeType, null);
            buf.append("      <foxml:contentLocation REF=\"" + location
                       + "\" TYPE=\"URL\"/>" + CR);
            closeDatastreamVersion(buf);
            closeDatastream(buf);
        }

        private static void openDatastream(StringBuilder buf,
                                           String dsID,
                                           String controlGroup) {
            buf.append("  <foxml:datastream");
            buf.append(" ID=\"" + dsID + "\"");
            buf.append(" CONTROL_GROUP=\"" + controlGroup + "\"");
            buf.append(">" + CR);
        }

        private static void openDatastreamVersion(StringBuilder buf,
                                                  String versionID,
                                                  String mimeType,
                                                  String formatURI) {
            buf.append("    <foxml:datastreamVersion");
            buf.append(" ID=\"" + versionID + "\"");
            buf.append(" MIMETYPE=\"" + mimeType + "\"");
            if (formatURI != null) {
                buf.append(" FORMAT_URI=\"" + formatURI + "\"");
            }
            buf.append(">" + CR);
        }

        private static void closeDatastreamVersion(StringBuilder buf) {
            buf.append("    </foxml:datastreamVersion>" + CR);
        }

        private static void closeDatastream(StringBuilder buf) {
            buf.append("  </foxml:datastream>" + CR);
        }

        private static void closeFOXML(StringBuilder buf) {
            buf.append("</foxml:digitalObject>");
        }

}


text:
package com.boundary.sdk.metric;

import java.util.Date;

import com.boundary.sdk.event.util.UnixTimeSerializer;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

public class MyDate {
	@JsonProperty
	@JsonSerialize(using = UnixTimeSerializer.class)
	private Date timestamp;

	public MyDate() {
		timestamp = new Date();
	}

	public MyDate(Date timestamp) {
		this.timestamp = timestamp;
	}

	public Date getTimestamp() {
		return timestamp;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("MyDate [timestamp=");
		builder.append(timestamp);
		builder.append("]");
		return builder.toString();
	}
}

redpajama_set_name: RedPajamaGithub


text:
module("Model: Comicbox.Models.Comic")

test("findAll", function(){
	stop(2000);
	Comicbox.Models.Comic.findAll({}, function(comics){
		start()
		ok(comics)
        ok(comics.length)
        ok(comics[0].name)
        ok(comics[0].description)
	});

})

test("create", function(){
	stop(2000);
	new Comicbox.Models.Comic({name: "dry cleaning", description: "take to street corner"}).save(function(comic){
		start();
		ok(comic);
        ok(comic.id);
        equals(comic.name,"dry cleaning")
        comic.destroy()
	})
})
test("update" , function(){
	stop();
	new Comicbox.Models.Comic({name: "cook dinner", description: "chicken"}).
            save(function(comic){
            	equals(comic.description,"chicken");
        		comic.update({description: "steak"},function(comic){
        			start()
        			equals(comic.description,"steak");
        			comic.destroy();
        		})
            })

});
test("destroy", function(){
	stop(2000);
	new Comicbox.Models.Comic({name: "mow grass", description: "use riding mower"}).
            destroy(function(comic){
            	start();
            	ok( true ,"Destroy called" )
            })
})


text:
package main

import (
	"bufio"
	"context"
	"expvar"
	"flag"
	"fmt"
	"io"
	"os"
	"os/signal"
	"runtime"
	"syscall"
	"time"

	"github.com/inbucket/inbucket/pkg/config"
	"github.com/inbucket/inbucket/pkg/message"
	"github.com/inbucket/inbucket/pkg/msghub"
	"github.com/inbucket/inbucket/pkg/policy"
	"github.com/inbucket/inbucket/pkg/rest"
	"github.com/inbucket/inbucket/pkg/server/pop3"
	"github.com/inbucket/inbucket/pkg/server/smtp"
	"github.com/inbucket/inbucket/pkg/server/web"
	"github.com/inbucket/inbucket/pkg/storage"
	"github.com/inbucket/inbucket/pkg/storage/file"
	"github.com/inbucket/inbucket/pkg/storage/mem"
	"github.com/inbucket/inbucket/pkg/stringutil"
	"github.com/inbucket/inbucket/pkg/webui"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

var (
	// version contains the build version number, populated during linking.
	version = "undefined"

	// date contains the build date, populated during linking.
	date = "undefined"
)

func init() {
	// Server uptime for status page.
	startTime := expvar.NewInt("startMillis")
	startTime.Set(time.Now().UnixNano() / 1000000)

	// Goroutine count for status page.
	expvar.Publish("goroutines", expvar.Func(func() interface{} {
		return runtime.NumGoroutine()
	}))

	// Register storage implementations.
	storage.Constructors["file"] = file.New
	storage.Constructors["memory"] = mem.New
}

func main() {
	// Command line flags.
	help := flag.Bool("help", false, "Displays help on flags and env variables.")
	pidfile := flag.String("pidfile", "", "Write our PID into the specified file.")
	logfile := flag.String("logfile", "stderr", "Write out log into the specified file.")
	logjson := flag.Bool("logjson", false, "Logs are written in JSON format.")
	netdebug := flag.Bool("netdebug", false, "Dump SMTP & POP3 network traffic to stdout.")
	flag.Usage = func() {
		fmt.Fprintln(os.Stderr, "Usage: inbucket [options]")
		flag.PrintDefaults()
	}
	flag.Parse()
	if *help {
		flag.Usage()
		fmt.Fprintln(os.Stderr, "")
		config.Usage()
		return
	}

	// Process configuration.
	config.Version = version
	config.BuildDate = date
	conf, err := config.Process()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Configuration error: %v\n", err)
		os.Exit(1)
	}
	if *netdebug {
		conf.POP3.Debug = true
		conf.SMTP.Debug = true
	}

	// Logger setup.
	closeLog, err := openLog(conf.LogLevel, *logfile, *logjson)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Log error: %v\n", err)
		os.Exit(1)
	}
	startupLog := log.With().Str("phase", "startup").Logger()

	// Setup signal handler.
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)

	// Initialize logging.
	startupLog.Info().Str("version", config.Version).Str("buildDate", config.BuildDate).
		Msg("Inbucket starting")

	// Write pidfile if requested.
	if *pidfile != "" {
		pidf, err := os.Create(*pidfile)
		if err != nil {
			startupLog.Fatal().Err(err).Str("path", *pidfile).Msg("Failed to create pidfile")
		}
		fmt.Fprintf(pidf, "%v\n", os.Getpid())
		if err := pidf.Close(); err != nil {
			startupLog.Fatal().Err(err).Str("path", *pidfile).Msg("Failed to close pidfile")
		}
	}

	// Configure internal services.
	rootCtx, rootCancel := context.WithCancel(context.Background())
	shutdownChan := make(chan bool)
	store, err := storage.FromConfig(conf.Storage)
	if err != nil {
		removePIDFile(*pidfile)
		startupLog.Fatal().Err(err).Str("module", "storage").Msg("Fatal storage error")
	}
	msgHub := msghub.New(rootCtx, conf.Web.MonitorHistory)
	addrPolicy := &policy.Addressing{Config: conf}
	mmanager := &message.StoreManager{AddrPolicy: addrPolicy, Store: store, Hub: msgHub}

	// Start Retention scanner.
	retentionScanner := storage.NewRetentionScanner(conf.Storage, store, shutdownChan)
	retentionScanner.Start()

	// Configure routes and start HTTP server.
	prefix := stringutil.MakePathPrefixer(conf.Web.BasePath)
	webui.SetupRoutes(web.Router.PathPrefix(prefix("/serve/")).Subrouter())
	rest.SetupRoutes(web.Router.PathPrefix(prefix("/api/")).Subrouter())
	web.Initialize(conf, shutdownChan, mmanager, msgHub)
	go web.Start(rootCtx)

	// Start POP3 server.
	pop3Server := pop3.New(conf.POP3, shutdownChan, store)
	go pop3Server.Start(rootCtx)

	// Start SMTP server.
	smtpServer := smtp.NewServer(conf.SMTP, shutdownChan, mmanager, addrPolicy)
	go smtpServer.Start(rootCtx)

	// Loop forever waiting for signals or shutdown channel.
signalLoop:
	for {
		select {
		case sig := <-sigChan:
			switch sig {
			case syscall.SIGINT:
				// Shutdown requested
				log.Info().Str("phase", "shutdown").Str("signal", "SIGINT").
					Msg("Received SIGINT, shutting down")
				close(shutdownChan)
			case syscall.SIGTERM:
				// Shutdown requested
				log.Info().Str("phase", "shutdown").Str("signal", "SIGTERM").
					Msg("Received SIGTERM, shutting down")
				close(shutdownChan)
			}
		case <-shutdownChan:
			rootCancel()
			break signalLoop
		}
	}

	// Wait for active connections to finish.
	go timedExit(*pidfile)
	smtpServer.Drain()
	pop3Server.Drain()
	retentionScanner.Join()
	removePIDFile(*pidfile)
	closeLog()
}

// openLog configures zerolog output, returns func to close logfile.
func openLog(level string, logfile string, json bool) (close func(), err error) {
	switch level {
	case "debug":
		zerolog.SetGlobalLevel(zerolog.DebugLevel)
	case "info":
		zerolog.SetGlobalLevel(zerolog.InfoLevel)
	case "warn":
		zerolog.SetGlobalLevel(zerolog.WarnLevel)
	case "error":
		zerolog.SetGlobalLevel(zerolog.ErrorLevel)
	default:
		return nil, fmt.Errorf("Log level %q not one of: debug, info, warn, error", level)
	}
	close = func() {}
	var w io.Writer
	color := runtime.GOOS != "windows"
	switch logfile {
	case "stderr":
		w = os.Stderr
	case "stdout":
		w = os.Stdout
	default:
		logf, err := os.OpenFile(logfile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
		if err != nil {
			return nil, err
		}
		bw := bufio.NewWriter(logf)
		w = bw
		color = false
		close = func() {
			_ = bw.Flush()
			_ = logf.Close()
		}
	}
	w = zerolog.SyncWriter(w)
	if json {
		log.Logger = log.Output(w)
		return close, nil
	}
	log.Logger = log.Output(zerolog.ConsoleWriter{
		Out:     w,
		NoColor: !color,
	})
	return close, nil
}

// removePIDFile removes the PID file if created.
func removePIDFile(pidfile string) {
	if pidfile != "" {
		if err := os.Remove(pidfile); err != nil {
			log.Error().Str("phase", "shutdown").Err(err).Str("path", pidfile).
				Msg("Failed to remove pidfile")
		}
	}
}

// timedExit is called as a goroutine during shutdown, it will force an exit after 15 seconds.
func timedExit(pidfile string) {
	time.Sleep(15 * time.Second)
	removePIDFile(pidfile)
	log.Error().Str("phase", "shutdown").Msg("Clean shutdown took too long, forcing exit")
	os.Exit(0)
}


text:
var fs = require('fs');

var constants = require('./util/constants');
var common = require('./util/common');

// main
makeCredentialsFile();
makeTestImageFolders();
makeRequireJSFixture();

// Create a credentials json file,
// to be required in jasmine test suites and test dashboard
function makeCredentialsFile() {
    var credentials = JSON.stringify({
        MAPBOX_ACCESS_TOKEN: constants.mapboxAccessToken
    }, null, 2);

    common.writeFile(constants.pathToCredentials, credentials);
    logger('make build/credentials.json');
}

// Make artifact folders for image tests
function makeTestImageFolders() {
    function makeOne(folderPath, info) {
        if(!common.doesDirExist(folderPath)) {
            fs.mkdirSync(folderPath);
            logger('initialize ' + info);
        } else logger(info + ' is present');
    }

    makeOne(constants.pathToTestImages, 'test image folder');
    makeOne(constants.pathToTestImagesDiff, 'test image diff folder');
}

// Make script file that define plotly in a RequireJS context
function makeRequireJSFixture() {
    var bundle = fs.readFileSync(constants.pathToPlotlyDistMin, 'utf-8');

    var index = [
        'define(\'plotly\', function(require, exports, module) {',
        bundle,
        '});'
    ].join('');

    common.writeFile(constants.pathToRequireJSFixture, index);
    logger('make build/requirejs_fixture.js');
}

function logger(task) {
    console.log('ok ' + task);
}


text:
MinGW-arch
=================
mingw-based build environment based on arch-linux. The image provides an easy to use cross-compilation for windows target. It is also CI-friendly. mingw- versions of Qt5, cmake, Eigen3, boost are included. Dosens of [other libraries][1] are available from the package manager.

Table of Contents
----------------------

1. [Usage](#Usage)
2. [Continuous Integration](#Continuous-Integration)
3. [Dependencies](#Dependencies)
4. [Supported tags](#Supported-tags)

Usage
----------------------
Start the docker container:
```bash
sudo docker run -it burningdaylight/mingw-arch:qt /bin/bash
```
Compile your application (QNapi is used as an example here):
```bash
git clone --recursive 'https://github.com/QNapi/qnapi.git'
cd qnapi/
x86_64-w64-mingw32-qmake-qt5
make
```
Or for CMake:
```bash
x86_64-w64-mingw32-cmake ..
```
To __deploy__ the program, you will need to copy the dlls from `/usr/{x86_64-w64-mingw32,i686-w64-mingw32}/{bin,lib/qt/plugins/{imageformats,iconengines,platforms}}` (for x64 and x32 builds respectively) to the directory with the .exe file. The list of necessary dlls may vary. If a dll is missing, Windows will usually show an error popup window with the name of the missing dll, when you try to start the program.

That's it!

Continuous Integration
----------------------
For Gitlab CI the config file could look something like this:
```
build-win64:
  stage: compile
  image: burningdaylight/mingw-arch:qt
  script:
    - mkdir -p ${CI_BUILD_NAME}
    - cd ${CI_BUILD_NAME}; x86_64-w64-mingw32-qmake-qt5 ..; make
  artifacts:
    paths:
      - "${CI_BUILD_NAME}/src/*/release/*.exe"
      - "${CI_BUILD_NAME}/src/*/release/*.dll"
```
You can also check out the a full [.gitlab-ci.yml][4] file.

Dependencies
----------------------
If you need some other dependencies, you can install them from [AUR][1].
```bash
yay -S --noconfirm mingw-w64-rapidjson
```
If mingw- version of the needed libarary is not available in AUR, you can add it yourself. The process is really straightforward. You would need to write a [PKBUILD file][2], which is as intuitive as it can get, see [mingw-w64-rapidjson][3], for example.

Supported tags
----------------------
- `base` minimal cross-compilation environment which includes `yay` to install additional libraries from AUR and a small set of mingw-w64- packages: `cmake`, `gcc`, `zlib`
- `latest`, `qt` full-blown cross-compilation environment, which includes `Qt5`, `boost`, `openssl`, etc.

[1]: https://aur.archlinux.org/packages/?O=0&SeB=nd&K=mingw-w64&outdated=&SB=v&SO=d&PP=250&do_Search=Go
[2]: https://wiki.archlinux.org/index.php/creating_packages
[3]: https://aur.archlinux.org/cgit/aur.git/tree/PKGBUILD?h=mingw-w64-rapidjson
[4]: https://github.com/Fluorescence-Tools/Olga/blob/master/.gitlab-ci.yml#L22


text:
package org.nd4j.linalg.api.ops.impl.reduce.bp;

import lombok.NoArgsConstructor;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.linalg.api.ndarray.INDArray;

@NoArgsConstructor
public class VarianceBp extends BaseReductionBp {

    private boolean biasCorrected;

    public VarianceBp(SameDiff sameDiff, SDVariable origInput, SDVariable gradAtOutput, boolean biasCorrected, boolean keepDims, int... dimensions) {
        super(sameDiff, origInput, gradAtOutput, keepDims, dimensions);
        this.biasCorrected = biasCorrected;
        addArgs();

    }

    public VarianceBp(SameDiff sameDiff, SDVariable origInput1, SDVariable origInput2, SDVariable gradAtOutput, boolean keepDims, boolean biasCorrected, int... dimensions) {
        super(sameDiff, origInput1, origInput2, gradAtOutput, keepDims, dimensions);
        this.biasCorrected = biasCorrected;
        addArgs();

    }

    public VarianceBp(INDArray origInput, INDArray gradAtOutput, INDArray output, boolean biasCorrected, boolean keepDims, int... dimensions){
        super(origInput, gradAtOutput, output, keepDims, dimensions);
        this.biasCorrected = biasCorrected;
        addArgs();

    }

    public VarianceBp(INDArray origInput1, INDArray origInput2, INDArray gradAtOutput, INDArray output, boolean keepDims, boolean biasCorrected, int... dimensions) {
        super(origInput1, origInput2, gradAtOutput, output, keepDims, dimensions);
        this.biasCorrected = biasCorrected;
        addArgs();

    }

    public VarianceBp(INDArray origInput1, INDArray origInput2, INDArray gradAtOutput, INDArray output1, INDArray output2, boolean keepDims, boolean biasCorrected, int... dimensions) {
        super(origInput1, origInput2, gradAtOutput, output1, output2, keepDims, dimensions);
        this.biasCorrected = biasCorrected;
        addArgs();

    }

    public VarianceBp(INDArray origInput, INDArray gradAtOutput, INDArray output, boolean keepDims, INDArray dimensions, boolean biasCorrected) {
        super(origInput, gradAtOutput, output, keepDims, dimensions);
        this.biasCorrected = biasCorrected;
        addArgs();

    }

    public VarianceBp(SameDiff sameDiff, SDVariable origInput, SDVariable gradAtOutput, boolean keepDims, SDVariable dimensions, boolean biasCorrected) {
        super(sameDiff, origInput, gradAtOutput, keepDims, dimensions);
        this.biasCorrected = biasCorrected;
        addArgs();
    }

    public VarianceBp(SameDiff sameDiff, SDVariable arg, SDVariable dLdVar, boolean keepDims, boolean biasCorrected, SDVariable dimensions) {
        super(sameDiff,arg,dLdVar,keepDims,dimensions);
        addBArgument(biasCorrected);
    }

    @Override
    protected void addArgs() {
        super.addArgs();
        addBArgument(biasCorrected);
    }

    public VarianceBp(boolean biasCorrected) {
        this.biasCorrected = biasCorrected;
    }

    @Override
    public String opName() {
        return "reduce_variance_bp";
    }
}


text:
var jwt = require('jwt-simple');
// var Team = require('../models/team');
var User = require('../models/user');

var sendJWT = function(user, res) {
  var token = jwt.encode(user, 'secret');
  res.json({
    token: token
  });
};

module.exports = {
  createUser: function(req, res, next) {
    console.log('body', req.body);
    var username = req.body.username.trim();
    var password = req.body.password.trim();
    if (username === '' || password === '') {
      return res.status(400).send('Username and Password must be present');
    }

    User.findOne({
      username: username
    }, function(err, user) {
      if (user) return res.status(400).send('Username exists');
      var newUser = new User({
        username: username,
        password: password
      });

      newUser.save(function(err, newUser) {
        if (err) return res.status(404).send(err);

        res.status(201);
        sendJWT(newUser, res);

      });
    });
  },
  getIndex: function(req, res, next) {
    res.render('index', {
      title: 'Express'
    });
  },
  loginUser: function(req, res, next) {
    var username = req.body.username.trim();
    var password = req.body.password.trim();
    if (username === '' || password === '') {
      return res.status(400).send('Username, Password, and Teamname must be present');
    }

    User.findOne({
      username: username
    }, function(err, user) {
      if (!user) return res.status(401).send('Username does not exist');

      user.comparePassword(password, function(match) {
        if (!match) return res.status(401).send('Password does not match');

        sendJWT(user, res);
      });
    });

  }
};


text:
package kiwi.model.kbase;

import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;

import javax.persistence.Basic;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Transient;

import kiwi.api.triplestore.TripleStore;
import kiwi.model.Constants;

import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Index;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;

/**
 * The KiWiUriResource is a subclass of KiWiResource that
 * is represented by an URI.
 *
 * @author Sebastian Schaffert
 */
@Entity
@DiscriminatorValue("u")
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@BatchSize(size = 100)
public class KiWiUriResource extends KiWiResource implements Serializable {

	private static final long serialVersionUID = -6294168809422493844L;

	@Basic
//	@Column(unique=true)
    @Index(name="uri_index")
    @Length(max=2048)
    @NotNull
    private String uri;

	@Transient
	private String namespacePrefixCache;

    public KiWiUriResource() {
    	this.uri="";
    }

    public KiWiUriResource(String uri) {
        this.uri = uri;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    @Override
    public int hashCode() {
        return this.getUri().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (! (obj instanceof KiWiNode && ((KiWiNode)obj).isUriResource()) ) {
            return false;
        }
        final KiWiUriResource other = (KiWiUriResource) obj;
        if (this.uri != other.uri && (this.uri == null || !this.uri.equals(other.uri))) {
            return false;
        }
        return true;
    }

    /**
     * Return the SeRQL id of this resource
     * @return
     */
    @Override
    public String getSeRQLID() {
        return "<" + getUri() + ">";
    }

    @Override
    public String toString() {
        return getUri();
    }

	@Override
	public void addType(KiWiResource type) {
		TripleStore ts = getContext();

		ts.createTriple(this, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", type);

//        KiWiUriResource rdf_type = ts.createUriResource();
//        ts.createTriple(this, rdf_type, type);
    }

	@Deprecated
	public static String getRDFUri() {
		return Constants.NS_RDF;
	}

	@Deprecated
	public static String getRDFSUri() {
		return Constants.NS_RDFS;
	}

	@Deprecated
	public static String getOWLUri() {
		return Constants.NS_OWL;
	}

	@Deprecated
	public static String getXMLUri() {
		return Constants.NS_XML;
	}

	@Deprecated
	public static String getXMLSUri() {
		return Constants.NS_XSD;
	}

	@Override
	public String getKiwiIdentifier() {
		return "uri::"+getUri();
	}

	/**
	 * @author
	 * @return
	 * @see kiwi.model.kbase.KiWiNode#getCacheKey()
	 */
	@Override
	public String getCacheKey() {
		return uri;
	}

	/**
	 * Return the namespace prefix for this uri resource.
	 * @return
	 */
	public String getNamespacePrefix() {
		// note that this caching is unsafe as it is not refreshed on namespace change, but
		// such changes occur infrequently and are non-critical
		if(namespacePrefixCache == null) {
			namespacePrefixCache = getContext().getNamespacePrefix(uri);
		}
		return namespacePrefixCache;
	}

	/**
	 * Return local name part of this uri resource.
	 *
	 * TODO: this is completely unefficient, but hopefully not called too frequently.
	 * Sebastian: changing it, because performance analysis shows it is called too often :-)
	 *
	 * @return
	 */
	public String getLocalName() {
//		KiWiNamespace ns = getContext().getNamespace(getNamespacePrefix());
//		return getUri().substring(ns.getUri().length());

		String label;
		if(uri.lastIndexOf("#") > 0) {
			label = uri.substring(uri.lastIndexOf("#")+1);
		} else {
			label = uri.substring(uri.lastIndexOf("/")+1);
		}
		return label;
	}

	/** Creates a short name for the URI - either the fragment or the word after the (second to the) last slash.
	 *
	 * For
	 * 		http://example.com/ns#frament 		it will return "fragment"
	 * 		http://example.com/ontology/		it will return "ontology"
	 * 		http://example.com/ontology			it will return "ontology"
	 *
	 *
	 * @return
	 * @throws URISyntaxException
	 */
	public String getShortName() throws URISyntaxException {
		String uri = getUri();
		if (uri == null)
			return "there's a bug somewhere";

		String name = new URI(uri).getFragment(); //URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] http://www.ietf.org/rfc/rfc2396.txt
		if (name == null || name.length() == 0) {
			if ((uri.lastIndexOf('/')+1) == uri.length())
				uri = uri.substring(0,uri.lastIndexOf('/'));

			name = uri.substring(uri.lastIndexOf('/')+1);
		}
		return name;
	}

	@Override
	public boolean isAnonymousResource() {
		return false;
	}

	@Override
	public boolean isLiteral() {
		return false;
	}

	@Override
	public boolean isUriResource() {
		return true;
	}

}


text:
/*
 *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
 *  SPDX-License-Identifier: Apache-2.0
 *
 *  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.
 */

#ifndef MBEDTLS_AES_ALT_H
#define MBEDTLS_AES_ALT_H

#if !defined(MBEDTLS_CONFIG_FILE)
#include "config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif

#include <stddef.h>
#include <stdint.h>

#ifdef MBEDTLS_AES_ALT

#include "ssi_aes.h"

#ifdef __cplusplus
extern "C" {
#endif

#if defined(__CC_ARM)
#pragma anon_unions
#endif

/**
 * @brief AES context structure
 */
typedef struct
{
#if NRF_MBEDTLS_AES_ALT_INTERRUPT_CONTEXT
    bool using_cc310;                               ///< Indicate whether it's using cc310 or not.
#endif

#if !NRF_MBEDTLS_AES_ALT_INTERRUPT_CONTEXT
    union
    {
#endif // !NRF_MBEDTLS_AES_ALT_INTERRUPT_CONTEXT
        struct
        {
            SaSiAesUserContext_t user_context;      ///< User context for CC310 AES.
            uint8_t              key_buffer[32];    ///< Buffer for an encryption key.
            SaSiAesUserKeyData_t key;               ///< CC310 AES key structure.
            SaSiAesEncryptMode_t mode;              ///< Current context operation mode (encrypt/decrypt).
        } hardware;
        struct
        {
            int       nr;                           ///<  number of rounds  */
            uint32_t *rk;                           ///<  AES round keys    */
            uint32_t  buf[68];                      ///<  unaligned data    */
       } software;
#if !NRF_MBEDTLS_AES_ALT_INTERRUPT_CONTEXT
    };
#endif // !NRF_MBEDTLS_AES_ALT_INTERRUPT_CONTEXT
}
mbedtls_aes_context;

#if defined(__CC_ARM)
#pragma no_anon_unions
#endif

/**
 * @brief Initialize AES context
 *
 * @param[in,out] ctx AES context to be initialized
 */
void mbedtls_aes_init(mbedtls_aes_context * ctx);

/**
 * @brief Clear AES context
 *
 * @param[in,out] ctx AES context to be cleared
 */
void mbedtls_aes_free(mbedtls_aes_context * ctx);

/**
 * @brief AES key schedule (encryption)
 *
 * @param[in,out] ctx     AES context to be initialized
 * @param[in]     key     encryption key
 * @param[in]     keybits must be 128, 192 or 256
 *
 * @return 0 if successful
 */
int mbedtls_aes_setkey_enc(mbedtls_aes_context * ctx,
                           const unsigned char * key,
                           unsigned int          keybits);

/**
 * @brief AES key schedule (decryption)
 *
 * @param[in,out] ctx     AES context to be initialized
 * @param[in]     key     decryption key
 * @param[in]     keybits must be 128, 192 or 256
 *
 * @return 0 if successful
 */
int mbedtls_aes_setkey_dec(mbedtls_aes_context * ctx,
                           const unsigned char * key,
                           unsigned int          keybits);

/**
 * @brief AES-ECB block encryption/decryption
 *
 * @param[in,out] ctx    AES context
 * @param[in]     mode   MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT
 * @param[in]     input  16-byte input block
 * @param[out]    output 16-byte output block
 *
 * @return 0 if successful
 */
int mbedtls_aes_crypt_ecb(mbedtls_aes_context * ctx,
                          int                   mode,
                          const unsigned char   input[16],
                          unsigned char         output[16]);

#ifdef __cplusplus
}
#endif

#endif /* MBEDTLS_AES_ALT */

#endif /* MBEDTLS_AES_ALT_H */


text:
package com.higgsbot.wifidirect;

public enum SnitchColorEnum {
	Red, Black
}


text:
<!DOCTYPE html>

<title>VirtualVinilo</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
	rel="stylesheet">

<link type="text/css" rel="stylesheet" href="css/bootstraptheme.css" />

	<!header>

			<button class="navbar-toggle" type="button" data-toggle="collapse"
				data-target="#navbar-main">

			</button>

OFERTAS
 {{#unlogged}}

USUARIO

Iniciar Sesión

Registrarse

 {{/unlogged}} {{#logged}}

{{#user}} {{
							name }} {{/user}}

Mi Perfil

 {{#admin}}

Administrador

 {{/admin}}

Cerrar sesion

 {{/logged}}

		 {{#messages}}

			<button type="button" class="close" data-dismiss="alert"
				aria-label="Close">
				×
			</button>
			{{messages}}

	{{/messages}}
	{{#error}}

			<button type="button" class="close" data-dismiss="alert"
				aria-label="Close">
				×
			</button>
			{{error}}

	{{/error}}

Carrito

Lista de la compra

									Continuar comprando

						{{#productos}}

									{{title}}

									{{subtitle}}

										{{precio}} €x

									<form action="/borrarCarrito" method="post">
									<input name="title" type="hidden" value="{{title}}"/>
									<button type="submit" class="btn btn-link btn-xs">

									</button>
									</form>

						{{/productos}}

							<form action="/aplicarCodigo" method="post">

										<input type="submit" class="btn btn-default btn-sm btn-block" value="Añadir
											codigo oferta" />

										<input type="text" class="form-control input-sm"
											placeholder="Codigo" name="code">

							</form>

									Precio Total: {{precioTotal}} €

								Terminar compra

Copyright © VirtualVinilo

Guillermo Urbano, Ilia Ramírez, Jorge
						Galindo, Daniel Camacho

						Quienes Somos


text:
namespace _04.DistanceBetweenPoints
{
    using System;
    using System.Linq;

    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }
    }

    public class DistanceBetweenPoints
    {
        public static void Main()
        {
            int[] first = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int[] secound = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

            Point firstPoint = new Point { X = first[0], Y = first[1] };
            Point secoundPoint = new Point { X = secound[0], Y = secound[1] };

            double distance = CalcDistance(firstPoint, secoundPoint);

            Console.WriteLine("{0:f3}", distance);
        }

        public static double CalcDistance(Point firstPoint, Point secondPoint)
        {
            var hypotenuse = Math.Sqrt(Math.Pow(firstPoint.X - secondPoint.X, 2) + Math.Pow(firstPoint.Y - secondPoint.Y, 2));
            return hypotenuse;
        }
    }
}


text:
const _ = require('lodash');

_.mixin({

    sortByKey: function (obj, comparator) {
        let keys = _.sortBy(_.keys(obj), (key) => key)
        return _.zipObject(keys, _.map(keys, (key) => obj[key]));
    }

});

export default _


text:
import re
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import get_callable, get_mod_func
from django.utils.encoding import smart_str

def patterns(prefix, *args):
    """
    The function to define the list of hosts (aka host confs), e.g.::

        from django_hosts import patterns

        host_patterns = patterns('path.to',
            (r'www', 'urls.default', 'default'),
            (r'api', 'urls.api', 'api'),
        )

    :param prefix: the URLconf prefix to pass to the host object
    :type prefix: str
    :param \*args: a list of :class:`~django_hosts.defaults.hosts` instances
                   or an iterable thereof
    """
    hosts = []
    for arg in args:
        if isinstance(arg, (list, tuple)):
            arg = host(prefix=prefix, *arg)
        else:
            arg.add_prefix(prefix)
        name = arg.name
        if name in [h.name for h in hosts]:
            raise ImproperlyConfigured("Duplicate host name: %s" % name)
        hosts.append(arg)
    return hosts

class host(object):
    """
    The host object used in host conf together with the
    :func:`django_hosts.defaults.patterns` function, e.g.::

        from django_hosts import patterns, host

        host_patterns = patterns('path.to',
            host(r'www', 'urls.default', name='default'),
            host(r'api', 'urls.api', name='api'),
        )

    :param regex: a regular expression to be used to match the request's
                  host.
    :type regex: str
    :param urlconf: the dotted path of a URLconf module of the host
    :type urlconf: str
    :param callback: a callable or the dotted path of a callable to be used
                     when matching has happened
    :type callback: callable or str
    :param prefix: the prefix to apply to the ``urlconf`` parameter
    :type prefix: str
    """
    def __init__(self, regex, urlconf, name, callback=None, prefix=''):
        """
        Compile hosts. We add a literal fullstop to the end of every
        pattern to avoid rather unwieldy escaping in every definition.
        """
        self.regex = regex
        self.compiled_regex = re.compile(r'%s(\.|$)' % regex)
        self.urlconf = urlconf
        self.name = name
        if callable(callback):
            self._callback = callback
        else:
            self._callback, self._callback_str = None, callback
        self.add_prefix(prefix)

    def __repr__(self):
        return smart_str(u'<%s %s: %s (%r)>' %
            (self.__class__.__name__, self.name, self.urlconf, self.regex))

    @property
    def callback(self):
        if self._callback is not None:
            return self._callback
        elif self._callback_str is None:
            return lambda *args, **kwargs: None
        try:
            self._callback = get_callable(self._callback_str)
        except ImportError, e:
            mod_name, _ = get_mod_func(self._callback_str)
            raise ImproperlyConfigured("Could not import '%s'. "
                                       "Error was: %s" %
                                       (mod_name, str(e)))
        except AttributeError, e:
            mod_name, func_name = get_mod_func(self._callback_str)
            raise ImproperlyConfigured("Tried '%s' in module '%s'. "
                                       "Error was: %s" %
                                       (func_name, mod_name, str(e)))
        return self._callback

    def add_prefix(self, prefix=''):
        """
        Adds the prefix string to a string-based urlconf.
        """
        if prefix:
            self.urlconf = prefix.rstrip('.') + '.' + self.urlconf


text:
"""
Bots are a special child typeclasses of
Player that are  controlled by the server.

"""
from __future__ import print_function

from django.conf import settings
from evennia.players.players import DefaultPlayer
from evennia.scripts.scripts import DefaultScript
from evennia.commands.command import Command
from evennia.commands.cmdset import CmdSet
from evennia.utils import search

_IDLE_TIMEOUT = settings.IDLE_TIMEOUT

_SESSIONS = None

# Bot helper utilities

class BotStarter(DefaultScript):
    """
    This non-repeating script has the
    sole purpose of kicking its bot
    into gear when it is initialized.

    """
    def at_script_creation(self):
        """
        Called once, when script is created.

        """
        self.key = "botstarter"
        self.desc = "bot start/keepalive"
        self.persistent = True
        self.db.started = False
        if _IDLE_TIMEOUT > 0:
            # call before idle_timeout triggers
            self.interval = int(max(60, _IDLE_TIMEOUT * 0.90))
            self.start_delay = True

    def at_start(self):
        """
        Kick bot into gear.

        """
        if not self.db.started:
            self.player.start()
            self.db.started = True

    def at_repeat(self):
        """
        Called self.interval seconds to keep connection. We cannot use
        the IDLE command from inside the game since the system will
        not catch it (commands executed from the server side usually
        has no sessions). So we update the idle counter manually here
        instead. This keeps the bot getting hit by IDLE_TIMEOUT.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS
        for session in _SESSIONS.sessions_from_player(self.player):
            session.update_session_counters(idle=True)

    def at_server_reload(self):
        """
        If server reloads we don't need to reconnect the protocol
        again, this is handled by the portal reconnect mechanism.

        """
        self.db.started = True

    def at_server_shutdown(self):
        """
        Make sure we are shutdown.

        """
        self.db.started = False

class CmdBotListen(Command):
    """
    This is a command that absorbs input aimed specifically at the
    bot. The session must prepend its data with bot_data_in for this
    to trigger.

    """
    key = "bot_data_in"
    def func(self):
        "Relay to typeclass"
        self.obj.execute_cmd(self.args.strip(), session=self.session)

class BotCmdSet(CmdSet):
    """
    Holds the BotListen command

    """
    key = "botcmdset"
    def at_cmdset_creation(self):
        self.add(CmdBotListen())

# Bot base class

class Bot(DefaultPlayer):
    """
    A Bot will start itself when the server starts (it will generally
    not do so on a reload - that will be handled by the normal Portal
    session resync)

    """

    def basetype_setup(self):
        """
        This sets up the basic properties for the bot.

        """
        # the text encoding to use.
        self.db.encoding = "utf-8"
        # A basic security setup
        lockstring = "examine:perm(Wizards);edit:perm(Wizards);delete:perm(Wizards);boot:perm(Wizards);msg:false()"
        self.locks.add(lockstring)
        # set the basics of being a bot
        self.cmdset.add_default(BotCmdSet)
        script_key = "%s" % self.key
        self.scripts.add(BotStarter, key=script_key)
        self.is_bot = True

    def start(self, **kwargs):
        """
        This starts the bot, whatever that may mean.

        """
        pass

    def msg(self, text=None, from_obj=None, session=None, **kwargs):
        """
        Evennia -> outgoing protocol

        """
        super(Bot, self).msg(text=text, from_obj=from_obj, session=session, **kwargs)

    def execute_cmd(self, raw_string, session=None):
        """
        Incoming protocol -> Evennia

        """
        super(Bot, self).msg(raw_string, session=session)

    def at_server_shutdown(self):
        """
        We need to handle this case manually since the shutdown may be
        a reset.

        """
        for session in self.sessions.all():
            session.sessionhandler.disconnect(session)

# Bot implementations

# IRC

class IRCBot(Bot):
    """
    Bot for handling IRC connections.

    """
    def start(self, ev_channel=None, irc_botname=None, irc_channel=None, irc_network=None, irc_port=None, irc_ssl=None):
        """
        Start by telling the portal to start a new session.

        Args:
            ev_channel (str): Key of the Evennia channel to connect to.
            irc_botname (str): Name of bot to connect to irc channel. If
                not set, use `self.key`.
            irc_channel (str): Name of channel on the form `#channelname`.
            irc_network (str): URL of the IRC network, like `irc.freenode.net`.
            irc_port (str): Port number of the irc network, like `6667`.
            irc_ssl (bool): Indicates whether to use SSL connection.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS

        # if keywords are given, store (the BotStarter script
        # will not give any keywords, so this should normally only
        # happen at initialization)
        if irc_botname:
            self.db.irc_botname = irc_botname
        elif not self.db.irc_botname:
            self.db.irc_botname = self.key
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." % ev_channel)
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if irc_channel:
            self.db.irc_channel = irc_channel
        if irc_network:
            self.db.irc_network = irc_network
        if irc_port:
            self.db.irc_port = irc_port
        if irc_ssl:
            self.db.irc_ssl = irc_ssl

        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {"uid":self.dbid,
                      "botname": self.db.irc_botname,
                      "channel": self.db.irc_channel ,
                      "network": self.db.irc_network,
                      "port": self.db.irc_port,
                      "ssl": self.db.irc_ssl}
        _SESSIONS.start_bot_session("evennia.server.portal.irc.IRCBotFactory", configdict)

    def msg(self, text=None, **kwargs):
        """
        Takes text from connected channel (only).

        Args:
            text (str, optional): Incoming text from channel.

        Kwargs:
            from_channel (str): dbid of a channel this text originated from.
            from_obj (str): dbid of an object sending this text.

        """
        if not self.ndb.ev_channel and self.db.ev_channel:
            # cache channel lookup
            self.ndb.ev_channel = self.db.ev_channel
        if "from_channel" in kwargs and text and self.ndb.ev_channel.dbid == kwargs["from_channel"]:
            if "from_obj" not in kwargs or kwargs["from_obj"] != [self.id]:
                text = "bot_data_out %s" % text
                super(IRCBot, self).msg(text=text)

    def execute_cmd(self, text=None, session=None):
        """
        Take incoming data and send it to connected channel. This is
        triggered by the CmdListen command in the BotCmdSet.

        Args:
            text (str, optional):  Command string.
            session (Session, optional): Session responsible for this
                command.

        """
        if not self.ndb.ev_channel and self.db.ev_channel:
            # cache channel lookup
            self.ndb.ev_channel = self.db.ev_channel
        if self.ndb.ev_channel:
            self.ndb.ev_channel.msg(text, senders=self.id)

# RSS

class RSSBot(Bot):
    """
    An RSS relayer. The RSS protocol itself runs a ticker to update
    its feed at regular intervals.

    """
    def start(self, ev_channel=None, rss_url=None, rss_rate=None):
        """
        Start by telling the portal to start a new RSS session

        Args:
            ev_channel (str): Key of the Evennia channel to connect to.
            rss_url (str): Full URL to the RSS feed to subscribe to.
            rss_update_rate (int): How often for the feedreader to update.

        Raises:
            RuntimeError: If `ev_channel` does not exist.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS

        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." % ev_channel)
            channel = channel[0]
            self.db.ev_channel = channel
        if rss_url:
            self.db.rss_url = rss_url
        if rss_rate:
            self.db.rss_rate = rss_rate
        # instruct the server and portal to create a new session with
        # the stored configuration
        configdict = {"uid": self.dbid,
                      "url": self.db.rss_url,
                      "rate": self.db.rss_rate}
        _SESSIONS.start_bot_session("evennia.server.portal.rss.RSSBotFactory", configdict)

    def execute_cmd(self, text=None, session=None):
        """
        Echo RSS input to connected channel

        """
        if not self.ndb.ev_channel and self.db.ev_channel:
            # cache channel lookup
            self.ndb.ev_channel = self.db.ev_channel
        if self.ndb.ev_channel:
            self.ndb.ev_channel.msg(text, senders=self.id)

# IMC2 (not tested currently)

class IMC2Bot(Bot):
    """
    IMC2 Bot

    """
    def start(self, ev_channel=None, imc2_network=None, imc2_mudname=None,
              imc2_port=None, imc2_client_pwd=None, imc2_server_pwd=None):
        """
        Start by telling the portal to start a new session

        Args:
            ev_channel (str, optional): Key of the Evennia channel to connect to.
            imc2_network (str, optional): IMC2 network name.
            imc2_mudname (str, optional): Registered mudname (if not given, use settings.SERVERNAME).
            imc2_port (int, optional): Port number of the IMC2 network.
            imc2_client_pwd (str, optional): Client password registered with IMC2 network.
            imc2_server_pwd (str, optional): Server password registered with IMC2 network.

        Raises:
            RuntimeError: If `ev_channel` was not found.

        """
        global _SESSIONS
        if not _SESSIONS:
            from evennia.server.sessionhandler import SESSIONS as _SESSIONS
        if ev_channel:
            # connect to Evennia channel
            channel = search.channel_search(ev_channel)
            if not channel:
                raise RuntimeError("Evennia Channel '%s' not found." % ev_channel)
            channel = channel[0]
            channel.connect(self)
            self.db.ev_channel = channel
        if imc2_network:
            self.db.imc2_network = imc2_network
        if imc2_port:
            self.db.imc2_port = imc2_port
        if imc2_mudname:
            self.db.imc2_mudname = imc2_mudname
        elif not self.db.imc2_mudname:
            self.db.imc2_mudname = settings.SERVERNAME
        # storing imc2 passwords in attributes - a possible
        # security issue?
        if imc2_server_pwd:
            self.db.imc2_server_pwd = imc2_server_pwd
        if imc2_client_pwd:
            self.db.imc2_client_pwd = imc2_client_pwd

        configdict = {"uid": self.dbid,
                      "mudname": self.db.imc2_mudname,
                      "network": self.db.imc2_network,
                      "port": self.db.imc2_port,
                      "client_pwd": self.db.client_pwd,
                      "server_pwd": self.db.server_pwd}

        _SESSIONS.start_bot_session("evennia.server.portal.imc2.IMC2BotFactory", configdict)

    def msg(self, text=None, **kwargs):
        """
        Takes text from connected channel (only).

        Args:
            text (str): Message from channel.

        Kwargs:
            from_channel (str): dbid of a channel this text originated from.
            from_obj (str): dbid of an object sending this text.

        """
        if not self.ndb.ev_channel and self.db.ev_channel:
            # cache channel lookup
            self.ndb.ev_channel = self.db.ev_channel
        if "from_channel" in kwargs and text and self.ndb.ev_channel.dbid == kwargs["from_channel"]:
            if "from_obj" not in kwargs or kwargs["from_obj"] != [self.id]:
                text = "bot_data_out %s" % text
                self.msg(text=text)

    def execute_cmd(self, text=None, session=None):
        """
        Relay incoming data to connected channel.

        Args:
            text (str, optional):  Command string.
            session (Session, optional): Session responsible for this
                command.

        """
        if not self.ndb.ev_channel and self.db.ev_channel:
            # cache channel lookup
            self.ndb.ev_channel = self.db.ev_channel
        if self.ndb.ev_channel:
            self.ndb.ev_channel.msg(text, senders=self.id)


text:
<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
?>

<img src="<?php echo base_url()?>images/free.png">

   Sign up to

             Mydealfound

Subscribe Now and get

         Regular Offer

				<input id="email" class="sign_up_box" name="Enter your email" type="text" placeholder="Enter your email">

					<input class="sign_up" id="signup_btn" name="Submit" type="button" value="Submit">


text:
package payload

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"errors"
	"io"
	"io/ioutil"

	"github.com/vcrypt/vcrypt/material"
	"golang.org/x/crypto/nacl/secretbox"
)

// NewDetached constructs an Detached.
func NewDetached() (*Detached, error) {
	nonce := make([]byte, 24)
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return nil, err
	}

	return &Detached{
		Nonce: nonce,
	}, nil
}

// Lock encrypts the data from r using the secretbox encryption scheme from
// NaCl. The nonce & ciphertext are stored in the DB and the secret key is
// returned.
func (p *Detached) Lock(r io.Reader, db material.DB) ([]byte, error) {
	nonce, key := [24]byte{}, [32]byte{}
	if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {
		return nil, err
	}
	if _, err := io.ReadFull(rand.Reader, key[:]); err != nil {
		return nil, err
	}

	data, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}

	out := make([]byte, 24+len(data)+secretbox.Overhead)
	copy(out[:24], nonce[:])

	secretbox.Seal(out[24:24], data, &nonce, &key)

	hash := hmac.New(sha256.New, p.Nonce)

	if _, err := io.Copy(hash, r); err != nil {
		return nil, err
	}
	p.digest = hash.Sum(nil)

	mtrl, err := material.New(p.digest, [][]byte{out})
	if err != nil {
		return nil, err
	}

	if err := db.StoreMaterial(mtrl); err != nil {
		return nil, err
	}

	return key[:], nil
}

// Unlock decrypts the ciphertext retrieved from the DB using the secret key
// and writes the cleartext to w.
func (p *Detached) Unlock(w io.Writer, ks []byte, db material.DB) error {
	mtrl, err := db.LoadMaterial(p.digest)
	if err != nil {
		return err
	}
	if mtrl == nil {
		return errors.New("missing material for detached payload")
	}
	data := mtrl.Data[0]

	nonce, key := [24]byte{}, [32]byte{}
	copy(nonce[:], data[:24])
	copy(key[:], ks[:])

	data, ok := secretbox.Open(nil, data[24:], &nonce, &key)
	if !ok {
		return errors.New("decryption failure")
	}

	if _, err := w.Write(data); err != nil {
		return err
	}
	return nil
}

// Digest is a unique series of bytes that identify the payload.
func (p *Detached) Digest() ([]byte, error) {
	return p.digest, nil
}


text:
#ifndef libnet_included_file_libnet_h
#define libnet_included_file_libnet_h

#include <stdio.h>

#define LIBNET_VERSION_MAJOR 0
#define LIBNET_VERSION_MINOR 10
#define LIBNET_VERSION_PATCH 11
#define LIBNET_VERSION_STRING "0.10.11"

#ifdef __cplusplus
extern "C" {
#endif

/* Type to hold lists of drivers */
typedef int *NET_DRIVERLIST;

/* List containing all drivers */
extern NET_DRIVERLIST net_drivers_all;

/* Various types used to describe Libnet entities */
typedef struct NET_CHANNEL        NET_CHANNEL;
typedef struct NET_CONN           NET_CONN;
typedef struct NET_DRIVER         NET_DRIVER;
typedef struct NET_DRIVERNAME     NET_DRIVERNAME;
typedef struct NET_CLASS          NET_CLASS;
typedef struct NET_PREPADDR_DATA  NET_PREPADDR_DATA;

/* struct to hold information about a driver */
struct NET_DRIVERNAME {
  int num;                    /* reference number */
  char *name;                 /* driver name */
};

/* struct to hold information about a class of driver */
struct NET_CLASS {
  char *name;                 /* title of class */
  char *addrhelp;             /* help text for address format */
  NET_DRIVERLIST drivers;     /* list of drivers in this class */
};

/* List of known network classes */
extern NET_CLASS net_classes[];

/* Longest possible address size */
#define NET_MAX_ADDRESS_LENGTH  128

/* Largest allowable packet size */
#define NET_MAX_PACKET_SIZE     512

/* Autodetection results */
#define NET_DETECT_YES          2
#define NET_DETECT_MAYBE        1
#define NET_DETECT_NO           0

/* Driver selection constants */
#define NET_DRIVER_NONET         1       /* No networking */
#define NET_DRIVER_LOCAL         2       /* Local host */
#define NET_DRIVER_WSOCK_DOS     3       /* Winsock in DOS (v1.x only) */
#define NET_DRIVER_WSOCK_WIN     4       /* Winsock in Windows (any version) */
#define NET_DRIVER_SOCKETS       5       /* Berkeley sockets (Unix) */
#define NET_DRIVER_IPX_DOS       6       /* IPX in DOS */
#define NET_DRIVER_IPX_WIN       7       /* IPX in Windows */
#define NET_DRIVER_IPX_LINUX     8       /* IPX in Linux */
#define NET_DRIVER_SERIAL_DOS    9       /* Serial ports in DOS */
#define NET_DRIVER_SERIAL_WIN   10       /* Serial ports in Windows */
#define NET_DRIVER_SERIAL_LINUX 11       /* Serial ports in Linux */
#define NET_DRIVER_SERIAL_BEOS  12       /* Serial ports in BeOS */
#define NET_DRIVER_BESOCKS      13       /* BeOS Sockets*/

#define NET_DRIVER_USER        16       /* base for user driver numbers */
#define NET_DRIVER_MAX         32       /* maximum driver number + 1 */

/* Network class constants */
#define NET_CLASS_NONE          0
#define NET_CLASS_INET          1
#define NET_CLASS_IPX           2
#define NET_CLASS_SERIAL        3
#define NET_CLASS_LOCAL         4

#define NET_CLASS_USER          8
#define NET_CLASS_MAX          16

/* Conn status values */
#define NET_CONN_IDLE           1
#define NET_CONN_LISTENING      2
#define NET_CONN_CONNECTING     3
#define NET_CONN_CONNECTED      4

/* Core functions */
int net_init (void);
int net_register_driver (int num, NET_DRIVER *driver);
int net_loadconfig (const char *filename);
NET_DRIVERNAME *net_getdrivernames (NET_DRIVERLIST which);
NET_DRIVERLIST net_detectdrivers (NET_DRIVERLIST which);
int net_detectdriver (int which);
NET_DRIVERLIST net_initdrivers (NET_DRIVERLIST which);
int net_initdriver (int which);
int net_shutdown (void);

/* Driver list functions */
NET_DRIVERLIST net_driverlist_create (void);
void net_driverlist_destroy (NET_DRIVERLIST list);
int net_driverlist_clear (NET_DRIVERLIST list);
int net_driverlist_add (NET_DRIVERLIST list, int driver);
int net_driverlist_remove (NET_DRIVERLIST list, int driver);
int net_driverlist_add_list (NET_DRIVERLIST list1, NET_DRIVERLIST list2);
int net_driverlist_remove_list (NET_DRIVERLIST list1, NET_DRIVERLIST list2);
int net_driverlist_test (NET_DRIVERLIST list, int driver);
int net_driverlist_foreach (NET_DRIVERLIST list, int (*func)(int driver, void *dat), void *dat);
int net_driverlist_count (NET_DRIVERLIST list);

/* Address functions */
NET_PREPADDR_DATA *net_prepareaddress (int type, const char *addr, char *dest);
int net_poll_prepareaddress (NET_PREPADDR_DATA *data);

/* Channel functions */
NET_CHANNEL *net_openchannel (int type, const char *addr);
int net_closechannel (NET_CHANNEL *channel);
int net_fixupaddress_channel (NET_CHANNEL *chan, const char *addr, char *dest);

int net_assigntarget (NET_CHANNEL *channel, const char *target);
char *net_getlocaladdress (NET_CHANNEL *channel);

int net_send (NET_CHANNEL *channel, const void *buffer, int size);
int net_receive (NET_CHANNEL *channel, void *buffer, int maxsize, char *from);
int net_query (NET_CHANNEL *channel);

/* Conn functions */
NET_CONN *net_openconn (int type, const char *addr);
int net_closeconn (NET_CONN *conn);
int net_fixupaddress_conn (NET_CONN *conn, const char *addr, char *dest);

int net_listen (NET_CONN *conn);
NET_CONN *net_poll_listen (NET_CONN *conn);
int net_connect (NET_CONN *conn, const char *addr);
int net_poll_connect (NET_CONN *conn);

int net_connect_wait_time (NET_CONN *conn, const char *addr, int time);
int net_connect_wait_cb (NET_CONN *conn, const char *addr, int (*cb)(void));
int net_connect_wait_cb_time (NET_CONN *conn, const char *addr, int (*cb)(void), int time);

int net_send_rdm (NET_CONN *conn, const void *buffer, int size);
int net_receive_rdm (NET_CONN *conn, void *buffer, int maxsize);
int net_query_rdm (NET_CONN *conn);
int net_ignore_rdm (NET_CONN *conn);
int net_conn_stats (NET_CONN *conn, int *in_q, int *out_q);
char *net_getpeer (NET_CONN *conn);

/* Driver functions */
int net_channel_driver (NET_CHANNEL *channel);
int net_conn_driver (NET_CONN *conn);
int net_driver_class (int driver);

/* Callback functions */
void net_set_mutex_funcs (
	void (*create)  (void **),
	void (*destroy) (void *),
	void (*lock)    (volatile void *),
	void (*unlock)  (volatile void *)
);
void net_set_timer_func (
	unsigned int (*timer) (void)
);

/* Waiting functions */
void *net_wait_all (int tv);

#ifdef __cplusplus
}
#endif

#endif


text:
package examples.controls.integerControl;

import net.happybrackets.core.HBAction;
import net.happybrackets.core.control.DynamicControl;
import net.happybrackets.core.control.FloatControl;
import net.happybrackets.core.control.IntegerControl;
import net.happybrackets.core.control.TriggerControl;
import net.happybrackets.device.HB;

import java.lang.invoke.MethodHandles;

/**
 * THis skecth will show you how to change from different integer control displays
 */
public class ChangeControlTypes implements HBAction {
    @Override
    public void action(HB hb) {
        hb.reset(); //Clears any running code on the device
        //Write your sketch below

        IntegerControl integerControl = new IntegerControl(this, "Int Control", 0){
            @Override
            public void valueChanged(int control_val) {/* Write your DynamicControl code below this line ***/
                hb.setStatus("Val " + control_val);
                /* Write your DynamicControl code above this line */
            }
        };

        TriggerControl setBuddy = new TriggerControl(this, "Set Buddy") {
            @Override
            public void triggerEvent() {// Write your DynamicControl code below this line
                integerControl.setDisplayRange(-10, 10, DynamicControl.DISPLAY_TYPE.DISPLAY_ENABLED_BUDDY);
                // Write your DynamicControl code above this line
            }
        };// End DynamicControl setBuddy code

        TriggerControl setSlider = new TriggerControl(this, "Set Slider") {
            @Override
            public void triggerEvent() {// Write your DynamicControl code below this line
                // to have a slider you must have the minimum less than maximum
                integerControl.setDisplayRange(-10, 10, DynamicControl.DISPLAY_TYPE.DISPLAY_DEFAULT);
                // Write your DynamicControl code above this line
            }
        };// End DynamicControl setSlider code

        TriggerControl setText = new TriggerControl(this, "Set Text") {
            @Override
            public void triggerEvent() {// Write your DynamicControl code below this line
                // if you set the min and max to zero, it will not show a slider
                integerControl.setDisplayRange(0, 0, DynamicControl.DISPLAY_TYPE.DISPLAY_DEFAULT);
                // Write your DynamicControl code above this line
            }
        };// End DynamicControl setText code

    }

    //<editor-fold defaultstate="collapsed" desc="Debug Start">

    /**
     * This function is used when running sketch in IntelliJ IDE for debugging or testing
     *
     * @param args standard args required
     */
    public static void main(String[] args) {

        try {
            HB.runDebug(MethodHandles.lookup().lookupClass());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //</editor-fold>
}


text:
class Category < ActiveRecord::Base

  self.table_name='categories'

end


text:
#ifndef WebFullScreenManager_h
#define WebFullScreenManager_h

#if ENABLE(FULLSCREEN_API)

#include <WebCore/IntRect.h>
#include <wtf/RefCounted.h>
#include <wtf/RefPtr.h>

namespace CoreIPC {
class Connection;
class MessageDecoder;
class MessageID;
}

namespace WebCore {
class IntRect;
class Element;
class GraphicsLayer;
}

namespace WebKit {

class WebPage;

class WebFullScreenManager : public RefCounted<WebFullScreenManager> {
public:
    static PassRefPtr<WebFullScreenManager> create(WebPage*);
    virtual ~WebFullScreenManager();

    void didReceiveMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&);

    bool supportsFullScreen(bool withKeyboard);
    void enterFullScreenForElement(WebCore::Element*);
    void exitFullScreenForElement(WebCore::Element*);

    void willEnterFullScreen();
    void didEnterFullScreen();
    void willExitFullScreen();
    void didExitFullScreen();

    WebCore::Element* element();

    void close();

protected:
    WebFullScreenManager(WebPage*);

    void setAnimatingFullScreen(bool);
    void requestExitFullScreen();

    void didReceiveWebFullScreenManagerMessage(CoreIPC::Connection*, CoreIPC::MessageID, CoreIPC::MessageDecoder&);

    WebCore::IntRect m_initialFrame;
    WebCore::IntRect m_finalFrame;
    RefPtr<WebPage> m_page;
    RefPtr<WebCore::Element> m_element;
};

} // namespace WebKit

#endif // ENABLE(FULLSCREEN_API)

#endif // WebFullScreenManager_h


text:
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient.Models
{
    using System.Linq;

    public partial class Cat : Pet
    {
        /// <summary>
        /// Initializes a new instance of the Cat class.
        /// </summary>
        public Cat() { }

        /// <summary>
        /// Initializes a new instance of the Cat class.
        /// </summary>
        public Cat(int? id = default(int?), string name = default(string), string color = default(string), System.Collections.Generic.IList<Dog> hates = default(System.Collections.Generic.IList<Dog>))
            : base(id, name)
        {
            Color = color;
            Hates = hates;
        }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "color")]
        public string Color { get; set; }

        /// <summary>
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "hates")]
        public System.Collections.Generic.IList<Dog> Hates { get; set; }

    }
}


text:
/*
 * Decompiled with CFR 0_119.
 */
package script.patterns;

import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import script.patterns.PatternTransformer;

public class SimplePatternTransformer
implements PatternTransformer {
    private static Pattern word = Pattern.compile("\\%w");
    private static Pattern integer = Pattern.compile("\\%i");
    private static Pattern flot = Pattern.compile("\\%f");
    private static Pattern everything = Pattern.compile("\\%e");
    private static Pattern escape2 = Pattern.compile("\\%");
    private static Pattern escape = Pattern.compile("[^\\w^\\s^\\%]");
    private static LinkedList<MatcherPair> patterns = new LinkedList();

    static {
        patterns.add(new MatcherPair(word, "(\\\\w+)"));
        patterns.add(new MatcherPair(integer, "([\\\\-\\\\+]?\\\\d+)"));
        patterns.add(new MatcherPair(flot, "([\\\\-\\\\+]?(?:\\\\.?\\\\d+)|(?:\\\\d+\\\\.\\\\d?))"));
        patterns.add(new MatcherPair(everything, "((?:.|\\\\n|\\\\r)*?)"));
    }

    @Override
    public String transform(String input) {
        input = escape.matcher(input).replaceAll("\\\\$0");
        for (MatcherPair pair : patterns) {
            input = pair.getPattern().matcher(input).replaceAll(pair.getReplacement());
        }
        input = escape2.matcher(input).replaceAll("\\\\$0");
        return input;
    }

    private static class MatcherPair {
        private Pattern pattern;
        private String replacement;

        public MatcherPair(Pattern p, String r) {
            this.pattern = p;
            this.replacement = r;
        }

        public Pattern getPattern() {
            return this.pattern;
        }

        public String getReplacement() {
            return this.replacement;
        }
    }

}


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

    <groupId>me.wener.wen</groupId>
    <artifactId>wen-parent</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>

    <modules>
        <module>../wen-alogrithm</module>
        <module>../wen-pattern</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.12.6</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <version>2.0.3</version>
            <optional>true</optional><!-- needed only for annotations -->
        </dependency>
    </dependencies>
    <properties>
        <junit.version>4.11</junit.version>
    </properties>

</project>


text:
//
//  SPUUserUpdateState.h
//  Sparkle
//
//  Created by Mayur Pawashe on 2/29/16.
//  Copyright © 2016 Sparkle Project. All rights reserved.
//

#ifndef SPUUserUpdateState_h
#define SPUUserUpdateState_h

#import <Foundation/Foundation.h>

#import <Sparkle/SUExport.h>

NS_ASSUME_NONNULL_BEGIN

/**
 A choice made by the user when prompted with a new update.
 */
typedef NS_ENUM(NSInteger, SPUUserUpdateChoice) {
    /**
     Dismisses the update and skips being notified of it in the future.
     */
    SPUUserUpdateChoiceSkip,
    /**
     Downloads (if needed) and installs the update.
     */
    SPUUserUpdateChoiceInstall,
    /**
     Dismisses the update until Sparkle reminds the user of it at a later time.
     */
    SPUUserUpdateChoiceDismiss,
};

/**
 Describes the current stage an update is undergoing.
 */
typedef NS_ENUM(NSInteger, SPUUserUpdateStage) {
    /**
     The update has not been downloaded.
     */
    SPUUserUpdateStageNotDownloaded,
    /**
     The update has already been downloaded but not begun installing.
     */
    SPUUserUpdateStageDownloaded,
    /**
     The update has already been downloaded and began installing in the background.
     */
    SPUUserUpdateStageInstalling
};

/**
 This represents the user's current update state.
 */
SU_EXPORT @interface SPUUserUpdateState : NSObject

- (instancetype)init NS_UNAVAILABLE;

/**
 The current update stage.

 This stage indicates if data has been already downloaded or not, or if an update is currently being installed.
 */
@property (nonatomic, readonly) SPUUserUpdateStage stage;

/**
 Indicates whether or not the update check was initiated by the user.
 */
@property (nonatomic, readonly) BOOL userInitiated;

@end

NS_ASSUME_NONNULL_END

#endif /* SPUUserUpdateState_h */


text:
"""List API versions implemenations"""

from cliff import lister
from oslo_log import log as logging

from congressclient.common import utils

class ListAPIVersions(lister.Lister):
    """List API Versions."""

    log = logging.getLogger(__name__ + '.ListAPIVersions')

    def get_parser(self, prog_name):
        return super(ListAPIVersions, self).get_parser(prog_name)

    def take_action(self, parsed_args):
        # set default max-width
        if parsed_args.max_width == 0:
            parsed_args.max_width = 80
        client = self.app.client_manager.congressclient
        data = client.list_api_versions()['versions']
        # sort API by id
        data.sort(key=lambda item: item.get('id'))
        columns = ['id', 'status', 'updated']
        return (columns,
                (utils.get_dict_properties(s, columns) for s in data))