text:
package org.pentaho.di.trans.steps.stepsmetrics;

import java.util.List;

import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;

/*
 * Created on 30-06-2008
 *
 */

public class StepsMetricsMeta extends BaseStepMeta implements StepMetaInterface {
  private static Class<?> PKG = StepsMetrics.class; // for i18n purposes, needed by Translator2!!

  public static final String[] RequiredStepsDesc = new String[] {
    BaseMessages.getString( PKG, "System.Combo.No" ), BaseMessages.getString( PKG, "System.Combo.Yes" ) };
  public static final String[] RequiredStepsCode = new String[] { "N", "Y" };

  public static final String YES = "Y";
  public static final String NO = "N";

  /** by which steps to display? */
  private String[] stepName;
  private String[] stepCopyNr;
  /** Array of boolean values as string, indicating if a step is required. */
  private String[] stepRequired;

  private String stepnamefield;
  private String stepidfield;
  private String steplinesinputfield;
  private String steplinesoutputfield;
  private String steplinesreadfield;
  private String steplinesupdatedfield;
  private String steplineswrittentfield;
  private String steplineserrorsfield;
  private String stepsecondsfield;

  public StepsMetricsMeta() {
    super(); // allocate BaseStepMeta
  }

  public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
    readData( stepnode );
  }

  public Object clone() {
    StepsMetricsMeta retval = (StepsMetricsMeta) super.clone();

    int nrfields = stepName.length;

    retval.allocate( nrfields );

    for ( int i = 0; i < nrfields; i++ ) {
      retval.stepName[i] = stepName[i];
      retval.stepCopyNr[i] = stepCopyNr[i];
      retval.stepRequired[i] = stepRequired[i];

    }
    return retval;
  }

  public void allocate( int nrfields ) {
    stepName = new String[nrfields];
    stepCopyNr = new String[nrfields];
    stepRequired = new String[nrfields];
  }

  /**
   * @return Returns the stepName.
   */
  public String[] getStepName() {
    return stepName;
  }

  /**
   * @return Returns the stepCopyNr.
   */
  public String[] getStepCopyNr() {
    return stepCopyNr;
  }

  /**
   * @param stepName
   *          The stepName to set.
   */
  public void setStepName( String[] stepName ) {
    this.stepName = stepName;
  }

  /**
   * @param stepCopyNr
   *          The stepCopyNr to set.
   */
  public void setStepCopyNr( String[] stepCopyNr ) {
    this.stepCopyNr = stepCopyNr;
  }

  public String getRequiredStepsDesc( String tt ) {
    if ( tt == null ) {
      return RequiredStepsDesc[0];
    }
    if ( tt.equals( RequiredStepsCode[1] ) ) {
      return RequiredStepsDesc[1];
    } else {
      return RequiredStepsDesc[0];
    }
  }

  public void getFields( RowMetaInterface r, String name, RowMetaInterface[] info, StepMeta nextStep,
    VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException {
    r.clear();
    String stepname = space.environmentSubstitute( stepnamefield );
    if ( !Const.isEmpty( stepname ) ) {
      ValueMetaInterface v = new ValueMeta( stepname, ValueMeta.TYPE_STRING );
      v.setOrigin( name );
      r.addValueMeta( v );
    }
    String stepid = space.environmentSubstitute( stepidfield );
    if ( !Const.isEmpty( stepid ) ) {
      ValueMetaInterface v = new ValueMeta( stepid, ValueMeta.TYPE_STRING );
      v.setOrigin( name );
      v.setLength( ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0 );
      r.addValueMeta( v );
    }
    String steplinesinput = space.environmentSubstitute( steplinesinputfield );
    if ( !Const.isEmpty( steplinesinput ) ) {
      ValueMetaInterface v = new ValueMeta( steplinesinput, ValueMeta.TYPE_INTEGER );
      v.setOrigin( name );
      v.setLength( ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0 );
      r.addValueMeta( v );
    }
    String steplinesoutput = space.environmentSubstitute( steplinesoutputfield );
    if ( !Const.isEmpty( steplinesoutput ) ) {
      ValueMetaInterface v = new ValueMeta( steplinesoutput, ValueMeta.TYPE_INTEGER );
      v.setOrigin( name );
      v.setLength( ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0 );
      r.addValueMeta( v );
    }
    String steplinesread = space.environmentSubstitute( steplinesreadfield );
    if ( !Const.isEmpty( steplinesread ) ) {
      ValueMetaInterface v = new ValueMeta( steplinesread, ValueMeta.TYPE_INTEGER );
      v.setOrigin( name );
      v.setLength( ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0 );
      r.addValueMeta( v );
    }
    String steplinesupdated = space.environmentSubstitute( steplinesupdatedfield );
    if ( !Const.isEmpty( steplinesupdated ) ) {
      ValueMetaInterface v = new ValueMeta( steplinesupdated, ValueMeta.TYPE_INTEGER );
      v.setOrigin( name );
      v.setLength( ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0 );
      r.addValueMeta( v );
    }
    String steplineswritten = space.environmentSubstitute( steplineswrittentfield );
    if ( !Const.isEmpty( steplineswritten ) ) {
      ValueMetaInterface v = new ValueMeta( steplineswritten, ValueMeta.TYPE_INTEGER );
      v.setOrigin( name );
      v.setLength( ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0 );
      r.addValueMeta( v );
    }
    String steplineserrors = space.environmentSubstitute( steplineserrorsfield );
    if ( !Const.isEmpty( steplineserrors ) ) {
      ValueMetaInterface v = new ValueMeta( steplineserrors, ValueMeta.TYPE_INTEGER );
      v.setOrigin( name );
      v.setLength( ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0 );
      r.addValueMeta( v );
    }
    String stepseconds = space.environmentSubstitute( stepsecondsfield );
    if ( !Const.isEmpty( stepseconds ) ) {
      ValueMetaInterface v = new ValueMeta( stepseconds, ValueMeta.TYPE_INTEGER );
      v.setOrigin( name );
      r.addValueMeta( v );
    }

  }

  private void readData( Node stepnode ) throws KettleXMLException {
    try {
      Node steps = XMLHandler.getSubNode( stepnode, "steps" );
      int nrsteps = XMLHandler.countNodes( steps, "step" );

      allocate( nrsteps );

      for ( int i = 0; i < nrsteps; i++ ) {
        Node fnode = XMLHandler.getSubNodeByNr( steps, "step", i );
        stepName[i] = XMLHandler.getTagValue( fnode, "name" );
        stepCopyNr[i] = XMLHandler.getTagValue( fnode, "copyNr" );
        stepRequired[i] = XMLHandler.getTagValue( fnode, "stepRequired" );
      }
      stepnamefield = XMLHandler.getTagValue( stepnode, "stepnamefield" );
      stepidfield = XMLHandler.getTagValue( stepnode, "stepidfield" );
      steplinesinputfield = XMLHandler.getTagValue( stepnode, "steplinesinputfield" );
      steplinesoutputfield = XMLHandler.getTagValue( stepnode, "steplinesoutputfield" );
      steplinesreadfield = XMLHandler.getTagValue( stepnode, "steplinesreadfield" );
      steplinesupdatedfield = XMLHandler.getTagValue( stepnode, "steplinesupdatedfield" );
      steplineswrittentfield = XMLHandler.getTagValue( stepnode, "steplineswrittentfield" );
      steplineserrorsfield = XMLHandler.getTagValue( stepnode, "steplineserrorsfield" );
      stepsecondsfield = XMLHandler.getTagValue( stepnode, "stepsecondsfield" );
    } catch ( Exception e ) {
      throw new KettleXMLException( "Unable to load step info from XML", e );
    }
  }

  public String getXML() {
    StringBuffer retval = new StringBuffer();

    retval.append( "    <steps>" + Const.CR );
    for ( int i = 0; i < stepName.length; i++ ) {
      retval.append( "      <step>" + Const.CR );
      retval.append( "        " + XMLHandler.addTagValue( "name", stepName[i] ) );
      retval.append( "        " + XMLHandler.addTagValue( "copyNr", stepCopyNr[i] ) );
      retval.append( "        " + XMLHandler.addTagValue( "stepRequired", stepRequired[i] ) );
      retval.append( "        </step>" + Const.CR );
    }
    retval.append( "      </steps>" + Const.CR );

    retval.append( "        " + XMLHandler.addTagValue( "stepnamefield", stepnamefield ) );
    retval.append( "        " + XMLHandler.addTagValue( "stepidfield", stepidfield ) );
    retval.append( "        " + XMLHandler.addTagValue( "steplinesinputfield", steplinesinputfield ) );
    retval.append( "        " + XMLHandler.addTagValue( "steplinesoutputfield", steplinesoutputfield ) );
    retval.append( "        " + XMLHandler.addTagValue( "steplinesreadfield", steplinesreadfield ) );
    retval.append( "        " + XMLHandler.addTagValue( "steplinesupdatedfield", steplinesupdatedfield ) );
    retval.append( "        " + XMLHandler.addTagValue( "steplineswrittentfield", steplineswrittentfield ) );
    retval.append( "        " + XMLHandler.addTagValue( "steplineserrorsfield", steplineserrorsfield ) );
    retval.append( "        " + XMLHandler.addTagValue( "stepsecondsfield", stepsecondsfield ) );

    return retval.toString();
  }

  public void setDefault() {
    int nrsteps = 0;

    allocate( nrsteps );

    for ( int i = 0; i < nrsteps; i++ ) {
      stepName[i] = "step" + i;
      stepCopyNr[i] = "CopyNr" + i;
      stepRequired[i] = NO;
    }

    stepnamefield = BaseMessages.getString( PKG, "StepsMetricsDialog.Label.Stepname" );
    stepidfield = BaseMessages.getString( PKG, "StepsMetricsDialog.Label.Stepid" );
    steplinesinputfield = BaseMessages.getString( PKG, "StepsMetricsDialog.Label.Linesinput" );
    steplinesoutputfield = BaseMessages.getString( PKG, "StepsMetricsDialog.Label.Linesoutput" );
    steplinesreadfield = BaseMessages.getString( PKG, "StepsMetricsDialog.Label.Linesread" );
    steplinesupdatedfield = BaseMessages.getString( PKG, "StepsMetricsDialog.Label.Linesupdated" );
    steplineswrittentfield = BaseMessages.getString( PKG, "StepsMetricsDialog.Label.Lineswritten" );
    steplineserrorsfield = BaseMessages.getString( PKG, "StepsMetricsDialog.Label.Lineserrors" );
    stepsecondsfield = BaseMessages.getString( PKG, "StepsMetricsDialog.Label.Time" );
  }

  public void setStepRequired( String[] stepRequiredin ) {
    for ( int i = 0; i < stepRequiredin.length; i++ ) {
      this.stepRequired[i] = getRequiredStepsCode( stepRequiredin[i] );
    }
  }

  public String getRequiredStepsCode( String tt ) {
    if ( tt == null ) {
      return RequiredStepsCode[0];
    }
    if ( tt.equals( RequiredStepsDesc[1] ) ) {
      return RequiredStepsCode[1];
    } else {
      return RequiredStepsCode[0];
    }
  }

  public String[] getStepRequired() {
    return stepRequired;
  }

  public String getStepNameFieldName() {
    return this.stepnamefield;
  }

  public void setStepNameFieldName( String stepnamefield ) {
    this.stepnamefield = stepnamefield;
  }

  public String getStepIdFieldName() {
    return this.stepidfield;
  }

  public void setStepIdFieldName( String stepidfield ) {
    this.stepidfield = stepidfield;
  }

  public String getStepLinesInputFieldName() {
    return this.steplinesinputfield;
  }

  public void setStepLinesInputFieldName( String steplinesinputfield ) {
    this.steplinesinputfield = steplinesinputfield;
  }

  public String getStepLinesOutputFieldName() {
    return this.steplinesoutputfield;
  }

  public void setStepLinesOutputFieldName( String steplinesoutputfield ) {
    this.steplinesoutputfield = steplinesoutputfield;
  }

  public String getStepLinesReadFieldName() {
    return this.steplinesreadfield;
  }

  public void setStepLinesReadFieldName( String steplinesreadfield ) {
    this.steplinesreadfield = steplinesreadfield;
  }

  public String getStepLinesWrittenFieldName() {
    return this.steplineswrittentfield;
  }

  public void setStepLinesWrittenFieldName( String steplineswrittentfield ) {
    this.steplineswrittentfield = steplineswrittentfield;
  }

  public String getStepLinesErrorsFieldName() {
    return this.steplineserrorsfield;
  }

  public String getStepSecondsFieldName() {
    return this.stepsecondsfield;
  }

  public void setStepSecondsFieldName( String fieldname ) {
    this.stepsecondsfield = fieldname;
  }

  public void setStepLinesErrorsFieldName( String steplineserrorsfield ) {
    this.steplineserrorsfield = steplineserrorsfield;
  }

  public String getStepLinesUpdatedFieldName() {
    return this.steplinesupdatedfield;
  }

  public void setStepLinesUpdatedFieldName( String steplinesupdatedfield ) {
    this.steplinesupdatedfield = steplinesupdatedfield;
  }

  public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases ) throws KettleException {
    try {

      int nrsteps = rep.countNrStepAttributes( id_step, "step_name" );

      allocate( nrsteps );

      for ( int i = 0; i < nrsteps; i++ ) {
        stepName[i] = rep.getStepAttributeString( id_step, i, "step_name" );
        stepCopyNr[i] = rep.getStepAttributeString( id_step, i, "step_CopyNr" );
        stepRequired[i] = rep.getStepAttributeString( id_step, i, "step_required" );
        if ( !YES.equalsIgnoreCase( stepRequired[i] ) ) {
          stepRequired[i] = NO;
        }
      }
      stepnamefield = rep.getStepAttributeString( id_step, "stepnamefield" );
      stepidfield = rep.getStepAttributeString( id_step, "stepidfield" );
      steplinesinputfield = rep.getStepAttributeString( id_step, "steplinesinputfield" );
      steplinesoutputfield = rep.getStepAttributeString( id_step, "steplinesoutputfield" );
      steplinesreadfield = rep.getStepAttributeString( id_step, "steplinesreadfield" );
      steplineswrittentfield = rep.getStepAttributeString( id_step, "steplineswrittentfield" );
      steplinesupdatedfield = rep.getStepAttributeString( id_step, "steplinesupdatedfield" );
      steplineserrorsfield = rep.getStepAttributeString( id_step, "steplineserrorsfield" );
      stepsecondsfield = rep.getStepAttributeString( id_step, "stepsecondsfield" );
    } catch ( Exception e ) {
      throw new KettleException( "Unexpected error reading step information from the repository", e );
    }
  }

  public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step ) throws KettleException {
    try {
      for ( int i = 0; i < stepName.length; i++ ) {
        rep.saveStepAttribute( id_transformation, id_step, i, "step_name", stepName[i] );
        rep.saveStepAttribute( id_transformation, id_step, i, "step_CopyNr", stepCopyNr[i] );
        rep.saveStepAttribute( id_transformation, id_step, i, "step_required", stepRequired[i] );
      }
      rep.saveStepAttribute( id_transformation, id_step, "stepnamefield", stepnamefield );
      rep.saveStepAttribute( id_transformation, id_step, "stepidfield", stepidfield );
      rep.saveStepAttribute( id_transformation, id_step, "steplinesinputfield", steplinesinputfield );
      rep.saveStepAttribute( id_transformation, id_step, "steplinesoutputfield", steplinesoutputfield );
      rep.saveStepAttribute( id_transformation, id_step, "steplinesreadfield", steplinesreadfield );
      rep.saveStepAttribute( id_transformation, id_step, "steplineswrittentfield", steplineswrittentfield );
      rep.saveStepAttribute( id_transformation, id_step, "steplinesupdatedfield", steplinesupdatedfield );
      rep.saveStepAttribute( id_transformation, id_step, "steplineserrorsfield", steplineserrorsfield );
      rep.saveStepAttribute( id_transformation, id_step, "stepsecondsfield", stepsecondsfield );
    } catch ( Exception e ) {
      throw new KettleException( "Unable to save step information to the repository for id_step=" + id_step, e );
    }
  }

  public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta,
    RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace space,
    Repository repository, IMetaStore metaStore ) {
    CheckResult cr;

    if ( prev == null || prev.size() == 0 ) {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
          PKG, "StepsMetricsMeta.CheckResult.NotReceivingFields" ), stepMeta );
      remarks.add( cr );
      if ( stepName.length > 0 ) {
        cr =
          new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
            PKG, "StepsMetricsMeta.CheckResult.AllStepsFound" ), stepMeta );
      } else {
        cr =
          new CheckResult( CheckResult.TYPE_RESULT_WARNING, BaseMessages.getString(
            PKG, "StepsMetricsMeta.CheckResult.NoStepsEntered" ), stepMeta );
      }
      remarks.add( cr );
    } else {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
          PKG, "StepsMetricsMeta.CheckResult.ReceivingFields" ), stepMeta );
      remarks.add( cr );
    }

    // See if we have input streams leading to this step!
    if ( input.length > 0 ) {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
          PKG, "StepsMetricsMeta.CheckResult.StepRecevingData2" ), stepMeta );
    } else {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
          PKG, "StepsMetricsMeta.CheckResult.NoInputReceivedFromOtherSteps" ), stepMeta );
    }
    remarks.add( cr );

  }

  public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta tr,
    Trans trans ) {
    return new StepsMetrics( stepMeta, stepDataInterface, cnr, tr, trans );
  }

  public StepDataInterface getStepData() {
    return new StepsMetricsData();
  }

}


text:
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.webapp.WebAppContext;

import java.net.URL;
import java.security.ProtectionDomain;

public class Runner {
    public static final int DEFAULT_PORT = 8081;
    private final Config conf = ConfigFactory.load().getConfig("bullseye");
    private Integer port;

    public Runner(final Integer port) {
	this.port = port;
    }

    public void start() {
	try {
	    final Server server = new Server();

	    if (port != null) {
		final SelectChannelConnector connector = new SelectChannelConnector();
		connector.setPort(port);
		connector.setMaxIdleTime(60000);
		server.addConnector(connector);
	    }

	    final ProtectionDomain domain = Runner.class.getProtectionDomain();
	    final URL location = domain.getCodeSource().getLocation();
	    final WebAppContext webapp = new WebAppContext();
	    webapp.setContextPath(conf.getString("app.contextPath"));
	    webapp.setWar(location.toExternalForm());
	    server.setHandler(webapp);

	    server.start();
	    server.join();
	} catch (Exception e) {
	    e.printStackTrace();
	    System.exit(-1);
	}
    }

    private static Integer getPort(final String[] args) {
	if (args.length >= 1) {
	    try {
		return Integer.parseInt(args[0]);
	    } catch (NumberFormatException e) {
		System.out.println("Error parsing port number as an integer: " + args[0]);
	    }
	}
	return null;
    }

    public static void main(final String[] args) {
	Integer port = getPort(args);
	if (port == null) port = DEFAULT_PORT;
	System.out.println("Starting embedded server on port [" + port + "]");
	final Runner runner = new Runner(port);
	runner.start();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" type="text/css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" type="text/css">
    <link rel="stylesheet" href="./resources/prism/prism.css" type="text/css">
    <link rel="stylesheet" href="../css/ol.css" type="text/css">
    <link rel="stylesheet" href="./resources/layout.css" type="text/css">

    <title>Limited Layer Extent</title>

         OpenLayers 3 Examples

  <button type="button" class="btn btn-default" id="northwest">northwest</button>
  <button type="button" class="btn btn-default" id="northeast">northeast</button>
  <button type="button" class="btn btn-default" id="southeast">southeast</button>
  <button type="button" class="btn btn-default" id="southwest">southwest</button>
  <button type="button" class="btn btn-default" id="world">world</button>

Limited Layer Extent

Restricting layer rendering to a limited extent.

This example uses the layer.setExtent() method to modify the extent of the overlay layer.  Use the controls below to limit rendering based on an extent.

extent, tilejson

Related API documentation:

ol.Map
,
ol.View
,
ol.layer.Tile
,
ol.proj
,
ol.source.TileJSON

           Copy
           Edit

        <form method="POST" id="jsfiddle-form" target="_blank" action="http://jsfiddle.net/api/post/jquery/1.11.0/">
          <textarea class="hidden" name="js">function transform(extent) {
  return ol.proj.transformExtent(extent, 'EPSG:4326', 'EPSG:3857');
}

var extents = {
  northwest: transform([-180, 0, 0, 85]),
  northeast: transform([0, 0, 180, 85]),
  southeast: transform([0, -85, 180, 0]),
  southwest: transform([-180, -85, 0, 0]),
  world: transform([-180, -85, 180, 85])
};

var base = new ol.layer.Tile({
  source: new ol.source.TileJSON({
    url: 'http://api.tiles.mapbox.com/v3/' +
        'mapbox.world-black.jsonp',
    crossOrigin: 'anonymous'
  })
});

var overlay = new ol.layer.Tile({
  extent: extents.northwest,
  source: new ol.source.TileJSON({
    url: 'http://api.tiles.mapbox.com/v3/' +
        'mapbox.world-glass.jsonp',
    crossOrigin: 'anonymous'
  })
});

var map = new ol.Map({
  layers: [base, overlay],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 1
  })
});

for (var key in extents) {
  document.getElementById(key).onclick = function(event) {
    overlay.setExtent(extents[event.target.id]);
  };
}
</textarea>
          <textarea class="hidden" name="css"></textarea>
          <textarea class="hidden" name="html"><div class="row-fluid">
  <div class="span12">
    <div id="map" class="map"></div>
  </div>
</div>
<div class="btn-group">
  <button type="button" class="btn btn-default" id="northwest">northwest</button>
  <button type="button" class="btn btn-default" id="northeast">northeast</button>
  <button type="button" class="btn btn-default" id="southeast">southeast</button>
  <button type="button" class="btn btn-default" id="southwest">southwest</button>
  <button type="button" class="btn btn-default" id="world">world</button>
</div>
</textarea>
          <input type="hidden" name="wrap" value="l">
          <input type="hidden" name="resources" value="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css,https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js,http://openlayers.org/en/v3.9.0/css/ol.css,http://openlayers.org/en/v3.9.0/build/ol.js">
        </form>

<!DOCTYPE html>
<html>
<head>
<title>Limited Layer Extent</title>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://openlayers.org/en/v3.9.0/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.9.0/build/ol.js"></script>

</head>
<body>
<div class="container-fluid">

<div class="row-fluid">
  <div class="span12">
    <div id="map" class="map"></div>
  </div>
</div>
<div class="btn-group">
  <button type="button" class="btn btn-default" id="northwest">northwest</button>
  <button type="button" class="btn btn-default" id="northeast">northeast</button>
  <button type="button" class="btn btn-default" id="southeast">southeast</button>
  <button type="button" class="btn btn-default" id="southwest">southwest</button>
  <button type="button" class="btn btn-default" id="world">world</button>
</div>

</div>
<script>
function transform(extent) {
  return ol.proj.transformExtent(extent, 'EPSG:4326', 'EPSG:3857');
}

var extents = {
  northwest: transform([-180, 0, 0, 85]),
  northeast: transform([0, 0, 180, 85]),
  southeast: transform([0, -85, 180, 0]),
  southwest: transform([-180, -85, 0, 0]),
  world: transform([-180, -85, 180, 85])
};

var base = new ol.layer.Tile({
  source: new ol.source.TileJSON({
    url: 'http://api.tiles.mapbox.com/v3/' +
        'mapbox.world-black.jsonp',
    crossOrigin: 'anonymous'
  })
});

var overlay = new ol.layer.Tile({
  extent: extents.northwest,
  source: new ol.source.TileJSON({
    url: 'http://api.tiles.mapbox.com/v3/' +
        'mapbox.world-glass.jsonp',
    crossOrigin: 'anonymous'
  })
});

var map = new ol.Map({
  layers: [base, overlay],
  target: 'map',
  view: new ol.View({
    center: [0, 0],
    zoom: 1
  })
});

for (var key in extents) {
  document.getElementById(key).onclick = function(event) {
    overlay.setExtent(extents[event.target.id]);
  };
}

</script>
</body>
</html>


text:
```lua
local palette = Palette()
local palette = Palette(numberOfColors)
local palette = Palette(otherPalette)
local palette = Palette{ fromFile=filename }
local palette = Palette{ fromResource=resourceID }
```

Creates a new palette. By default it will contain 256 colors, but you
can specify a `numberOfColors` (integer value).

`otherPalette` can be another palette object to create a copy of it.

If `fromFile` is given, the palette is loaded from the file name.

If `fromResource` is given, the `resourceID` is an ID specified in one
of the [extensions
palette](https://github.com/aseprite/aseprite/tree/main/data/extensions)
(e.g.
[`DB16`](https://github.com/aseprite/aseprite/blob/8e193b592ae06abb36be6f72ef43c308b511b24c/data/extensions/dawnbringer-palettes/package.json#L13),
[`DB32`](https://github.com/aseprite/aseprite/blob/8e193b592ae06abb36be6f72ef43c308b511b24c/data/extensions/dawnbringer-palettes/package.json#L14),
[`Solarized`](https://github.com/aseprite/aseprite/blob/8e193b592ae06abb36be6f72ef43c308b511b24c/data/extensions/software-palettes/package.json#L15)).

## #Palette

```lua
local ncolors = #palette
```

Returns the number of colors in the palette (remember that valid indexes in the palette go from `0` to `ncolors-1`).

## Palette:resize()

```lua
palette:resize(ncolors)
```

Changes the number of the palette colors to `ncolors` (an integer
value).

## Palette:getColor()

```lua
local color = palette:getColor(index)
```

Returns the [`color`](color.md#color) in the given entry `index` (the `index` goes from `0` to `#palette-1`).

## Palette:setColor()

```lua
palette:setColor(index, color)
```

Changes a palette color in the given entry `index` (the `index` goes from `0` to `#palette-1`).
The `color` can be a [`Color`](color.md#color) object or an [integer pixel value](pixelcolor.md#apppixelcolor).

## Palette.frame

At the moment it always return the first [frame](frame.md#frame), but in a
near future Aseprite will support palette changes over time (in
different frames), so this field should be the frame number where this
palette is displayed for first time in the [sprite](sprite.md#sprite).

## Palette:saveAs()

```lua
palette:saveAs(filename)
```

Saves the palette in the given `filename`.


text:
/* globals it, describe, before, beforeEach, expect, chai, sinonChai, sinon, fixture */
/* eslint no-unused-expressions: 0 */
import th from 'triggerhappy'

import panjs from '../../src/';

let element;
let node;
let pan;

describe('events', () => {
  before(() => {
    fixture.setBase('test');
  });

  beforeEach(() => {
    fixture.load('test.html');
    element = fixture.el.querySelector('.wrapper');
  });

  describe('onMouseMove, onMouseEnter, onMouseLeave', () => {
    beforeEach(() => {
      node = element.querySelector('.img-wrapper');
      pan = panjs(node);
    });

    it('should fire mousemove event', (done) => {
      pan.on('mousemove', () => { done() });
      th.fire('MouseEvent', 'mousemove', node)
    });

    it('should fire mouseenter event', (done) => {
      pan.on('mouseenter', () => { done() });
      th.fire('MouseEvent', 'mouseenter', node)
    });

    it('should fire mouseleave event', (done) => {
      pan.on('mouseleave', () => { done() });
      th.fire('mouseleave', 'mouseleave', node)
    });
  });
});


text:
(function () {
  var head = window.head || {};
  var Logging = function (src) {
    this.src = src + '?';
  };
  Logging.prototype.log = function (message) {
    var src = this.src + '&t=' + +new Date() + '&' + message;
    setTimeout(function () {
      var img = new Image();
      img.onload = img.onerror = function () {
        img = null;
      };
      img.src = src;
    }, 0);
  };
  head.getLogger = function (loggingUrl) {
    return new Logging(loggingUrl);
  };
  window.head = head;

  var defaultLogger = new Logging('REPLACE_ME');
  head.logger = defaultLogger;

  // ** error tracking out of the box
  var oldErrorHandler = window.onerror;

  window.onerror = function(msg, url, line) {
    if (!url) {
      return false;
    }

    var message = encodeURIComponent([msg, url, line].join('|'));
    defaultLogger.log(message);

    if (oldErrorHandler) {
      return oldErrorHandler(msg, url, line);
    } else {
      return false;
    }
  }
}());


text:
"""
    Author: João Ventura <flatangleweb@gmail.com>

    A tropical solar year is the length from spring equinox
    to the following spring equinox.

    This recipe was implemented to reply to a topic opened
    at http://skyscript.co.uk/forums/viewtopic.php?t=8563
    and shows that the solar year has an amplitude of more
    than 25 minutes, considering the average year of 365.2425
    days.

    To plot the graphics you must have matplotlib installed.

"""

from flatlib.datetime import Datetime
from flatlib.ephem import ephem

def plot(hdiff, title):
    """ Plots the tropical solar length
    by year.

    """
    import matplotlib.pyplot as plt
    years = [elem[0] for elem in hdiff]
    diffs = [elem[1] for elem in hdiff]
    plt.plot(years, diffs)
    plt.ylabel('Distance in minutes')
    plt.xlabel('Year')
    plt.title(title)
    plt.axhline(y=0, c='red')
    plt.show()

# Set the starting year
sYear = 1980

# Get successive spring equinox dates
equinoxes = []
span = 100
for year in range(sYear, sYear + span):

    # Get the spring equinox date for the year
    dt = Datetime('%s/01/01' % year, '00:00')
    sr = ephem.nextSolarReturn(dt, 0.00)
    equinoxes.append([year, sr.jd])

# Compute successive differences
diffs = []
for i in range(len(equinoxes) - 1):
    year1, jd1 = equinoxes[i]
    year2, jd2 = equinoxes[i+1]
    diffs.append([year1, (jd2 - jd1 - 365.2425) * 24 * 60])

print(diffs)
title = 'Solar year length from %s to %s\n' % (sYear , sYear + span)
title+= '(Compared to average year of 365.2425)'
plot(diffs, title)


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { RawViewComponent } from './raw-view.component';
import {MockResourcesService} from '../../mocks/mock.resources.service';
import {ResourcesService} from '../resources.service';
import {ServicePatientResource} from '../../models/Resource';

describe('RawViewComponent', () => {
  let component: RawViewComponent;
  let fixture: ComponentFixture<RawViewComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ RawViewComponent ],
      providers: [
        {provide : ResourcesService, useClass: MockResourcesService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(RawViewComponent);
    component = fixture.componentInstance;
    component = fixture.componentInstance;
    component.resource = new ServicePatientResource();
    component.resource.resourceJson = { resourceType: 'Patient' };
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});


text:
extern "Java"
{
  namespace java
  {
    namespace net
    {
        class ServerSocket;
    }
    namespace rmi
    {
      namespace server
      {
          class RMIServerSocketFactory;
      }
    }
  }
}

class java::rmi::server::RMIServerSocketFactory : public ::java::lang::Object
{

public:
  virtual ::java::net::ServerSocket * createServerSocket(jint) = 0;
  static ::java::lang::Class class$;
} __attribute__ ((java_interface));

#endif // __java_rmi_server_RMIServerSocketFactory__


text:
#ifdef KAA_USE_NOTIFICATIONS

#include "kaa/notification/NotificationManager.hpp"

#include <sstream>

#include "kaa/logging/Log.hpp"
#include "kaa/logging/LoggingUtils.hpp"
#include "kaa/utils/IThreadPool.hpp"
#include "kaa/context/IExecutorContext.hpp"
#include "kaa/IKaaClientStateStorage.hpp"
#include "kaa/common/AvroByteArrayConverter.hpp"
#include "kaa/common/exception/KaaException.hpp"
#include "kaa/common/exception/UnavailableTopicException.hpp"
#include "kaa/common/exception/TransportNotFoundException.hpp"

namespace kaa {

NotificationManager::NotificationManager(IKaaClientStateStoragePtr status, IExecutorContext& executorContext)
    : executorContext_(executorContext), clientStatus_(status)
{
    const DetailedTopicStates& topicStates = clientStatus_->getTopicStates();

    for (auto &topicState : topicStates) {
        Topic topic;
        topic.id = topicState.second.topicId;
        topic.name = topicState.second.topicName;
        topic.subscriptionType = topicState.second.subscriptionType;

        if (topics_.insert(std::make_pair(topicState.first, topic)).second) {
            KAA_LOG_INFO(boost::format("Loaded topic: id='%1%', name='%2%', type=%3%")
                % topic.id % topic.name % LoggingUtils::TopicSubscriptionTypeToString(topic.subscriptionType));
        }
    }
}

void NotificationManager::topicsListUpdated(const Topics& topicList)
{
    KAA_LOG_INFO(boost::format("New list of available topics received (topic_count=%1%)") % topicList.size());

    KAA_MUTEX_LOCKING("topicsGuard_");
    KAA_MUTEX_UNIQUE_DECLARE(topicsLock, topicsGuard_);
    KAA_MUTEX_LOCKED("topicsGuard_");

    std::unordered_map<std::string/*Topic ID*/, Topic> newTopics;

    for (const auto& topic : topicList) {
        newTopics.insert(std::make_pair(topic.id, topic));
        topics_.erase(topic.id);
    }

    {
        KAA_MUTEX_LOCKING("optionalListenersGuard_");
        KAA_MUTEX_UNIQUE_DECLARE(optionalListenersLock, optionalListenersGuard_);
        KAA_MUTEX_LOCKED("optionalListenersGuard_");

        if (!topics_.empty()) {
            KAA_LOG_INFO(boost::format("Going to remove optional listener(s) for %1% obsolete topics") % topics_.size());
            for (const auto& pair : topics_) {
                if (optionalListeners_.erase(pair.second.id)) {
                    KAA_LOG_TRACE(boost::format("Removed optional listener(s) for obsolete topic '%1%'") % pair.second.id);
                }
            }
        }
    }

    topics_ = newTopics;

    KAA_MUTEX_UNLOCKING("topicsGuard_");
    KAA_UNLOCK(topicsLock);
    KAA_MUTEX_UNLOCKED("topicsGuard_");

    notifyTopicUpdateSubscribers(topicList);
}

void NotificationManager::notificationReceived(const Notifications& notifications)
{
    AvroByteArrayConverter<KaaNotification> deserializer;

    for (const Notification& notification : notifications) {
        try {
            findTopic(notification.topicId);

            auto deserializedNotification = std::make_shared<KaaNotification>();
            deserializer.fromByteArray(notification.body.data(), notification.body.size(), *deserializedNotification);

            if (!notifyOptionalNotificationSubscribers(notification.topicId, deserializedNotification)) {
                notifyMandatoryNotificationSubscribers(notification.topicId, deserializedNotification);
            }
        } catch (const UnavailableTopicException& e) {
            KAA_LOG_WARN(boost::format("Received notification for unknown topic (id='%1%')") % notification.topicId);
        }
    }
}

void NotificationManager::addTopicListListener(INotificationTopicListListener& listener)
{
    topicListeners_.addCallback(&listener, std::bind(&INotificationTopicListListener::onListUpdated, &listener,
                                                     std::placeholders::_1));
}

void NotificationManager::removeTopicListListener(INotificationTopicListListener& listener)
{
    topicListeners_.removeCallback(&listener);
}

Topics NotificationManager::getTopics()
{
    KAA_MUTEX_LOCKING("topicsGuard_");
    KAA_MUTEX_UNIQUE_DECLARE(topicsLock, topicsGuard_);
    KAA_MUTEX_LOCKED("topicsGuard_");

    std::vector<Topic> topics;
    topics.reserve(topics_.size());

    for (const auto& it : topics_) {
        topics.push_back(it.second);
    }

    return topics;
}

void NotificationManager::addNotificationListener(INotificationListener& listener)
{
    mandatoryListeners_.addCallback(&listener, std::bind(&INotificationListener::onNotification, &listener,
                                                         std::placeholders::_1, std::placeholders::_2));
}

void NotificationManager::addNotificationListener(const std::string& topidId, INotificationListener& listener)
{
    findTopic(topidId);

    KAA_MUTEX_LOCKING("optionalListenersGuard_");
    KAA_MUTEX_UNIQUE_DECLARE(optionalListenersLock, optionalListenersGuard_);
    KAA_MUTEX_LOCKED("optionalListenersGuard_");

    auto it = optionalListeners_.find(topidId);
    if (it == optionalListeners_.end()) {
        it = optionalListeners_.insert(std::make_pair(topidId, std::make_shared<NotificationObservable>())).first;
    }

    it->second->addCallback(&listener, std::bind(&INotificationListener::onNotification, &listener,
                            std::placeholders::_1, std::placeholders::_2));
}

void NotificationManager::removeNotificationListener(INotificationListener& listener)
{
    mandatoryListeners_.removeCallback(&listener);
}

void NotificationManager::removeNotificationListener(const std::string& topidId, INotificationListener& listener)
{
    findTopic(topidId);

    KAA_MUTEX_LOCKING("optionalListenersGuard_");
    KAA_MUTEX_UNIQUE_DECLARE(optionalListenersLock, optionalListenersGuard_);
    KAA_MUTEX_LOCKED("optionalListenersGuard_");

    auto it = optionalListeners_.find(topidId);
    if (it != optionalListeners_.end()) {
        it->second->removeCallback(&listener);
        if (it->second->isEmpty()) {
            optionalListeners_.erase(topidId);
        }
    }
}

void NotificationManager::subscribeToTopic(const std::string& id, bool forceSync)
{
    if (findTopic(id).subscriptionType != OPTIONAL_SUBSCRIPTION) {
        KAA_LOG_WARN(boost::format("Failed to subscribe: topic '%1%' isn't optional") % id);
        throw UnavailableTopicException(boost::format("Topic '%1%' isn't optional") % id);
    }

    updateSubscriptionInfo(id, SubscriptionCommandType::ADD);

    if (forceSync) {
        KAA_LOG_INFO(boost::format("Going to subscribe to topic '%1%'") % id);
        sync();
    } else {
        KAA_LOG_INFO(boost::format("Subscription to topic '%1%' is postponed till sync") % id);
    }
}

void NotificationManager::subscribeToTopics(const std::list<std::string>& idList, bool forceSync)
{
    std::ostringstream iss;
    SubscriptionCommands subscriptions;

    for (const auto& id : idList) {
        if (findTopic(id).subscriptionType != OPTIONAL_SUBSCRIPTION) {
            KAA_LOG_WARN(boost::format("Failed to subscribe: topic '%1%' isn't optional") % id);
            throw UnavailableTopicException(boost::format("Topic '%1%' isn't optional") % id);
        }

        SubscriptionCommand cmd;
        cmd.command = SubscriptionCommandType::ADD;
        cmd.topicId = id;
        subscriptions.push_back(cmd);
        iss << "'" << id << "' ";
    }

    updateSubscriptionInfo(subscriptions);

    if (forceSync) {
        KAA_LOG_INFO(boost::format("Going to subscribe to topics %1%") % iss.str());
        sync();
    } else {
        KAA_LOG_INFO(boost::format("Subscription to topics '%1%' is postponed till sync") % iss.str());
    }
}

void NotificationManager::unsubscribeFromTopic(const std::string& id, bool forceSync)
{
    if (findTopic(id).subscriptionType != OPTIONAL_SUBSCRIPTION) {
        KAA_LOG_WARN(boost::format("Failed to unsubscribe: topic '%1%' isn't optional") % id);
        throw UnavailableTopicException(boost::format("Topic '%1%' isn't optional") % id);
    }

    updateSubscriptionInfo(id, SubscriptionCommandType::REMOVE);

    if (forceSync) {
        KAA_LOG_INFO(boost::format("Going to unsubscribe from topic '%1%'") % id);
        sync();
    } else {
        KAA_LOG_INFO(boost::format("Unsubscription from topic '%1%' is postponed till sync") % id);
    }
}

void NotificationManager::unsubscribeFromTopics(const std::list<std::string>& idList, bool forceSync)
{
    std::ostringstream iss;
    SubscriptionCommands subscriptions;

    for (const auto& id : idList) {
        if (findTopic(id).subscriptionType != OPTIONAL_SUBSCRIPTION) {
            KAA_LOG_WARN(boost::format("Failed to unsubscribe: topic '%1%' isn't optional") % id);
            throw UnavailableTopicException(boost::format("Topic '%1%' isn't optional") % id);
        }

        SubscriptionCommand cmd;
        cmd.command = SubscriptionCommandType::REMOVE;
        cmd.topicId = id;
        subscriptions.push_back(cmd);
        iss << "'" << id << "' ";
    }

    updateSubscriptionInfo(subscriptions);

    if (forceSync) {
        KAA_LOG_INFO(boost::format("Going to unsubscribe from topics %1%") % iss.str());
        sync();
    } else {
        KAA_LOG_INFO(boost::format("Unsubscription from topics '%1%' is postponed till sync") % iss.str());
    }
}

void NotificationManager::sync()
{
    if (!transport_) {
        KAA_LOG_ERROR("Failed to sync: notification transport not found");
        throw TransportNotFoundException("Notification transport not found");
    }

    KAA_MUTEX_LOCKING("subscriptionsGuard_");
    KAA_MUTEX_UNIQUE_DECLARE(subscriptionLock, subscriptionsGuard_);
    KAA_MUTEX_LOCKED("subscriptionsGuard_");

    if (!subscriptions_.empty()) {
        KAA_LOG_INFO(boost::format("Going to sync %1% topic subscription(s)...") % subscriptions_.size());
        transport_->onSubscriptionChanged(std::move(subscriptions_));
        subscriptions_ = SubscriptionCommands();
        transport_->sync();
    } else {
        KAA_LOG_TRACE("Nothing to sync. There are no topic subscriptions");
    }
}

void NotificationManager::updateSubscriptionInfo(const std::string& id, SubscriptionCommandType type)
{
    KAA_MUTEX_LOCKING("subscriptionsGuard_");
    KAA_MUTEX_UNIQUE_DECLARE(subscriptionLock, subscriptionsGuard_);
    KAA_MUTEX_LOCKED("subscriptionsGuard_");

    SubscriptionCommand cmd;
    cmd.command = type;
    cmd.topicId = id;
    subscriptions_.push_back(cmd);
}

void NotificationManager::updateSubscriptionInfo(const SubscriptionCommands& newSubscriptions)
{
    KAA_MUTEX_LOCKING("subscriptionsGuard_");
    KAA_MUTEX_UNIQUE_DECLARE(subscriptionLock, subscriptionsGuard_);
    KAA_MUTEX_LOCKED("subscriptionsGuard_");

    subscriptions_.insert(subscriptions_.end(), newSubscriptions.begin(), newSubscriptions.end());
}

const Topic& NotificationManager::findTopic(const std::string& id)
{
    try {
        KAA_MUTEX_LOCKING("topicsGuard_");
        KAA_MUTEX_UNIQUE_DECLARE(topicsLock, topicsGuard_);
        KAA_MUTEX_LOCKED("topicsGuard_");

        return topics_.at(id);
    } catch (const std::out_of_range&) {
        KAA_LOG_WARN(boost::format("Failed to find topic by id '%1%'") % id);
        throw UnavailableTopicException(boost::format("Unknown topic id '%1%'") % id);
    }
}

void NotificationManager::notifyTopicUpdateSubscribers(const Topics& topics)
{
    executorContext_.getCallbackExecutor().add([this, topics] () { topicListeners_(topics); });
}

void NotificationManager::notifyMandatoryNotificationSubscribers(const std::string& id, KaaNotificationPtr notification)
{
    executorContext_.getCallbackExecutor().add([this, id, notification] () { mandatoryListeners_(id, *notification); });
}

bool NotificationManager::notifyOptionalNotificationSubscribers(const std::string& id, KaaNotificationPtr notification)
{
    bool notified = false;

    KAA_MUTEX_LOCKING("optionalListenersGuard_");
    KAA_MUTEX_UNIQUE_DECLARE(optionalListenersLock, optionalListenersGuard_);
    KAA_MUTEX_LOCKED("optionalListenersGuard_");

    auto it = optionalListeners_.find(id);
    if (it != optionalListeners_.end()) {
        auto notifier = it->second;

        KAA_MUTEX_UNLOCKING("optionalListenersGuard_");
        KAA_UNLOCK(optionalListenersLock);
        KAA_MUTEX_UNLOCKED("optionalListenersGuard_");

        notified = true;

        executorContext_.getCallbackExecutor().add([notifier, id, notification] () { (*notifier)(id, *notification); });
    }

    return notified;
}

void NotificationManager::setTransport(std::shared_ptr<NotificationTransport> transport)
{
       if (transport) {
           transport_ = transport;
           transport_->setNotificationProcessor(this);
       }
   }

} /* namespace kaa */

#endif


text:
/* Written by Pádraig Brady

   This is backwards compatible with the FreeBSD utility, but is more
   flexible wrt the size specifications and the use of long options,
   to better fit the "GNU" environment.  */

#include <config.h>             /* sets _FILE_OFFSET_BITS=64 etc. */
#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>

#include "system.h"
#include "error.h"
#include "posixver.h"
#include "quote.h"
#include "xstrtol.h"

/* The official name of this program (e.g., no `g' prefix).  */
#define PROGRAM_NAME "truncate"

#define AUTHORS proper_name_utf8 ("Padraig Brady", "P\303\241draig Brady")

/* (-c) If true, don't create if not already there */
static bool no_create;

/* (-o) If true, --size refers to blocks not bytes */
static bool block_mode;

/* (-r) Reference file to use size from */
static char const *ref_file;

static struct option const longopts[] =
{
  {"no-create", no_argument, NULL, 'c'},
  {"io-blocks", no_argument, NULL, 'o'},
  {"reference", required_argument, NULL, 'r'},
  {"size", required_argument, NULL, 's'},
  {GETOPT_HELP_OPTION_DECL},
  {GETOPT_VERSION_OPTION_DECL},
  {NULL, 0, NULL, 0}
};

typedef enum
{ rm_abs = 0, rm_rel, rm_min, rm_max, rm_rdn, rm_rup } rel_mode_t;

/* Set size to the value of STR, interpreted as a decimal integer,
   optionally multiplied by various values.
   Return -1 on error, 0 on success.

   This supports dd BLOCK size suffixes + lowercase g,t,m for bsd compat
   Note we don't support dd's b=512, c=1, w=2 or 21x512MiB formats.  */
static int
parse_len (char const *str, off_t *size)
{
  enum strtol_error e;
  intmax_t tmp_size;
  e = xstrtoimax (str, NULL, 10, &tmp_size, "EgGkKmMPtTYZ0");
  if (e == LONGINT_OK
      && !(OFF_T_MIN <= tmp_size && tmp_size <= OFF_T_MAX))
    e = LONGINT_OVERFLOW;

  if (e == LONGINT_OK)
    {
      errno = 0;
      *size = tmp_size;
      return 0;
    }

  errno = (e == LONGINT_OVERFLOW ? EOVERFLOW : 0);
  return -1;
}

void
usage (int status)
{
  if (status != EXIT_SUCCESS)
    fprintf (stderr, _("Try `%s --help' for more information.\n"),
             program_name);
  else
    {
      printf (_("Usage: %s OPTION... FILE...\n"), program_name);
      fputs (_("\
Shrink or extend the size of each FILE to the specified size\n\
\n\
A FILE argument that does not exist is created.\n\
\n\
If a FILE is larger than the specified size, the extra data is lost.\n\
If a FILE is shorter, it is extended and the extended part (hole)\n\
reads as zero bytes.\n\
\n\
"), stdout);
      fputs (_("\
Mandatory arguments to long options are mandatory for short options too.\n\
"), stdout);
      fputs (_("\
  -c, --no-create        do not create any files\n\
"), stdout);
      fputs (_("\
  -o, --io-blocks        treat SIZE as number of IO blocks instead of bytes\n\
"), stdout);
      fputs (_("\
  -r, --reference=RFILE  base size on RFILE\n\
  -s, --size=SIZE        set or adjust the file size by SIZE\n"), stdout);
      fputs (HELP_OPTION_DESCRIPTION, stdout);
      fputs (VERSION_OPTION_DESCRIPTION, stdout);
      emit_size_note ();
      fputs (_("\n\
SIZE may also be prefixed by one of the following modifying characters:\n\
`+' extend by, `-' reduce by, `<' at most, `>' at least,\n\
`/' round down to multiple of, `%' round up to multiple of.\n"), stdout);
      emit_ancillary_info ();
    }
  exit (status);
}

/* return true on success, false on error.  */
static bool
do_ftruncate (int fd, char const *fname, off_t ssize, off_t rsize,
              rel_mode_t rel_mode)
{
  struct stat sb;
  off_t nsize;

  if ((block_mode || (rel_mode && rsize < 0)) && fstat (fd, &sb) != 0)
    {
      error (0, errno, _("cannot fstat %s"), quote (fname));
      return false;
    }
  if (block_mode)
    {
      off_t const blksize = ST_BLKSIZE (sb);
      if (ssize < OFF_T_MIN / blksize || ssize > OFF_T_MAX / blksize)
        {
          error (0, 0,
                 _("overflow in %" PRIdMAX
                   " * %" PRIdMAX " byte blocks for file %s"),
                 (intmax_t) ssize, (intmax_t) blksize,
                 quote (fname));
          return false;
        }
      ssize *= blksize;
    }
  if (rel_mode)
    {
      uintmax_t const fsize = rsize < 0 ? sb.st_size : rsize;

      if (rsize < 0) /* fstat used above to get size.  */
        {
          if (!S_ISREG (sb.st_mode) && !S_TYPEISSHM (&sb))
            {
              error (0, 0, _("cannot get the size of %s"), quote (fname));
              return false;
            }
          if (sb.st_size < 0)
            {
              /* Sanity check. Overflow is the only reason I can think
                 this would ever go negative. */
              error (0, 0, _("%s has unusable, apparently negative size"),
                     quote (fname));
              return false;
            }
        }

      if (rel_mode == rm_min)
        nsize = MAX (fsize, (uintmax_t) ssize);
      else if (rel_mode == rm_max)
        nsize = MIN (fsize, (uintmax_t) ssize);
      else if (rel_mode == rm_rdn)
        /* 0..ssize-1 -> 0 */
        nsize = (fsize / ssize) * ssize;
      else if (rel_mode == rm_rup)
        /* 1..ssize -> ssize */
        {
          /* Here ssize>=1 && fsize>=0 */
          uintmax_t const overflow = ((fsize + ssize - 1) / ssize) * ssize;
          if (overflow > OFF_T_MAX)
            {
              error (0, 0, _("overflow rounding up size of file %s"),
                     quote (fname));
              return false;
            }
          nsize = overflow;
        }
      else
        {
          if (ssize > OFF_T_MAX - (off_t)fsize)
            {
              error (0, 0, _("overflow extending size of file %s"),
                     quote (fname));
              return false;
            }
          nsize = fsize + ssize;
        }
    }
  else
    nsize = ssize;
  if (nsize < 0)
    nsize = 0;

  if (ftruncate (fd, nsize) == -1)      /* note updates mtime & ctime */
    {
      error (0, errno,
             _("failed to truncate %s at %" PRIdMAX " bytes"), quote (fname),
             (intmax_t) nsize);
      return false;
    }

  return true;
}

int
main (int argc, char **argv)
{
  bool got_size = false;
  bool errors = false;
  off_t size IF_LINT ( = 0);
  off_t rsize = -1;
  rel_mode_t rel_mode = rm_abs;
  mode_t omode;
  int c, fd = -1, oflags;
  char const *fname;

  initialize_main (&argc, &argv);
  set_program_name (argv[0]);
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  atexit (close_stdout);

  while ((c = getopt_long (argc, argv, "cor:s:", longopts, NULL)) != -1)
    {
      switch (c)
        {
        case 'c':
          no_create = true;
          break;

        case 'o':
          block_mode = true;
          break;

        case 'r':
          ref_file = optarg;
          break;

        case 's':
          /* skip any whitespace */
          while (isspace (to_uchar (*optarg)))
            optarg++;
          switch (*optarg)
            {
            case '<':
              rel_mode = rm_max;
              optarg++;
              break;
            case '>':
              rel_mode = rm_min;
              optarg++;
              break;
            case '/':
              rel_mode = rm_rdn;
              optarg++;
              break;
            case '%':
              rel_mode = rm_rup;
              optarg++;
              break;
            }
          /* skip any whitespace */
          while (isspace (to_uchar (*optarg)))
            optarg++;
          if (*optarg == '+' || *optarg == '-')
            {
              if (rel_mode)
                {
                  error (0, 0, _("multiple relative modifiers specified"));
                  /* Note other combinations are flagged as invalid numbers */
                  usage (EXIT_FAILURE);
                }
              rel_mode = rm_rel;
            }
          if (parse_len (optarg, &size) == -1)
            error (EXIT_FAILURE, errno, _("invalid number %s"),
                   quote (optarg));
          /* Rounding to multiple of 0 is nonsensical */
          if ((rel_mode == rm_rup || rel_mode == rm_rdn) && size == 0)
            error (EXIT_FAILURE, 0, _("division by zero"));
          got_size = true;
          break;

        case_GETOPT_HELP_CHAR;

        case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);

        default:
          usage (EXIT_FAILURE);
        }
    }

  argv += optind;
  argc -= optind;

  /* must specify either size or reference file */
  if (!ref_file && !got_size)
    {
      error (0, 0, _("you must specify either %s or %s"),
             quote_n (0, "--size"), quote_n (1, "--reference"));
      usage (EXIT_FAILURE);
    }
  /* must specify a relative size with a reference file */
  if (ref_file && got_size && !rel_mode)
    {
      error (0, 0, _("you must specify a relative %s with %s"),
             quote_n (0, "--size"), quote_n (1, "--reference"));
      usage (EXIT_FAILURE);
    }
  /* block_mode without size is not valid */
  if (block_mode && !got_size)
    {
      error (0, 0, _("%s was specified but %s was not"),
             quote_n (0, "--io-blocks"), quote_n (1, "--size"));
      usage (EXIT_FAILURE);
    }
  /* must specify at least 1 file */
  if (argc < 1)
    {
      error (0, 0, _("missing file operand"));
      usage (EXIT_FAILURE);
    }

  if (ref_file)
    {
      /* FIXME: Maybe support getting size of block devices.  */
      struct stat sb;
      if (stat (ref_file, &sb) != 0)
        error (EXIT_FAILURE, errno, _("cannot stat %s"), quote (ref_file));
      if (!S_ISREG (sb.st_mode) && !S_TYPEISSHM (&sb))
        error (EXIT_FAILURE, 0, _("cannot get the size of %s"),
               quote (ref_file));
      if (!got_size)
        size = sb.st_size;
      else
        rsize = sb.st_size;
    }

  oflags = O_WRONLY | (no_create ? 0 : O_CREAT) | O_NONBLOCK;
  omode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;

  while ((fname = *argv++) != NULL)
    {
      if ((fd = open (fname, oflags, omode)) == -1)
        {
          /* `truncate -s0 -c no-such-file`  shouldn't gen error
             `truncate -s0 no-such-dir/file` should gen ENOENT error
             `truncate -s0 no-such-dir/` should gen EISDIR error
             `truncate -s0 .` should gen EISDIR error */
          if (!(no_create && errno == ENOENT))
            {
              error (0, errno, _("cannot open %s for writing"),
                     quote (fname));
              errors = true;
            }
          continue;
        }

      if (fd != -1)
        {
          errors |= !do_ftruncate (fd, fname, size, rsize, rel_mode);
          if (close (fd) != 0)
            {
              error (0, errno, _("closing %s"), quote (fname));
              errors = true;
            }
        }
    }

  return errors ? EXIT_FAILURE : EXIT_SUCCESS;
}


text:
#ifndef READREADER_H_
#define READREADER_H_

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<cassert>
#include<fstream>

#include "utils.h"
#include "SingleRead.h"
#include "SingleReadQ.h"
#include "PairedEndRead.h"
#include "PairedEndReadQ.h"
#include "ReadIndex.h"

template<class ReadType>
class ReadReader {
public:
	ReadReader() { s = 0; indices = NULL; arr = NULL; hasPolyA = false; seedLen = -1; }
	ReadReader(int s, char readFs[][STRLEN], bool hasPolyA = false, int seedLen = -1);
	~ReadReader();

	void setIndices(ReadIndex** indices) {
		this->indices = indices;
	}

	bool locate(READ_INT_TYPE); // You should guarantee that indices exist and rid is valid, otherwise return false; If it fails, you should reset it manually!
	void reset();

	bool next(ReadType& read, int flags = 7) {
		bool success = read.read(s, (std::istream**)arr, flags);
		if (success && seedLen > 0) { read.calc_lq(hasPolyA, seedLen); }
		return success;
	}

private:
	int s; // number of files
	ReadIndex **indices;
	std::ifstream** arr;
	std::streampos *locations;

	bool hasPolyA;
	int seedLen;
};

template<class ReadType>
ReadReader<ReadType>::ReadReader(int s, char readFs[][STRLEN], bool hasPolyA, int seedLen) {
	assert(s > 0);
	this->s = s;
	arr = new std::ifstream*[s];
	locations = new std::streampos[s];
	indices = NULL;
	for (int i = 0; i < s; i++) {
		arr[i] = new std::ifstream(readFs[i]);
		if (!arr[i]->is_open()) { fprintf(stderr, "Cannot open %s! It may not exist.\n", readFs[i]); exit(-1); }
		locations[i] = arr[i]->tellg();
	}
	this->hasPolyA = hasPolyA;
	this->seedLen = seedLen;
}

template<class ReadType>
ReadReader<ReadType>::~ReadReader() {
	indices = NULL;
	if (arr != NULL) {
		for (int i = 0; i < s; i++) {
			arr[i]->close();
			delete arr[i];
		}
		delete[] arr;
	}
	if (locations != NULL) {
		delete[] locations;
	}
}

template<class ReadType>
bool ReadReader<ReadType>::locate(READ_INT_TYPE rid) {
	READ_INT_TYPE crid = -1;
	ReadType read;

	if (indices == NULL) return false;

	//We should make sure that crid returned by each indices is the same
	for (int i = 0; i < s; i++) {
		READ_INT_TYPE val = indices[i]->locate(rid, *arr[i]);
		if (i == 0) { crid = val; } else { assert(crid == val); }
	}
	assert(crid <= rid);
	while (crid < rid && read.read(s, (std::istream**)arr, 0)) ++crid;

	if (crid < rid) return false;

	std::streampos tmp[s];
	for (int i = 0; i < s; i++) { tmp[i] = arr[i]->tellg(); }

	if (!read.read(s, (std::istream**)arr, 0)) return false;

	for (int i = 0; i < s; i++) {
		locations[i] = tmp[i];
		arr[i]->seekg(locations[i]);
	}

	return true;
}

template<class ReadType>
void ReadReader<ReadType>::reset() {
	for (int i = 0; i < s; i++) {
		arr[i]->seekg(locations[i]);
	}
}

#endif /* READREADER_H_ */


text:
var exports = module.exports = {};

exports.parseCommand = function(words) {
    switch (words[0].toLowerCase()) {
        case "search":
            var query = words.slice(1, words.length).toString().replace(',', ' + ');
            console.log("giphy searching for : " + query);
            break;
        default:
            console.log("no matched command for giphy found.");
    }
}


text:
//  -*- C++ -*-

/*
 * Copyright (C) 1990,91   Silicon Graphics, Inc.
 *
 _______________________________________________________________________
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 |
 |   $Revision: 1.1.1.1 $
 |
 |   Description:
 |	This file defines the SoV1CustomNode class, which is used to
 |      read in and convert old nodes into new nodes.
 |
 |   Author(s)		: Gavin Bell
 |
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 _______________________________________________________________________
 */

#ifndef  _SO_V1CUSTOMNODE_
#define  _SO_V1CUSTOMNODE_

#include <Inventor/misc/upgraders/SoUpgrader.h>
#include <Inventor/fields/SoMFName.h>
#include <Inventor/fields/SoMFString.h>

//////////////////////////////////////////////////////////////////////////////
//
//  Class: SoV1CustomNode
//
//////////////////////////////////////////////////////////////////////////////

class INVENTOR_API SoV1CustomNode : public SoUpgrader {

    SO_NODE_HEADER(SoV1CustomNode);

  public:
    // Fields
    SoMFName		className;	// Names in custom subclass hierarchy
    SoMFString		fields;		// Field data strings, 1 per subclass
    SoMFString		customData;	// Custom data strings, 1 per subclass

    // Default constructor
    SoV1CustomNode();

    // There are 9 steps to reading in and upgrading a custom node;
    // happily, subclasses only have to worry about three virtual
    // methods:
    //   createNewNode()       -- MUST be implemented
    //   interpretCustomData() -- optional
    //   setUpNewNode()        -- also optional
    // See comments below for more info...
    virtual SbBool	upgrade(SoInput *in, const SbName &refName,
				SoBase *&result);

  protected:
    // which is responsible for looking at the
    //   className field and creating an appropriate replacement node.

  SoINTERNAL public:
    static void		initClass();

  protected:
    // createNewNode should look at the className field and create an
    // appropriate replacement node.  The default method prints an
    // error message.  This is called after fields have been read, but
    // before children are read.
    virtual SoNode	*createNewNode();

    // This method is called to let subclass instances do whatever they
    // have to do based on the info in the customData field value with the
    // given index after the given instance has been read. The default
    // does nothing.  This is called after createNewNode, before
    // children have been read.
    virtual void	interpretCustomData(SoV1CustomNode *inst,
					    int index) const;

    // This method is passed the new node (created by the
    // createNewNode method, above).  It must copy the fields from the
    // V1 upgrader instance into the new node, and must move the
    // children from the upgrader to the new node.  The default method
    // does nothing.
    virtual void	setUpNewNode(SoNode *newNode);

    virtual ~SoV1CustomNode();
};

// Note: use the generic SO_NODE_HEADER/etc macros instead of the
// SO_CUSTOM macros.

#endif /* _SO_V1CUSTOMNODE_ */


text:
/**
 * A {@code Grid} data structure.
 * <p>
 * The grid data structure provides a grid of values accessed by row and column.
 * It differs from Guava's {@code Table} in that the row and column are always {@code int}.
 */
package org.joda.collect.grid;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="robots" content="index,follow">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="A research blog for the AHRC funded Sonic Writing research project. This project explores how musical instrument design, musical notation techniques, and phonography is translated into current works in digital media.">

    <title>News and Events - Sonic Writing</title>

    <link rel="canonical" href="http://www.sonicwriting.org/news.html">

    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <link rel="stylesheet" href="/css/clean-blog.css">

    <link rel="stylesheet" href="/css/syntax.css">

    <link href='//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Josefin+Sans&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

    <link type="application/atom+xml" rel="alternate" href="http://www.sonicwriting.org/feed.xml" title="" />

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                Toggle navigation

            </button>
            Sonic Writing

                    Blog

                    About

                    News and Events

                    Publications

                    Contact

News and Events

                    News about workshops, symposia and publications

Interagency in Technologically-Mediated Performance [ January 29th 2016 ]

The Sonic Writing research projected started by participating in a wonderful symposium at Bournemouth University on the philosophy of technology in the domain of musical performance, called Interagency in Technologically-Mediated Performance. I presented a paper on questioning music technology and how technology should be seen as something we do, rather than something we buy.

The symposium will be recorded and eventually uploaded onto the  Translating Improvisation project website.

LCRN Day in Somerset House [ January 28th 2016 ]

The last event organised under the two-year AHRC funded Live Code Research Network took place in the Somerset House in London. The day set out to plan the future of the network, which includes this year's ICLC, which will be in Hamilton, Canada in October.

The Sound and Music organisation for new music then hosted a Creative Data Club, where we presented some live coding projects. The day ended with two live coding performances as part of the  Big Bang Data exhibition.

Copyright © Thor Magnusson 2016


text:
import signal
import gevent
import random
import marshal
import logging
from StringIO import StringIO

import zmq.green as zmq
from collections import defaultdict
from utils import zmq_addr

try:
    import msgpack as srl
except ImportError:
    import cPickle as srl

try:
    import marshal as marshal
    #import dill as marshal
except ImportError:
    import marshal

# States
# ------
START     = 0
MAP       = 1
SHUFFLE   = 2
PARTITION = 3
REDUCE    = 4
COLLECT   = 5

# Shufle Backends
# ---------------
MEMORY = 0

# Server instructions
# -------------------
#MAP      = 'map'
#REDUCE   = 'reduce'
#DONE     = 'done'
#BYTECODE = 'bytecode'

# Client instructions
# -------------------
CONNECT     = 'connect'
MAPATOM     = 'mapdone'
MAPCHUNK    = 'mapkeydone'
REDUCEATOM  = 'reducedone'

# Heartbeat
# ---------

PING = 'ping'
PONG = 'pong'

class Server(object):

    def __init__(self, backend=MEMORY):
        self.workers = set()
        self.state = START

        self.backend = backend

        self.mapfn = None
        self.reducefn = None
        self.datafn = None

        self.bytecode = None

        self.started = False
        self.completed = False

        self.working_maps = {}

        logging.basicConfig(logging=logging.DEBUG)
        logging.getLogger("").setLevel(logging.INFO)
        self.logging = logging

    def heartbeat_loop(self):
        while True:
            for worker in self.workers:
                print 'ping'
                self.ctrl_socket.send_multipart([worker, 'heartbeat'])
            gevent.sleep(1)

    def main_loop(self):
        self.started = True

        poller = zmq.Poller()

        poller.register(self.pull_socket, zmq.POLLIN  | zmq.POLLERR)
        poller.register(self.push_socket, zmq.POLLOUT | zmq.POLLERR)
        poller.register(self.ctrl_socket, zmq.POLLOUT | zmq.POLLERR)

        while self.started and not self.completed:
            try:
                events = dict(poller.poll())
            except zmq.ZMQError:
                self._kill()
                break

            if any(ev & zmq.POLLERR for ev in events.itervalues()):
                self.logging.error('Socket error')
                self._kill()
                break

            # TODO: Specify number of nodes
            if len(self.workers) > 0:
                if events.get(self.push_socket) == zmq.POLLOUT:
                    self.start_new_task()
                if events.get(self.ctrl_socket) == zmq.POLLIN:
                    self.manage()
                if events.get(self.pull_socket) == zmq.POLLIN:
                    self.collect_task()
            else:
                if events.get(self.pull_socket) == zmq.POLLIN:
                    self.collect_task()
                if events.get(self.ctrl_socket) == zmq.POLLIN:
                    self.manage()

            gevent.sleep(1)

    def connect(self, push_addr=None, pull_addr=None, control_addr=None):
        c = zmq.Context()

        # Pull tasks across manager
        pull_addr = zmq_addr(6666, transport='tcp')

        self.pull_socket = c.socket(zmq.PULL)
        self.pull_socket.bind(pull_addr)

        push_addr = zmq_addr(5555, transport='tcp')

        self.push_socket = c.socket(zmq.PUSH)
        self.push_socket.bind(push_addr)

        ctrl_addr = zmq_addr(7777, transport='tcp')

        self.ctrl_socket = c.socket(zmq.ROUTER)
        self.ctrl_socket.bind(ctrl_addr)

    def start(self, timeout=None):
        gevent.signal(signal.SIGQUIT, gevent.shutdown)

        self.gen_bytecode()
        self.logging.info('Started Server')

        main      = gevent.spawn(self.main_loop)
        heartbeat = gevent.spawn(self.heartbeat_loop)

        gevent.joinall([
            main,
            heartbeat,
        ])

        # Clean exit
        self.done()

    def done(self):
        for worker in self.workers:
            self.ctrl_socket.send_multipart([worker, 'done'])

    def manage(self):
        """
        Manage hearbeats on workers. Keep track of clients that
        are alive.
        """
        msg = self.ctrl_socket.recv_multipart()

    def _kill(self):
        gr = gevent.getcurrent()
        gr.kill()

    def results(self):
        if self.completed:
            return self.reduce_results
        else:
            return None

    def send_datum(self, command, key, data):
        self.push_socket.send(command, flags=zmq.SNDMORE)
        self.push_socket.send(str(key), flags=zmq.SNDMORE)

        if self.state == MAP:
            self.push_socket.send(data, copy=False)
        else:
            self.push_socket.send(srl.dumps(data))

    def send_command(self, command, payload=None):

        if payload:
            self.send_datum(command, *payload)
        else:
            self.push_socket.send(command)

    def start_new_task(self):
        action = self.next_task()
        if action:
            command, payload = action
            self.send_command(command, payload)

    def next_task(self):
        """
        The main work cycle, does all the distribution.
        """

        # -------------------------------------------
        if self.state == START:
            self.map_iter = self.datafn()

            if self.backend is MEMORY:
                self.map_results = defaultdict(list)
            else:
                raise NotImplementedError()

            self.state = MAP
            self.logging.info('Mapping')

        # -------------------------------------------
        if self.state == MAP:
            try:
                map_key, map_item = next(self.map_iter)
                self.working_maps[str(map_key)] = map_item
                return 'map', (map_key, map_item)
            except StopIteration:
                self.logging.info('Shuffling')
                self.state = SHUFFLE

        # -------------------------------------------
        if self.state == SHUFFLE:
            self.reduce_iter = self.map_results.iteritems()
            self.working_reduces = set()
            self.reduce_results = {}

            if len(self.working_maps) == 0:
                self.logging.info('Reducing')
                self.state = PARTITION
            else:
                self.logging.debug('Remaining %s ' % len(self.working_maps))
                #self.logging.debug('Pending chunks %r' % self.working_maps.keys())

        # -------------------------------------------
        if self.state == PARTITION:
            # Normally we would define some sort way to balance the work
            # across workers ( key modulo n ) but ZMQ PUSH/PULL load
            # balances for us.
            self.state = REDUCE

        # -------------------------------------------
        if self.state == REDUCE:
            try:
                reduce_key, reduce_value = next(self.reduce_iter)
                self.working_reduces.add(reduce_key)
                return 'reduce', (reduce_key, reduce_value)
            except StopIteration:
                self.logging.info('Collecting')
                self.state = COLLECT
        # -------------------------------------------

        if self.state == COLLECT:
            if len(self.working_reduces) == 0:
                self.completed = True
                self.logging.info('Finished')
            else:
                self.logging.debug('Still collecting %s' % len(self.working_reduces))

    def collect_task(self):
        # Don't use the results if they've already been counted
        command = self.pull_socket.recv(flags=zmq.SNDMORE)

        if command == CONNECT:
            worker_id = self.pull_socket.recv()
            self.send_code(worker_id)

        # Maps Units
        # ==========

        elif command == MAPCHUNK:
            key = self.pull_socket.recv()
            del self.working_maps[key]

        elif command == MAPATOM:
            key = self.pull_socket.recv(flags=zmq.SNDMORE)
            tkey = self.pull_socket.recv(flags=zmq.SNDMORE)
            value = self.pull_socket.recv()

            self.map_results[tkey].extend(value)

        # Reduce Units
        # ============

        elif command == REDUCEATOM:
            key = self.pull_socket.recv(flags=zmq.SNDMORE)
            value = srl.loads(self.pull_socket.recv())

            # Don't use the results if they've already been counted
            if key not in self.working_reduces:
                return

            self.reduce_results[key] = value
            self.working_reduces.remove(key)

        else:
            raise RuntimeError("Unknown wire chatter")

    def gen_bytecode(self):
        self.bytecode = (
            marshal.dumps(self.mapfn.func_code),
            marshal.dumps(self.reducefn.func_code),
        )

    def gen_llvm(self, mapfn, reducefn):
        mapbc = StringIO()
        reducebc = StringIO()

        mapfn.mod.to_bitcode(mapbc)
        mapfn.mod.to_bitcode(reducebc)

        return (mapbc, reducebc)

    def send_code(self, worker_id):
        # A new worker
        if worker_id not in self.workers:
            self.logging.info('Worker Registered: %s' % worker_id)
            self.workers.add(worker_id)

            payload = ('bytecode', self.bytecode)
            # The worker_id uniquely identifies the worker in
            # the ZMQ topology.
            self.ctrl_socket.send_multipart([worker_id, srl.dumps(payload)])
            self.logging.info('Sending Bytecode to %s' % worker_id)
        else:
            self.logging.debug('Worker asking for code again?')

if __name__ == '__main__':
    import sys
    import imp
    import argparse

    parser = argparse.ArgumentParser()

    parser.add_argument('path', help='Verbose logging')
    parser.add_argument('--verbose', help='Verbose logging')
    parser.add_argument('--config',  help='Configuration')
    parser.add_argument('--backend', help='Storage backend')

    args = parser.parse_args()

    #fp, pathname, description = imp.find_module(args.path)
    #mod = imp.load_module(args.path, fp, pathname, description)

    srv = Server(backend=args.backend)
    srv.connect()


text:
use lib "/perfstat/dev/1.40/lib";

use Service;
use Metric;
use Graph;

$perfhome = "/perfstat/dev/1.40";

#add create new service
$service = Service->new(	RRA => "RRA:AVERAGE:0.5:1:288 RRA:AVERAGE:0.5:7:288 RRA:AVERAGE:0.5:30:288 RRA:AVERAGE:0.5:365:288",
				rrdStep => "300",
				operatingSystem	=> "Linux",
				serviceName 	=> "socket",
						);

#add metric 0
$obj = Metric->new(	rrdIndex => 0,
					metricName => "activeOpens",
					friendlyName => "Active Open Connections",
					rrdDST => GAUGE,
					rrdHeartbeat => 600,
					rrdMin => 0,
					rrdMax => U,
					hasEvents => 1,
					warnThreshold => 100,
					critThreshold => 500,
					thresholdUnit => "Number",
					);
$service->addMetric($obj);

#add metric 1
$obj = Metric->new(	rrdIndex => 1,
					metricName => "passiveOpens",
					friendlyName => "Passive Open Connections",
					rrdDST => GAUGE,
					rrdHeartbeat => 600,
					rrdMin => 0,
					rrdMax => U,
					hasEvents => 0,
					warnThreshold => 100,
					critThreshold => 500,
					thresholdUnit => "Number",
					);
$service->addMetric($obj);

#add metric 2
$obj = Metric->new(	rrdIndex => 2,
					metricName => "estConnections",
					friendlyName => "Established Connections",
					rrdDST => GAUGE,
					rrdHeartbeat => 600,
					rrdMin => 0,
					rrdMax => U,
					hasEvents => 1,
					warnThreshold => 100,
					critThreshold => 300,
					thresholdUnit => "Number",
					);
$service->addMetric($obj);

#print out this service
print ("Ref: ref($service)\n");

$os = $service->getOS();
$serviceName = $service->getServiceName();
$RRA = $service->getRRA();
$rrdStep = $service->getRRDStep();
print ("OS: $os\n");
print ("serviceName: $serviceName\n");
print ("RRA: $RRA\n");
print ("rrdStep: $rrdStep\n");

#print out this services metrics
$arrayLength = $service->getMetricArrayLength();
print ("metric Array Length = $arrayLength\n\n");

for ($counter=0; $counter < $arrayLength; $counter++)
{
	$metricObject = $service->{metricArray}->[$counter];

	$rrdIndex = $metricObject->getRRDIndex();
        $rrdDST = $metricObject->getRRDDST();
        $rrdHeartbeat = $metricObject->getRRDHeartbeat();
        $rrdMin = $metricObject->getRRDMin();
        $rrdMax = $metricObject->getRRDMax();
	$metricName = $metricObject->getMetricName();
	$friendlyName = $metricObject->getFriendlyName();
	$hasEvents = $metricObject->getHasEvents();
	$warnThreshold = $metricObject->getWarnThreshold();
	$critThreshold = $metricObject->getCritThreshold();
	$thresholdUnit	= $metricObject->getThresholdUnit();

	print ("rrdIndex: $rrdIndex\n");
        print ("rrdDST: $rrdDST\n");
        print ("rrdHeartbeat: $rrdHeartbeat\n");
        print ("rrdMin: $rrdMin\n");
        print ("rrdMax: $rrdMax\n");
	print ("metricName: $metricName\n");
	print ("friendlyName: $friendlyName\n");
	print ("hasEvents: $hasEvents\n");
	print ("warnThreshold: $warnThreshold\n");
	print ("critThreshold: $critThreshold\n");
	print ("threshUnit: $thresholdUnit\n\n");
}

#print out this services graphs
$arrayLength = $service->getGraphArrayLength();
print ("graph Array Length = $arrayLength\n\n");

for ($counter=0; $counter < $arrayLength; $counter++)
{
	$graphObject = $service->{graphArray}->[$counter];

	$name = $graphObject->getName();
	$title = $graphObject->getTitle();
	$y_axis = $graphObject->getYaxis();
	$legend = $graphObject->getLegend();
	$text = $graphObject->getText();

	print ("name: $name\n");
	print ("title: $title\n");
	print ("y_axis: $y_axis\n");
	print ("legend: $legend\n");
	print ("text: $text\n");

	$arrayLength2 = $graphObject->getOptionsArrayLength();
	for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
	{
		print ("option: $graphObject->{optionsArray}->[$counter2]\n");
	}
	$arrayLength2 = $graphObject->getDefArrayLength();
	for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
	{
		print ("def: $graphObject->{defArray}->[$counter2]\n");
	}
	$arrayLength2 = $graphObject->getCdefArrayLength();
	for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
	{
		print ("cdef: $graphObject->{cdefArray}->[$counter2]\n");
	}
	$arrayLength2 = $graphObject->getLineArrayLength();
	for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
	{
		print ("line: $graphObject->{lineArray}->[$counter2]\n");
	}
}

#Store the service
$service->store("$perfhome/etc/configs/$service->{operatingSystem}/$service->{serviceName}.ser") or die("can't store $service->{serviceName}.ser?\n");


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace YAORMTesting.Utils
{
    public static class ConnectionStringUtils
    {
        public static string GetConnectionString()
        {
            string realConnectionString = Environment.GetEnvironmentVariable("yaorm.test.conn_string", EnvironmentVariableTarget.User);

            if (null == realConnectionString) Assert.Fail("Cannnot find the connection string");

            return realConnectionString;
        }
    }
}


text:
package org.ovirt.engine.api.restapi.resource;

import java.util.List;

import javax.ws.rs.core.Response;

import org.ovirt.engine.api.model.DataCenter;
import org.ovirt.engine.api.model.Network;
import org.ovirt.engine.api.model.Networks;
import org.ovirt.engine.api.resource.NetworkResource;
import org.ovirt.engine.core.common.action.AddNetworkStoragePoolParameters;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;

public class BackendDataCenterNetworksResource extends BackendNetworksResource {

    protected Guid dataCenterId;

    public BackendDataCenterNetworksResource(String dataCenterId) {
        super(VdcQueryType.GetNetworksByDataCenterId);
        this.dataCenterId = asGuid(dataCenterId);
    }

    @Override
    public Response add(Network network) {
        validateParameters(network, getRequiredAddFields());
        validateEnums(Network.class, network);
        DataCenter dataCenter = new DataCenter();
        dataCenter.setId(dataCenterId.toString());
        network.setDataCenter(dataCenter);
        org.ovirt.engine.core.common.businessentities.network.Network entity = map(network);
        AddNetworkStoragePoolParameters params = getAddParameters(network, entity);
        return performCreate(addAction,
                               params,
                               new DataCenterNetworkIdResolver(network.getName(), params.getStoragePoolId().toString()));
    }

    @Override
    public Networks list() {
        Networks networks = mapCollection(getNetworks());

        for (Network network : networks.getNetworks()) {
            network.setDisplay(null);
        }
        return networks;
    }

    protected List<org.ovirt.engine.core.common.businessentities.network.Network> getNetworks() {
        return getBackendCollection(VdcQueryType.GetNetworksByDataCenterId, getQueryParameters());
    }

    @Override
    protected VdcQueryParametersBase getQueryParameters() {
        return new IdQueryParameters(dataCenterId);
    }

    @Override
    protected String[] getRequiredAddFields() {
        return new String[] { "name"};
    }

    @Override
    public NetworkResource getNetworkSubResource(String id) {
        return inject(new BackendDataCenterNetworkResource(id, this));
    }

}


text:
var proxyquire = require('proxyquire').noPreserveCache(),
    M = require('mstring'),
    utils = require('./utils');

describe('ResultWriter', () => {
    var ResultWriter, csvWriter;

    function setup() {
        csvWriter = jasmine.createSpyObj('csvWriter', ['writeRecord']);
        var csv = {
            createCsvStreamWriter: jasmine.createSpy().andReturn(csvWriter)
        };
        ResultWriter = proxyquire('../lib/resultwriter', {
            'ya-csv': csv
        });
    }

    describe('create', () => {
        beforeEach(() => {
            setup();
        });

        function testCreate(code, type) {
            expect(ResultWriter.create(code) instanceof type).toBe(true);
        }

        it('returns JsonWriter for j and json', () => {
            testCreate('j', ResultWriter.JsonWriter);
            testCreate('json', ResultWriter.JsonWriter);
        });

        it('returns XmlWriter for x and xml', () => {
            testCreate('x', ResultWriter.XmlWriter);
            testCreate('xml', ResultWriter.XmlWriter);
        });

        it('returns CsvWriter for c and csv', () => {
            testCreate('c', ResultWriter.CsvWriter);
            testCreate('csv', ResultWriter.CsvWriter);
        });

        it('returns TableWriter for t and table', () => {
            testCreate('t', ResultWriter.TableWriter);
            testCreate('table', ResultWriter.TableWriter);
        });

        it('throws for unknown code', () => {
            expect(ResultWriter.create.bind(null, 'abc')).toThrow();
        });
    });

    describe('JsonWriter', () => {
        var writer, output = '';

        beforeEach(() => {
            writer = new ResultWriter.JsonWriter();
            spyOn(console, 'log').andCallFake(text => {
                output += text;
            });
        });

        afterEach(() => {
            console.log = console.log.originalValue;
        });

        it('writes json', () => {
            var result = [{
                title: 'abc',
                count: 54
            }];

            var json = M(function() { /***
            [{
                "title": "abc",
                "count": 54
            }]
            ***/});

            writer.start();
            writer.write(result);
            writer.end();

            expect(console.log).toHaveBeenCalled();
            utils.stringEqual(output, json);
        });
    });

    describe('XmlWriter', () => {
        var writer, output = '';

        beforeEach(() => {
            writer = new ResultWriter.XmlWriter();
            spyOn(console, 'log').andCallFake(text => {
                output += text;
            });
        });

        afterEach(() => {
            console.log = console.log.originalValue;
        });

        it('writes xml', () => {
            var result = [{
                title: 'abc',
                count: 54
            }];

            var xml = M(function() { /***
            <?xml version="1.0"?>
            <result>
                <item>
                    <title>abc</title>
                    <count>54</count>
                </item>
            </result>
            ***/});

            writer.start();
            writer.write(result);
            writer.end();

            expect(console.log).toHaveBeenCalled();
            utils.stringEqual(output, xml);
        });
    });

    describe('TableWriter', () => {
        var writer, output = '';

        beforeEach(() => {
            writer = new ResultWriter.TableWriter();
            spyOn(console, 'log').andCallFake(text => {
                output += text;
            });
        });

        afterEach(() => {
            console.log = console.log.originalValue;
        });

        it('writes tabular data', () => {
            var result = [{
                title: 'abc',
                count: 54
            }];

            var table = M(function() { /***
            title   count
            -----   -----
            abc     54
            ***/});

            writer.start();
            writer.write(result);
            writer.end();

            expect(console.log).toHaveBeenCalled();
            utils.stringEqual(output, table);
        });
    });

    describe('CsvWriter', () => {
        var writer, output = '';

        beforeEach(() => {
            csvWriter.writeRecord.reset();
            writer = new ResultWriter.CsvWriter();
        });

        it('writes csv', () => {
            var result = [{
                title: 'abc',
                count: 54
            }];

            writer.start();
            writer.write(result);
            writer.end();

            expect(csvWriter.writeRecord).toHaveBeenCalledWith(['title', 'count']);
            expect(csvWriter.writeRecord).toHaveBeenCalledWith(['abc', 54]);
        });
    });
});