text:
import Cartographic from "../Core/Cartographic.js";
import defaultValue from "../Core/defaultValue.js";
import defer from "../Core/defer.js";
import defined from "../Core/defined.js";
import Ellipsoid from "../Core/Ellipsoid.js";
import HeadingPitchRoll from "../Core/HeadingPitchRoll.js";
import CesiumMath from "../Core/Math.js";
import Matrix3 from "../Core/Matrix3.js";
import Matrix4 from "../Core/Matrix4.js";
import Resource from "../Core/Resource.js";
import Quaternion from "../Core/Quaternion.js";
import Transforms from "../Core/Transforms.js";
import Cesium3DTile from "./Cesium3DTile.js";
import I3SFeature from "./I3SFeature.js";
import I3SField from "./I3SField.js";
import I3SGeometry from "./I3SGeometry.js";

/**
 * This class implements an I3S Node. In CesiumJS each I3SNode creates a Cesium3DTile.
 * <p>
 * Do not construct this directly, instead access tiles through {@link I3SLayer}.
 * </p>
 * @alias I3SNode
 * @internalConstructor
 */
function I3SNode(parent, ref, isRoot) {
  let level;
  let layer;
  let nodeIndex;
  let resource;

  if (isRoot) {
    level = 0;
    layer = parent;
  } else {
    level = parent._level + 1;
    layer = parent._layer;
  }

  if (typeof ref === "number") {
    nodeIndex = ref;
  } else {
    resource = parent.resource.getDerivedResource({
      url: `${ref}/`,
    });
  }

  this._parent = parent;
  this._dataProvider = parent._dataProvider;
  this._isRoot = isRoot;
  this._level = level;
  this._layer = layer;
  this._nodeIndex = nodeIndex;
  this._resource = resource;

  this._tile = undefined;
  this._data = undefined;
  this._geometryData = [];
  this._featureData = [];
  this._fields = {};
  this._children = [];
  this._childrenReadyPromise = undefined;
  this._globalTransform = undefined;
  this._inverseGlobalTransform = undefined;
  this._inverseRotationMatrix = undefined;
}

Object.defineProperties(I3SNode.prototype, {
  /**
   * Gets the resource for the node.
   * @memberof I3SNode.prototype
   * @type {Resource}
   * @readonly
   */
  resource: {
    get: function () {
      return this._resource;
    },
  },
  /**
   * Gets the parent layer.
   * @memberof I3SNode.prototype
   * @type {I3SLayer}
   * @readonly
   */
  layer: {
    get: function () {
      return this._layer;
    },
  },
  /**
   * Gets the parent node.
   * @memberof I3SNode.prototype
   * @type {I3SNode|undefined}
   * @readonly
   */
  parent: {
    get: function () {
      return this._parent;
    },
  },
  /**
   * Gets the children nodes.
   * @memberof I3SNode.prototype
   * @type {I3SNode[]}
   * @readonly
   */
  children: {
    get: function () {
      return this._children;
    },
  },
  /**
   * Gets the collection of geometries.
   * @memberof I3SNode.prototype
   * @type {I3SGeometry[]}
   * @readonly
   */
  geometryData: {
    get: function () {
      return this._geometryData;
    },
  },
  /**
   * Gets the collection of features.
   * @memberof I3SNode.prototype
   * @type {I3SFeature[]}
   * @readonly
   */
  featureData: {
    get: function () {
      return this._featureData;
    },
  },
  /**
   * Gets the collection of fields.
   * @memberof I3SNode.prototype
   * @type {I3SField[]}
   * @readonly
   */
  fields: {
    get: function () {
      return this._fields;
    },
  },
  /**
   * Gets the Cesium3DTile for this node.
   * @memberof I3SNode.prototype
   * @type {Cesium3DTile}
   * @readonly
   */
  tile: {
    get: function () {
      return this._tile;
    },
  },
  /**
   * Gets the I3S data for this object.
   * @memberof I3SNode.prototype
   * @type {Object}
   * @readonly
   */
  data: {
    get: function () {
      return this._data;
    },
  },
});

/**
 * @private
 */
I3SNode.prototype.load = function () {
  const that = this;

  function processData() {
    if (!that._isRoot) {
      // Create a new tile
      const tileDefinition = that._create3DTileDefinition();

      that._tile = new Cesium3DTile(
        that._layer._tileset,
        that._dataProvider.resource,
        tileDefinition,
        that._parent._tile
      );

      that._tile._i3sNode = that;
    }
  }

  // If we don't have a nodepage index load from json
  if (!defined(this._nodeIndex)) {
    return this._dataProvider._loadJson(this._resource).then(function (data) {
      // Success
      that._data = data;
      processData();
    });
  }

  return this._layer._getNodeInNodePages(this._nodeIndex).then(function (node) {
    that._data = node;
    let uri;
    if (that._isRoot) {
      uri = "nodes/root/";
    } else if (defined(node.mesh)) {
      const uriIndex = node.mesh.geometry.resource;
      uri = `../${uriIndex}/`;
    }
    if (defined(uri)) {
      that._resource = that._parent.resource.getDerivedResource({ url: uri });
    }

    processData();
  });
};

/**
 * Loads the node fields.
 * @returns {Promise.<void>} A promise that is resolved when the I3S Node fields are loaded
 */
I3SNode.prototype.loadFields = function () {
  // Check if we must load fields
  const fields = this._layer._data.attributeStorageInfo;

  const that = this;
  function createAndLoadField(fields, index) {
    const newField = new I3SField(that, fields[index]);
    that._fields[newField._storageInfo.name] = newField;
    return newField.load();
  }

  const promises = [];
  if (defined(fields)) {
    for (let i = 0; i < fields.length; i++) {
      promises.push(createAndLoadField(fields, i));
    }
  }

  return Promise.all(promises);
};

/**
 * Returns the fields for a given picked position
 * @param {Cartesian3} pickedPosition The picked position
 * @returns {Object} Object containing field names and their values
 */
I3SNode.prototype.getFieldsForPickedPosition = function (pickedPosition) {
  const geometry = this.geometryData[0];
  if (!defined(geometry.customAttributes.featureIndex)) {
    return {};
  }

  const location = geometry.getClosestPointIndexOnTriangle(
    pickedPosition.x,
    pickedPosition.y,
    pickedPosition.z
  );

  if (
    location.index === -1 ||
    location.index > geometry.customAttributes.featureIndex.length
  ) {
    return {};
  }

  const featureIndex = geometry.customAttributes.featureIndex[location.index];
  return this.getFieldsForFeature(featureIndex);
};

/**
 * Returns the fields for a given feature
 * @param {Number} featureIndex Index of the feature whose attributes we want to get
 * @returns {Object} Object containing field names and their values
 */
I3SNode.prototype.getFieldsForFeature = function (featureIndex) {
  const featureFields = {};
  for (const fieldName in this.fields) {
    if (this.fields.hasOwnProperty(fieldName)) {
      const field = this.fields[fieldName];
      if (featureIndex >= 0 && featureIndex < field.values.length) {
        featureFields[field.name] = field.values[featureIndex];
      }
    }
  }
  return featureFields;
};

/**
 * @private
 */
I3SNode.prototype._loadChildren = function () {
  const that = this;
  // If the promise for loading the children was already created, just return it
  if (defined(this._childrenReadyPromise)) {
    return this._childrenReadyPromise;
  }

  const childPromises = [];
  if (defined(that._data.children)) {
    for (
      let childIndex = 0;
      childIndex < that._data.children.length;
      childIndex++
    ) {
      const child = that._data.children[childIndex];
      const newChild = new I3SNode(
        that,
        defaultValue(child.href, child),
        false
      );
      that._children.push(newChild);
      childPromises.push(newChild.load());
    }
  }

  this._childrenReadyPromise = Promise.all(childPromises).then(function () {
    for (let i = 0; i < that._children.length; i++) {
      that._tile.children.push(that._children[i]._tile);
    }
  });

  return this._childrenReadyPromise;
};

/**
 * @private
 */
I3SNode.prototype._loadGeometryData = function () {
  const geometryPromises = [];

  // To debug decoding for a specific tile, add a condition
  // that wraps this if/else to match the tile uri
  if (defined(this._data.geometryData)) {
    for (
      let geomIndex = 0;
      geomIndex < this._data.geometryData.length;
      geomIndex++
    ) {
      const curGeometryData = new I3SGeometry(
        this,
        this._data.geometryData[geomIndex].href
      );
      this._geometryData.push(curGeometryData);
      geometryPromises.push(curGeometryData.load());
    }
  } else if (defined(this._data.mesh)) {
    const geometryDefinition = this._layer._findBestGeometryBuffers(
      this._data.mesh.geometry.definition,
      ["position", "uv0"]
    );

    const geometryURI = `./geometries/${geometryDefinition.bufferIndex}/`;
    const newGeometryData = new I3SGeometry(this, geometryURI);
    newGeometryData._geometryDefinitions = geometryDefinition.definition;
    newGeometryData._geometryBufferInfo = geometryDefinition.geometryBufferInfo;
    this._geometryData.push(newGeometryData);
    geometryPromises.push(newGeometryData.load());
  }

  return Promise.all(geometryPromises);
};

/**
 * @private
 */
I3SNode.prototype._loadFeatureData = function () {
  const featurePromises = [];

  // To debug decoding for a specific tile, add a condition
  // that wraps this if/else to match the tile uri
  if (defined(this._data.featureData)) {
    for (
      let featureIndex = 0;
      featureIndex < this._data.featureData.length;
      featureIndex++
    ) {
      const newFeatureData = new I3SFeature(
        this,
        this._data.featureData[featureIndex].href
      );
      this._featureData.push(newFeatureData);
      featurePromises.push(newFeatureData.load());
    }
  }

  return Promise.all(featurePromises);
};

/**
 * @private
 */
I3SNode.prototype._clearGeometryData = function () {
  this._geometryData = [];
};

/**
 * @private
 */
I3SNode.prototype._create3DTileDefinition = function () {
  const obb = this._data.obb;
  const mbs = this._data.mbs;

  if (!defined(obb) && !defined(mbs)) {
    console.error("Failed to load I3S node. Bounding volume is required.");
    return undefined;
  }

  let geoPosition;

  if (defined(obb)) {
    geoPosition = Cartographic.fromDegrees(
      obb.center[0],
      obb.center[1],
      obb.center[2]
    );
  } else {
    geoPosition = Cartographic.fromDegrees(mbs[0], mbs[1], mbs[2]);
  }

  // Offset bounding box position if we have a geoid service defined
  if (defined(this._dataProvider._geoidDataList) && defined(geoPosition)) {
    for (let i = 0; i < this._dataProvider._geoidDataList.length; i++) {
      const tile = this._dataProvider._geoidDataList[i];
      const projectedPos = tile.projection.project(geoPosition);
      if (
        projectedPos.x > tile.nativeExtent.west &&
        projectedPos.x < tile.nativeExtent.east &&
        projectedPos.y > tile.nativeExtent.south &&
        projectedPos.y < tile.nativeExtent.north
      ) {
        geoPosition.height += sampleGeoid(projectedPos.x, projectedPos.y, tile);
        break;
      }
    }
  }

  let boundingVolume = {};
  let position;
  let span = 0;
  if (defined(obb)) {
    boundingVolume = {
      box: [
        0,
        0,
        0,
        obb.halfSize[0],
        0,
        0,
        0,
        obb.halfSize[1],
        0,
        0,
        0,
        obb.halfSize[2],
      ],
    };
    span = Math.max(
      Math.max(this._data.obb.halfSize[0], this._data.obb.halfSize[1]),
      this._data.obb.halfSize[2]
    );
    position = Ellipsoid.WGS84.cartographicToCartesian(geoPosition);
  } else {
    boundingVolume = {
      sphere: [0, 0, 0, mbs[3]],
    };
    position = Ellipsoid.WGS84.cartographicToCartesian(geoPosition);
    span = this._data.mbs[3];
  }
  span *= 2;
  // Compute the geometric error
  let metersPerPixel = Infinity;

  // Get the meters/pixel density required to pop the next LOD
  if (defined(this._data.lodThreshold)) {
    if (
      this._layer._data.nodePages.lodSelectionMetricType ===
      "maxScreenThresholdSQ"
    ) {
      const maxScreenThreshold = Math.sqrt(
        this._data.lodThreshold / (Math.PI * 0.25)
      );
      metersPerPixel = span / maxScreenThreshold;
    } else if (
      this._layer._data.nodePages.lodSelectionMetricType ===
      "maxScreenThreshold"
    ) {
      const maxScreenThreshold = this._data.lodThreshold;
      metersPerPixel = span / maxScreenThreshold;
    } else {
      // Other LOD selection types can only be used for point cloud data
      console.error("Invalid lodSelectionMetricType in Layer");
    }
  } else if (defined(this._data.lodSelection)) {
    for (
      let lodIndex = 0;
      lodIndex < this._data.lodSelection.length;
      lodIndex++
    ) {
      if (
        this._data.lodSelection[lodIndex].metricType === "maxScreenThreshold"
      ) {
        metersPerPixel = span / this._data.lodSelection[lodIndex].maxError;
      }
    }
  }

  if (metersPerPixel === Infinity) {
    metersPerPixel = 100000;
  }

  // Calculate the length of 16 pixels in order to trigger the screen space error
  const geometricError = metersPerPixel * 16;

  // Transformations
  const hpr = new HeadingPitchRoll(0, 0, 0);
  let orientation = Transforms.headingPitchRollQuaternion(position, hpr);

  if (defined(this._data.obb)) {
    orientation = new Quaternion(
      this._data.obb.quaternion[0],
      this._data.obb.quaternion[1],
      this._data.obb.quaternion[2],
      this._data.obb.quaternion[3]
    );
  }

  const rotationMatrix = Matrix3.fromQuaternion(orientation);
  const inverseRotationMatrix = Matrix3.inverse(rotationMatrix, new Matrix3());

  const globalTransform = new Matrix4(
    rotationMatrix[0],
    rotationMatrix[1],
    rotationMatrix[2],
    0,
    rotationMatrix[3],
    rotationMatrix[4],
    rotationMatrix[5],
    0,
    rotationMatrix[6],
    rotationMatrix[7],
    rotationMatrix[8],
    0,
    position.x,
    position.y,
    position.z,
    1
  );

  const inverseGlobalTransform = Matrix4.inverse(
    globalTransform,
    new Matrix4()
  );

  const localTransform = Matrix4.clone(globalTransform);

  if (defined(this._parent._globalTransform)) {
    Matrix4.multiply(
      globalTransform,
      this._parent._inverseGlobalTransform,
      localTransform
    );
  }

  this._globalTransform = globalTransform;
  this._inverseGlobalTransform = inverseGlobalTransform;
  this._inverseRotationMatrix = inverseRotationMatrix;

  // get children definition
  const childrenDefinition = [];
  for (let childIndex = 0; childIndex < this._children.length; childIndex++) {
    childrenDefinition.push(
      this._children[childIndex]._create3DTileDefinition()
    );
  }

  // Create a tile set
  const inPlaceTileDefinition = {
    children: childrenDefinition,
    refine: "REPLACE",
    boundingVolume: boundingVolume,
    transform: [
      localTransform[0],
      localTransform[4],
      localTransform[8],
      localTransform[12],
      localTransform[1],
      localTransform[5],
      localTransform[9],
      localTransform[13],
      localTransform[2],
      localTransform[6],
      localTransform[10],
      localTransform[14],
      localTransform[3],
      localTransform[7],
      localTransform[11],
      localTransform[15],
    ],
    content: {
      uri: defined(this._resource) ? this._resource.url : undefined,
    },
    geometricError: geometricError,
  };

  return inPlaceTileDefinition;
};

/**
 * @private
 */
I3SNode.prototype._createI3SDecoderTask = function (dataProvider, data) {
  // Prepare the data to send to the worker
  const parentData = data.geometryData._parent._data;
  const parentRotationInverseMatrix =
    data.geometryData._parent._inverseRotationMatrix;

  let longitude = 0.0;
  let latitude = 0.0;
  let height = 0.0;

  if (defined(parentData.obb)) {
    longitude = parentData.obb.center[0];
    latitude = parentData.obb.center[1];
    height = parentData.obb.center[2];
  } else if (defined(parentData.mbs)) {
    longitude = parentData.mbs[0];
    latitude = parentData.mbs[1];
    height = parentData.mbs[2];
  }

  const axisFlipRotation = Matrix3.fromRotationX(-CesiumMath.PI_OVER_TWO);
  const parentRotation = new Matrix3();

  Matrix3.multiply(
    axisFlipRotation,
    parentRotationInverseMatrix,
    parentRotation
  );

  const cartographicCenter = Cartographic.fromDegrees(
    longitude,
    latitude,
    height
  );

  const cartesianCenter = Ellipsoid.WGS84.cartographicToCartesian(
    cartographicCenter
  );

  const payload = {
    binaryData: data.geometryData._data,
    featureData:
      defined(data.featureData) && defined(data.featureData[0])
        ? data.featureData[0].data
        : undefined,
    schema: data.defaultGeometrySchema,
    bufferInfo: data.geometryData._geometryBufferInfo,
    ellipsoidRadiiSquare: Ellipsoid.WGS84.radiiSquared,
    url: data.url,
    geoidDataList: data.geometryData._dataProvider._geoidDataList,
    cartographicCenter: cartographicCenter,
    cartesianCenter: cartesianCenter,
    parentRotation: parentRotation,
  };

  const decodeI3STaskProcessor = dataProvider._getDecoderTaskProcessor();

  const transferrableObjects = [];
  return dataProvider._taskProcessorReadyPromise.then(function () {
    return decodeI3STaskProcessor.scheduleTask(payload, transferrableObjects);
  });
};

/**
 * @private
 */
I3SNode.prototype._createContentURL = function () {
  let rawGltf = {
    scene: 0,
    scenes: [
      {
        nodes: [0],
      },
    ],
    nodes: [
      {
        name: "singleNode",
      },
    ],
    meshes: [],
    buffers: [],
    bufferViews: [],
    accessors: [],
    materials: [],
    textures: [],
    images: [],
    samplers: [],
    asset: {
      version: "2.0",
    },
  };

  // Load the geometry data
  const dataPromises = [this._loadGeometryData()];
  if (this._dataProvider.legacyVersion16) {
    dataPromises.push(this._loadFeatureData());
  }

  const that = this;
  return Promise.all(dataPromises).then(function () {
    // Binary glTF
    let generateGltfPromise = Promise.resolve();
    if (defined(that._geometryData) && that._geometryData.length > 0) {
      const parameters = {
        geometryData: that._geometryData[0],
        featureData: that._featureData,
        defaultGeometrySchema: that._layer._data.store.defaultGeometrySchema,
        url: that._geometryData[0].resource.url,
        tile: that._tile,
      };

      const task = that._createI3SDecoderTask(that._dataProvider, parameters);
      if (!defined(task)) {
        // Postponed
        return;
      }

      generateGltfPromise = task.then(function (result) {
        rawGltf = parameters.geometryData._generateGltf(
          result.meshData.nodesInScene,
          result.meshData.nodes,
          result.meshData.meshes,
          result.meshData.buffers,
          result.meshData.bufferViews,
          result.meshData.accessors
        );

        that._geometryData[0]._customAttributes =
          result.meshData._customAttributes;
      });
    }

    return generateGltfPromise.then(function () {
      const binaryGltfData = that._dataProvider._binarizeGltf(rawGltf);
      const glbDataBlob = new Blob([binaryGltfData], {
        type: "application/binary",
      });
      that._glbURL = URL.createObjectURL(glbDataBlob);
    });
  });
};

// Reimplement Cesium3DTile.prototype.requestContent so that
// We get a chance to load our own gltf from I3S data
Cesium3DTile.prototype._hookedRequestContent =
  Cesium3DTile.prototype.requestContent;

/**
 * @private
 */
Cesium3DTile.prototype._resolveHookedObject = function () {
  const that = this;
  // Keep a handle on the early promises
  // Call the real requestContent function
  this._hookedRequestContent();

  // Fulfill the promises
  this._contentReadyToProcessPromise.then(function () {
    that._contentReadyToProcessDefer.resolve();
  });

  this._contentReadyPromise.then(function (content) {
    that._isLoading = false;
    that._contentReadyDefer.resolve(content);
  });
};

Cesium3DTile.prototype.requestContent = function () {
  const that = this;
  if (!this.tileset._isI3STileSet) {
    return this._hookedRequestContent();
  }

  if (!this._isLoading) {
    this._isLoading = true;

    // Create early promises that will be fulfilled later
    this._contentReadyToProcessDefer = defer();
    this._contentReadyDefer = defer();
    this._contentReadyToProcessPromise = this._contentReadyToProcessDefer.promise;
    this._contentReadyPromise = this._contentReadyDefer.promise;

    this._i3sNode._createContentURL().then(function () {
      that._contentResource = new Resource({ url: that._i3sNode._glbURL });
      that._resolveHookedObject();
    });

    // Returns the number of requests
    return 0;
  }

  return 1;
};

function bilinearInterpolate(tx, ty, h00, h10, h01, h11) {
  const a = h00 * (1 - tx) + h10 * tx;
  const b = h01 * (1 - tx) + h11 * tx;
  return a * (1 - ty) + b * ty;
}

function sampleMap(u, v, width, data) {
  const address = u + v * width;
  return data[address];
}

function sampleGeoid(sampleX, sampleY, geoidData) {
  const extent = geoidData.nativeExtent;
  let x =
    ((sampleX - extent.west) / (extent.east - extent.west)) *
    (geoidData.width - 1);
  let y =
    ((sampleY - extent.south) / (extent.north - extent.south)) *
    (geoidData.height - 1);
  const xi = Math.floor(x);
  let yi = Math.floor(y);

  x -= xi;
  y -= yi;

  const xNext = xi < geoidData.width ? xi + 1 : xi;
  let yNext = yi < geoidData.height ? yi + 1 : yi;

  yi = geoidData.height - 1 - yi;
  yNext = geoidData.height - 1 - yNext;

  const h00 = sampleMap(xi, yi, geoidData.width, geoidData.buffer);
  const h10 = sampleMap(xNext, yi, geoidData.width, geoidData.buffer);
  const h01 = sampleMap(xi, yNext, geoidData.width, geoidData.buffer);
  const h11 = sampleMap(xNext, yNext, geoidData.width, geoidData.buffer);

  let finalHeight = bilinearInterpolate(x, y, h00, h10, h01, h11);
  finalHeight = finalHeight * geoidData.scale + geoidData.offset;
  return finalHeight;
}

Object.defineProperties(Cesium3DTile.prototype, {
  /**
   * Gets the I3S Node for the tile.
   * @memberof Cesium3DTile.prototype
   * @type {String}
   */
  i3sNode: {
    get: function () {
      return this._i3sNode;
    },
  },
});

export default I3SNode;


text:
Upcoming things:

            <time datetime={{event.start}} class="icon">
              {{event.start | date: 'EEEE'}}
              {{event.start | date: 'MMMM'}}
              {{event.start | date: 'dd'}}
            </time>

            {{event.title}}

            Event {{humanizeTime(event.start)}}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="fos_oauth_server.client_manager.default" class="FOS\OAuthServerBundle\Entity\ClientManager">
            <argument type="service" id="fos_oauth_server.entity_manager" />
            <argument>%fos_oauth_server.model.client.class%</argument>
        </service>

        <service id="fos_oauth_server.access_token_manager.default" class="FOS\OAuthServerBundle\Entity\AccessTokenManager">
            <argument type="service" id="fos_oauth_server.entity_manager" />
            <argument>%fos_oauth_server.model.access_token.class%</argument>
        </service>

        <service id="fos_oauth_server.refresh_token_manager.default" class="FOS\OAuthServerBundle\Entity\RefreshTokenManager">
            <argument type="service" id="fos_oauth_server.entity_manager" />
            <argument>%fos_oauth_server.model.refresh_token.class%</argument>
        </service>

        <service id="fos_oauth_server.auth_code_manager.default" class="FOS\OAuthServerBundle\Entity\AuthCodeManager">
            <argument type="service" id="fos_oauth_server.entity_manager" />
            <argument>%fos_oauth_server.model.auth_code.class%</argument>
        </service>

        <service id="fos_oauth_server.entity_manager" factory-service="doctrine" factory-method="getManager" class="Doctrine\ORM\EntityManager" public="false">
            <argument>%fos_oauth_server.model_manager_name%</argument>
        </service>
    </services>

</container>


text:
title: How to use a drop down list editor and populate it with data
description: How to manually populate the data source of the PropertyGridDropDownListEditor data source.
type: how-to
page_title: How to populate a PropertyGridDropDownListEditor data source
slug: propertygrid-dropdown-editor
position: 0
tags: Customize Editor, PropertyGrid, PropertyGridDropDownListEditor, PropertyGrid Editor Cusomtization
ticketid: 1168968
res_type: kb
---

## Environment

		Product
		RadPropertyGrid for WinForms

## Description
By default, when you have a string property in the RadPropertyGrid.**SelectedObject**, a [PropertyGridTextBoxEditor]({%slug winforms/propertygrid/editors/overview%}) will be activated. A common requirement is to offer the user a list of predefined values when editing this property. This article demonstrates the different approaches for achieving such a requirement.

## Solution

Let's consider that we have a **Person** class with two string properties, **Name** and **OriginCountry**. When you try to edit the country you will obtain the following result:

![propertygrid-dropdown-editor 001](images/propertygrid-dropdown-editor001.png)

The desired result is to select the country from a drop down list:

![propertygrid-dropdown-editor 002](images/propertygrid-dropdown-editor002.png)

## Handling the EditorRequired event

Subscribe to the RadPropertyGrid.[EditorRequired]({%slug winforms/propertygrid/editors/events%}) event and set the PropertyGridEditorRequiredEventArgs.**Editor** property to **PropertyGridDropDownListEditor**. The code snippet below demonstrates how to populate the drop down with country options:

{{source=..\SamplesCS\KnowledgeBase\PropertyGridDropDownEditor.cs region=EditorRequired}}
{{source=..\SamplesVB\KnowledgeBase\PropertyGridDropDownEditor.vb region=EditorRequired}}

````C#

private void radPropertyGrid1_EditorRequired(object sender, Telerik.WinControls.UI.PropertyGridEditorRequiredEventArgs e)
{
    if (e.Item.Name == "OriginCountry")
    {
        PropertyGridDropDownListEditor ddl = new PropertyGridDropDownListEditor();
        BaseDropDownListEditorElement el = ddl.EditorElement as BaseDropDownListEditorElement;
        el.DataSource = GetCountries();
        e.Editor = ddl;
    }
}

private object GetCountries()
{
    List<string> countries = new List<string>();
    countries.Add("USA");
    countries.Add("France");
    countries.Add("UK");
    countries.Add("Germany");
    countries.Add("Australia");
    return countries;
}

````
````VB.NET
Private Sub radPropertyGrid1_EditorRequired(sender As Object, e As Telerik.WinControls.UI.PropertyGridEditorRequiredEventArgs)
    If e.Item.Name = "OriginCountry" Then
        Dim ddl As PropertyGridDropDownListEditor = New PropertyGridDropDownListEditor()
        Dim el As BaseDropDownListEditorElement = TryCast(ddl.EditorElement, BaseDropDownListEditorElement)
        el.DataSource = GetCountries()
        e.Editor = ddl
    End If
End Sub
Private Function GetCountries() As Object
    Dim countries As List(Of String) = New List(Of String)()
    countries.Add("USA")
    countries.Add("France")
    countries.Add("UK")
    countries.Add("Germany")
    countries.Add("Australia")
    Return countries
End Function

````

{{endregion}}

## Using EditorAttribute and handling the EditorInitialized event

You can specify the [EditorAttribute](https://msdn.microsoft.com/en-us/library/system.componentmodel.editorattribute(v=vs.110).aspx) in the Person.**OriginCountry** property indicating that the **PropertyGridDropDownListEditor** will be used:

````C#

[Editor(typeof(PropertyGridDropDownListEditor), typeof(BaseInputEditor))]

````
````VB.NET
 <Editor(GetType(PropertyGridDropDownListEditor), GetType(BaseInputEditor))> _
````

Then, subscribe to the RadPropertyGrid.[EditorInitialized]({%slug winforms/propertygrid/editors/events%}) event where you can set the editor's **DataSource** property:

{{source=..\SamplesCS\KnowledgeBase\PropertyGridDropDownEditor.cs region=Initialized}}
{{source=..\SamplesVB\KnowledgeBase\PropertyGridDropDownEditor.vb region=Initialized}}

````C#

private void radPropertyGrid1_EditorInitialized(object sender, PropertyGridItemEditorInitializedEventArgs e)
{
    PropertyGridDropDownListEditor ddl = e.Editor as  PropertyGridDropDownListEditor;
    if (ddl != null)
    {
        BaseDropDownListEditorElement el = ddl.EditorElement as BaseDropDownListEditorElement;
        el.DataSource = GetCountries();
        el.Text = ((PropertyGridItem)e.Item).Value + "";
    }
}

````
````VB.NET
Private Sub EditorInitialized(sender As Object, e As PropertyGridItemEditorInitializedEventArgs)
    Dim ddl As PropertyGridDropDownListEditor = TryCast(e.Editor, PropertyGridDropDownListEditor)
    If ddl IsNot Nothing Then
        Dim el As BaseDropDownListEditorElement = TryCast(ddl.EditorElement, BaseDropDownListEditorElement)
        el.DataSource = GetCountries()
        el.Text = (CType(e.Item, PropertyGridItem)).Value & ""
    End If
End Sub

````

{{endregion}}

## Using a custom TypeConverter

You can also create a [TypeConverter](https://msdn.microsoft.com/en-us/library/ayybcxe5.aspx). In it we will override the **GetStandardValuesSupported** method, which indicates whether the object supports a standard set of values that can be picked from a predefined list. Then, we will override the **GetStandardValuesExclusive** method which indicates whether the collection of standard values is exclusive or the user is allowed to add custom values. Lastly, in the **GetStandardValues** method we should specify the predefined list. The property grid uses this collection to build a list and provide it to the user for selection.

{{source=..\SamplesCS\KnowledgeBase\PropertyGridDropDownEditor.cs region=TypeConverter}}
{{source=..\SamplesVB\KnowledgeBase\PropertyGridDropDownEditor.vb region=TypeConverter}}

````C#
public class CustomTypeConverter : TypeConverter
{
    public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
    {
        return true;
    }
    public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
    {
        return true;
    }
    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
    {
        return new StandardValuesCollection(new string[] { "USA", "France", "UK", "Germany", "Australia" });
    }
}

````
````VB.NET
Public Class CustomTypeConverter
    Inherits TypeConverter
    Public Overrides Function GetStandardValuesSupported(ByVal context As ITypeDescriptorContext) As Boolean
        Return True
    End Function
    Public Overrides Function GetStandardValuesExclusive(ByVal context As ITypeDescriptorContext) As Boolean
        Return True
    End Function
    Public Overrides Function GetStandardValues(ByVal context As ITypeDescriptorContext) As StandardValuesCollection
        Return New StandardValuesCollection(New String() {"USA", "France", "UK", "Germany", "Australia"})
    End Function
End Class

````

{{endregion}}

After applying the [TypeConverterAttribute](https://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverterattribute(v=vs.110).aspx), when you try to modify the **OriginCountry** property **RadPropertyGrid** will display a drop down list editor with the predefined set of values:

````C#
 [TypeConverter(typeof(CustomTypeConverter))]

````
````VB.NET
<TypeConverter(GetType(CustomTypeConverter))>

````

# See Also

 * [PropertyGrid Overview]({%slug winforms/propertygrid%})
 * [PropertyGrid Events ]({%slug winforms/propertygrid/editors/events%})


text:
local http = require "resty.http"
local server = require "spec.support.server"

describe("hook secret", function()
  before_each(server.stop)
  after_each(server.stop)

  it("writes a friendly error message when auto_ssl_settings dict is missing", function()
    server.start({
      disable_auto_ssl_settings_dict = true,
    })

    local error_log = server.read_error_log()
    assert.matches("auto-ssl: dict auto_ssl_settings could not be found. Please add it to your configuration: `lua_shared_dict auto_ssl_settings 64k;`", error_log, nil, true)
  end)

  it("doesn't change the hook secret after reloading", function()
    server.start({
      auto_ssl_http_server_config = [[
        location /auto-ssl-init {
          content_by_lua_block {
            auto_ssl:init()
            ngx.print("init")
          }
        }
      ]],
    })

    local httpc = http.new()

    local res, err = httpc:request_uri("http://127.0.0.1:9080/hook-server-secret")
    assert.equal(nil, err)
    assert.equal(200, res.status)
    assert.string(res.body)
    assert.equal(64, string.len(res.body))
    local secret1 = res.body

    local init_res, init_err = httpc:request_uri("http://127.0.0.1:9080/auto-ssl-init")
    assert.equal(nil, init_err)
    assert.equal(200, init_res.status)
    assert.equal("init", init_res.body)

    local res2, err2 = httpc:request_uri("http://127.0.0.1:9080/hook-server-secret")
    assert.equal(nil, err2)
    assert.equal(200, res2.status)
    assert.string(res2.body)
    assert.equal(64, string.len(res2.body))
    local secret2 = res2.body

    assert.equal(secret1, secret2)

    local error_log = server.read_error_log()
    assert.Not.matches("[warn]", error_log, nil, true)
    assert.Not.matches("[error]", error_log, nil, true)
    assert.Not.matches("[alert]", error_log, nil, true)
    assert.Not.matches("[emerg]", error_log, nil, true)
  end)
end)


text:
function []=cost_xx(dirModel,dirMat,doComp,dirTex,nameTex);
%object:	compute cost function term for atmospheric controls
%inputs:	dirModel is the model directory
%               dirMat is the directory where diagnozed .mat files will be saved
%                     -> set it to '' to use the default [dirModel 'mat/']
%		doComp is a switch (1->compute; 0->display)
%optional:      dirTex is the directory where tex and figures files are created
%                 (if not specified then display all results to screen instead)
%               nameTex is the tex file name (default : 'myPlots')

if isempty(dirMat); dirMat=[dirModel 'mat' filesep]; else; dirMat=[dirMat filesep]; end;
if isempty(dir(dirMat));     mkdir([dirMat]); end;

%determine if and where to create tex and figures files
dirMat=[dirMat filesep];
if isempty(who('dirTex'));
  addToTex=0;
else;
  if ~ischar(dirTex); error('mis-specified dirTex'); end;
  addToTex=1;
  if isempty(who('nameTex')); nameTex='myPlots'; end;
  fileTex=[dirTex filesep nameTex '.tex'];
end;

for ii=1:6;
switch ii;
case 1; xxName='atemp'; nameSigma='cap_sigma_tmp2m_degC_eccollc.bin'; cc=2; uni='K';
case 2; xxName='aqh'; nameSigma='cap_sigma_spfh2m_eccollc.bin'; cc=2; uni='g/kg';
case 3; xxName='tauu'; nameSigma='cap_sigma_ustr_eccollc.bin'; cc=0.04; uni='N/m2';
case 4; xxName='tauv'; nameSigma='cap_sigma_vstr_eccollc.bin'; cc=0.04; uni='N/m2';
case 5; xxName='lwdown'; nameSigma='cap_sigma_dlw_eccollc.bin'; cc=20; uni='W/m2';
case 6; xxName='swdown'; nameSigma='cap_sigma_dsw_eccollc.bin'; cc=40; uni='W/m2';
end;

if doComp;

%load grid
gcmfaces_global;
if ~isfield(mygrid,'XC'); grid_load('./GRID/',5,'compact'); end;
if ~isfield(mygrid,'LATS_MASKS'); gcmfaces_lines_zonal; end;

if ~isempty(dir([dirModel nameSigma]));
  dirSig=dirModel;
else;
  warning(['could not find ' nameSigma ' -> abort']);
  return;
end;

if ~isempty(dir([dirModel 'xx_' xxName '.effective.*data']));
  dirXX=dirModel;
else;
  dirXX=[dirModel 'ADXXfiles' filesep];
end;

%read model cost output
tmp1=dir([dirXX 'xx_' xxName '.effective.*data']);
tmp2=size(convert2gcmfaces(mygrid.XC));
fld_xx=read2memory([dirXX tmp1.name],[tmp2 tmp1.bytes/tmp2(1)/tmp2(2)/4]);
fld_xx=convert2gcmfaces(fld_xx);
%does not work when adjoint overwrites xx*effective*meta     fld_xx=rdmds2gcmfaces([dirXX 'xx_' xxName '.effective.*']);

fld_sig=read_bin([dirSig nameSigma],1,0);
if strcmp(xxName,'aqh'); fld_xx=fld_xx*1000; fld_sig=fld_sig*1000; end;

%compute xx stats
fld_rms=sqrt(mean(fld_xx.^2,3));
fld_mean=mean(fld_xx,3);
fld_std=std(fld_xx,[],3);

%mask
fld_rms=fld_rms.*mygrid.mskC(:,:,1);
fld_sig=fld_sig.*mygrid.mskC(:,:,1);
fld_mean=fld_mean.*mygrid.mskC(:,:,1);
fld_std=fld_std.*mygrid.mskC(:,:,1);

clear fld_xx;

if ~isdir([dirMat 'cost/']); mkdir([dirMat 'cost/']); end;
eval(['save ' dirMat '/cost/cost_xx_' xxName '.mat fld_* cc uni;']);

else;%display previously computed results

global mygrid;

if ~isdir([dirMat 'cost/']); dirMat=[dirMat 'cost/']; end;

eval(['load ' dirMat '/cost_xx_' xxName '.mat;']);

figure;
m_map_gcmfaces(fld_sig,0,{'myCaxis',[0:0.05:0.5 0.6:0.1:1 1.25]*cc});
myCaption={['prior uncertainty -- ' xxName ' (' uni ')']};
if addToTex; write2tex(fileTex,2,myCaption,gcf); end;

figure;
m_map_gcmfaces(fld_rms,0,{'myCaxis',[0:0.05:0.5 0.6:0.1:1 1.25]*cc});
myCaption={['rms adjustment -- ' xxName ' (' uni ')']};
if addToTex; write2tex(fileTex,2,myCaption,gcf); end;

figure;
m_map_gcmfaces(fld_std,0,{'myCaxis',[0:0.05:0.5 0.6:0.1:1 1.25]*cc});
myCaption={['std adjustment -- ' xxName ' (' uni ')']};
if addToTex; write2tex(fileTex,2,myCaption,gcf); end;

figure;
m_map_gcmfaces(fld_mean,0,{'myCaxis',[-0.5:0.05:0.5]*cc});
myCaption={['mean adjustment -- ' xxName ' (' uni ')']};
if addToTex; write2tex(fileTex,2,myCaption,gcf); end;

end;

end;%for ii=1:6;


text:
require 'test_helper'
require 'sidekiq'

class SidekiqWorkersSendMetricsTest < AcceptanceTestCase

  def test_sidekiq_worker_sends_metrics
    test_sidekiq_worker = TestSidekiqServer.new
    test_endpoint = TestEndpoint.new(port: 8081)

    test_endpoint.listen
    test_sidekiq_worker.push_job
    test_sidekiq_worker.boot(chillout_port: 8081)

    if ENV['STRATEGY'] != 'active_job'
      assert test_endpoint.has_received_information_about_startup
    end
    assert test_endpoint.has_one_creation_for_entity_resource

    assert sidekiq = test_endpoint.has_one_sidekiq_metric
    assert_equal "CreateEntityJob", sidekiq.fetch("tags").fetch("class")
    assert_equal "default", sidekiq.fetch("tags").fetch("queue")
    assert_equal "true", sidekiq.fetch("tags").fetch("retriable")
    assert_equal "true", sidekiq.fetch("tags").fetch("success")

    assert sidekiq.fetch("timestamp")

    assert_equal 1, sidekiq.fetch("values").fetch("finished")
    assert_operator 90, :>, sidekiq.fetch("values").fetch("duration")
    assert_operator  0, :<, sidekiq.fetch("values").fetch("duration")
    assert_operator 8000, :>, sidekiq.fetch("values").fetch("delay")
    assert_operator  200, :<, sidekiq.fetch("values").fetch("delay")
  ensure
    if test_sidekiq_worker
      test_sidekiq_worker.clear_jobs
      test_sidekiq_worker.shutdown
    end
  end

end if ENV['SIDEKIQ_SUPPORTED']


text:
/* Depandances PROVIDE :
 * =====================
 */
stage.provide("io.authentication.SASL");
stage.provide("SASL");
 /*
 * Depandances REQUIRE :
 * =====================
 */
stage.require("io");

stage.register.call(stage.io.authentication,"SASL",function(context, name){

	var defaultSettings = {
		mechanism : "DIGEST-MD5"
	};

	var implementedMechanisms = {
		"DIGEST-MD5":stage.io.mechanisms.digestMD5.digestMD5,
		"PLAIN":0
	};

	var SASL = function(settingsSasl){

		// Manage settings
		this.settings = stage.extend( true, {}, defaultSettings, settingsSasl);

		this.state = "INITIATED";

		if(implementedMechanisms[this.settings.mechanism]){

			var settings = {
				domain:this.settings.domain,
				userName:this.settings.userName,
				pwd:this.settings.pwd
			}
			this.mechanism = new implementedMechanisms[this.settings.mechanism](settings);

		}else{
			// Log error
		}
	};

	SASL.prototype.getBestMechanism = function(){

		return this.settings.mechanism;
	};

	SASL.prototype.getResponseChallenge = function(challenge){

		this.state = "CHALLENGED";

		if(challenge){
			this.mechanism.parseChallenge(challenge);
			var responseMechanism = this.mechanism.buildResponse(this.settings.userName, this.settings.pwd);
			return responseMechanism;

		}else{
			// RETURN ERROR
		}

	};

	SASL.prototype.checkServerResponseChallenge = function(challenge){

		if(challenge){

			if(this.mechanism.checkServerResponseChallenge(challenge)){
				this.state = "SUCCESS";
				return true;
			}else{
				//RETURN error
			}
		}else{
			//RETURN ERROR
		}
	};

	return SASL;

});


text:
// Type definitions for URI Template JS 0.3
// Project: https://github.com/fxa/uritemplate-js
// Definitions by: Chui Tey <https://github.com/teyc>
//                 Ruben Taelman <https://github.com/rubensworks>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

export class UriTemplate {
    /**
     * Expands template into a string using parameter
     * supplied
     */
    expand(data: {}): string;
}

export interface UriTemplateErrorOptions {
    expressionText: string;
    message: string;
    position: number;
}

export class UriTemplateError {
    constructor(options: UriTemplateErrorOptions);
}

/**
 * parse template text returning instance of UriTemplate
 * @param template text
 * @return instance of UriTemplate
 * @example
 *   import UriTemplate = require('uritemplate');
 *   let template = UriTemplate.parse('http://localhost/query{?name,city}');
 *   let result   = template.expand({name: 'Jayden', city: 'Wodonga'});
 *   // returns http://localhost/query?name=Jayden&city=Wodonga
 */
export function parse(templateText: string): UriTemplate;


text:
package de.adesso.jenkinshue.common.dto;

import java.io.Serializable;
import java.security.Principal;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 *
 * @author wennier
 *
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PrincipalDTO implements Serializable {

	private static final long serialVersionUID = 2531641403888873781L;

	private Principal principal;

	private long userId;

	private long teamId;

}


text:
id: 5900f4301000cf542c50ff42
challengeType: 5
title: 'Problem 196: Prime triplets'
videoUrl: ''
localeTitle: ''
---

## Description
undefined

## Instructions
undefined

## Tests

```yml
tests:
  - text: ''
    testString: 'assert.strictEqual(euler196(), 322303240771079940, "<code>euler196()</code> should return 322303240771079940.");'

```

## Challenge Seed

```js
function euler196() {
  // Good luck!
  return true;
}

euler196();

```

## Solution

```js
// solution required
```


text:
import React, { useRef, useState } from 'react';
import { useSearchBox } from 'react-instantsearch-hooks';

import { SearchBox as SearchBoxUiComponent } from '../ui/SearchBox';

import type { SearchBoxProps as SearchBoxUiComponentProps } from '../ui/SearchBox';
import type { UseSearchBoxProps } from 'react-instantsearch-hooks';

type UiProps = Pick<
  SearchBoxUiComponentProps,
  | 'inputRef'
  | 'isSearchStalled'
  | 'onChange'
  | 'onReset'
  | 'onSubmit'
  | 'value'
  | 'autoFocus'
  | 'translations'
>;

export type SearchBoxProps = Omit<
  SearchBoxUiComponentProps,
  Exclude<keyof UiProps, 'onSubmit' | 'autoFocus'>
> &
  UseSearchBoxProps & {
    /**
     * Whether to trigger the search only on submit.
     * @default true
     */
    searchAsYouType?: boolean;
    translations?: Partial<UiProps['translations']>;
  };

export function SearchBox({
  queryHook,
  searchAsYouType = true,
  translations,
  ...props
}: SearchBoxProps) {
  const { query, refine, isSearchStalled } = useSearchBox(
    { queryHook },
    { $$widgetType: 'ais.searchBox' }
  );
  const [inputValue, setInputValue] = useState(query);
  const inputRef = useRef<HTMLInputElement>(null);

  function setQuery(newQuery: string) {
    setInputValue(newQuery);

    if (searchAsYouType) {
      refine(newQuery);
    }
  }

  function onReset() {
    setQuery('');

    if (!searchAsYouType) {
      refine('');
    }
  }

  function onChange(event: React.ChangeEvent<HTMLInputElement>) {
    setQuery(event.currentTarget.value);
  }

  function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    if (!searchAsYouType) {
      refine(inputValue);
    }

    if (props.onSubmit) {
      props.onSubmit(event);
    }
  }

  // Track when the InstantSearch query changes to synchronize it with
  // the React state.
  // We bypass the state update if the input is focused to avoid concurrent
  // updates when typing.
  if (query !== inputValue && document.activeElement !== inputRef.current) {
    setInputValue(query);
  }

  const uiProps: UiProps = {
    inputRef,
    isSearchStalled,
    onChange,
    onReset,
    onSubmit,
    value: inputValue,
    translations: {
      submitButtonTitle: 'Submit the search query',
      resetButtonTitle: 'Clear the search query',
      ...translations,
    },
  };

  return <SearchBoxUiComponent {...props} {...uiProps} />;
}


text:
#ifndef RenderInline_h
#define RenderInline_h

#include "core/editing/PositionWithAffinity.h"
#include "core/rendering/InlineFlowBox.h"
#include "core/rendering/RenderBoxModelObject.h"
#include "core/rendering/RenderLineBoxList.h"

namespace blink {

class RenderInline : public RenderBoxModelObject {
public:
    explicit RenderInline(Element*);
    virtual void trace(Visitor*) override;

    static RenderInline* createAnonymous(Document*);

    RenderObject* firstChild() const { ASSERT(children() == virtualChildren()); return children()->firstChild(); }
    RenderObject* lastChild() const { ASSERT(children() == virtualChildren()); return children()->lastChild(); }

    // If you have a RenderInline, use firstChild or lastChild instead.
    void slowFirstChild() const WTF_DELETED_FUNCTION;
    void slowLastChild() const WTF_DELETED_FUNCTION;

    virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0) override;

    Element* node() const { return toElement(RenderBoxModelObject::node()); }

    virtual LayoutUnit marginLeft() const override final;
    virtual LayoutUnit marginRight() const override final;
    virtual LayoutUnit marginTop() const override final;
    virtual LayoutUnit marginBottom() const override final;
    virtual LayoutUnit marginBefore(const RenderStyle* otherStyle = 0) const override final;
    virtual LayoutUnit marginAfter(const RenderStyle* otherStyle = 0) const override final;
    virtual LayoutUnit marginStart(const RenderStyle* otherStyle = 0) const override final;
    virtual LayoutUnit marginEnd(const RenderStyle* otherStyle = 0) const override final;

    virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const override final;
    virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const override;

    virtual LayoutSize offsetFromContainer(const RenderObject*, const LayoutPoint&, bool* offsetDependsOnPoint = 0) const override final;

    IntRect linesBoundingBox() const;
    LayoutRect linesVisualOverflowBoundingBox() const;

    InlineFlowBox* createAndAppendInlineFlowBox();

    void dirtyLineBoxes(bool fullLayout);

    RenderLineBoxList* lineBoxes() { return &m_lineBoxes; }
    const RenderLineBoxList* lineBoxes() const { return &m_lineBoxes; }

    InlineFlowBox* firstLineBox() const { return m_lineBoxes.firstLineBox(); }
    InlineFlowBox* lastLineBox() const { return m_lineBoxes.lastLineBox(); }
    InlineBox* firstLineBoxIncludingCulling() const { return alwaysCreateLineBoxes() ? firstLineBox() : culledInlineFirstLineBox(); }
    InlineBox* lastLineBoxIncludingCulling() const { return alwaysCreateLineBoxes() ? lastLineBox() : culledInlineLastLineBox(); }

    virtual RenderBoxModelObject* virtualContinuation() const override final { return continuation(); }
    RenderInline* inlineElementContinuation() const;

    virtual void updateDragState(bool dragOn) override final;

    LayoutSize offsetForInFlowPositionedInline(const RenderBox& child) const;

    virtual void addFocusRingRects(Vector<LayoutRect>&, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer) const override final;

    using RenderBoxModelObject::continuation;
    using RenderBoxModelObject::setContinuation;

    bool alwaysCreateLineBoxes() const { return alwaysCreateLineBoxesForRenderInline(); }
    void setAlwaysCreateLineBoxes(bool alwaysCreateLineBoxes = true) { setAlwaysCreateLineBoxesForRenderInline(alwaysCreateLineBoxes); }
    void updateAlwaysCreateLineBoxes(bool fullLayout);

    virtual LayoutRect localCaretRect(InlineBox*, int, LayoutUnit* extraWidthToEndOfLine) override final;

    bool hitTestCulledInline(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset);

protected:
    virtual void willBeDestroyed() override;

    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) override;

    virtual void computeSelfHitTestRects(Vector<LayoutRect>& rects, const LayoutPoint& layerOffset) const override;

private:
    virtual RenderObjectChildList* virtualChildren() override final { return children(); }
    virtual const RenderObjectChildList* virtualChildren() const override final { return children(); }
    const RenderObjectChildList* children() const { return &m_children; }
    RenderObjectChildList* children() { return &m_children; }

    virtual const char* renderName() const override;

    virtual bool isRenderInline() const override final { return true; }

    LayoutRect culledInlineVisualOverflowBoundingBox() const;
    InlineBox* culledInlineFirstLineBox() const;
    InlineBox* culledInlineLastLineBox() const;

    template<typename GeneratorContext>
    void generateLineBoxRects(GeneratorContext& yield) const;
    template<typename GeneratorContext>
    void generateCulledLineBoxRects(GeneratorContext& yield, const RenderInline* container) const;

    void addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild);
    virtual void addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild = 0) override final;

    void splitInlines(RenderBlock* fromBlock, RenderBlock* toBlock, RenderBlock* middleBlock,
                      RenderObject* beforeChild, RenderBoxModelObject* oldCont);
    void splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
                   RenderObject* newChild, RenderBoxModelObject* oldCont);

    virtual void layout() override final { ASSERT_NOT_REACHED(); } // Do nothing for layout()

    virtual void paint(PaintInfo&, const LayoutPoint&) override final;

    virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) override final;

    virtual LayerType layerTypeRequired() const override { return isRelPositioned() || createsGroup() || hasClipPath() || style()->shouldCompositeForCurrentAnimations() ? NormalLayer : NoLayer; }

    virtual LayoutUnit offsetLeft() const override final;
    virtual LayoutUnit offsetTop() const override final;
    virtual LayoutUnit offsetWidth() const override final { return linesBoundingBox().width(); }
    virtual LayoutUnit offsetHeight() const override final { return linesBoundingBox().height(); }

    virtual LayoutRect clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* = 0) const override;
    virtual LayoutRect rectWithOutlineForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, LayoutUnit outlineWidth, const PaintInvalidationState* = 0) const override final;
    virtual void mapRectToPaintInvalidationBacking(const RenderLayerModelObject* paintInvalidationContainer, LayoutRect&, const PaintInvalidationState*) const override final;

    virtual void mapLocalToContainer(const RenderLayerModelObject* paintInvalidationContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0, const PaintInvalidationState* = 0) const override;

    virtual PositionWithAffinity positionForPoint(const LayoutPoint&) override final;

    virtual IntRect borderBoundingBox() const override final
    {
        IntRect boundingBox = linesBoundingBox();
        return IntRect(0, 0, boundingBox.width(), boundingBox.height());
    }

    virtual InlineFlowBox* createInlineFlowBox(); // Subclassed by SVG and Ruby

    virtual void dirtyLinesFromChangedChild(RenderObject* child) override final { m_lineBoxes.dirtyLinesFromChangedChild(this, child); }

    virtual LayoutUnit lineHeight(bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const override final;
    virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const override final;

    virtual void childBecameNonInline(RenderObject* child) override final;

    virtual void updateHitTestResult(HitTestResult&, const LayoutPoint&) override final;

    virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) override final;

    virtual void addAnnotatedRegions(Vector<AnnotatedRegionValue>&) override final;

    virtual void updateFromStyle() override final;

    RenderInline* clone() const;

    RenderBoxModelObject* continuationBefore(RenderObject* beforeChild);

    RenderObjectChildList m_children;
    RenderLineBoxList m_lineBoxes;   // All of the line boxes created for this inline flow.  For example, Hello
world. will have two  line boxes.
};

DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderInline, isRenderInline());

} // namespace blink

#endif // RenderInline_h


text:
<resources>

    <dimen name="padding_small">8dp</dimen>
    <dimen name="padding_medium">8dp</dimen>
    <dimen name="padding_large">16dp</dimen>
    <dimen name="image_thumbnail_width">320dp</dimen>
    <dimen name="image_thumbnail_height">133dp</dimen>

    <dimen name="oflc_rating_width">33dp</dimen>
    <dimen name="oflc_rating_height">33dp</dimen>

	<dimen name="image_thumbnail_size">100dp</dimen>
    <dimen name="image_thumbnail_spacing">1dp</dimen>

    <dimen name="the_feed_item_text_separation">24.0dip</dimen>

    <dimen name="thumbnail_background_border_width">1.0dip</dimen>

    <item type="dimen" name="default_video_item_title_font_size">@dimen/large_font_size</item>
    <item type="dimen" name="default_video_item_duration_font_size">@dimen/medium_font_size</item>

    <dimen name="large_font_size">18.0sp</dimen>
    <dimen name="medium_font_size">16.0sp</dimen>

    <dimen name="sliding_menu_width">240dp</dimen>
    <dimen name="slidingmenu_offset">60dp</dimen>

</resources>


text:
Copyright (C) 2011-2013 David McCuskey. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:

The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

--]]

-- VERSION: Modified by David Gross

--====================================================================--
-- DMC Corona Library : DMC Buttons
--====================================================================--

-- Semantic Versioning Specification: http://semver.org/

local VERSION = "0.4.0"

--====================================================================--
-- DMC Corona Library Config
--====================================================================--

--====================================================================--
-- Support Functions

local Utils = {} -- make copying from dmc_utils easier

function Utils.extend( fromTable, toTable )

	function _extend( fT, tT )

		for k,v in pairs( fT ) do

			if type( fT[ k ] ) == "table" and
				type( tT[ k ] ) == "table" then

				tT[ k ] = _extend( fT[ k ], tT[ k ] )

			elseif type( fT[ k ] ) == "table" then
				tT[ k ] = _extend( fT[ k ], {} )

			else
				tT[ k ] = v
			end
		end

		return tT
	end

	return _extend( fromTable, toTable )
end

--====================================================================--
-- Configuration

local dmc_lib_data, dmc_lib_info

-- boot dmc_library with boot script or
-- setup basic defaults if it doesn't exist
--
if false == pcall( function() require( "dmc_corona_boot" ) end ) then
	_G.__dmc_corona = {
		dmc_corona={},
	}
end

dmc_lib_data = _G.__dmc_corona
dmc_lib_info = dmc_lib_data.dmc_library

--====================================================================--
-- DMC Drag Drop
--====================================================================--

--====================================================================--
-- Configuration

dmc_lib_data.dmc_dragdrop = dmc_lib_data.dmc_dragdrop or {}

local DMC_DRAGDROP_DEFAULTS = {
	debug_active=false,
}

local dmc_states_data = Utils.extend( dmc_lib_data.dmc_dragdrop, DMC_DRAGDROP_DEFAULTS )

--====================================================================--
-- Imports
-- =========================================================

-- import DMC Objects file
local Objects = require( "scripts.dmc.dmc_objects" )

-- setup some aliases to make code cleaner
local inheritsFrom = Objects.inheritsFrom
local Object = Objects.Object

local coronaMetaTable = getmetatable( display.getCurrentStage() )

--- Returns true for any object returned from display.new*().
-- note that all Corona types seem to share the same metatable...
local isDisplayObject = function( object )
	return type( object ) == "table" and getmetatable( object ) == coronaMetaTable
end

local color_blue = { 25, 100, 255 }
local color_lightblue = { 90, 170, 255 }
local color_green = { 50, 255, 50 }
local color_lightgreen = { 170, 225, 170 }
local color_red = { 255, 50, 50 }
local color_lightred = { 255, 120, 120 }
local color_grey = { 180, 180, 180 }
local color_lightgrey = { 200, 200, 200 }

-- createSquare()
--
-- function to help create shapes, useful for drag/drop target examples
--
local function createSquare( size, color )
	local s = display.newRect(0, 0, unpack( size ) )
	s.strokeWidth = 3
	s:setFillColor( unpack( color ) )
	s:setStrokeColor( unpack( color_grey ) )

	return s
end

--====================================================================--
-- Drag Drop class
--====================================================================--

local DragDrop = inheritsFrom( Object )
DragDrop.NAME = "Drag Drop"

DragDrop._registered = {}	-- hash of all registered objects
DragDrop._onDragStart = {}	-- list of registered objects with dragStart()
DragDrop._onDragStop = {}	-- list of registered objects with dragStop()

-- property name holding Corona display object
DragDrop.DISPLAY_PROPERTY = "display"

DragDrop.ANIMATE_TIME_SLOW = 500
DragDrop.ANIMATE_TIME_FAST = 200

-- Drag Targets Info
-- a hash, indexed by drag target source
DragDrop._drag_targets = {}

-- Drop Target Info
-- drop_target: object being dropped on, Display Object
-- drop_target: dropped point is selected, Boolean
DragDrop.drop_target = nil
DragDrop.drop_target_accept = false

function DragDrop:setDisplayProperty( name )
	self.DISPLAY_PROPERTY = name
end

function DragDrop:register( obj, params )

	-- create our storage data structure for the object
	local ds = {}
	ds.obj = obj
	ds.call_with_object = false 	-- whether we call using object
	local t
	if not params then
		ds.call_with_object = true
		t = obj
	else
		ds.call_with_object = false
		t = params
	end

	ds.dragStart = t.dragStart or nil
	ds.dragEnter = t.dragEnter or nil
	ds.dragOver = t.dragOver or nil
	ds.dragDrop = t.dragDrop or nil
	ds.dragExit = t.dragExit or nil
	ds.dragStop = t.dragStop or nil

	self._registered[ obj ] = ds

	-- save for lookup optimization
	if ds.dragStart then
		table.insert( self._onDragStart, obj )
	end
	if ds.dragStop then
		table.insert( self._onDragStop, obj )
	end
end

function DragDrop:unregister(obj)
	local registered = {}
	for k,v in pairs(self._registered) do
			if(k ~= obj) then
					registered[k] = v
			end
	end
	self._registered = registered

	local onDragStart = {}
	local currentOnDragStart = self._onDragStart
	if(currentOnDragStart) then
			for _,item in ipairs(currentOnDragStart) do
					if(item ~= nil and item ~= obj) then
							table.insert(onDragStart, item)
					end
			end
			self._onDragStart = onDragStart
	end

	local onDragStop = {}
	local currentOnDragStop = self._onDragStop
	if(currentOnDragStop) then
			for _, item in ipairs(currentOnDragStop) do
					if(item ~= nil and item ~= obj) then
							table.insert(onDragStop, item)
					end
			end
			self._onDragStop = onDragStop
	end

end

function DragDrop:doDrag( drag_orgin, event, drag_op_info )

	--== process Drag Target Info params

	local drag_op_info = drag_op_info or {}

	local size = {
		drag_orgin.width,
		drag_orgin.height
	}
	local drag_proxy = drag_op_info.proxy or createSquare( size, color_lightgrey );

	--== Create data structure for this drag operation

	--[[
		source: dragged item, Display Object / dmc_object
		origin: dragged item origin object, Dislay Object
		format: dragged item data format, String
		data: any data to be sent around, <any>
		x_offset: dragged item x-offset from touch center, Integer
		y_offset: dragged item y-offset from touch center, Integer
		alpha: dragged item alpha, Number
	--]]
	local drag_info = {}

	drag_info.proxy = drag_proxy
	drag_info.origin = drag_orgin
	drag_info.format = drag_op_info.format
	drag_info.data = drag_op_info.data
	drag_info.x_offset = drag_op_info.xOffset or 0
	drag_info.y_offset = drag_op_info.yOffset or 0
	drag_info.alpha = drag_op_info.alpha or 0.5

	DragDrop._drag_targets[ drag_proxy ] = drag_info

	--== Update the Drag Target visual item

	drag_proxy.x = event.x + drag_info.x_offset
	drag_proxy.y = event.y + drag_info.y_offset
	drag_proxy.alpha = drag_info.alpha

	--== Start our drag operation
	drag_proxy.__is_dmc_drag = true
	display.getCurrentStage():setFocus( drag_proxy, event.id )

	self:_doDragStart( drag_proxy )
	self:_startListening( drag_proxy )

end

function DragDrop:_createEventStructure( obj, drag_info, touch )

	local drag_info = drag_info or {}
	local e = {
		target = obj,
		format = drag_info.format,
		data = drag_info.data,
		proxy = drag_info.proxy
	}
	if touch then
		e.x=touch.x
		e.y=touch.y
	end
	return e
end

function DragDrop:_doDragStart( drag_proxy )

	local drag_info = DragDrop._drag_targets[ drag_proxy ]
	local dragList = self._onDragStart
	for i=1, #dragList do

		local o = dragList[ i ]
		local ds = self._registered[ o ]
		local f = ds.dragStart
		local e = self:_createEventStructure( o, drag_info )

		if ds.call_with_object then
			f( o, e )
		else
			f( e )
		end
	end
end

function DragDrop:_doDragStop( drag_proxy )

	local drag_info = DragDrop._drag_targets[ drag_proxy ]
	local dragList = self._onDragStop
	for i=1, #dragList do

		local o = dragList[ i ]
		local ds = self._registered[ o ]
		local f = ds.dragStop
		local e = self:_createEventStructure( o, drag_info )

		if ds.call_with_object then
			f( o, e )
		else
			f( e )
		end
	end
end

function DragDrop:acceptDragDrop()
	DragDrop.drop_target_accept = true
end

function DragDrop:touch( e )

	local proxy = e.target
	local phase = e.phase
	local result = false
	local touch = e

	local drag_info = DragDrop._drag_targets[ proxy ]

	if proxy.__is_dmc_drag then

		if ( phase == "moved" ) then

			-- keep the dragged item moving with the touch coordinates
			proxy.x = e.x + drag_info.x_offset
			proxy.y = e.y + drag_info.y_offset

			-- see if we are over any drop targets
			local newDropTarget = self:_searchDropTargets( e.x, e.y )

			if DragDrop.drop_target == newDropTarget then
				-- same object, so call dragOver()
				if DragDrop.drop_target and DragDrop.drop_target_accept then

					local o = newDropTarget
					local ds = self._registered[ o ]
					local f = ds.dragOver
					if f then
						local e = self:_createEventStructure( o, drag_info, touch )

						if ds.call_with_object then
							result = f( o, e )
						else
							result = f( e )
						end
					end
				end

			elseif DragDrop.drop_target ~= newDropTarget then
				-- new target is nil,
				-- we exited, so call dragExit()
				if DragDrop.drop_target and DragDrop.drop_target_accept then

					local o = DragDrop.drop_target
					local ds = self._registered[ o ]
					local f = ds.dragExit
					if f then
						local e = self:_createEventStructure( o, drag_info, touch )

						if ds.call_with_object then
							result = f( o, e )
						else
							result = f( e )
						end
					end
				end

				self.drop_target_accept = false

				-- call dragEnter on newDropTarget
				if newDropTarget then
					local o = newDropTarget
					local ds = self._registered[ newDropTarget ]
					local f = ds.dragEnter
					if f then
						local e = self:_createEventStructure( o, drag_info, touch )

						if ds.call_with_object then
							result = f( ds.obj, e )
						else
							result = f( e )
						end
					end
				end
			end

			DragDrop.drop_target = newDropTarget

		elseif phase == "ended" or phase == "cancelled" then
			local func

			--if phase == "ended" then

				if DragDrop.drop_target and DragDrop.drop_target_accept then
					-- same object, so call dragDrop()

					local o = DragDrop.drop_target
					local ds = self._registered[ o ]
					local f = ds.dragDrop
					if f then
						local e = self:_createEventStructure( o, drag_info, touch )

						if ds.call_with_object then
							result = f( o, e )
						else
							result = f( e )
						end
					end
					-- keep on Drop Target, and shrink
					--[[
					func = self:_createEndAnimation( { x=o.x, y=o.y,
						time=DragDrop.ANIMATE_TIME_FAST,
						resize=true, drag_proxy=proxy
					})
					--]]
					-- DIG version
					local x,y = e.x, e.y
					func = self:_createEndAnimation( { x=x, y=y,
						time=DragDrop.ANIMATE_TIME_FAST,
						resize=true, drag_proxy=proxy
					})
				else
					-- drop not accepted, so move back to drag origin
					--[[
					func = self:_createEndAnimation({ x=drag_info.origin.x,
						y=drag_info.origin.y, time=DragDrop.ANIMATE_TIME_SLOW,
						resize=false, drag_proxy=proxy
					})
					--]]
					-- DIG version
					local x,y = drag_info.origin:localToContent(0,0)
					func = self:_createEndAnimation({ x=x,
						y=y, time=DragDrop.ANIMATE_TIME_SLOW,
						resize=false, drag_proxy=proxy
					})
				end

			--end

			self.drop_target = nil
			self.drop_target_accept = false

			self:_doDragStop( proxy )
			self:_stopListening( proxy )
			func()

			proxy.__is_dmc_drag = nil
			display.getCurrentStage():setFocus( proxy, nil )

		end
	end

	return result
end

function DragDrop:_createEndAnimation( params )

	local params = params or {}
	local default_transition_time = 600
	local fDelete, doFunc

	local drag_proxy = params.drag_proxy

	-- create final removal
	fDelete = function( e )
		local dt = drag_proxy
		DragDrop._drag_targets[ dt ] = nil
		dt:removeSelf()
		dt = nil
	end

	-- move and/or shrink the object

	local p = {}
	p.onComplete = fDelete
	p.time = params.time or default_transition_time
	p.x = params.x
	p.y = params.y
	if params.resize then
		p.width = 10 ; p.height = 10
	end

	doFunc = function( e )
		transition.to( drag_proxy, p )
	end

	return doFunc
end

function DragDrop:_startListening( drag_proxy )
	local drag_info = DragDrop._drag_targets[ drag_proxy ]
	drag_info.proxy:addEventListener( "touch", self )
end

function DragDrop:_stopListening( drag_proxy )
	local drag_info = DragDrop._drag_targets[ drag_proxy ]
	drag_info.proxy:removeEventListener( "touch", self )
end

function DragDrop:_searchDropTargets( x, y )
	local dropList = self._registered
	for k, _ in pairs( dropList ) do
		local o = k
		if not isDisplayObject( k ) then
			o = k[ DragDrop.DISPLAY_PROPERTY ]
			if o == nil then
				print( "\nWARNING: object not of type Corona Display nor does it have display property '" .. DragDrop.DISPLAY_PROPERTY .. "'\n" )
			end
		end
		local bounds = o.contentBounds

		-- Catch error if target has been removed for some reason.
		if (not bounds) then
			print ("ERROR: DragDrop:_searchDropTargets: The DragDrop target object has disappeared!")
		else
			local isWithinBounds = bounds.xMin <= x and bounds.xMax >= x and bounds.yMin <= y and bounds.yMax >= y
			if isWithinBounds then return k end
		end
	end

	return nil
end

return DragDrop


text:
/*
 * File:   Shift595.h
 * Author: Rick
 *
 * Created on May 11, 2015, 1:44 AM
 */

#ifndef SHIFT595_H
#define	SHIFT595_H

#define num_of_595s 3
#define RegPins num_of_595s * 8

int registers[RegPins];

extern void StartUp595(void);
extern void SetPin595(int Reg, int pin, int value);
extern void Clear595(void);
extern void writeRegisters(void);

#endif	/* SHIFT595_H */


text:
"""
    Kodi urlresolver plugin
    Copyright (C) 2016  alifrezser

    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 3 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, see <http://www.gnu.org/licenses/>.
"""

import re, json
from lib import helpers
from urlresolver9 import common
from urlresolver9.resolver import UrlResolver, ResolverError

class IndavideoResolver(UrlResolver):
    name = "indavideo"
    domains = ["indavideo.hu"]
    pattern = '(?://|\.)(indavideo\.hu)/(?:player/video/|video/)([^/]+)'

    def __init__(self):
        self.net = common.Net()

    def get_media_url(self, host, media_id):
        web_url = self.get_url(host, media_id)
        headers = {'User-Agent': common.FF_USER_AGENT}
        html = self.net.http_GET(web_url, headers=headers).content
        data = json.loads(html)

        if data['success'] == '0':
            html = self.net.http_GET('http://indavideo.hu/video/%s' % media_id).content

            hash = re.search('emb_hash.+?value\s*=\s*"([^"]+)', html)
            if not hash:
                raise ResolverError('File not found')

            web_url = self.get_url(host, hash.group(1))

            html = self.net.http_GET(web_url).content
            data = json.loads(html)

        if data['success'] == '1':
            video_file = data['data']['video_file']
            if video_file == '':
                raise ResolverError('File removed')

            video_file = video_file.rsplit('/', 1)[0] + '/'
            sources = list(set(data['data']['flv_files']))
            sources = [(i.rsplit('.', 2)[-2] + 'p', i.split('?')[0] + '?channel=main') for i in sources]
            sources = sorted(sources, key=lambda x: x[0])[::-1]
            return video_file + helpers.pick_source(sources)

        raise ResolverError('File not found')

    def get_url(self, host, media_id):
        return 'http://amfphp.indavideo.hu/SYm0json.php/player.playerHandler.getVideoData/%s' % (media_id)


text:
package com.datatorrent.lib.db.jdbc;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.List;

import javax.annotation.Nonnull;

import org.junit.Assert;
import org.junit.Test;

import com.google.common.collect.Lists;

import com.datatorrent.api.Attribute;
import com.datatorrent.api.Context;
import com.datatorrent.api.DAG;
import com.datatorrent.lib.helper.OperatorContextTestHelper;
import com.datatorrent.lib.helper.TestPortContext;
import com.datatorrent.lib.testbench.CollectorTestSink;
import com.datatorrent.lib.util.FieldInfo;
import com.datatorrent.lib.util.TestUtils;

/**
 * Tests for {@link AbstractJdbcTransactionableOutputOperator} and
 * {@link AbstractJdbcInputOperator}
 */
public class JdbcPojoOperatorTest extends JdbcOperatorTest
{

  private static class TestOutputOperator extends AbstractJdbcTransactionableOutputOperator<TestEvent>
  {
    private static final String INSERT_STMT = "INSERT INTO " + TABLE_NAME + " values (?)";

    TestOutputOperator()
    {
      cleanTable();
    }

    @Nonnull
    @Override
    protected String getUpdateCommand()
    {
      return INSERT_STMT;
    }

    @Override
    protected void setStatementParameters(PreparedStatement statement, TestEvent tuple) throws SQLException
    {
      statement.setInt(1, tuple.id);
    }

    public int getNumOfEventsInStore()
    {
      Connection con;
      try {
        con = DriverManager.getConnection(URL);
        Statement stmt = con.createStatement();

        String countQuery = "SELECT count(*) from " + TABLE_NAME;
        ResultSet resultSet = stmt.executeQuery(countQuery);
        resultSet.next();
        return resultSet.getInt(1);
      } catch (SQLException e) {
        throw new RuntimeException("fetching count", e);
      }
    }
  }

  private static class TestInputOperator extends AbstractJdbcInputOperator<TestEvent>
  {

    private static final String retrieveQuery = "SELECT * FROM " + TABLE_NAME;

    TestInputOperator()
    {
      cleanTable();
    }

    @Override
    public TestEvent getTuple(ResultSet result)
    {
      try {
        return new TestEvent(result.getInt(1));
      } catch (SQLException e) {
        throw new RuntimeException(e);
      }
    }

    @Override
    public String queryToRetrieveData()
    {
      return retrieveQuery;
    }
  }

  private static class TestPOJOOutputOperator extends JdbcPOJOInsertOutputOperator
  {
    TestPOJOOutputOperator()
    {
      cleanTable();
    }

    public int getNumOfEventsInStore(String tableName)
    {
      Connection con;
      try {
        con = DriverManager.getConnection(URL);
        Statement stmt = con.createStatement();

        String countQuery = "SELECT count(*) from " + tableName;
        ResultSet resultSet = stmt.executeQuery(countQuery);
        resultSet.next();
        return resultSet.getInt(1);
      } catch (SQLException e) {
        throw new RuntimeException("fetching count", e);
      }
    }

    public int getNumOfNullEventsInStore(String tableName)
    {
      Connection con;
      try {
        con = DriverManager.getConnection(URL);
        Statement stmt = con.createStatement();

        String countQuery = "SELECT count(*) from " + tableName + " where name1 is null";
        ResultSet resultSet = stmt.executeQuery(countQuery);
        resultSet.next();
        return resultSet.getInt(1);
      } catch (SQLException e) {
        throw new RuntimeException("fetching count", e);
      }
    }

    private static class TestPOJONonInsertOutputOperator extends JdbcPOJONonInsertOutputOperator
    {
      public TestPOJONonInsertOutputOperator()
      {
        cleanTable();
      }

      public int getNumOfEventsInStore()
      {
        Connection con;
        try {
          con = DriverManager.getConnection(URL);
          Statement stmt = con.createStatement();

          String countQuery = "SELECT count(*) from " + TABLE_POJO_NAME;
          ResultSet resultSet = stmt.executeQuery(countQuery);
          resultSet.next();
          return resultSet.getInt(1);
        } catch (SQLException e) {
          throw new RuntimeException("fetching count", e);
        }
      }

      public int getDistinctNonUnique()
      {
        Connection con;
        try {
          con = DriverManager.getConnection(URL);
          Statement stmt = con.createStatement();

          String countQuery = "SELECT count(distinct(name)) from " + TABLE_POJO_NAME;
          ResultSet resultSet = stmt.executeQuery(countQuery);
          resultSet.next();
          return resultSet.getInt(1);
        } catch (SQLException e) {
          throw new RuntimeException("fetching count", e);
        }
      }
    }
  }

  @Test
  public void testJdbcOutputOperator()
  {
    JdbcTransactionalStore transactionalStore = new JdbcTransactionalStore();
    transactionalStore.setDatabaseDriver(DB_DRIVER);
    transactionalStore.setDatabaseUrl(URL);

    com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap attributeMap = new com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap();
    attributeMap.put(DAG.APPLICATION_ID, APP_ID);
    OperatorContextTestHelper.TestIdOperatorContext context = new OperatorContextTestHelper.TestIdOperatorContext(
        OPERATOR_ID, attributeMap);

    TestOutputOperator outputOperator = new TestOutputOperator();
    outputOperator.setBatchSize(3);
    outputOperator.setStore(transactionalStore);

    outputOperator.setup(context);

    outputOperator.activate(context);
    List<TestEvent> events = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
      events.add(new TestEvent(i));
    }

    outputOperator.beginWindow(0);
    for (TestEvent event : events) {
      outputOperator.input.process(event);
    }
    outputOperator.endWindow();

    Assert.assertEquals("rows in db", 10, outputOperator.getNumOfEventsInStore());
    cleanTable();
  }

  @Test
  public void testJdbcPojoOutputOperator()
  {
    JdbcTransactionalStore transactionalStore = new JdbcTransactionalStore();
    transactionalStore.setDatabaseDriver(DB_DRIVER);
    transactionalStore.setDatabaseUrl(URL);

    com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap attributeMap = new com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap();
    attributeMap.put(DAG.APPLICATION_ID, APP_ID);
    OperatorContextTestHelper.TestIdOperatorContext context = new OperatorContextTestHelper.TestIdOperatorContext(
        OPERATOR_ID, attributeMap);

    TestPOJOOutputOperator outputOperator = new TestPOJOOutputOperator();
    outputOperator.setBatchSize(3);
    outputOperator.setTablename(TABLE_POJO_NAME);

    List<JdbcFieldInfo> fieldInfos = Lists.newArrayList();
    fieldInfos.add(new JdbcFieldInfo("ID", "id", null, Types.INTEGER));
    fieldInfos.add(new JdbcFieldInfo("NAME", "name", null, Types.VARCHAR));
    outputOperator.setFieldInfos(fieldInfos);

    outputOperator.setStore(transactionalStore);

    outputOperator.setup(context);

    Attribute.AttributeMap.DefaultAttributeMap portAttributes = new Attribute.AttributeMap.DefaultAttributeMap();
    portAttributes.put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class);
    TestPortContext tpc = new TestPortContext(portAttributes);
    outputOperator.input.setup(tpc);

    outputOperator.activate(context);

    List<TestPOJOEvent> events = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
      events.add(new TestPOJOEvent(i, "test" + i));
    }

    outputOperator.beginWindow(0);
    for (TestPOJOEvent event : events) {
      outputOperator.input.process(event);
    }
    outputOperator.endWindow();

    Assert.assertEquals("rows in db", 10, outputOperator.getNumOfEventsInStore(TABLE_POJO_NAME));
  }

  /**
   * This test will assume direct mapping for POJO fields to DB columns All
   * fields in DB present in POJO
   */
  @Test
  public void testJdbcPojoInsertOutputOperator()
  {
    JdbcTransactionalStore transactionalStore = new JdbcTransactionalStore();
    transactionalStore.setDatabaseDriver(DB_DRIVER);
    transactionalStore.setDatabaseUrl(URL);

    com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap attributeMap = new com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap();
    attributeMap.put(DAG.APPLICATION_ID, APP_ID);
    OperatorContextTestHelper.TestIdOperatorContext context = new OperatorContextTestHelper.TestIdOperatorContext(
        OPERATOR_ID, attributeMap);

    TestPOJOOutputOperator outputOperator = new TestPOJOOutputOperator();
    outputOperator.setBatchSize(3);
    outputOperator.setTablename(TABLE_POJO_NAME);

    outputOperator.setStore(transactionalStore);

    outputOperator.setup(context);

    Attribute.AttributeMap.DefaultAttributeMap portAttributes = new Attribute.AttributeMap.DefaultAttributeMap();
    portAttributes.put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class);
    TestPortContext tpc = new TestPortContext(portAttributes);
    outputOperator.input.setup(tpc);

    CollectorTestSink<Object> errorSink = new CollectorTestSink<>();
    TestUtils.setSink(outputOperator.error, errorSink);

    outputOperator.activate(context);

    List<TestPOJOEvent> events = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
      events.add(new TestPOJOEvent(i, "test" + i));
    }
    events.add(new TestPOJOEvent(0, "test0")); // Records violating PK constraint
    events.add(new TestPOJOEvent(2, "test2")); // Records violating PK constraint
    events.add(new TestPOJOEvent(10, "test10")); // Clean record
    events.add(new TestPOJOEvent(11, "test11")); // Clean record
    events.add(new TestPOJOEvent(3, "test3")); // Records violating PK constraint
    events.add(new TestPOJOEvent(12, "test12")); // Clean record

    outputOperator.beginWindow(0);
    for (TestPOJOEvent event : events) {
      outputOperator.input.process(event);
    }
    outputOperator.endWindow();

    Assert.assertEquals("rows in db", 13, outputOperator.getNumOfEventsInStore(TABLE_POJO_NAME));
    Assert.assertEquals("Error tuples", 3, errorSink.collectedTuples.size());
  }

  /**
   * This test will assume direct mapping for POJO fields to DB columns All
   * fields in DB present in POJO and will test it for exactly once criteria
   */
  @Test
  public void testJdbcPojoInsertOutputOperatorExactlyOnce()
  {
    JdbcTransactionalStore transactionalStore = new JdbcTransactionalStore();
    transactionalStore.setDatabaseDriver(DB_DRIVER);
    transactionalStore.setDatabaseUrl(URL);

    com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap attributeMap = new com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap();
    attributeMap.put(DAG.APPLICATION_ID, APP_ID);
    OperatorContextTestHelper.TestIdOperatorContext context = new OperatorContextTestHelper.TestIdOperatorContext(
        OPERATOR_ID, attributeMap);

    TestPOJOOutputOperator outputOperator = new TestPOJOOutputOperator();
    outputOperator.setBatchSize(3);
    outputOperator.setTablename(TABLE_POJO_NAME);

    outputOperator.setStore(transactionalStore);

    outputOperator.setup(context);

    Attribute.AttributeMap.DefaultAttributeMap portAttributes = new Attribute.AttributeMap.DefaultAttributeMap();
    portAttributes.put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class);
    TestPortContext tpc = new TestPortContext(portAttributes);
    outputOperator.input.setup(tpc);

    CollectorTestSink<Object> errorSink = new CollectorTestSink<>();
    TestUtils.setSink(outputOperator.error, errorSink);

    outputOperator.activate(context);

    List<TestPOJOEvent> events = Lists.newArrayList();
    for (int i = 0; i < 70; i++) {
      events.add(new TestPOJOEvent(i, "test" + i));
    }

    outputOperator.beginWindow(0);
    for (int i = 0; i < 10; i++) {
      outputOperator.input.process(events.get(i));
    }
    outputOperator.endWindow();

    outputOperator.beginWindow(1);
    for (int i = 10; i < 20; i++) {
      outputOperator.input.process(events.get(i));
    }
    outputOperator.endWindow();

    outputOperator.beginWindow(2);
    for (int i = 20; i < 30; i++) {
      outputOperator.input.process(events.get(i));
    }
    outputOperator.endWindow();

    outputOperator.setup(context);
    outputOperator.input.setup(tpc);
    outputOperator.activate(context);

    outputOperator.beginWindow(0);
    for (int i = 30; i < 40; i++) {
      outputOperator.input.process(events.get(i));
    }
    outputOperator.endWindow();

    outputOperator.beginWindow(1);
    for (int i = 40; i < 50; i++) {
      outputOperator.input.process(events.get(i));
    }
    outputOperator.endWindow();

    outputOperator.beginWindow(2);
    for (int i = 50; i < 60; i++) {
      outputOperator.input.process(events.get(i));
    }

    outputOperator.beginWindow(3);
    for (int i = 60; i < 70; i++) {
      outputOperator.input.process(events.get(i));
    }
    outputOperator.endWindow();

    outputOperator.deactivate();
    outputOperator.teardown();

    Assert.assertEquals("rows in db", 40, outputOperator.getNumOfEventsInStore(TABLE_POJO_NAME));

  }

  /**
   * This test will assume direct mapping for POJO fields to DB columns Nullable
   * DB field missing in POJO name1 field, which is nullable in DB is missing
   * from POJO POJO(id, name) -> DB(id, name1)
   */
  @Test
  public void testJdbcPojoInsertOutputOperatorNullName()
  {
    JdbcTransactionalStore transactionalStore = new JdbcTransactionalStore();
    transactionalStore.setDatabaseDriver(DB_DRIVER);
    transactionalStore.setDatabaseUrl(URL);

    com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap attributeMap = new com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap();
    attributeMap.put(DAG.APPLICATION_ID, APP_ID);
    OperatorContextTestHelper.TestIdOperatorContext context = new OperatorContextTestHelper.TestIdOperatorContext(
        OPERATOR_ID, attributeMap);

    TestPOJOOutputOperator outputOperator = new TestPOJOOutputOperator();
    outputOperator.setBatchSize(3);
    outputOperator.setTablename(TABLE_POJO_NAME_NAME_DIFF);

    outputOperator.setStore(transactionalStore);

    outputOperator.setup(context);

    Attribute.AttributeMap.DefaultAttributeMap portAttributes = new Attribute.AttributeMap.DefaultAttributeMap();
    portAttributes.put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class);
    TestPortContext tpc = new TestPortContext(portAttributes);
    outputOperator.input.setup(tpc);

    outputOperator.activate(context);

    List<TestPOJOEvent> events = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
      events.add(new TestPOJOEvent(i, "test" + i));
    }

    outputOperator.beginWindow(0);
    for (TestPOJOEvent event : events) {
      outputOperator.input.process(event);
    }
    outputOperator.endWindow();

    Assert.assertEquals("rows in db", 10, outputOperator.getNumOfEventsInStore(TABLE_POJO_NAME_NAME_DIFF));
    Assert
        .assertEquals("null name rows in db", 10, outputOperator.getNumOfNullEventsInStore(TABLE_POJO_NAME_NAME_DIFF));
  }

  /**
   * This test will assume direct mapping for POJO fields to DB columns.
   * Non-Nullable DB field missing in POJO id1 field which is non-nullable in DB
   * is missing from POJO POJO(id, name) -> DB(id1, name)
   */
  @Test
  public void testJdbcPojoInsertOutputOperatorNullId()
  {
    JdbcTransactionalStore transactionalStore = new JdbcTransactionalStore();
    transactionalStore.setDatabaseDriver(DB_DRIVER);
    transactionalStore.setDatabaseUrl(URL);

    com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap attributeMap = new com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap();
    attributeMap.put(DAG.APPLICATION_ID, APP_ID);
    OperatorContextTestHelper.TestIdOperatorContext context = new OperatorContextTestHelper.TestIdOperatorContext(
        OPERATOR_ID, attributeMap);

    TestPOJOOutputOperator outputOperator = new TestPOJOOutputOperator();
    outputOperator.setBatchSize(3);
    outputOperator.setTablename(TABLE_POJO_NAME_ID_DIFF);

    outputOperator.setStore(transactionalStore);

    outputOperator.setup(context);

    Attribute.AttributeMap.DefaultAttributeMap portAttributes = new Attribute.AttributeMap.DefaultAttributeMap();
    portAttributes.put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class);
    TestPortContext tpc = new TestPortContext(portAttributes);
    outputOperator.input.setup(tpc);

    boolean exceptionOccurred = false;
    try {
      outputOperator.activate(context);
    } catch (Exception e) {
      exceptionOccurred = true;
      Assert.assertTrue(e instanceof RuntimeException);
      Assert.assertTrue(e.getMessage().toLowerCase().contains("id1 not found in pojo"));
    }
    Assert.assertTrue(exceptionOccurred);
  }

  @Test
  public void testJdbcPojoOutputOperatorMerge()
  {
    JdbcTransactionalStore transactionalStore = new JdbcTransactionalStore();
    transactionalStore.setDatabaseDriver(DB_DRIVER);
    transactionalStore.setDatabaseUrl(URL);

    com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap attributeMap = new com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap();
    attributeMap.put(DAG.APPLICATION_ID, APP_ID);
    OperatorContextTestHelper.TestIdOperatorContext context = new OperatorContextTestHelper.TestIdOperatorContext(
        OPERATOR_ID, attributeMap);

    TestPOJOOutputOperator.TestPOJONonInsertOutputOperator updateOperator = new TestPOJOOutputOperator.TestPOJONonInsertOutputOperator();
    updateOperator.setBatchSize(3);

    updateOperator.setStore(transactionalStore);

    updateOperator.setSqlStatement("MERGE INTO " + TABLE_POJO_NAME + " AS T USING (VALUES (?, ?)) AS FOO(id, name) "
        + "ON T.id = FOO.id " + "WHEN MATCHED THEN UPDATE SET name = FOO.name "
        + "WHEN NOT MATCHED THEN INSERT( id, name ) VALUES (FOO.id, FOO.name);");

    List<JdbcFieldInfo> fieldInfos = Lists.newArrayList();
    fieldInfos.add(new JdbcFieldInfo("id", "id", null, Types.INTEGER));
    fieldInfos.add(new JdbcFieldInfo("name", "name", null, Types.VARCHAR));
    updateOperator.setFieldInfos(fieldInfos);
    updateOperator.setup(context);

    Attribute.AttributeMap.DefaultAttributeMap portAttributes = new Attribute.AttributeMap.DefaultAttributeMap();
    portAttributes.put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class);
    TestPortContext tpc = new TestPortContext(portAttributes);
    updateOperator.input.setup(tpc);

    updateOperator.activate(context);

    List<TestPOJOEvent> events = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
      events.add(new TestPOJOEvent(i, "test" + i));
    }
    for (int i = 0; i < 5; i++) {
      events.add(new TestPOJOEvent(i, "test" + 100));
    }

    updateOperator.getDistinctNonUnique();
    updateOperator.beginWindow(0);
    for (TestPOJOEvent event : events) {
      updateOperator.input.process(event);
    }
    updateOperator.endWindow();

    // Expect 10 unique ids: 0 - 9
    Assert.assertEquals("rows in db", 10, updateOperator.getNumOfEventsInStore());
    // Expect 6 unique name: test-100, test-5, test-6, test-7, test-8, test-9
    Assert.assertEquals("rows in db", 6, updateOperator.getDistinctNonUnique());
  }

  @Test
  public void testJdbcInputOperator()
  {
    JdbcStore store = new JdbcStore();
    store.setDatabaseDriver(DB_DRIVER);
    store.setDatabaseUrl(URL);

    com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap attributeMap = new com.datatorrent.api.Attribute.AttributeMap.DefaultAttributeMap();
    attributeMap.put(DAG.APPLICATION_ID, APP_ID);
    OperatorContextTestHelper.TestIdOperatorContext context = new OperatorContextTestHelper.TestIdOperatorContext(
        OPERATOR_ID, attributeMap);

    TestInputOperator inputOperator = new TestInputOperator();
    inputOperator.setStore(store);
    insertEventsInTable(10);

    CollectorTestSink<Object> sink = new CollectorTestSink<>();
    inputOperator.outputPort.setSink(sink);

    inputOperator.setup(context);
    inputOperator.beginWindow(0);
    inputOperator.emitTuples();
    inputOperator.endWindow();

    Assert.assertEquals("rows from db", 10, sink.collectedTuples.size());
  }

  @Test
  public void testJdbcPojoInputOperator()
  {
    JdbcStore store = new JdbcStore();
    store.setDatabaseDriver(DB_DRIVER);
    store.setDatabaseUrl(URL);

    Attribute.AttributeMap.DefaultAttributeMap attributeMap = new Attribute.AttributeMap.DefaultAttributeMap();
    attributeMap.put(DAG.APPLICATION_ID, APP_ID);
    OperatorContextTestHelper.TestIdOperatorContext context = new OperatorContextTestHelper.TestIdOperatorContext(
        OPERATOR_ID, attributeMap);

    insertEvents(10, true, 0);

    JdbcPOJOInputOperator inputOperator = new JdbcPOJOInputOperator();
    inputOperator.setStore(store);
    inputOperator.setTableName(TABLE_POJO_NAME);

    List<FieldInfo> fieldInfos = Lists.newArrayList();
    fieldInfos.add(new FieldInfo("ID", "id", null));
    fieldInfos.add(new FieldInfo("STARTDATE", "startDate", null));
    fieldInfos.add(new FieldInfo("STARTTIME", "startTime", null));
    fieldInfos.add(new FieldInfo("STARTTIMESTAMP", "startTimestamp", null));
    fieldInfos.add(new FieldInfo("SCORE", "score", FieldInfo.SupportType.DOUBLE));
    inputOperator.setFieldInfos(fieldInfos);

    inputOperator.setFetchSize(5);

    CollectorTestSink<Object> sink = new CollectorTestSink<>();
    inputOperator.outputPort.setSink(sink);

    Attribute.AttributeMap.DefaultAttributeMap portAttributes = new Attribute.AttributeMap.DefaultAttributeMap();
    portAttributes.put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class);
    TestPortContext tpc = new TestPortContext(portAttributes);

    inputOperator.setup(context);
    inputOperator.outputPort.setup(tpc);

    inputOperator.activate(context);

    inputOperator.beginWindow(0);
    inputOperator.emitTuples();
    inputOperator.endWindow();

    Assert.assertEquals("rows from db", 5, sink.collectedTuples.size());
    int i = 0;
    for (Object tuple : sink.collectedTuples) {
      TestPOJOEvent pojoEvent = (TestPOJOEvent)tuple;
      Assert.assertTrue("i=" + i, pojoEvent.getId() == i);
      Assert.assertTrue("date", pojoEvent.getStartDate() instanceof Date);
      Assert.assertTrue("time", pojoEvent.getStartTime() instanceof Time);
      Assert.assertTrue("timestamp", pojoEvent.getStartTimestamp() instanceof Timestamp);
      i++;
    }
    sink.collectedTuples.clear();

    inputOperator.beginWindow(1);
    inputOperator.emitTuples();
    inputOperator.endWindow();

    Assert.assertEquals("rows from db", 5, sink.collectedTuples.size());
    for (Object tuple : sink.collectedTuples) {
      TestPOJOEvent pojoEvent = (TestPOJOEvent)tuple;
      Assert.assertTrue("i=" + i, pojoEvent.getId() == i);
      Assert.assertTrue("date", pojoEvent.getStartDate() instanceof Date);
      Assert.assertTrue("time", pojoEvent.getStartTime() instanceof Time);
      Assert.assertTrue("timestamp", pojoEvent.getStartTimestamp() instanceof Timestamp);
      Assert.assertTrue("score", pojoEvent.getScore() == 55.4);
      i++;
    }

    sink.collectedTuples.clear();

    inputOperator.beginWindow(2);
    inputOperator.emitTuples();
    inputOperator.endWindow();

    Assert.assertEquals("rows from db", 0, sink.collectedTuples.size());

    // Insert 3 more tuples and check if they are read successfully.
    insertEvents(3, false, 10);

    inputOperator.beginWindow(3);
    inputOperator.emitTuples();
    inputOperator.endWindow();

    Assert.assertEquals("rows from db", 3, sink.collectedTuples.size());
    for (Object tuple : sink.collectedTuples) {
      TestPOJOEvent pojoEvent = (TestPOJOEvent)tuple;
      Assert.assertTrue("i=" + i, pojoEvent.getId() == i);
      Assert.assertTrue("date", pojoEvent.getStartDate() instanceof Date);
      Assert.assertTrue("time", pojoEvent.getStartTime() instanceof Time);
      Assert.assertTrue("timestamp", pojoEvent.getStartTimestamp() instanceof Timestamp);
      Assert.assertTrue("score", pojoEvent.getScore() == 55.4);
      i++;
    }
  }

}


text:
package org.gradle.api.internal.tasks.properties;

import org.gradle.internal.file.TreeType;

import javax.annotation.Nullable;
import java.io.File;

public interface OutputFilePropertySpec extends FilePropertySpec {
    TreeType getOutputType();
    @Nullable
    File getOutputFile();
}


text:
import javax.swing.JApplet;

/**
 * A simple applet that can display the messages "Hello World"
 * and "Goodbye World".  The applet contains a button, and it
 * switches from one message to the other when the button is
 * clicked.  The content of the applet is an object of type
 * HelloWorldPanel.
 */

public class HelloWorldApplet2 extends JApplet {
   public void init() {
      HelloWorldPanel content = new HelloWorldPanel();
      setContentPane(content);
   }
}


text:
class AddUniqueIndexOnMembers < ActiveRecord::Migration
  def self.up
    # Clean and reassign MemberRole rows if needed
    MemberRole.delete_all("member_id NOT IN (SELECT id FROM #{Member.table_name})")
    MemberRole.update_all("member_id =" +
      " (SELECT min(m2.id) FROM #{Member.table_name} m1, #{Member.table_name} m2" +
      " WHERE m1.user_id = m2.user_id AND m1.project_id = m2.project_id" +
      " AND m1.id = #{MemberRole.table_name}.member_id)")
    # Remove duplicates
    Member.connection.select_values("SELECT m.id FROM #{Member.table_name} m" +
      " WHERE m.id > (SELECT min(m1.id) FROM #{Member.table_name} m1 WHERE m1.user_id = m.user_id AND m1.project_id = m.project_id)").each do |i|
        Member.delete_all(["id = ?", i])
      end

    # Then add a unique index
    add_index :members, [:user_id, :project_id], :unique => true
  end

  def self.down
    remove_index :members, [:user_id, :project_id]
  end
end


text:
C:\"Program Files\Racket\raco.exe" exe src\waxeye\waxeye.scm
C:\"Program Files\Racket\raco.exe" distribute . src\waxeye\waxeye.exe
DEL src\waxeye\waxeye.exe


text:
var movementControlApi = require('./app/api/movementControlAPI');

// Methods
exports.routes = function(router) {
  router.post('/notifyMovement', movementControlApi.notifyMovementAPI);
};