text:
#include "PovrayWriter.hpp"

#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <string>

#include "DataCollector.hpp"
#include "DOFVector.hpp"
#include "Traverse.hpp"

using namespace std;

namespace AMDiS
{
  namespace io
  {

    /* destructor */
    PovrayWriter::~PovrayWriter()
    {
      // free the memory for the bounding box
      if (bBox)
      {
        delete bBox;
        bBox = NULL;
      }
    }

    /* some forward declarations */
    double computeWeight(double&, double&, double&);
    string getColorString(double&);

    void PovrayWriter::tryMeshTraversal(ofstream& out)
    {
      /* prepare some data structures */
      DOFVector<double>* values = dataCollector->getValues();
      const FiniteElemSpace* feSpace = dataCollector->getFeSpace();
      const BasisFunction* basFcts = feSpace->getBasisFcts();
      std::vector<DegreeOfFreedom> dofs(basFcts->getNumber());

      /* create an 'iterator' */
      TraverseStack stack;
      ElInfo* elInfo =  stack.traverseFirst(dataCollector->getMesh(), -1,
                                            Mesh::CALL_LEAF_EL | Mesh::FILL_COORDS);

      /* find min and max values */
      double min_value = 0;
      double max_value = 0;
      if (values->getSize() > 0)
        min_value = max_value = (*values)[0];

      for (int index = 1; index < values->getSize(); index++)
      {
        min_value = std::min(min_value, (*values)[index]);
        max_value = std::max(max_value, (*values)[index]);
      }

      /* map DOFs to values */
      std::map <DegreeOfFreedom, double> value_map;
      while (elInfo)
      {
        basFcts->getLocalIndices(elInfo->getElement(), feSpace->getAdmin(), dofs);

        int max = Global::getGeo(WORLD)==2 ? 3 : 4;

        for (int i = 0; i < max; i++)
        {
          double value = (*values)[dofs[i]];
          value_map[dofs[i]] = value;
        }

        elInfo = stack.traverseNext(elInfo);
      }

      out << "\ttexture_list {" << endl;
      out << "\t" << value_map.size() << "," << endl;
      std::map<DegreeOfFreedom, double>::iterator map_iter;
      for (map_iter = value_map.begin(); map_iter != value_map.end(); ++map_iter)
      {
        double value = map_iter->second;
        double color_weight =  computeWeight(min_value,max_value,value);
        out << "\t\ttexture{ pigment{ " << getColorString(color_weight) << "}}";
        std::map<DegreeOfFreedom, double>::iterator final_iter = value_map.end();
        --final_iter;
        if (map_iter != final_iter)
          out << ",";
        out << endl;
      }
      out << "\t}" << endl; // end of texture_list
    }

    // provides the bounding box of the mesh
    //
    // note: computation is done during the first call other, this might cause
    //       problems in simulations with changing geometries
    BoundingBox* PovrayWriter::getBoundingBox(ofstream& /*out*/)
    {
      if (bBox != NULL)
        return bBox;

      DOFVector<std::list<VertexInfo>>* vertexInfos = dataCollector->getVertexInfos();
      DOFVector<std::list<VertexInfo>>::Iterator it(vertexInfos, USED_DOFS);
      int dow = Global::getGeo(WORLD);
      bBox = new BoundingBox();

      it.reset();
      std::list<VertexInfo>::iterator it2 = it->begin();
      bBox->minx = it2->coords[0];
      bBox->maxx = it2->coords[0];
      bBox->miny = it2->coords[1];
      bBox->maxy = it2->coords[1];
      if (dow == 3)
      {
        bBox->minz = it2->coords[2];
        bBox->maxz = it2->coords[2];
      }
      else
      {
        bBox->minz = bBox->maxz = 0;
      }

      for (it.reset(); !it.end(); ++it)
      {
        // initialize mit and max values with coordinates of first vertex
        std::list<VertexInfo>::iterator it2 = it->begin();
        bBox->minx = std::min(bBox->minx, it2->coords[0]);
        bBox->maxx = std::max(bBox->maxx, it2->coords[0]);
        bBox->miny = std::min(bBox->miny, it2->coords[1]);
        bBox->maxy = std::max(bBox->maxy, it2->coords[1]);
        if (dow == 3)
        {
          bBox->minz = std::min(bBox->minz, it2->coords[2]);
          bBox->maxz = std::max(bBox->maxz, it2->coords[2]);
        }
      }

      return bBox;
    }

    // computes the weight of a value for color computation
    double computeWeight(double& min, double& max, double& value)
    {
      double interval_length = (max - min);
      return (value - min) / interval_length;
    }

    // determines the color for a given value/weight
    string getColorString(double& value)
    {
      value = std::max(0.0, value);
      value = std::min(value, 1.0);

      // rot: 1,0,0
      // blau: 0,0,1

      // currently blue->red gradient
      stringstream res;
      res << "rgb<" << value << ",0," << (1 - value) << ">";
      return res.str();
    }

    // writes a povray script for the current time step to the specified file
    void PovrayWriter::writeFile(std::string filename)
    {
      ofstream out;
      out.open(filename.c_str(), ios::out);

      // delegate all the work to other subroutines
      writeHeader(out);
      writeIncludes(out);
      writeCamera(out);
      writeLight(out);
      writeTestStuff(out, *dataCollector);
      writeMesh2(out, *dataCollector);

      out.close();
    }

    // writes a simple info header (comments only)
    void PovrayWriter::writeHeader(ofstream& out)
    {
      out << "// povray file created by AMDiS" << endl;
      out << endl;
    }

    // writes all neccessary include file declarations
    void PovrayWriter::writeIncludes(ofstream& out)
    {
      out << "#include \"colors.inc\"" << endl;
      out << "#include \"stones.inc\"" << endl;
      out << endl;
    }

    // computes an appropriate camera position and writes it to the povray file
    void PovrayWriter::writeCamera(ofstream& out)
    {
      /* TODO: compute adequate camera position (computation needs to be performed
         only once, same camera position will be used for all iterations) */

      /* TODO: check whether camera position and location have been specified in the
         init file, use them if present*/

      BoundingBox* box = getBoundingBox(out);
      int dow = Global::getGeo(WORLD);
      double centerx = (box->minx+box->maxx)/2.;
      double centery = (box->miny+box->maxy)/2.;
      double centerz = (box->minz+box->maxz)/2.;

      if (dow == 2)
      {
        out << "camera {" << endl;
        out << "\tlocation <" << centerx << ", " << centery << ", -3>" << endl;
        out << "\tlook_at  <" << centerx << ", " << centery << ",  0>" << endl;
        out << "}" << endl << endl;
      }
      else
      {
        out << "camera {" << endl;
        out << "\tlocation <"<< centerx <<", "<<centery<<", -3>" << endl;
        out << "\tlook_at  <"<< centerx <<", "<<centery<<",  "<<centerz<<">" << endl;
        out << "}" << endl << endl;
      }
    }

    // computes an appropriate light source and writes it to the povray file
    void PovrayWriter::writeLight(ofstream& out)
    {
      // TODO: compute adequate light position
      out << "light_source { <0, 0, -15> color White}" << endl;
    }

    // writes the data in the 'mesh2' format
    void PovrayWriter::writeMesh2(ofstream& out, DataCollector<>& dataCollector)
    {
      // initialization and preparations
      //Mesh *mesh = dataCollector.getMesh();

      // begin of mesh2 block
      out << "mesh2 {" << endl;

      // delegate work to other methods
      writeVertexVectors(out, dataCollector);
      //writeTextureList(out, dataCollector);
      tryMeshTraversal(out);
      writeFaceIndices(out, dataCollector);
      out << "\t" << "pigment {rgb 1}" << endl;
      // end of mesh2 block
      out << "}" << endl;
    }

    // writes all vertices of the model
    void PovrayWriter::writeVertexVectors(ofstream& out, DataCollector<>& dataCollector)
    {
      // initialization and preparations
      Mesh* mesh = dataCollector.getMesh();
      DOFVector<std::list<VertexInfo>>* vertexInfos = dataCollector.getVertexInfos();
      DOFVector<std::list<VertexInfo>>::Iterator it(vertexInfos, USED_DOFS);

      // begin of vertex_vectors block
      out << "\tvertex_vectors {" << endl;
      int nVertices = mesh->getNumberOfVertices();
      out << "\t\t" << nVertices << "," << endl;

      // For all DOFs of vertices, write the coordinates.
      for (it.reset(); !it.end(); ++it)
      {
        // for all vertex infos of this DOF
        for (std::list<VertexInfo>::iterator it2 = it->begin(); it2 != it->end(); ++it2)
        {
          out << endl;
          // TODO: right implementation using STL vector/iterator
          out  << "\t\t<";
          WorldVector<double> coords;
          coords = it2->coords;
          for (int i = 0; i < Global::getGeo(WORLD); i++)
          {
            if (i > 0)
              out << ", ";

            out << std::scientific << coords[i];
          }
          for (int i = Global::getGeo(WORLD); i < 3; i++)
            out << ", 0.0";
          out << ">,";
        }
      }
      // undo last comma
      long pos = out.tellp(); //tells pos the actual stream position
      out.seekp(pos - 1);     //sets stream position -1
      out <<  endl;         //overwrites the las comma with space
      // end of vertex_vectors block
      out << "\t}" << endl;
    }

    // writes the list of textures (basically one color for each vertex, used to draw a color gradient on each triangle)
    void PovrayWriter::writeTextureList(ofstream& out, DataCollector<>& dataCollector)
    {
      // prepare some data structures
      Mesh* mesh = dataCollector.getMesh();
      DOFVector<std::list<VertexInfo>>* vertexInfos = dataCollector.getVertexInfos();
      DOFVector<std::list<VertexInfo>>::Iterator it(vertexInfos, USED_DOFS);

      // begin of texture_list block
      out << "\ttexture_list {" << endl;

      // compute and write the number of textures/colors (one for each vertex)
      int nTextures = mesh->getNumberOfVertices();
      out << "\t\t" << nTextures << "," << endl;

      // For all DOFs of vertices, write the coordinates.
      for (it.reset(); !it.end(); ++it)
      {
        // for all vertex infos of this DOF
        for (std::list<VertexInfo>::iterator it2 = it->begin(); it2 != it->end(); ++it2)
        {
          // test: use y-coordinate to compute color
          double redValue = it2->coords[1];
          redValue = std::max(0., redValue);
          redValue = std::min(redValue, 1.);

          out << "\n\t\ttexture{ pigment{ rgb"<< getColorString(redValue) <<" } }" << ",";
        }
      }
      long pos = out.tellp();
      out.seekp(pos - 1);
      out << endl;
      // end of texture_list block
      out << "\t}" << endl;
    }

    // writes the connectivity
    void PovrayWriter::writeFaceIndices(ofstream& out, DataCollector<>& dataCollector)
    {
      // begin of face_indices block
      out << "\tface_indices {" << endl;

      std::list<ElementInfo>* elementInfos = dataCollector.getElementInfos();
      int vertices = dataCollector.getMesh()->getGeo(VERTEX);
      int meshDim = dataCollector.getMesh()->getDim();
      int counter = 0;

      if (meshDim == 2)
      {
        size_t nElements = dataCollector.getElementInfos()->size();
        out << "\t\t" << nElements << "," << endl;
        for (std::list<ElementInfo>::iterator iter = elementInfos->begin();
             iter != elementInfos->end(); iter++)
        {
          out << endl;
          out << "\t\t<";
          for (int i = 0; i < vertices; i++)
          {
            if (i > 0)
              out << ", ";

            out << iter->vertexInfo[i]->outputIndex;
          }
          out << ">";

          // write indices again for texture/color mapping
          for (int i = 0; i < vertices; i++)
          {
            out << ", ";
            out << iter->vertexInfo[i]->outputIndex;
          }

          out << ",";
        }
        //Delete last comma
        long pos = out.tellp();
        out.seekp(pos - 1);
        out << endl;
      }
      else if (meshDim == 3)
      {
        size_t nElements = dataCollector.getElementInfos()->size() * 4;
        out << "\t\t" << nElements << "," << endl;
        for (std::list<ElementInfo>::iterator iter = elementInfos->begin();
             iter != elementInfos->end(); iter++)
        {
          for (int j = 0; j < vertices; j++)
          {
            out << "/* " << counter++ << " */";
            out << "\t\t<";
            for (int i = 0; i < vertices; i++)
            {
              if (i==j)
                continue;

              if (!((j > 0 && i == 0) || (j == 0 && i == 1)))
                out << ", ";

              out << iter->vertexInfo[i]->outputIndex;
            }
            out << ">";
            // write indices again for texture/color mapping
            for (int i = 0; i < vertices; i++)
            {
              if (i == j)
                continue;
              out << ", ";
              out << iter->vertexInfo[i]->outputIndex;
            }
            out << "," << endl;
          }
        }
      }

      // end of face_indices block
      out << "\n\t}" << endl; //
    }

    /// writes some additional information for debugging purposes
    void PovrayWriter::writeTestStuff(ofstream& out, DataCollector<>& dataCollector)
    {
      Mesh* mesh = dataCollector.getMesh();

      out << "/*" << endl;
      out << "TestData:" << endl;

      int dow = Global::getGeo(WORLD);
      out << " world dimension:\t" << dow << endl;

      out << " dimension:\t" << mesh->getDim() << endl;
      out << " numberOfNodes:\t" << mesh->getNumberOfNodes() << endl;
      out << " numberOfEdges:\t" << mesh->getNumberOfEdges() << endl;
      out << " numberOfVertices:\t" << mesh->getNumberOfVertices() << endl;
      out << " numberOfFaces:\t" << mesh->getNumberOfFaces() << endl;
      out << " numberOfElements:\t" << mesh->getNumberOfElements() << endl;
      out << "*/" << endl << endl;
    }

  }
} // end of namespace io, AMDiS


text:
function vesiclerf_train(outputFile, set, scale, fname)
% Function to train a RF classifier on a fixed region of interest (AC4)
%
% **Inputs**
%
% outputFile: (string)
%   - Location of output file containing classifier, saved as a matlab file in a variable named 'classifier'
%
% **Outputs**
%
%	No explicit outputs.  Output file is saved to disk rather than
%	output as a variable to allow for downstream integration with LONI.
%
% **Notes**
%
%	Currently training region is hardcoded, but can be adjusted as needed by getting new '\*DataTrain'.

addpath(genpath(pwd))

%eData = h5read(strcat('../../../../../../kasthuri_data/Data/', set, '/', set, '.h5'),'/image');
%sData = h5read(strcat('../../../../../../kasthuri_data/Data/', set, '/', set, '.h5'),'/synapse');
%vData = h5read(strcat('../../../../../../kasthuri_data/Data/', set, '/', set, '.h5'),'/vesicle');
%mData = h5read(strcat('../../../../../../kasthuri_data/Data/', set, '/', set, '.h5'),'/membrane');

eData = load(strcat('../../../../../../kasthuri_data/Data/', set, '/eData_', set, '.mat'));
eData = eData.cube.data;

mData = load(strcat('../../../../../../kasthuri_data/Data/', set, '/mData_', set, '.mat'));
mData = mData.cube.data;

sData = load(strcat('../../../../../../kasthuri_data/Data/', set, '/sData_', set, '.mat'));
sData = sData.cube.data;

vData = load(strcat('../../../../../../kasthuri_data/Data/', set, '/vData_', set, '.mat'));
vData = vData.cube.data;

if exist('scale','var')==1
    imSize = size(eData);
    images = imSize(3);

    % Image Data.
    temp = eData;
    eData = zeros(imSize(1)*scale,imSize(2)*scale,images);
    for i = 1:images
        eData(:,:,i) = imresize(temp(:,:,i),scale);
    end

    % Synapse Data.
    temp = sData;
    sData = zeros(imSize(1)*scale,imSize(2)*scale,images);
    for i = 1:images
        sData(:,:,i) = imresize(temp(:,:,i),scale);
    end

    % Vesicle Data.
    temp = vData;
    vData = zeros(imSize(1)*scale,imSize(2)*scale,images);
    for i = 1:images
        vData(:,:,i) = imresize(temp(:,:,i),scale);
    end

    % Membrane Data.
    temp = mData;
    mData = zeros(imSize(1)*scale,imSize(2)*scale,images);
    for i = 1:images
        mData(:,:,i) = imresize(temp(:,:,i),scale);
    end
end

% Find valid pixels
mThresh = 0.75;
mm = (mData>mThresh);
%mm = imdilate(mm,strel('disk',5));
%mm = bwareaopen(mm, 1000, 4);
pixValid = find(mm > 0);

disp('Beginning training (vesiclerf_train.m).')
st = tic;

% Extract Features
Xtrain = vesiclerf_feats(eData, pixValid, vData);

% Classifier training
Ytrain = create_labels_pixel(sData, pixValid, [50,50,2]);

% Classifier training
trTarget = find(Ytrain>0);
trClutter = find(Ytrain==0);

idxT = randperm(length(trTarget));
idxC = randperm(length(trClutter));

nPoints = min(200000, length(trTarget)); % todo - should be 200,000

trainLabel = [Ytrain(trTarget(idxT(1:nPoints))); ...
    Ytrain(trClutter(idxC(1:nPoints)))];

trainFeat = [Xtrain(trTarget(idxT(1:nPoints)),:); ...
    Xtrain(trClutter(idxC(1:nPoints)),:)];

classifier = classRF_train(double(trainFeat),double(trainLabel),...
    200,floor(sqrt(size(trainFeat,2))));%,extra_options);  % todo - should be 200.
classifier.scale = scale;

save(outputFile,'classifier', '-v7.3');

t = toc(st);

fprintf('Training complete, time elapsed: %0.2f.\n', t);

fid = fopen(strcat(fname, '/report.txt'),'a');
fprintf(fid,'Training complete, time elapsed: %0.2f.\n', t);
fclose(fid);

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>PhoneGap Div-Table</title>
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" href="buttons.css" />
    <link rel="stylesheet" href="app.css" />
    <link rel="stylesheet" href="navsim.css" />

	Phonegap Div-Table
	<button id=exit-button onclick='navigator.app.exitApp()' class="button button-pill button-primary button-large">Exit</button>

BACK

    Created by Jesus Monroy, Jr. © 2015


text:
jberet-support module includes `xmlItemReader` and `xmlItemWriter` to handle XML chunk-oriented data. `xmlItemReader` reads and binds data to instances of custom POJO bean provided by the batch application.

`xmlItemReader` and `xmlItemWriter` leverages `jackson` and `jackson-dataformat-xml` libraries to handle XML data parsing and binding. The following `jackson` dependencies are required:

```xml
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>${version.com.fasterxml.jackson}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${version.com.fasterxml.jackson}</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>${version.com.fasterxml.jackson}</version>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>${version.com.fasterxml.jackson}</version>
</dependency>

<!-- POJO beans may contain either jackson annotations, or JAXB annotations -->
<!-- Include this dependency if JAXB annotation introspector is needed -->
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-jaxb-annotations</artifactId>
    <version>${version.com.fasterxml.jackson}</version>
</dependency>
```

##Batch Configuration Properties in Job XML
`xmlItemReader` and `xmlItemWriter` are configured through `<reader>` or `<writer>` batch properties in job xml. All properties are of type `String`, unless noted otherwise. The following is an example job xml that references `xmlItemReader` and `xmlItemWriter`:

```xml
<job id="XmlItemReaderTest" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0">
    <step id="XmlItemReaderTest.step1">
        <chunk item-count="100">
            <reader ref="xmlItemReader">
                <properties>
                    <property name="resource" value="#{jobParameters['resource']}"/>
                    <property name="start" value="1"/>
                    <property name="end" value="#{jobParameters['end']}"/>
                    <property name="beanType" value="org.jberet.support.io.Movie"/>
                </properties>
            </reader>
            <writer ref="xmlItemWriter">
                <properties>
                    <property name="resource" value="#{jobParameters['writeResource']}"/>
                    <property name="rootElementName" value="movies"/>
                    <property name="writeMode" value="#{jobParameters['writeMode']}?:overwrite;"/>
                    <!--<property name="prettyPrinter" value="com.fasterxml.jackson.core.util.MinimalPrettyPrinter"/>-->
                </properties>
            </writer>
        </chunk>
    </step>
</job>
```

###Batch Properties for Both `xmlItemReader` and `xmlItemWriter`

####resource

The resource to read from (for batch readers), or write to (for batch writers).

####xmlFactoryLookup

JNDI lookup name for `com.fasterxml.jackson.dataformat.xml.XmlFactory`, which is used for constructing `com.fasterxml.jackson.dataformat.xml.deser.FromXmlParser` in `xmlItemReader` and `com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator` in `xmlItemWriter`. See class [org.jberet.support.io.XmlFactoryObjectFactory](http://docs.jboss.org/jberet/latest/javadoc/jberet-support/org/jberet/support/io/XmlFactoryObjectFactory.html) for more details.

####customDataTypeModules

A comma-separated list of Jackson datatype module type ids that extend `com.fasterxml.jackson.databind.Module`. These modules will be registered with `xmlMapper`. For example,

`com.fasterxml.jackson.datatype.joda.JodaModule,
com.fasterxml.jackson.datatype.jsr353.JSR353Module,
com.fasterxml.jackson.datatype.jsr310.JSR310Module,
com.fasterxml.jackson.module.afterburner.AfterburnerModule`

###Batch Properties for `xmlItemReader` Only
In addition to the above common properties, `xmlItemReader` also supports the following batch properties in job xml:

####skipBeanValidation
`boolean`

Indicates whether the current batch reader will invoke Bean Validation API to validate the incoming data POJO. Optional property and defaults to `false`, i.e., the reader will validate data POJO bean where appropriate.

####beanType
`java.lang.Class`

The bean class that represents individual data item in the `resource` XML, and the `readItem()` method reads one item at a time and binds it to the provided bean type. Required property. For example,

* `org.jberet.support.io.StockTrade`
* `org.jberet.support.io.Person`
* `my.own.custom.ItemBean`

####start
`int`

Specifies the start position (a positive integer starting from `1`) to read the data. If reading from the beginning of the input XML, there is no need to specify this property.

####end
`int`

Specify the end position in the data set (inclusive). Optional property, and defaults to `Integer.MAX_VALUE`. If reading till the end of the input XML, there is no need to specify this property.

####inputDecorator
`java.lang.Class`

Fully-qualified class name of `com.fasterxml.jackson.core.io.InputDecorator`, which can be used to decorate input sources. Optional property, and defaults to `null`. See `com.fasterxml.jackson.core.io.InputDecorator`, and  `com.fasterxml.jackson.core.JsonFactory#setInputDecorator(com.fasterxml.jackson.core.io.InputDecorator)` for more details.

####xmlTextElementName
Alternate "virtual name" to use for XML CDATA segments; that is, text values. Optional property and defaults to `null` (empty String, "", is used as the virtual name). See `com.fasterxml.jackson.dataformat.xml.JacksonXmlModule#setXMLTextElementName(java.lang.String)` for more details.

###Batch Properties for `xmlItemWriter` Only
In addition to the above common properties, `xmlItemWriter` also supports the following batch properties in job xml:

####writeMode
Instructs this class, when the target XML resource already exists, whether to append to, or overwrite the existing resource, or fail. Valid values are `"append"`, `"overwrite"`, and `"failIfExists"`. Optional property, and defaults to append.

####defaultUseWrapper
Whether use wrapper for indexed (List, array) properties or not, if there are no explicit annotations. Optional property, valid values are `"true"` and `"false"`, and defaults to `"true"`. See `com.fasterxml.jackson.dataformat.xml.JacksonXmlModule#setDefaultUseWrapper(boolean)`, and  ` com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper` for more details.

####rootElementName
Local name of the output XML root element. Required property. See `javax.xml.stream.XMLStreamWriter#writeStartElement` for more details.

####rootElementPrefix
The prefix of the XML root element tag. Optional property and defaults to `null`. See `javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String, java.lang.String, java.lang.String)` for more details.

####rootElementNamespaceURI
The namespaceURI of the prefix to use. Optional property and defaults to `null`. See `javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String, java.lang.String, java.lang.String)`, and `javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String, java.lang.String)` for more details.

####prettyPrinter
`java.lang.Class`

The fully-qualified class name of `com.fasterxml.jackson.core.PrettyPrinter`, which implements pretty printer functionality, such as indentation. Optional property and defaults to `null` (default pretty printer is used). See `com.fasterxml.jackson.core.PrettyPrinter`, and `com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator#setPrettyPrinter(com.fasterxml.jackson.core.PrettyPrinter)` for more details.

####outputDecorator
`java.lang.Class`

The fully-qualified class name of `com.fasterxml.jackson.core.io.OutputDecorator`, which can be used to decorate output destinations. Optional property and defaults to null. See `com.fasterxml.jackson.core.io.OutputDecorator`, and `com.fasterxml.jackson.core.JsonFactory#setOutputDecorator(com.fasterxml.jackson.core.io.OutputDecorator)` for more details.


text:
package xxxxx.yyyyy.zzzzz.domain.shared;

import java.io.Serializable;

public interface ValueObject<T extends ValueObject<T>> extends Serializable {

    default boolean isSameValueAs(final T other) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}


text:
package io.cattle.platform.app;

import io.cattle.platform.archaius.eventing.impl.ArchaiusEventListenerImpl;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ArchaiusConfig {

    @Bean
    ArchaiusEventListenerImpl ArchaiusEventListenerImpl() {
        return new ArchaiusEventListenerImpl();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
    Copyright (C) 2010 The Android Open Source Project 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.
-->
<resources
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <dimen name="tab_width">180dp</dimen>
    <dimen name="tab_height">44dp</dimen>
    <dimen name="tab_overlap">8dp</dimen>
    <dimen name="tab_addoverlap">14dp</dimen>
    <dimen name="tab_slice">15.5dp</dimen>
    <dimen name="tab_focus_stroke">2dip</dimen>
    <dimen name="max_tab_width">300dp</dimen>
    <dimen name="bookmarkThumbnailWidth">90dip</dimen>
    <dimen name="bookmarkThumbnailHeight">80dip</dimen>
    <!-- Height determined by measuring the TableLayout in
        browser_add_bookmark_content and matching that. -->
    <dimen name="folder_selector_height">181dip</dimen>
    <dimen name="widgetItemMinHeight">48dip</dimen>
    <dimen name="favicon_size">16dip</dimen>
    <dimen name="favicon_padded_size">20dip</dimen>
    <dimen name="qc_radius_start">65dip</dimen>
    <dimen name="qc_radius_increment">80dip</dimen>
    <dimen name="qc_slop">10dip</dimen>
    <dimen name="qc_touch_offset">15dip</dimen>
    <dimen name="qc_tab_title_height">24dip</dimen>
    <dimen name="qc_thumb_width">150dip</dimen>
    <dimen name="qc_thumb_height">100dip</dimen>
    <dimen name="qc_item_size">40dip</dimen>
    <dimen name="bookmark_widget_thumb_size">32dip</dimen>
    <dimen name="bookmark_widget_favicon_size">26dip</dimen>
    <!-- For the most visited page (we use px as these are adjusted by the browser) -->
    <dimen name="mv_max_width">450px</dimen>
    <dimen name="mv_item_width">80px</dimen>
    <dimen name="mv_item_width_portrait">80px</dimen>
    <dimen name="mv_border_width">2px</dimen>
    <dimen name="tab_padding_top">12dp</dimen>
    <dimen name="tab_first_padding_left">12dp</dimen>
    <dimen name="list_favicon_padding">5dip</dimen>
    <dimen name="list_favicon_corner_radius">3dip</dimen>
    <dimen name="tab_favicon_corner_radius">2dip</dimen>
    <dimen name="widgetThumbnailHeight">94dip</dimen>
    <dimen name="widgetHorizontalSpacing">6dip</dimen>
    <dimen name="widgetVerticalSpacing">6dip</dimen>
    <dimen name="widgetColumnWidth">80dip</dimen>
    <!-- For the combined Bookmarks History view -->
    <dimen name="combo_paddingTop">0dip</dimen>
    <dimen name="combo_horizontalSpacing">6dip</dimen>
    <dimen name="tab_view_thumbnail_height">76dip</dimen>
    <!-- Preference activity side margins -->
    <dimen name="preference_screen_side_margin">0dp</dimen>
    <!-- Preference activity side margins negative-->
    <dimen name="preference_screen_side_margin_negative">0dp</dimen>
    <!-- Preference widget area width (to the left of the text) -->
    <dimen name="preference_widget_width">56dp</dimen>
    <dimen name="nav_tab_spacing">8dp</dimen>
    <dimen name="menu_width">240dip</dimen>
    <dimen name="menu_height">32dip</dimen>
    <dimen name="toolbar_height">52dip</dimen>
    <dimen name="tab_thumbnail_width">240dip</dimen>
    <dimen name="tab_thumbnail_height">160dip</dimen>
    <dimen name="nav_tab_width">240dip</dimen>
    <dimen name="nav_tab_height">160dip</dimen>
    <dimen name="nav_tab_titleheight">32dip</dimen>
    <dimen name="nav_tab_text_normal">18sp</dimen>
    <dimen name="nav_tab_text_small">14sp</dimen>
    <dimen name="suggest_item_padding">8dp</dimen>
    <dimen name="progress_bar_margin">-11dip</dimen>
</resources>


text:
package server;

import com.github.seratch.signedrequest4j.HttpMethod;
import org.eclipse.jetty.server.Request;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetHandler extends BasicHandler {

	@Override
	public void handle(String target,
	                   Request baseRequest,
	                   HttpServletRequest request,
	                   HttpServletResponse response) {
		try {
			_handle(request.getMethod() == HttpMethod.GET.name(), HttpMethod.GET, baseRequest, request, response);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}


text:
package com.haskforce.parsing.srcExtsDatatypes;

/**
 * TyCon   l (QName l)
 */
public class TyCon extends TypeTopType {
    public SrcInfoSpan srcInfoSpan;
    public QNameTopType qName;

    @Override
    public String toString() {
        return "TyCon{" +
                "qName=" + qName +
                '}';
    }
}


text:
module MiqReportResult::Purging
  extend ActiveSupport::Concern
  include PurgingMixin

  module ClassMethods
    def purge_mode_and_value
      value = ::Settings.reporting.history.keep_reports
      mode  = value.number_with_method? ? :date : :remaining
      value = value.to_i_with_method.seconds.ago.utc if mode == :date
      return mode, value
    end

    def purge_window_size
      ::Settings.reporting.history.purge_window_size
    end

    def purge_count(mode, value)
      send("purge_count_by_#{mode}", value)
    end

    def purge(mode, value, window = nil, &block)
      send("purge_by_#{mode}", value, window, &block)
    end

    def purge_associated_records(ids)
      MiqReportResultDetail.where(:miq_report_result_id => ids).delete_all
      BinaryBlob.where(:resource_type => name, :resource_id => ids).destroy_all
    end

    private

    #
    # By Remaining
    #

    # @return [Symbol, Array<Symbol>] resource that is referenced by this table.
    def purge_remaining_foreign_key
      :miq_report_id
    end

    #
    # By Date
    #
    def purge_scope(older_than)
      where(arel_table[:created_on].lt(older_than))
    end
  end
end


text:
<!-- Import this file to WebStorm JavaScript code styles -->
<code_scheme name="ReactJSX">
  <JSCodeStyleSettings>
    <option name="SPACES_WITHIN_OBJECT_LITERAL_BRACES" value="true" />
    <option name="SPACES_WITHIN_IMPORTS" value="true" />
  </JSCodeStyleSettings>
  <MarkdownNavigatorCodeStyleSettings>
    <option name="RIGHT_MARGIN" value="72" />
  </MarkdownNavigatorCodeStyleSettings>
  <XML>
    <option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
  </XML>
  <codeStyleSettings language="JavaScript">
    <option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
  </codeStyleSettings>
  <codeStyleSettings language="SASS">
    <indentOptions>
      <option name="INDENT_SIZE" value="4" />
    </indentOptions>
  </codeStyleSettings>
  <codeStyleSettings language="SCSS">
    <indentOptions>
      <option name="INDENT_SIZE" value="4" />
    </indentOptions>
  </codeStyleSettings>
</code_scheme>


text:
namespace net {

HttpNetworkSessionPeer::HttpNetworkSessionPeer(
    const scoped_refptr<HttpNetworkSession>& session)
    : session_(session) {}

HttpNetworkSessionPeer::~HttpNetworkSessionPeer() {}

void HttpNetworkSessionPeer::SetClientSocketPoolManager(
    scoped_ptr<ClientSocketPoolManager> socket_pool_manager) {
  session_->normal_socket_pool_manager_.swap(socket_pool_manager);
}

void HttpNetworkSessionPeer::SetProxyService(ProxyService* proxy_service) {
  session_->proxy_service_ = proxy_service;
}

void HttpNetworkSessionPeer::SetHttpStreamFactory(
    scoped_ptr<HttpStreamFactory> http_stream_factory) {
  session_->http_stream_factory_.swap(http_stream_factory);
}

void HttpNetworkSessionPeer::SetHttpStreamFactoryForWebSocket(
    scoped_ptr<HttpStreamFactory> http_stream_factory) {
  session_->http_stream_factory_for_websocket_.swap(http_stream_factory);
}

}  // namespace net


text:
module.exports = function doDoubleClick (callback) {

    var requestOptions = {
        path:"/session/:sessionId/doubleclick",
        method:"POST"
    };

    this.requestHandler.create(requestOptions,{},callback);

};


text:
layout: article
title: "Créer vos propres contenu et structure"
description: "Le contenu est l'élément le plus important d'un site. Ce guide vous explique comment planifier rapidement la création de votre premier site multi-appareil."
introduction: " Le contenu est l'élément le plus important d'un site. Il est donc essentiel de faire en sorte que le contenu ne soit pas dicté par les impératifs de conception. Dans ce guide, nous allons identifier le contenu prioritaire, créer une structure de page en fonction de ce contenu, puis présenter la page dans une disposition linéaire simple adaptée à la fois aux fenêtres d'affichage larges et étroites."
notes:
  styling:
    - Style viendra plus tard
article:
  written_on: 2014-04-17
  updated_on: 2014-04-23
  order: 1
id: multi-screen-content
collection: multi-screen
authors:
  - paulkinlan
translators:
related-guides:
  create-amazing-forms:
    -
      title: Créer de superbes formulaires
      href: fundamentals/input/form/
      section:
        id: user-input
        title: "Formulaires"
        href: fundamentals/input/form/
    -
      title: Étiqueter et nommer correctement des entrées
      href: fundamentals/input/form/label-and-name-inputs
      section:
        id: user-input
        title: "Formulaires"
        href: fundamentals/input/form/
    -
      title: Choisir le meilleur type d'entrée
      href: fundamentals/input/form/choose-the-best-input-type
      section:
        id: user-input
        title: "Formulaires"
        href: fundamentals/input/form/
  video:
    -
      title: Utiliser efficacement la vidéo
      href: fundamentals/media/video/
      section:
        id: introduction-to-media
        title: "Vidéo"
        href: fundamentals/media/
    -
      title: Modifier la position de départ
      href: fundamentals/media/video/add-a-video#specify-a-start-and-end-time
      section:
        id: introduction-to-media
        title: "Vidéo"
        href: fundamentals/media/
    -
      title: Inclure une image poster
      href: fundamentals/media/video/add-a-video#include-a-poster-image
      section:
        id: introduction-to-media
        title: "Vidéo"
        href: fundamentals/media/
  images:
    -
      title: Utiliser efficacement des images
      href: fundamentals/media/images/
      section:
        id: introduction-to-media
        title: "Images"
        href: fundamentals/media/
    -
      title:  Utilisation correcte des images dans le balisage
      href: fundamentals/media/images/images-in-markup
      section:
        id: introduction-to-media
        title: "Images"
        href: fundamentals/media/
    -
      title: Optimisation d'images
      href: fundamentals/performance/optimizing-content-efficiency/image-optimization
      section:
        id: introduction-to-media
        title: "Images"
        href: fundamentals/media/

key-takeaways:
  content-critical:
    - Identifiez le contenu dont vous avez besoin en premier.
    - Esquissez l'architecture d'information (AI) nécessaire pour les fenêtres d'affichage larges et étroites.
    - Créez une vue schématique de la page avec le contenu, mais sans les styles.
---

{% wrap content %}

{% include modules/toc.liquid %}

## Créer la structure de page

Nous avons identifié nos besoins :

1. Une zone qui décrit notre produit à un haut niveau 'CS256 : Cours de développement de contenu Web pour mobile'
2. Un formulaire pour rassembler des informations auprès des utilisateurs intéressés par notre produit
3. Une description détaillée et une vidéo
4. Des images du produit en action
5. Un tableau de données contenant des informations pour soutenir les réclamations

{% include modules/takeaway.liquid list=page.key-takeaways.content-critical %}

Nous vous proposons également une disposition et une architecture d'information rudimentaires pour les fenêtres d'affichage larges et étroites.

Une conversion peut être effectuée facilement dans les sections rudimentaires d'une page schématique que nous utiliserons pour le reste de ce projet.

{% include_code _code/addstructure.html structure %}

## Ajouter du contenu à la page

La structure de base de ce site est terminée. Nous connaissons les sections dont nous avons besoin, le contenu à y afficher, ainsi que la position du contenu dans l'architecture d'information globale. Nous pouvons donc passer maintenant à la création du site.

{% include modules/remember.liquid title="Note" inline="true" list=page.notes.styling %}

### Créer le titre et le formulaire

Le titre et le formulaire de notification de demande sont les composants essentiels de notre page. Ils doivent être présentés immédiatement à l'utilisateur.

Dans le titre, ajoutez simplement du texte pour décrire le cours :

{% include_code _code/addheadline.html headline %}

Vous devez également compléter le formulaire.
Il s'agit d'un formulaire simple où sont renseignés les noms et numéros de téléphone des utilisateurs, ainsi que le meilleur moment pour les rappeler.

Des étiquettes et des espaces réservés doivent être associés à tous les formulaires pour permettre aux utilisateurs d'activer facilement des éléments et de comprendre ce qu'ils sont censés contenir, et aussi d'aider les outils d'accessibilité à comprendre la structure du formulaire. Outre l'envoi de la valeur de formulaire au serveur, l'attribut de nom est utilisé pour fournir au navigateur de précieuses indications sur la manière de compléter automatiquement ce formulaire.

Des types sémantiques seront ajoutés pour permettre aux utilisateurs de saisir, en un tournemain, du contenu sur un appareil mobile. Par exemple, lors de la saisie d'un numéro de téléphone, l'utilisateur doit simplement voir un clavier de numérotation.

{% include_code _code/addform.html form %}

{% include modules/related_guides.liquid inline=true list=page.related-guides.create-amazing-forms %}

### Créer la section 'Vidéo et informations'

La section de contenu 'Vidéo et informations' sera un peu plus détaillée.
Elle contiendra une liste à puces des caractéristiques de nos produits, ainsi qu'un espace vidéo réservé présentant le produit en action.

{% include_code _code/addcontent.html section1 %}

La vidéo est souvent utilisée pour décrire le contenu de manière plus interactive et pour faire la démonstration d'un produit ou concept.

L'application des bonnes pratiques vous permet d'intégrer aisément du contenu vidéo dans votre site :

* Ajoutez un attribut `controls` pour permettre une lecture facile de la vidéo.
* Ajoutez une image `poster` pour proposer aux utilisateurs un aperçu du contenu.
* Ajoutez plusieurs éléments `<source>` en fonction des formats vidéo acceptés.
* Ajoutez du texte de remplacement pour permettre aux utilisateurs de télécharger la vidéo s'il s'avère impossible de la lire dans la fenêtre.

{% include_code _code/addvideo.html video html %}

{% include modules/related_guides.liquid inline=true list=page.related-guides.video %}

### Créer la section 'Images'

Un site sans images peut être pour le moins ennuyeux. Il existe deux types d'images :

* Images de contenu : il s'agit d'images intégrées au document, utilisées pour véhiculer des informations supplémentaires sur le contenu.
* Images stylistiques : images utilisées pour embellir le site. Il s'agit généralement d'images d'arrière-plan, de motifs et de dégradés. Ces images seront traitées dans l'[article suivant]({{site.baseurl}}{{page.article.next.url}}).

La section 'Images' de notre page est un ensemble d'images de contenu.

Les images de contenu sont essentielles pour transmettre le sens de la page. On peut les comparer aux images utilisées dans des articles de journaux. Les images que nous utilisons sont les photos des formateurs du projet, à savoir : Chris Wilson, Peter Lubbers et Sean Bennet.

{% include_code _code/addimages.html images html %}

Les images sont définies sur une échelle de 100 % de la largeur de l'écran. Cela fonctionne très bien sur les appareils présentant une fenêtre d'affichage étroite, mais moins bien sur une fenêtre d'affichage large (un ordinateur de bureau, par exemple). Nous traiterons ce point dans la section relative à la conception de sites Web adaptatifs.

{% include modules/related_guides.liquid inline=true list=page.related-guides.images %}

De nombreux utilisateurs n'ont pas la possibilité d'afficher des images et ont souvent recours à une technologie assistive, telle qu'un lecteur d'écran qui analyse les données de la page et les leur transmet verbalement. Vous devez vous assurer que toutes vos images de contenu comportent une balise `alt` que le lecteur d'écran peut lire à l'utilisateur.

Lorsque vous ajoutez des balises `alt`, faites en sorte que le texte situé entre les balises soit aussi concis que possible pour décrire l'image en détail. Dans notre exemple de démonstration, l'attribut est simplement formaté en tant que `Name: Role`. Suffisamment d'informations sont présentées pour permettre à l'utilisateur de comprendre que cette section concerne les auteurs et leur fonction.

### Ajouter la section 'Données tabulées'

La dernière section est un simple tableau utilisé pour afficher des statistiques spécifiques sur le produit.

Les tableaux ne doivent être utilisés que pour les données tabulaires, telles que des matrices d'information.

{% include_code _code/addcontent.html section3 %}

### Ajouter un pied de page

Sur la plupart des sites, un pied de page est nécessaire pour afficher du contenu tel que des conditions d'utilisation, des clauses de non-responsabilité, ou d'autres informations qui ne sont pas censées se trouver dans la zone de navigation principale ou la zone de contenu principale de la page.

Notre site comportera simplement des liens vers les conditions d'utilisation, une page 'Contact' et nos profils de médias sociaux.

{% include_code _code/addcontent.html footer %}

## Résumé

Nous avons créé la structure du site et identifié tous les principaux éléments structuraux. Nous nous sommes également assurés que tout le contenu pertinent était prêt et disponible pour satisfaire nos besoins.

Comme vous pouvez le constater, la page n'a pas fière allure. Ne vous inquiétez pas, c'est voulu !
Le contenu est l'élément le plus important d'un site, et nous devions nous assurer que nous disposions d'une densité et d'une architecture d'information robuste. Ce guide nous a donné un excellent point de départ. Dans le guide suivant, nous nous chargerons du style de contre contenu.

{% include modules/nextarticle.liquid %}

{% endwrap %}


text:
/*globals it,describe,before,after*/
var path = require('path'),
    utils = require('./res/utils'),
    assert = require('assert'),
    nop = require('nop'),
    fse = require('fs-extra'),
    Logger = require('../src/Logger'),
    LayoutManager = require(__dirname+'/../src/LayoutManager'),
    rm_rf = require('rimraf'),
    _ = require('lodash');

var logger = new Logger(),
    manager = new LayoutManager(logger),
    emitter = logger._emitter;

// Useful constants
var TMP_DIR = path.join(__dirname, '..', 'test-tmp'),
    WebGMEConfig = path.join('config', 'config.webgme.js'),
    PROJECT_DIR = path.join(TMP_DIR, 'ExampleLayoutProject'),
    CONFIG_NAME = 'webgme-setup.json',
    CONFIG_PATH = path.join(PROJECT_DIR, CONFIG_NAME),
    OTHER_PROJECT = path.join(__dirname, 'res', 'OtherProject'),
    OTHER_LAYOUT = 'OtherLayout',
    otherProject;

describe('Layout tests', function() {
    'use strict';

    var LAYOUT_NAME = 'MyNewLayout',
        LayoutBasePath = path.join(PROJECT_DIR, 'src', 'layouts'),
        LAYOUT_SRC = path.join(LayoutBasePath, LAYOUT_NAME, LAYOUT_NAME+'.js'),
        LAYOUT_TEST = path.join(PROJECT_DIR, 'test', 'layouts', LAYOUT_NAME, LAYOUT_NAME+'.spec.js');

    before(function(done) {
        utils.getCleanProject(PROJECT_DIR, done);
    });

    describe('new layout', function() {
        before(function(done) {
            process.chdir(PROJECT_DIR);  // Start in different directory
            manager.new({layoutID: LAYOUT_NAME}, done);
        });

        it('should create the layout source file', function() {
            assert(fse.existsSync(LAYOUT_SRC));
        });

        it('should create the layout config file', function() {
            var configPath = path.join(LayoutBasePath, LAYOUT_NAME, LAYOUT_NAME+'Config.json');
            assert(fse.existsSync(configPath));
        });

        it('should create the layout html file', function() {
            var htmlPath = path.join(LayoutBasePath, LAYOUT_NAME,
                'templates', LAYOUT_NAME+'.html');
            assert(fse.existsSync(htmlPath));
        });
        it('should be valid js', function() {
            var content = fse.readFileSync(LAYOUT_SRC, 'utf8');
            assert(utils.isValidJs(content));
        });

        it('should not have desc (if none provided)', function() {
            var content = fse.readFileSync(LAYOUT_SRC, 'utf8');
            assert.equal(content.indexOf('getDescription'), -1);
        });

        it('should add the layout (relative) path to the config file', function() {
            const config = require(path.join(PROJECT_DIR, WebGMEConfig));
            const layoutPaths = config.visualization.layout.basePaths.map(dir => path.resolve(dir));
            const layoutDir = path.resolve(LayoutBasePath);

            assert(layoutPaths.includes(layoutDir));
        });

        it('should record the layout in webgme-setup.json', function() {
            var config = require(CONFIG_PATH);
            assert.notEqual(config.components.layouts[LAYOUT_NAME], undefined);
        });

        describe('2nd layout', function() {
            var secondLayoutName = 'ABrandNewLayout';
            before(function(done) {
                process.chdir(PROJECT_DIR);  // Start in different directory
                manager.new({layoutID: secondLayoutName}, done);
            });

            it('should have both dirs in src/layouts', function() {
                [LAYOUT_NAME, secondLayoutName]
                    .map(function(name) {
                        return path.join(PROJECT_DIR, 'src', 'layouts', name);
                    })
                    .forEach(function(layoutPath) {
                        assert(fse.existsSync(layoutPath), layoutPath + ' doesn\'t exist!');
                    });
            });
        });

        describe('list layouts', function() {
            it('should list the new layout', function(done) {
                emitter.once('write', function(msg) {
                    assert.notEqual(-1, msg.indexOf(LAYOUT_NAME));
                    done();
                });

                manager.ls({}, nop);
            });

            it('should not list layouts in wrong directory ', function(done) {
                process.chdir(__dirname);
                manager.ls({}, function(err) {
                    assert(err);
                    process.chdir(PROJECT_DIR);
                    done();
                });
            });
        });
    });

    describe('rm layout', function() {
        var LAYOUT_NAME = 'MyLayout',
            RM_PROJECT = path.join(PROJECT_DIR, 'RM_LAYOUT');
        before(function(done) {
            utils.getCleanProject(RM_PROJECT, () => {
                process.chdir(RM_PROJECT);
                manager.rm({name: LAYOUT_NAME}, done);
            });
        });

        it('should remove layout src directory', function() {
            var layoutPath = path.join(RM_PROJECT, 'src', 'layouts', LAYOUT_NAME);
            assert.equal(fse.existsSync(layoutPath), false);
        });

        it('should remove layout test directory', function() {
            var layoutPath = path.join(RM_PROJECT, 'test', 'layouts', LAYOUT_NAME);
            assert.equal(fse.existsSync(layoutPath), false);
        });

        it('should remove layout entry from '+CONFIG_NAME, function() {
            var config = require(path.join(RM_PROJECT, 'webgme-setup.json'));
            assert.equal(config.components.layouts[LAYOUT_NAME], undefined);
        });
    });

    describe('import layout', function() {

        describe('errors', function() {
            it('should not miss layout or project', function(done) {
                emitter.once('error', done.bind(this, null));
                manager.import({name: OTHER_LAYOUT}, nop);
            });
        });

        describe('projects NOT created with webgme-setup-tool', function() {
            var previousDir, oldConfigPath;
            before(function(done) {
                this.timeout(10000);
                oldConfigPath = CONFIG_PATH;
                previousDir = PROJECT_DIR;

                otherProject = path.join(__dirname, 'res', 'NonCliProj');
                PROJECT_DIR = path.join(PROJECT_DIR, 'NewProject');
                CONFIG_PATH = path.join(PROJECT_DIR, CONFIG_NAME),
                utils.getCleanProject(PROJECT_DIR, function() {
                    process.chdir(PROJECT_DIR);
                    manager.import({name: 'DefaultLayout',
                                 project: otherProject}, done);
                });
            });

            after(function() {
                PROJECT_DIR = previousDir;
                CONFIG_PATH = oldConfigPath;
            });

            it('should add the project to the package.json', function() {
                var pkg = require(path.join(PROJECT_DIR, 'package.json')),
                depName = otherProject.split(path.sep).pop().toLowerCase();
                assert.notEqual(pkg.dependencies[depName], undefined);
            });

            it('should add the project to the '+CONFIG_NAME, function() {
                var configText = fse.readFileSync(CONFIG_PATH),
                    config = JSON.parse(configText);
                assert.notEqual(config.dependencies.layouts.DefaultLayout, undefined);
            });

            it('should add the path to the webgme config', function() {
                var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                paths = config.visualization.layout.basePaths.join(';');
                assert.notEqual(paths.indexOf(otherProject.split(path.sep)[1]), -1);
            });

            it('should add the relative path to the requirejsPaths webgme config', function() {
                var config = require(path.join(PROJECT_DIR, WebGMEConfig));

                assert.notEqual(config.requirejsPaths.DefaultLayout, undefined);
                assert.notEqual(config.requirejsPaths.DefaultLayout[0], '/');
            });

            describe('rm dependency layout', function() {
                before(function(done) {
                    process.chdir(PROJECT_DIR);
                    manager.rm({name: 'DefaultLayout'}, done);
                });

                it('should remove the path from the webgme config', function() {
                    var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                    paths = config.visualization.layout.basePaths.join(';');
                    assert.equal(paths.indexOf('DefaultLayout'), -1);
                });

                it('should remove layout entry from '+CONFIG_NAME, function() {
                    var configText = fse.readFileSync(CONFIG_PATH),
                        config = JSON.parse(configText);
                    assert.equal(config.dependencies.layouts.DefaultLayout, undefined);
                });

                it.skip('should remove project from package.json', function() {
                    // TODO
                });

                it.skip('should not remove project from package.json if used', function() {
                    // TODO
                });
            });
        });

        describe('projects created with webgme-setup-tool', function() {
            before(function(done) {
                this.timeout(5000);
                otherProject = path.join(__dirname, 'res', 'OtherProject');
                process.chdir(PROJECT_DIR);
                manager.import({name: OTHER_LAYOUT,
                             project: otherProject}, function() {
                    utils.requireReload(
                        path.join(PROJECT_DIR, 'package.json')
                    );
                    done();
                });
            });

            it('should add the project to the package.json', function() {
                var pkg = require(path.join(PROJECT_DIR, 'package.json')),
                depName = otherProject.split(path.sep).pop().toLowerCase();
                assert.notEqual(pkg.dependencies[depName], undefined);
            });

            it('should add the project to the '+CONFIG_NAME, function() {
                var configText = fse.readFileSync(CONFIG_PATH),
                    config = JSON.parse(configText);
                assert.notEqual(config.dependencies.layouts[OTHER_LAYOUT], undefined);
            });

            it('should add the path to the webgme config', function() {
                var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                paths = config.visualization.layout.basePaths.join(';');
                assert.notEqual(paths.indexOf(otherProject.split(path.sep)[1]), -1);
            });

            describe('rm dependency layout', function() {
                before(function(done) {
                    process.chdir(PROJECT_DIR);
                    manager.rm({name: OTHER_LAYOUT}, done);
                });

                it('should remove the path from the webgme config', function() {
                    var config = require(path.join(PROJECT_DIR, WebGMEConfig)),
                    paths = config.visualization.layout.basePaths.join(';');
                    assert.equal(paths.indexOf(OTHER_LAYOUT), -1);
                });

                it('should remove layout entry from '+CONFIG_NAME, function() {
                    var configText = fse.readFileSync(CONFIG_PATH),
                        config = JSON.parse(configText);
                    assert.equal(config.dependencies.layouts[OTHER_LAYOUT], undefined);
                });

                it.skip('should remove project from package.json', function() {
                    // TODO
                });

                it.skip('should not remove project from package.json if used', function() {
                    // TODO
                });
            });
        });
    });

    describe('enable layout', function() {
        var ENABLE_PROJECT = path.join(PROJECT_DIR, 'EnableProject');
        before(function(done) {
            utils.getCleanProject(ENABLE_PROJECT, function() {
                process.chdir(ENABLE_PROJECT);
                manager.enable({name: 'MyLayout'}, done);
            });
        });

        it('should fail if layout does not exist', function(done) {
            manager.enable({name: 'IDontExist'}, (err) => {
                assert(err);
                done();
            });
        });

        it('should set the default in the webgme-setup.json', function() {
            var config = require(path.join(ENABLE_PROJECT, 'webgme-setup.json'));
            assert(config.components.layouts.MyLayout.enabled);
        });

        it('should disable old layout', function() {
            var config = require(path.join(ENABLE_PROJECT, 'webgme-setup.json'));
            assert(!config.components.layouts.EnabledLayout.enabled);
        });

        it('should set the default in the config.webgme.js', function() {
            var config = require(path.join(ENABLE_PROJECT, 'config'));
            assert.equal(config.visualization.layout.default, 'MyLayout');
        });

        describe('enable default layout', function() {
            var ENABLE_DEF_LAYOUT = path.join(ENABLE_PROJECT, 'DEFAULT');
            before(function(done) {
                utils.getCleanProject(ENABLE_DEF_LAYOUT, function() {
                    process.chdir(ENABLE_DEF_LAYOUT);
                    manager.enable({name: 'DefaultLayout'}, done);
                });
            });

            it('should enable DefaultLayout', function() {
                var configPath = path.join(ENABLE_DEF_LAYOUT, 'config', 'config.webgme.js'),
                    configContent = fse.readFileSync(configPath, 'utf8');

                assert.equal(configContent.indexOf('EnabledLayout'), -1);
            });
        });

    });

    describe('disable layout', function() {
        var DISABLE_PROJECT = path.join(PROJECT_DIR, 'DisableProject2');
        before(function(done) {
            utils.getCleanProject(DISABLE_PROJECT, function() {
                process.chdir(DISABLE_PROJECT);
                manager.disable({name: 'EnabledLayout'}, (err) => {
                    assert(!err, 'Disabling layout failed: ' + err);
                    done();
                });
            });
        });

        it('should set the default back to DefaultLayout', function() {
            var configPath = path.join(DISABLE_PROJECT, 'config', 'config.webgme.js'),
                configTxt = fse.readFileSync(configPath, 'utf8');

            assert.equal(configTxt.indexOf('EnabledLayout'), -1);
        });

        it('should check that layout exists', function(done) {
            manager.disable({name: 'IDontExist'}, (err) => {
                assert(err);
                done();
            });
        });

        it('should not allow the user to disable DefaultLayout', function(done) {
            manager.disable({name: 'DefaultLayout'}, (err) => {
                assert(err);
                done();
            });
        });
    });

    after(function(done) {
        if (fse.existsSync(PROJECT_DIR)) {
            rm_rf(PROJECT_DIR, done);
        } else {
            done();
        }
    });
});


text:
package org.apache.hadoop.hbase.master.procedure;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotDisabledException;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
import org.apache.hadoop.hbase.procedure2.ProcedureResult;
import org.apache.hadoop.hbase.procedure2.ProcedureTestingUtility;
import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.DeleteTableState;
import org.apache.hadoop.hbase.testclassification.MasterTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

@Category({MasterTests.class, MediumTests.class})
public class TestDeleteTableProcedure {
  private static final Log LOG = LogFactory.getLog(TestDeleteTableProcedure.class);

  protected static final HBaseTestingUtility UTIL = new HBaseTestingUtility();

  private static void setupConf(Configuration conf) {
    conf.setInt(MasterProcedureConstants.MASTER_PROCEDURE_THREADS, 1);
  }

  @BeforeClass
  public static void setupCluster() throws Exception {
    setupConf(UTIL.getConfiguration());
    UTIL.startMiniCluster(1);
  }

  @AfterClass
  public static void cleanupTest() throws Exception {
    try {
      UTIL.shutdownMiniCluster();
    } catch (Exception e) {
      LOG.warn("failure shutting down cluster", e);
    }
  }

  @Before
  public void setup() throws Exception {
    final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExec, false);
    assertTrue("expected executor to be running", procExec.isRunning());
  }

  @After
  public void tearDown() throws Exception {
    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(getMasterProcedureExecutor(), false);
    for (HTableDescriptor htd: UTIL.getHBaseAdmin().listTables()) {
      LOG.info("Tear down, remove table=" + htd.getTableName());
      UTIL.deleteTable(htd.getTableName());
    }
  }

  @Test(timeout=60000, expected=TableNotFoundException.class)
  public void testDeleteNotExistentTable() throws Exception {
    final TableName tableName = TableName.valueOf("testDeleteNotExistentTable");

    final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
    ProcedurePrepareLatch latch = new ProcedurePrepareLatch.CompatibilityLatch();
    long procId = ProcedureTestingUtility.submitAndWait(procExec,
        new DeleteTableProcedure(procExec.getEnvironment(), tableName, latch));
    latch.await();
  }

  @Test(timeout=60000, expected=TableNotDisabledException.class)
  public void testDeleteNotDisabledTable() throws Exception {
    final TableName tableName = TableName.valueOf("testDeleteNotDisabledTable");

    final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
    MasterProcedureTestingUtility.createTable(procExec, tableName, null, "f");

    ProcedurePrepareLatch latch = new ProcedurePrepareLatch.CompatibilityLatch();
    long procId = ProcedureTestingUtility.submitAndWait(procExec,
        new DeleteTableProcedure(procExec.getEnvironment(), tableName, latch));
    latch.await();
  }

  @Test(timeout=60000)
  public void testDeleteDeletedTable() throws Exception {
    final TableName tableName = TableName.valueOf("testDeleteDeletedTable");
    final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();

    HRegionInfo[] regions = MasterProcedureTestingUtility.createTable(
      procExec, tableName, null, "f");
    UTIL.getHBaseAdmin().disableTable(tableName);

    // delete the table (that exists)
    long procId1 = procExec.submitProcedure(
        new DeleteTableProcedure(procExec.getEnvironment(), tableName));
    // delete the table (that will no longer exist)
    long procId2 = procExec.submitProcedure(
        new DeleteTableProcedure(procExec.getEnvironment(), tableName));

    // Wait the completion
    ProcedureTestingUtility.waitProcedure(procExec, procId1);
    ProcedureTestingUtility.waitProcedure(procExec, procId2);

    // First delete should succeed
    ProcedureTestingUtility.assertProcNotFailed(procExec, procId1);
    MasterProcedureTestingUtility.validateTableDeletion(
      UTIL.getHBaseCluster().getMaster(), tableName, regions, "f");

    // Second delete should fail with TableNotFound
    ProcedureResult result = procExec.getResult(procId2);
    assertTrue(result.isFailed());
    LOG.debug("Delete failed with exception: " + result.getException());
    assertTrue(result.getException().getCause() instanceof TableNotFoundException);
  }

  @Test(timeout=60000)
  public void testSimpleDelete() throws Exception {
    final TableName tableName = TableName.valueOf("testSimpleDelete");
    final byte[][] splitKeys = null;
    testSimpleDelete(tableName, splitKeys);
  }

  @Test(timeout=60000)
  public void testSimpleDeleteWithSplits() throws Exception {
    final TableName tableName = TableName.valueOf("testSimpleDeleteWithSplits");
    final byte[][] splitKeys = new byte[][] {
      Bytes.toBytes("a"), Bytes.toBytes("b"), Bytes.toBytes("c")
    };
    testSimpleDelete(tableName, splitKeys);
  }

  private void testSimpleDelete(final TableName tableName, byte[][] splitKeys) throws Exception {
    HRegionInfo[] regions = MasterProcedureTestingUtility.createTable(
      getMasterProcedureExecutor(), tableName, splitKeys, "f1", "f2");
    UTIL.getHBaseAdmin().disableTable(tableName);

    // delete the table
    final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
    long procId = ProcedureTestingUtility.submitAndWait(procExec,
      new DeleteTableProcedure(procExec.getEnvironment(), tableName));
    ProcedureTestingUtility.assertProcNotFailed(procExec, procId);
    MasterProcedureTestingUtility.validateTableDeletion(
      UTIL.getHBaseCluster().getMaster(), tableName, regions, "f1", "f2");
  }

  @Test(timeout=60000)
  public void testRecoveryAndDoubleExecution() throws Exception {
    final TableName tableName = TableName.valueOf("testRecoveryAndDoubleExecution");

    // create the table
    byte[][] splitKeys = null;
    HRegionInfo[] regions = MasterProcedureTestingUtility.createTable(
      getMasterProcedureExecutor(), tableName, splitKeys, "f1", "f2");
    UTIL.getHBaseAdmin().disableTable(tableName);

    final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
    ProcedureTestingUtility.waitNoProcedureRunning(procExec);
    ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExec, true);

    // Start the Delete procedure && kill the executor
    long procId = procExec.submitProcedure(
      new DeleteTableProcedure(procExec.getEnvironment(), tableName));

    // Restart the executor and execute the step twice
    // NOTE: the 6 (number of DeleteTableState steps) is hardcoded,
    //       so you have to look at this test at least once when you add a new step.
    MasterProcedureTestingUtility.testRecoveryAndDoubleExecution(
      procExec, procId, 6, DeleteTableState.values());

    MasterProcedureTestingUtility.validateTableDeletion(
      UTIL.getHBaseCluster().getMaster(), tableName, regions, "f1", "f2");
  }

  private ProcedureExecutor<MasterProcedureEnv> getMasterProcedureExecutor() {
    return UTIL.getHBaseCluster().getMaster().getMasterProcedureExecutor();
  }
}


text:
STATUS_API_DELEGATE=src/generated/java/org/lockss/laaws/mdq/api/StatusApiDelegate.java
sed -i.backup "s/import org.lockss.laaws.mdq.model.ApiStatus/import org.lockss.util.rest.status.ApiStatus/" $STATUS_API_DELEGATE && rm $STATUS_API_DELEGATE.backup

# Edit StatusApi.java.
STATUS_API=src/generated/java/org/lockss/laaws/mdq/api/StatusApi.java
sed -i.backup "s/import org.lockss.laaws.mdq.model.ApiStatus/import org.lockss.util.rest.status.ApiStatus/" $STATUS_API && rm $STATUS_API.backup

# Edit the ApiDelegate.
API_DELEGATE=src/generated/java/org/lockss/laaws/mdq/api/MetadataApiDelegate.java
sed -i.backup "s/import org.lockss.laaws.mdq.model.ItemMetadata;/import org.lockss.metadata.ItemMetadata;/" $API_DELEGATE && rm $API_DELEGATE.backup

# Edit the Api.
API=src/generated/java/org/lockss/laaws/mdq/api/MetadataApi.java
sed -i.backup "s/import org.lockss.laaws.mdq.model.ItemMetadata;/import org.lockss.metadata.ItemMetadata;/" $API && rm $API.backup

# Edit AuMetadataPageInfo.java.
CLASS=src/generated/java/org/lockss/laaws/mdq/model/AuMetadataPageInfo.java
sed -i.backup "s/import org.lockss.laaws.mdq.model.ItemMetadata;/import org.lockss.metadata.ItemMetadata;/" $CLASS && rm $CLASS.backup


text:
import simuvex
from simuvex.s_type import SimTypeString

class strcpy(simuvex.SimProcedure):
    #pylint:disable=arguments-differ

    def run(self, dst, src):
        self.argument_types = {0: self.ty_ptr(SimTypeString()),
                               1: self.ty_ptr(SimTypeString())}
        self.return_type = self.ty_ptr(SimTypeString())

        strlen = simuvex.SimProcedures['libc.so.6']['strlen']
        strncpy = simuvex.SimProcedures['libc.so.6']['strncpy']
        src_len = self.inline_call(strlen, src)

        ret_expr = self.inline_call(strncpy, dst, src, src_len.ret_expr+1, src_len=src_len).ret_expr
        return ret_expr


text:
package com.test.captchahandler;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;

import com.stackdeveloper.lib.CustomWebChromeClient;
import com.stackdeveloper.lib.CustomWebViewClient;
import com.stackdeveloper.lib.HandlerPageLoad;
import com.stackdeveloper.lib.HandlerWebViewHtmlContent;
import com.stackdeveloper.lib.JsObject;

public class HtmlSourceGetActivity extends Activity
{
	private final static String URL="http://ismailkocacan.blogspot.com.tr";

	private JsObject mJsObject;
	private WebView mWebView1;
	private MyWebViewPageLoadHandler mMyWebViewPageLoadHandler;
	private MyHandlerWebViewHtmlContent mMyHandlerWebViewHtmlContent;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_html_source_get);
		initialize();
	}

	public class MyWebViewPageLoadHandler implements HandlerPageLoad
	{
		@Override
		public void onPageLoad(WebView webView, String url)
		{
			mJsObject.jsGetHtmlContent(mMyHandlerWebViewHtmlContent);
		}
	}

	public class MyHandlerWebViewHtmlContent implements HandlerWebViewHtmlContent
	{
		@Override
		public void onGetHtmlContent(String htmlContent)
		{
		   Toast.makeText(getApplicationContext(), htmlContent, Toast.LENGTH_LONG).show();
		}
	}

	private void initialize()
	{
		mWebView1 = (WebView)findViewById(R.id.webView1);
		mJsObject = new JsObject(this, mWebView1);

		mMyWebViewPageLoadHandler = new MyWebViewPageLoadHandler();
		mMyHandlerWebViewHtmlContent = new MyHandlerWebViewHtmlContent();

		CustomWebViewClient webViewClient = new CustomWebViewClient();
		webViewClient.addHandlerPageLoad(mMyWebViewPageLoadHandler);
		mJsObject.getWebView().setWebViewClient(webViewClient);

		CustomWebChromeClient chromeClient = new CustomWebChromeClient();
		mJsObject.getWebView().setWebChromeClient(chromeClient);
	}

	public void btnGetHtmlCode(View sender)
	{
		mWebView1.loadUrl(URL);
	}
}


text:
<?php

$moduleName = 'fieldnames';
define('MODULE_PATH',dirname(__FILE__));
include APP_BASE_PATH.'header.php';
include APP_BASE_PATH.'modulejslibs.inc.php';
?>

<?=LanguageManager::tran('Custom Fields')?>

<?php include APP_BASE_PATH.'footer.php';?>


text:
<?php
/**
 * Methods to play with strings.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

/**
 * A collection of static methods to play with strings.
 */
class StringUtils {
	/**
	 * Test whether a string is valid UTF-8.
	 *
	 * The function check for invalid byte sequences, overlong encoding but
	 * not for different normalisations.
	 *
	 * @note In MediaWiki 1.21, this function did not provide proper UTF-8 validation.
	 * In particular, the pure PHP code path did not in fact check for overlong forms.
	 * Beware of this when backporting code to that version of MediaWiki.
	 *
	 * @since 1.21
	 * @param string $value String to check
	 * @return bool Whether the given $value is a valid UTF-8 encoded string
	 */
	static function isUtf8( $value ) {
		$value = (string)$value;

		// HHVM 3.4 and older come with an outdated version of libmbfl that
		// incorrectly allows values above U+10FFFF, so we have to check
		// for them separately. (This issue also exists in PHP 5.3 and
		// older, which are no longer supported.)
		static $newPHP;
		if ( $newPHP === null ) {
			$newPHP = !mb_check_encoding( "\xf4\x90\x80\x80", 'UTF-8' );
		}

		return mb_check_encoding( $value, 'UTF-8' ) &&
			( $newPHP || preg_match( "/\xf4[\x90-\xbf]|[\xf5-\xff]/S", $value ) === 0 );
	}

	/**
	 * Perform an operation equivalent to `preg_replace()`
	 *
	 * Matches this code:
	 *
	 *     preg_replace( "!$startDelim(.*?)$endDelim!", $replace, $subject );
	 *
	 * ..except that it's worst-case O(N) instead of O(N^2). Compared to delimiterReplace(), this
	 * implementation is fast but memory-hungry and inflexible. The memory requirements are such
	 * that I don't recommend using it on anything but guaranteed small chunks of text.
	 *
	 * @param string $startDelim
	 * @param string $endDelim
	 * @param string $replace
	 * @param string $subject
	 * @return string
	 */
	static function hungryDelimiterReplace( $startDelim, $endDelim, $replace, $subject ) {
		$segments = explode( $startDelim, $subject );
		$output = array_shift( $segments );
		foreach ( $segments as $s ) {
			$endDelimPos = strpos( $s, $endDelim );
			if ( $endDelimPos === false ) {
				$output .= $startDelim . $s;
			} else {
				$output .= $replace . substr( $s, $endDelimPos + strlen( $endDelim ) );
			}
		}

		return $output;
	}

	/**
	 * Perform an operation equivalent to `preg_replace_callback()`
	 *
	 * Matches this code:
	 *
	 *     preg_replace_callback( "!$startDelim(.*)$endDelim!s$flags", $callback, $subject );
	 *
	 * If the start delimiter ends with an initial substring of the end delimiter,
	 * e.g. in the case of C-style comments, the behavior differs from the model
	 * regex. In this implementation, the end must share no characters with the
	 * start, so e.g. `/*\/` is not considered to be both the start and end of a
	 * comment. `/*\/xy/*\/` is considered to be a single comment with contents `/xy/`.
	 *
	 * The implementation of delimiterReplaceCallback() is slower than hungryDelimiterReplace()
	 * but uses far less memory. The delimiters are literal strings, not regular expressions.
	 *
	 * @param string $startDelim Start delimiter
	 * @param string $endDelim End delimiter
	 * @param callable $callback Function to call on each match
	 * @param string $subject
	 * @param string $flags Regular expression flags
	 * @throws InvalidArgumentException
	 * @return string
	 */
	static function delimiterReplaceCallback( $startDelim, $endDelim, $callback,
		$subject, $flags = ''
	) {
		$inputPos = 0;
		$outputPos = 0;
		$output = '';
		$foundStart = false;
		$encStart = preg_quote( $startDelim, '!' );
		$encEnd = preg_quote( $endDelim, '!' );
		$strcmp = strpos( $flags, 'i' ) === false ? 'strcmp' : 'strcasecmp';
		$endLength = strlen( $endDelim );
		$m = [];

		while ( $inputPos < strlen( $subject ) &&
			preg_match( "!($encStart)|($encEnd)!S$flags", $subject, $m, PREG_OFFSET_CAPTURE, $inputPos )
		) {
			$tokenOffset = $m[0][1];
			if ( $m[1][0] != '' ) {
				if ( $foundStart &&
					$strcmp( $endDelim, substr( $subject, $tokenOffset, $endLength ) ) == 0
				) {
					# An end match is present at the same location
					$tokenType = 'end';
					$tokenLength = $endLength;
				} else {
					$tokenType = 'start';
					$tokenLength = strlen( $m[0][0] );
				}
			} elseif ( $m[2][0] != '' ) {
				$tokenType = 'end';
				$tokenLength = strlen( $m[0][0] );
			} else {
				throw new InvalidArgumentException( 'Invalid delimiter given to ' . __METHOD__ );
			}

			if ( $tokenType == 'start' ) {
				# Only move the start position if we haven't already found a start
				# This means that START START END matches outer pair
				if ( !$foundStart ) {
					# Found start
					$inputPos = $tokenOffset + $tokenLength;
					# Write out the non-matching section
					$output .= substr( $subject, $outputPos, $tokenOffset - $outputPos );
					$outputPos = $tokenOffset;
					$contentPos = $inputPos;
					$foundStart = true;
				} else {
					# Move the input position past the *first character* of START,
					# to protect against missing END when it overlaps with START
					$inputPos = $tokenOffset + 1;
				}
			} elseif ( $tokenType == 'end' ) {
				if ( $foundStart ) {
					# Found match
					$output .= call_user_func( $callback, [
						substr( $subject, $outputPos, $tokenOffset + $tokenLength - $outputPos ),
						substr( $subject, $contentPos, $tokenOffset - $contentPos )
					] );
					$foundStart = false;
				} else {
					# Non-matching end, write it out
					$output .= substr( $subject, $inputPos, $tokenOffset + $tokenLength - $outputPos );
				}
				$inputPos = $outputPos = $tokenOffset + $tokenLength;
			} else {
				throw new InvalidArgumentException( 'Invalid delimiter given to ' . __METHOD__ );
			}
		}
		if ( $outputPos < strlen( $subject ) ) {
			$output .= substr( $subject, $outputPos );
		}

		return $output;
	}

	/**
	 * Perform an operation equivalent to `preg_replace()` with flags.
	 *
	 * Matches this code:
	 *
	 *     preg_replace( "!$startDelim(.*)$endDelim!$flags", $replace, $subject );
	 *
	 * @param string $startDelim Start delimiter regular expression
	 * @param string $endDelim End delimiter regular expression
	 * @param string $replace Replacement string. May contain $1, which will be
	 *  replaced by the text between the delimiters
	 * @param string $subject String to search
	 * @param string $flags Regular expression flags
	 * @return string The string with the matches replaced
	 */
	static function delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags = '' ) {
		$replacer = new RegexlikeReplacer( $replace );

		return self::delimiterReplaceCallback( $startDelim, $endDelim,
			$replacer->cb(), $subject, $flags );
	}

	/**
	 * More or less "markup-safe" explode()
	 * Ignores any instances of the separator inside `<...>`
	 * @param string $separator
	 * @param string $text
	 * @return array
	 */
	static function explodeMarkup( $separator, $text ) {
		$placeholder = "\x00";

		// Remove placeholder instances
		$text = str_replace( $placeholder, '', $text );

		// Replace instances of the separator inside HTML-like tags with the placeholder
		$replacer = new DoubleReplacer( $separator, $placeholder );
		$cleaned = StringUtils::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );

		// Explode, then put the replaced separators back in
		$items = explode( $separator, $cleaned );
		foreach ( $items as $i => $str ) {
			$items[$i] = str_replace( $placeholder, $separator, $str );
		}

		return $items;
	}

	/**
	 * More or less "markup-safe" str_replace()
	 * Ignores any instances of the separator inside `<...>`
	 * @param string $search
	 * @param string $replace
	 * @param string $text
	 * @return string
	 */
	static function replaceMarkup( $search, $replace, $text ) {
		$placeholder = "\x00";

		// Remove placeholder instances
		$text = str_replace( $placeholder, '', $text );

		// Replace instances of the separator inside HTML-like tags with the placeholder
		$replacer = new DoubleReplacer( $search, $placeholder );
		$cleaned = StringUtils::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );

		// Explode, then put the replaced separators back in
		$cleaned = str_replace( $search, $replace, $cleaned );
		$text = str_replace( $placeholder, $search, $cleaned );

		return $text;
	}

	/**
	 * Escape a string to make it suitable for inclusion in a preg_replace()
	 * replacement parameter.
	 *
	 * @param string $string
	 * @return string
	 */
	static function escapeRegexReplacement( $string ) {
		$string = str_replace( '\\', '\\\\', $string );
		$string = str_replace( '$', '\\$', $string );
		return $string;
	}

	/**
	 * Workalike for explode() with limited memory usage.
	 *
	 * @param string $separator
	 * @param string $subject
	 * @return ArrayIterator|ExplodeIterator
	 */
	static function explode( $separator, $subject ) {
		if ( substr_count( $subject, $separator ) > 1000 ) {
			return new ExplodeIterator( $separator, $subject );
		} else {
			return new ArrayIterator( explode( $separator, $subject ) );
		}
	}
}


text:
#ifndef CRIMILD_VULKAN_RENDERING_RENDER_PASSES_GENERATE_DIRECTIONAL_LIGHTS_SHADOW_MAPS_
#define CRIMILD_VULKAN_RENDERING_RENDER_PASSES_GENERATE_DIRECTIONAL_LIGHTS_SHADOW_MAPS_

#include "Rendering/RenderPasses/VulkanRenderPassBase.hpp"
#include "Rendering/VulkanFramebufferAttachment.hpp"
#include "Rendering/VulkanSceneRenderState.hpp"
#include "Simulation/Event.hpp"

namespace crimild {

    class UniformBuffer;
    class Simulation;
    class Light;
    class Primitive;
    class Geometry;
    class Node;
    class Camera;

    namespace vulkan {

        class Framebuffer;
        class Image;
        class RenderDevice;
        class RenderPass;
        class GraphicsPipeline;

        /**
         * \brief Generate shadows for directional lights
         *
         * \details This pass generates shadow maps only for directional lights. For each directional light,
         * we generate its shadow map using a shared framebuffer which is later copied into the lights
         * own shadow map image.
         *
         * This pass implements cascade shadow mapping, splitting the camera frustum into multiple frustums,
         * each getting its own full-resolution shadow map. This is implemented using a multi-layered,
         * depth-only image.
         *
         * \todo Support different shadow resultions (HIGH, MED, LOW). Not sure if custom resulutions should
         * be supported, though.
         *
         * \todo Use geometry shaders to do a single-pass render for the depth map cascades.
         */
        class GenerateDirectionalLightsShadowMaps : public RenderPassBase {
        public:
            GenerateDirectionalLightsShadowMaps( RenderDevice *renderDevice ) noexcept;
            virtual ~GenerateDirectionalLightsShadowMaps( void ) noexcept;

            Event handle( const Event & ) noexcept;

            void render(
                const SceneRenderState::Lights &lights,
                const SceneRenderState::ShadowCasters &shadowCasters,
                const Camera *camera
            ) noexcept;

        private:
            void init( void ) noexcept;
            void clear( void ) noexcept;

            void renderShadowMapImage(
                const Light *light,
                const SceneRenderState::ShadowCasters &shadowCasters,
                const Matrix4f &lightSpaceMatrix,
                SharedPointer< vulkan::Image > const &shadowMapImage,
                uint32_t layerIndex
            ) noexcept;

            void createRenderPassObjects( void ) noexcept;
            void destroyRenderPassObjects( void ) noexcept;

            void createGeometryObjects( void ) noexcept;
            void bindGeometryDescriptors( VkCommandBuffer cmds, Index currentFrameIndex, Geometry *geometry ) noexcept;
            void destroyGeometryObjects( void ) noexcept;

            void drawPrimitive( VkCommandBuffer cmds, const Primitive *primitive ) noexcept;

        private:
            SharedPointer< vulkan::RenderPass > m_renderPass;
            std::vector< SharedPointer< vulkan::Framebuffer > > m_framebuffers;

            vulkan::FramebufferAttachment m_shadowAttachment;

            std::unique_ptr< GraphicsPipeline > m_pipeline;
        };

    }

}

#endif


text:
import { IncomingWebhook } from '@slack/client';

import * as _ from 'lodash';
import * as os from 'os';
import { Configuration } from './configuration';

/**
 * Send a message to slack via a slack webhook.
 * @param url slack webhook address
 * @param slackMessage The message to send to slack
 */
export function message(url: string, slackMessage: string | {}): Promise<boolean | Error> {
  return new Promise((resolve, reject) => {
    const webhook = new IncomingWebhook(url);

    webhook.send(slackMessage, (err: Error, res: any) => {
      if (err !== null && err !== undefined) {
        reject(err);
      }
      resolve(res);
    });
  });
}

/**
 * Sends out a red warning twich message to the provided webhook url
 * @param url the url for the webhook
 */
export function serviceDownMessage(url: string, service: string): Promise<boolean | Error> {
  const serviceMessage = {
    text: 'Service Update',

    attachments: [
      {
        color: '#FF0032',
        fallback: 'Offline services',
        fields: [
          {
            short: false,
            title: `${service} is currently down`,
            value: `As of ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()} the serice ${service} is down`,
          },
        ],
      },
    ],
  };

  return message(url, serviceMessage);
}

/**
 * Gets the current webhook from the configuration wrapper
 * @param config the configuration wrapper
 */
export function getWebhookURL(config: Configuration): string {
  if (_.isNil(config)) {
    return null;
  }

  let webhookUrl: string = config.getKey('slack').mercury;

  if (process.env.NODE_ENV !== 'production') {
    webhookUrl = config.getKey('slack').debug;
  }

  return webhookUrl;
}

/**
 * Generates a simple health check for the system and sends it to slack.
 * @param url slack webhook address
 * @param email online boolean
 * @param database online boolean
 */
export function healthCheck(url: string, email: boolean, database: boolean): Promise<boolean | Error> {
  const online = [];
  const offline = [];

  email ? online.push('Email') : offline.push('Email');
  database ? online.push('Database') : offline.push('Database');

  const healthMessage = {
    text: 'Health Check',

    attachments: [
      {
        color: '#FF0032',
        fallback: 'Offline services',
        fields: [],
      },
      {
        color: 'good',
        fallback: 'Online services',
        fields: [
          {
            short: true,
            title: 'Slack',
            value: 'Online',
          },
        ],
      },
    ],
  };

  _.forEach(offline, (name) => {
    healthMessage.attachments[0].fields.push({
      short: true,
      title: name,
      value: 'Offline',
    });
  });

  _.forEach(online, (name) => {
    healthMessage.attachments[1].fields.push({
      short: true,
      title: name,
      value: 'Online',
    });
  });

  healthMessage.attachments.push({
    color: '#0000FF',
    fallback: 'Extra information',
    fields: [
      {
        short: true,
        title: 'Architecture',
        value: os.arch(),
      },
      {
        short: true,
        title: 'CPU Usage',
        value: `${cpuAverage()}%`,
      },
      {
        short: true,
        title: 'Memory',
        value: `${formatBytes(os.totalmem)}`,
      },
      {
        short: true,
        title: 'Memory Usage',
        value: `${formatBytes(os.freemem())}`,
      },
      {
        short: true,
        title: 'Uptime',
        value: `${(Math.floor(os.uptime()) / 60).toFixed(2)} min`,
      },
    ],
  });

  return message(url, healthMessage);
}

/**
 * Returns a string formatted system memory
 * @param bytes number of system memory in bytes
 */
function formatBytes(bytes): string {
  if (bytes === 0) {
    return '0 Bytes';
  }

  const k: number = 1024;
  const dm: number = 2;
  const memSizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i: number = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + memSizes[i];
}

/**
 * returns a object with average idle and average cpu usage
 * @param cpus os.cpus()
 */
function cpuAverage(): string {
  if (os.platform() === 'win32') {
    return 'Windows not supported';
  }

  const averageLoad: number[] = os.loadavg();
  let average: number = 0;

  _.forEach(averageLoad, (cpu: number) => {
    average += cpu;
  });

  return average.toFixed(2);
}


text:
package com.microsoft.azure.management.containerinstance.v2018_02_01_preview;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The properties of the Azure File volume. Azure File shares are mounted as
 * volumes.
 */
public class AzureFileVolume {
    /**
     * The name of the Azure File share to be mounted as a volume.
     */
    @JsonProperty(value = "shareName", required = true)
    private String shareName;

    /**
     * The flag indicating whether the Azure File shared mounted as a volume is
     * read-only.
     */
    @JsonProperty(value = "readOnly")
    private Boolean readOnly;

    /**
     * The name of the storage account that contains the Azure File share.
     */
    @JsonProperty(value = "storageAccountName", required = true)
    private String storageAccountName;

    /**
     * The storage account access key used to access the Azure File share.
     */
    @JsonProperty(value = "storageAccountKey")
    private String storageAccountKey;

    /**
     * Get the name of the Azure File share to be mounted as a volume.
     *
     * @return the shareName value
     */
    public String shareName() {
        return this.shareName;
    }

    /**
     * Set the name of the Azure File share to be mounted as a volume.
     *
     * @param shareName the shareName value to set
     * @return the AzureFileVolume object itself.
     */
    public AzureFileVolume withShareName(String shareName) {
        this.shareName = shareName;
        return this;
    }

    /**
     * Get the flag indicating whether the Azure File shared mounted as a volume is read-only.
     *
     * @return the readOnly value
     */
    public Boolean readOnly() {
        return this.readOnly;
    }

    /**
     * Set the flag indicating whether the Azure File shared mounted as a volume is read-only.
     *
     * @param readOnly the readOnly value to set
     * @return the AzureFileVolume object itself.
     */
    public AzureFileVolume withReadOnly(Boolean readOnly) {
        this.readOnly = readOnly;
        return this;
    }

    /**
     * Get the name of the storage account that contains the Azure File share.
     *
     * @return the storageAccountName value
     */
    public String storageAccountName() {
        return this.storageAccountName;
    }

    /**
     * Set the name of the storage account that contains the Azure File share.
     *
     * @param storageAccountName the storageAccountName value to set
     * @return the AzureFileVolume object itself.
     */
    public AzureFileVolume withStorageAccountName(String storageAccountName) {
        this.storageAccountName = storageAccountName;
        return this;
    }

    /**
     * Get the storage account access key used to access the Azure File share.
     *
     * @return the storageAccountKey value
     */
    public String storageAccountKey() {
        return this.storageAccountKey;
    }

    /**
     * Set the storage account access key used to access the Azure File share.
     *
     * @param storageAccountKey the storageAccountKey value to set
     * @return the AzureFileVolume object itself.
     */
    public AzureFileVolume withStorageAccountKey(String storageAccountKey) {
        this.storageAccountKey = storageAccountKey;
        return this;
    }

}


text:
FROM quay.io/sorah/rbenv:2.2
MAINTAINER her@sorah.jp

ADD Gemfile* /app/
ENV BUNDLE_GEMFILE /app/Gemfile
RUN bundle install --jobs 4 --path /app/vendor/bundle --deployment --without development:test

ADD *.rb /app/

CMD bundle exec ruby /app/conoha-monitor.rb


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

   <title>MMSODA Toolbox for MATLAB - mmsodaSubplotScreen</title>

   <meta name="keywords" content="mmsodaSubplotScreen">

   <meta name="description" content="mmsodaSubplotScreen">

   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

   <meta name="robots" content="index, follow">

   <meta author="Jurriaan H. Spaaks">

   <link type="text/css" rel="stylesheet" href="styles/mmsoda-styles.css">

View source code of the function mmsodaSubplotScreen() in the MATLAB editor

Toolbox contents

mmsodaSubplotScreen

Syntax

        mmsodaSubplotScreen(A,B,C)

        mmsodaSubplotScreen()

        mmsodaSubplotScreen(A,B,C,'figureNumber',D)

Description

        mmsodaSubplotScreen(A,B,C)

        does for figures what MATLAB's built-in subplot does for axes. For example:

        mmsodaSubplotScreen(1,2,1)

        creates a empty figure window on the left side of the screen. Similarly

for k=1:6
   mmsodaSubplotScreen(3,2,k)
end

        creates 6 empty figure windows, arranged in 3 rows and 2 columns on the screen.

        mmsodaSubplotScreen()

        If no input arguments are supplied, mmsodaSubplotScreen(1,1,1) is assumed.

        mmsodaSubplotScreen(A,B,C,'figureNumber',D)

        You can use the 'figureNumber'option to identify a certain figure. For example:

for k=1:6
   mmsodaSubplotScreen(3,2,k,'figureNumber',1000+k)
end

        creates figures 1001:1:1006.


text:
module Mandy
  module Reducers
    class MaxReducer < Base
      def reducer(key,values)
        values.map! {|value| value.to_f}
        emit(key, values.max)
      end
    end
  end
end


text:
<resources>

    <!-- the theme applied to the application or activity -->
    <style name="MainBar" parent="android:Theme.Holo">
        <item name="android:windowActionBarOverlay">true</item>
        <item name="android:actionBarStyle">@style/action_bar_theme</item>
        <item name="android:actionMenuTextColor">#fff</item>
    </style>

    <style name="action_bar_theme" parent="@android:style/Widget.Holo.ActionBar">
        <item name="android:background">@drawable/banner</item>
        <!-- <item name="android:background">#b3000000</item> -->
    </style>

    <style name="LoadingTheme" parent="@android:style/Theme.Holo.Light">
    <item name="android:windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

</resources>


text:
package org.uberfire.ext.wires.bpmn.client.resources.i18n;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.Messages;

public interface BpmnEditorConstants
        extends
        Messages {

    public static final BpmnEditorConstants INSTANCE = GWT.create( BpmnEditorConstants.class );

    String bpmnResourceTypeDescription();

    String bpmnPerspectiveTitle();

    String bpmnExplorerTitle();

    String bpmnExplorerNoFilesFound();

    String bpmnExplorerNoFilesOpen();

    String bpmnExplorerFileUrl();

    String bpmnEditorTitle();

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2015 Evolveum
  ~
  ~ 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.
  -->

<c:account oid="a0c010c0-d34d-b33f-f00d-111111111333"
	xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3"
	xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"
	xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3'
	xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3">
	<c:name>uid=guybrush123,ou=People,dc=example,dc=com</c:name>
	<c:resourceRef oid="ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff" />
	<c:objectClass>ri:inetOrgPerson</c:objectClass>
	<c:attributes>
		<ri:dn>uid=guybrush123,ou=People,dc=example,dc=com</ri:dn>
		<ri:entryUUID>f1f2f3f4-1234-6543-1234-hjk345j8j090</ri:entryUUID>
	</c:attributes>
</c:account>