text:
import typer from 'typer';
import {inject,transient,Container} from 'aurelia-dependency-injection';
import {Config} from 'aurelia-api';
import {metadata} from 'aurelia-metadata';
import {Validator,ValidationRules} from 'aurelia-validation';
import {getLogger} from 'aurelia-logging';

import {AssociationSelect} from './component/association-select';
import {Paged} from './component/paged';

/**
 * The Repository basis class
 */
@inject(Config)
export class Repository {
  transport = null;

  /**
   * Construct.
   *
   * @param {Config} clientConfig
   *
   * @constructor
   */
  constructor(clientConfig) {
    this.clientConfig = clientConfig;
  }

  /**
   * Get the transport for the resource this repository represents.
   *
   * @return {Rest}
   */
  getTransport() {
    if (this.transport === null) {
      this.transport = this.clientConfig.getEndpoint(this.getMeta().fetch('endpoint'));

      if (!this.transport) {
        throw new Error(`No transport found for '${this.getMeta().fetch('endpoint') || 'default'}'.`);
      }
    }

    return this.transport;
  }

  /**
   * Set the associated entity's meta data
   *
   * @param {{}} meta
   */
  setMeta(meta) {
    this.meta = meta;
  }

  /**
   * Get the associated entity's meta data.
   * @return {{}}
   */
  getMeta() {
    return this.meta;
  }

  /**
   * Set the resource
   *
   * @param {string} resource
   * @return {Repository} this
   * @chainable
   */
  setResource(resource) {
    this.resource = resource;

    return this;
  }

  /**
   * Get the resource
   *
   * @return {string|null}
   */
  getResource() {
    return this.resource;
  }

  /**
   * Perform a find query and populate entities with the retrieved data.
   *
   * @param {{}|number|string} criteria Criteria to add to the query. A plain string or number will be used as relative path.
   * @param {boolean}          [raw]    Set to true to get a POJO in stead of populated entities.
   *
   * @return {Promise<Entity|[Entity]>}
   */
  find(criteria, raw) {
    return this.findPath(this.resource, criteria, raw);
  }

  /**
   * Perform a find query and populate entities with the retrieved data, limited to one result.
   *
   * @param {{}|number|string} criteria Criteria to add to the query. A plain string or number will be used as relative path.
   * @param {boolean}          [raw]    Set to true to get a POJO in stead of populated entities.
   *
   * @return {Promise<Entity|[Entity]>}
   */
  findOne(criteria, raw) {
    return this.findPath(this.resource, criteria, raw, true);
  }

  /**
   * Perform a find query for `path` and populate entities with the retrieved data.
   *
   * @param {string}           path
   * @param {{}|number|string} criteria Criteria to add to the query. A plain string or number will be used as relative path.
   * @param {boolean}          [raw]    Set to true to get a POJO in stead of populated entities.
   * @param {boolean}          [single] Whether or not this is a findOne.
   *
   * @return {Promise<Entity|[Entity]>}
   */
  findPath(path, criteria, raw, single) {
    let transport = this.getTransport();
    let findQuery;

    if (single) {
      if (typeof criteria === 'object' && criteria !== null) {
        criteria.limit = 1;
      }

      findQuery = transport.findOne(path, criteria);
    } else {
      findQuery = transport.find(path, criteria);
    }

    if (raw) {
      return findQuery;
    }

    return findQuery
      .then(response => {
        return this.populateEntities(response);
      })
      .then(populated => {
        if (!populated) {
          return null;
        }

        if (!Array.isArray(populated)) {
          return populated.markClean();
        }

        populated.forEach(entity => entity.markClean());

        return populated;
      });
  }

  /**
   * Perform a count on the resource.
   *
   * @param {null|{}} criteria
   *
   * @return {Promise<number>}
   */
  count(criteria) {
    return this.getTransport().find(this.resource + '/count', criteria);
  }

  /**
   * Get new populated entity or entities based on supplied data including associations
   *
   * @param {{}|[{}]} data|[data] The data to populate with
   *
   * @return {Entity|[Entity]}
   */
  populateEntities(data) {
    if (!data) {
      return null;
    }

    if (!Array.isArray(data)) {
      return this.getPopulatedEntity(data);
    }

    let collection = [];

    data.forEach(source => {
      collection.push(this.getPopulatedEntity(source));
    });

    return collection;
  }

  /**
   * Populate a (new) entity including associations
   *
   * @param {{}}     data The data to populate with
   * @param {Entity} [entity] optional. if not set, a new entity is returned
   *
   * @return {Entity}
   */
  getPopulatedEntity(data, entity) {
    entity             = entity || this.getNewEntity();
    let entityMetadata = entity.getMeta();
    let populatedData  = {};
    let key;

    for (key in data) {
      if (!data.hasOwnProperty(key)) {
        continue;
      }

      let value = data[key];

      if (entityMetadata.has('types', key)) {
        populatedData[key] = typer.cast(value, entityMetadata.fetch('types', key));

        continue;
      }

      if (!entityMetadata.has('associations', key) || typeof value !== 'object') {
        // Not an association, or not an object. clean copy.
        populatedData[key] = value;

        continue;
      }

      let repository = this.entityManager.getRepository(entityMetadata.fetch('associations', key).entity);

      populatedData[key] = repository.populateEntities(value);
    }

    return entity.setData(populatedData);
  }

  /**
   * Get a new instance for entityReference.
   *
   * @return {Entity}
   */
  getNewEntity() {
    return this.entityManager.getEntity(this.resource);
  }

  /**
   * Populate a new entity with the empty associations set.
   *
   * @return {Entity}
   */
  getNewPopulatedEntity() {
    let entity       = this.getNewEntity();
    let associations = entity.getMeta().fetch('associations');

    for (let property in associations) {
      if (associations.hasOwnProperty(property)) {
        let assocMeta = associations[property];

        if (assocMeta.type !== 'entity') {
          continue;
        }

        entity[property] = this.entityManager.getRepository(assocMeta.entity).getNewEntity();
      }
    }

    return entity;
  }
}

/**
 * The DefaultRepository class
 * @transient
 */
@transient()
export class DefaultRepository extends Repository {
}

export class OrmMetadata {
  static forTarget(target) {
    return metadata.getOrCreateOwn(Metadata.key, Metadata, target, target.name);
  }
}

/**
 * The MetaData class for Entity and Repository
 *
 */
export class Metadata {
  // The key used to identify this specific metadata
  static key = 'spoonx:orm:metadata';

  /**
   * Construct metadata with sensible defaults (so we can make assumptions in the code).
   */
  constructor() {
    this.metadata = {
      repository  : DefaultRepository,
      resource    : null,
      endpoint    : null,
      name        : null,
      idProperty  : 'id',
      associations: {}
    };
  }

  /**
   * Add a value to an array.
   *
   * @param {string} key
   * @param {*} value
   *
   * @return {Metadata} itself
   * @chainable
*/
  addTo(key, value) {
    if (typeof this.metadata[key] === 'undefined') {
      this.metadata[key] = [];
    } else if (!Array.isArray(this.metadata[key])) {
      this.metadata[key] = [this.metadata[key]];
    }

    this.metadata[key].push(value);

    return this;
  }

  /**
   * Set a value for key, or one level deeper (key.key).
   *
   * @param {string} key
   * @param {string|*} valueOrNestedKey
   * @param {null|*} [valueOrNull]
   *
   * @return {Metadata} itself
   * @chainable
   */
  put(key, valueOrNestedKey, valueOrNull) {
    if (!valueOrNull) {
      this.metadata[key] = valueOrNestedKey;

      return this;
    }

    if (typeof this.metadata[key] !== 'object') {
      this.metadata[key] = {};
    }

    this.metadata[key][valueOrNestedKey] = valueOrNull;

    return this;
  }

  /**
   * Check if key, or key.nested exists.
   *
   * @param {string} key
   * @param {string} [nested]
   *
   * @return {boolean}
   */
  has(key, nested) {
    if (typeof nested === 'undefined') {
      return typeof this.metadata[key] !== 'undefined';
    }

    return typeof this.metadata[key] !== 'undefined' && typeof this.metadata[key][nested] !== 'undefined';
  }

  /**
   * Fetch key or key.nested from metadata.
   *
   * @param {string} key
   * @param {string} [nested]
   *
   * @return {*}
   */
  fetch(key, nested) {
    if (!nested) {
      return this.has(key) ? this.metadata[key] : null;
    }

    if (!this.has(key, nested)) {
      return null;
    }

    return this.metadata[key][nested];
  }
}

/* eslint-disable max-lines */
/**
 * The Entity basis class
 * @transient
 */
@transient()
export class Entity {

  /**
   * Construct a new entity.
   *
   * @param {Validator} validator
   */
  constructor() {
    this
      .define('__meta', OrmMetadata.forTarget(this.constructor))
      .define('__cleanValues', {}, true);
  }

  /**
   * Get the transport for the resource this repository represents.
   *
   * @return {Rest}
   */
  getTransport() {
    return this.getRepository().getTransport();
  }

  /**
   * Get reference to the repository.
   *
   * @return {Repository}
   */
  getRepository() {
    return this.__repository;
  }

  /**
   * Set reference to the repository.
   *
   * @param {Repository} repository
   *
   * @return {Entity} this
   * @chainable
   */
  setRepository(repository) {
    return this.define('__repository', repository);
  }

  /**
   * Define a non-enumerable property on the entity.
   *
   * @param {string}  property
   * @param {*}       value
   * @param {boolean} [writable]
   * @chainable
   *
   * @return {Entity} this
   * @chainable
   */
  define(property, value, writable) {
    Object.defineProperty(this, property, {
      value     : value,
      writable  : !!writable,
      enumerable: false
    });

    return this;
  }

  /**
   * Get the metadata for this entity.
   *
   * @return {Metadata}
   */
  getMeta() {
    return this.__meta;
  }

  /**
   * Get the id property name for this entity.
   *
   * @return {string}
   */
  getIdProperty() {
    return this.getMeta().fetch('idProperty');
  }

  /**
   * Get the id property name of the entity (static).
   *
   * @return {string}
   */
  static getIdProperty() {
    let idProperty = OrmMetadata.forTarget(this).fetch('idProperty');

    return idProperty;
  }

  /**
   * Get the Id value for this entity.
   *
   * @return {number|string}
   */
  getId() {
    return this[this.getIdProperty()];
  }

  /**
   * Set the Id value for this entity.
   *
   * @param {number|string} id
   *
   * @return {Entity}  this
   * @chainable
   */
  setId(id) {
    this[this.getIdProperty()] = id;

    return this;
  }

  /**
   * Persist the entity's state to the server.
   * Either creates a new record (POST) or updates an existing one (PUT) based on the entity's state,
   *
   * @return {Promise}
   */
  save() {
    if (!this.isNew()) {
      return this.update();
    }

    let response;

    return this.getTransport()
      .create(this.getResource(), this.asObject(true))
      .then(created => {
        this.setId(created[this.getIdProperty()]);
        response = created;
      })
      .then(() => this.saveCollections())
      .then(() => this.markClean())
      .then(() => response);
  }

  /**
   * Persist the changes made to this entity to the server.
   *
   * @see .save()
   *
   * @return {Promise}
   *
   * @throws {Error}
   */
  update() {
    if (this.isNew()) {
      throw new Error('Required value "id" missing on entity.');
    }

    // We're clean, no need to update.
    if (this.isClean()) {
      // Always save collections (might have new).
      return this.saveCollections()
        .then(() => this.markClean())
        .then(() => null);
    }

    let requestBody = this.asObject(true);
    let response;

    delete requestBody[this.getIdProperty()];

    return this.getTransport()
      .update(this.getResource(), this.getId(), requestBody)
      .then(updated => { response = updated; })
      .then(() => this.saveCollections())
      .then(() => this.markClean())
      .then(() => response);
  }

  /**
   * Add an entity to a collection (persist).
   *
   * When given entity has data, create the entity and set up the relation.
   *
   * @param {Entity|number} entity     Entity or id
   * @param {string}        [property] The name of the property
   *
   * @return {Promise}
   */
  addCollectionAssociation(entity, property) {
    property = property || getPropertyForAssociation(this, entity);
    let url  = [this.getResource(), this.getId(), property];

    if (this.isNew()) {
      throw new Error('Cannot add association to entity that does not have an id.');
    }

    if (!(entity instanceof Entity)) {
      url.push(entity);

      return this.getTransport().create(url.join('/'));
    }

    if (entity.isNew()) {
      let associationProperty = getPropertyForAssociation(entity, this);
      let relation            = entity.getMeta().fetch('association', associationProperty);

      if (!relation || relation.type !== 'entity') {
        // Many relation, create and then link.
        return entity.save()
          .then(() => {
            if (entity.isNew()) {
              throw new Error('Entity did not return return an id on saving.');
            }

            return this.addCollectionAssociation(entity, property);
          });
      }

      // toOne relation, pass in ID to prevent extra request. Something something performance.
      entity[associationProperty] = this.getId();

      return entity.save()
        .then(() => entity);
    }

    // Entity isn't new, just add id to url.
    url.push(entity.getId());

    return this.getTransport()
      .create(url.join('/'))
      .then(() => entity);
  }

  /**
   * Remove an entity from a collection.
   *
   * @param {Entity|number} entity     Entity or id
   * @param {string}        [property] The name of the property
   *
   * @return {Promise}
   */
  removeCollectionAssociation(entity, property) {
    property       = property || getPropertyForAssociation(this, entity);
    let idToRemove = entity;

    if (entity instanceof Entity) {
      if (!entity.getId()) {
        return Promise.resolve(null);
      }

      idToRemove = entity.getId();
    }

    return this.getTransport().destroy([this.getResource(), this.getId(), property, idToRemove].join('/'));
  }

  /**
   * Persist the collections on the entity.
   *
   * @return {Promise} itself
   */
  saveCollections() {
    let tasks              = [];
    let currentCollections = getCollectionsCompact(this, true);
    let cleanCollections   = this.__cleanValues.data ? this.__cleanValues.data.collections : null;

    let addTasksForDifferences = (base, candidate, method) => {
      if (base === null) {
        return;
      }

      Object.getOwnPropertyNames(base).forEach(property => {
        base[property].forEach(id => {
          if (candidate === null || !Array.isArray(candidate[property]) || candidate[property].indexOf(id) === -1) {
            tasks.push(method.call(this, id, property));
          }
        });
      });
    };

    // Something to add?
    addTasksForDifferences(currentCollections, cleanCollections, this.addCollectionAssociation);

    // Something to remove?
    addTasksForDifferences(cleanCollections, currentCollections, this.removeCollectionAssociation);

    return Promise.all(tasks).then(results => this);
  }

  /**
   * Mark this entity as clean, in its current state.
   *
   * @return {Entity} itself
   * @chainable
   */
  markClean() {
    let cleanValues    = getFlat(this);

    this.__cleanValues = {
      checksum: JSON.stringify(cleanValues),
      data    : cleanValues
    };

    return this;
  }

  /**
   * Return if the entity is clean.
   *
   * @return {boolean}
   */
  isClean() {
    return getFlat(this, true) === this.__cleanValues.checksum;
  }

  /**
   * Return if the entity is dirty.
   *
   * @return {boolean}
   */
  isDirty() {
    return !this.isClean();
  }

  /**
   * Return if the entity is new (ergo, hasn't been persisted to the server).
   *
   * @return {boolean}
   */
  isNew() {
    return !this.getId();
  }

  /**
   * Resets the entity to the clean state
   *
   * @param {boolean} [shallow]
   *
   * @return {Entity} itself
   */
  reset(shallow) {
    let pojo     = {};
    let metadata = this.getMeta();

    Object.keys(this).forEach(propertyName => {
      let value       = this[propertyName];
      let association = metadata.fetch('associations', propertyName);

      // No meta data, no value or no association property: simple assignment.
      if (!association || !value) {
        pojo[propertyName] = value;

        return;
      }
    });

    if (this.isClean()) {
      return this;
    }

    let isNew        = this.isNew();
    let associations = this.getMeta().fetch('associations');

    Object.keys(this).forEach(propertyName => {
      if (Object.getOwnPropertyNames(associations).indexOf(propertyName) === -1) {
        delete this[propertyName];
      }
    });

    if (isNew) {
      return this.markClean();
    }

    this.setData(this.__cleanValues.data.entity);

    if (shallow) {
      return this.markClean();
    }

    let collections = this.__cleanValues.data.collections;

    Object.getOwnPropertyNames(collections).forEach(index => {
      this[index] = [];
      collections[index].forEach(entity => {
        if (typeof entity === 'number') {
          this[index].push(entity);
        }
      });
    });

    return this.markClean();
  }

  /**
   * Get the resource name of this entity's reference (static).
   *
   * @return {string|null}
   */
  static getResource() {
    return OrmMetadata.forTarget(this).fetch('resource');
  }

  /**
   * Get the resource name of this entity instance
   *
   * @return {string|null}
   */
  getResource() {
    return this.__resource || this.getMeta().fetch('resource');
  }

  /**
   * Set this instance's resource.
   *
   * @param {string} resource
   *
   * @return {Entity} itself
   * @chainable
   */
  setResource(resource) {
    return this.define('__resource', resource);
  }

  /**
   * Destroy this entity (DELETE request to the server).
   *
   * @return {Promise}
   */
  destroy() {
    if (!this.getId()) {
      throw new Error('Required value "id" missing on entity.');
    }

    return this.getTransport().destroy(this.getResource(), this.getId());
  }

  /**
   * Get the name of the entity. This is useful for labels in texts.
   *
   * @return {string}
   */
  getName() {
    let metaName = this.getMeta().fetch('name');

    if (metaName) {
      return metaName;
    }

    return this.getResource();
  }

  /**
   * Get the name of the entity (static). This is useful for labels in texts.
   *
   * @return {string}
   */
  static getName() {
    let metaName = OrmMetadata.forTarget(this).fetch('name');

    if (metaName) {
      return metaName;
    }

    return this.getResource();
  }

  /**
   * Set data on this entity.
   *
   * @param {{}} data
   * @param {boolean} markClean
   * @return {Entity} itself
   * @chainable
   */
  setData(data, markClean) {
    Object.assign(this, data);

    if (markClean) {
      this.markClean();
    }

    return this;
  }

  /**
   * Set the validator instance.
   *
   * @param {Validator} validator
   * @return {Entity} itself
   * @chainable
   */
  setValidator(validator) {
    this.define('__validator', validator);

    return this;
  }

  /**
   * Get the validator instance.
   *
   * @return {Validator}
   */
  getValidator() {
    if (!this.hasValidation()) {
      return null;
    }

    return this.__validator;
  }

  /**
   * Check if entity has validation enabled.
   *
   * @return {boolean}
   */
  hasValidation() {
    return !!this.getMeta().fetch('validation');
  }

  /**
   * Validates the entity
   *
   * @param {string|null} propertyName Optional. The name of the property to validate. If unspecified,
   * all properties will be validated.
   * @param {Rule<*, *>[]|null} rules Optional. If unspecified, the rules will be looked up using
   * the metadata for the object created by ValidationRules....on(class/object)
   * @return {Promise<ValidationError[]>}
   */
  validate(propertyName, rules) {
    // entities without validation are to be considered valid
    if (!this.hasValidation()) {
      return Promise.resolve([]);
    }

    return propertyName ? this.getValidator().validateProperty(this, propertyName, rules)
                        : this.getValidator().validateObject(this, rules);
  }

  /**
   * Get the data in this entity as a POJO.
   *
   * @param {boolean} [shallow]
   *
   * @return {{}}
   */
  asObject(shallow) {
    return asObject(this, shallow);
  }

  /**
   * Get the data in this entity as a json string.
   *
   * @param {boolean} [shallow]
   *
   * @return {string}
   */
  asJson(shallow) {
    return asJson(this, shallow);
  }
}

/**
 * Entity representation as pojo.
 *
 * @param {Entity} entity
 * @param {boolean} [shallow]
 *
 * @return {{}}
 */
function asObject(entity, shallow) {
  let pojo     = {};
  let metadata = entity.getMeta();

  Object.keys(entity).forEach(propertyName => {
    let value       = entity[propertyName];
    let association = metadata.fetch('associations', propertyName);

    // No meta data, no value or no association property: simple assignment.
    if (!association || !value) {
      pojo[propertyName] = value;

      return;
    }

    // When shallow, we only assign toOne associations.
    if (shallow) {
      if (association.type === 'collection') {
        return;
      }

      if (value instanceof Entity && value.getId()) {
        pojo[propertyName] = value.getId();

        return;
      }

      if (value instanceof Entity) {
        pojo[propertyName] = value.asObject();

        return;
      }

      if (['string', 'number', 'boolean'].indexOf(typeof value) > -1 || value.constructor === Object) {
        pojo[propertyName] = value;

        return;
      }
    }

    // Array, treat children as potential entities.
    if (!Array.isArray(value)) {
      // Single value not an instance of entity? Simple assignment.
      pojo[propertyName] = !(value instanceof Entity) ? value : value.asObject(shallow);

      return;
    }

    let asObjects = [];

    value.forEach(childValue => {
      if (typeof childValue !== 'object') {
        return;
      }

      if (!(childValue instanceof Entity)) {
        asObjects.push(childValue);

        return;
      }

      // If shallow, we don't handle toMany.
      if (!shallow || (typeof childValue === 'object' && !childValue.getId())) {
        asObjects.push(childValue.asObject(shallow));
      }
    });

    // We don't send along empty arrays.
    if (asObjects.length > 0) {
      pojo[propertyName] = asObjects;
    }
  });

  return pojo;
}

/**
 * Entity representation as json
 *
 * @param {Entity} entity
 * @param {boolean} [shallow]
 *
 * @return {string}
 */
function asJson(entity, shallow) {
  let json;

  try {
    json = JSON.stringify(asObject(entity, shallow));
  } catch (error) {
    json = '';
  }

  return json;
}

/**
 * Get a compact object of collections (arrays of ids)
 *
 * @param {Entity}  forEntity
 * @param {boolean} [includeNew]
 *
 * @return {{}}
 */
function getCollectionsCompact(forEntity, includeNew) {
  let associations = forEntity.getMeta().fetch('associations');
  let collections  = {};

  Object.getOwnPropertyNames(associations).forEach(index => {
    let association = associations[index];

    if (association.type !== 'collection') {
      return;
    }

    collections[index] = [];
    if (!Array.isArray(forEntity[index])) {
      return;
    }

    forEntity[index].forEach(entity => {
      if (typeof entity === 'number') {
        collections[index].push(entity);

        return;
      }

      if (!(entity instanceof Entity)) {
        return;
      }

      if (entity.getId()) {
        collections[index].push(entity.getId());

        return;
      }

      if (includeNew) {
        collections[index].push(entity);

        return;
      }
    });
  });

  return collections;
}

/**
 * Get a flat, plain representation of the entity and its associations.
 *
 * @param {Entity}  entity
 * @param {boolean} [json]
 *
 * @return {{}} {entity, collections}
 */
function getFlat(entity, json) {
  let flat = {
    entity     : asObject(entity, true),
    collections: getCollectionsCompact(entity)
  };

  if (json) {
    flat = JSON.stringify(flat);
  }

  return flat;
}

/**
 * Get the property of the association on this entity.
 *
 * @param {Entity} forEntity
 * @param {Entity} entity
 *
 * @return {string}
 */
function getPropertyForAssociation(forEntity, entity) {
  let associations = forEntity.getMeta().fetch('associations');

  return Object.keys(associations).filter(key => {
    return associations[key].entity === entity.getResource();
  })[0];
}

/**
 * Set the id property for en entity
 *
 * @export
 * @param {string} propertyName
 * @returns {function}
 *
 * @decorator
 */
export function idProperty(propertyName) {
  return function(target) {
    OrmMetadata.forTarget(target).put('idProperty', propertyName);
  };
}

/**
 * Set the 'name' metadata on the entity
 *
 * @param {string} entityName=target.name.toLowerCase The (custom) name to use
 *
 * @return {function}
 *
 * @decorator
 */
export function name(entityName) {
  return function(target) {
    OrmMetadata.forTarget(target).put('name', entityName || target.name.toLowerCase());
  };
}

/**
 * Set the repositoryReference metadata on the entity
 *
 * @param {string} repositoryReference The repository reference to use
 *
 * @return {function}
 *
 * @decorator
 */
export function repository(repositoryReference) {
  return function(target) {
    OrmMetadata.forTarget(target).put('repository', repositoryReference);
  };
}

/**
 * Set the 'resourceName' metadata on the entity
 *
 * @param {string} resourceName The name of the resource
 *
 * @return {function}
 *
 * @decorator
 */
export function resource(resourceName) {
  return function(target) {
    OrmMetadata.forTarget(target).put('resource', resourceName || target.name.toLowerCase());
  };
}

/**
 * Set the 'validation' metadata to 'true'
 *
 * @param {[function]} ValidatorClass = Validator
 *
 * @return {function}
 *
 * @decorator
 */
export function validation(ValidatorClass = Validator) {
  return function(target) {
    OrmMetadata.forTarget(target).put('validation', ValidatorClass);
  };
}

/**
 * The EntityManager class
 */
@inject(Container)
export class EntityManager {
  repositories = {};
  entities     = {};

  /**
   * Construct a new EntityManager.
   *
   * @param {Container} container
   */
  constructor(container) {
    this.container = container;
  }

  /**
   * Register an array of entity classes.
   *
   * @param {function[]|function} EntityClasses Array or object of Entity constructors.
   *
   * @return {EntityManager} itself
   * @chainable
   */
  registerEntities(EntityClasses) {
    for (let property in EntityClasses) {
      if (EntityClasses.hasOwnProperty(property)) {
        this.registerEntity(EntityClasses[property]);
      }
    }

    return this;
  }

  /**
   * Register an Entity class.
   *
   * @param {function} EntityClass
   *
   * @return {EntityManager} itself
   * @chainable
   */
  registerEntity(EntityClass) {
    this.entities[OrmMetadata.forTarget(EntityClass).fetch('resource')] = EntityClass;

    return this;
  }

  /**
   * Get a repository instance.
   *
   * @param {Entity|string} entity
   *
   * @return {Repository}
   * @throws {Error}
   */
  getRepository(entity) {
    let reference = this.resolveEntityReference(entity);
    let resource  = entity;

    if (typeof reference.getResource === 'function') {
      resource = reference.getResource() || resource;
    }

    if (typeof resource !== 'string') {
      throw new Error('Unable to find resource for entity.');
    }

    // Cached instance available. Return.
    if (this.repositories[resource]) {
      return this.repositories[resource];
    }

    // Get instance of repository
    let metaData   = OrmMetadata.forTarget(reference);
    let repository = metaData.fetch('repository');
    let instance   = this.container.get(repository);

    // Already setup instance? Return.
    if (instance.meta && instance.resource && instance.entityManager) {
      return instance;
    }

    // Tell the repository instance what resource it should use.
    instance.setMeta(metaData);
    instance.resource      = resource;
    instance.entityManager = this;

    if (instance instanceof DefaultRepository) {
      // This is a default repository. We'll cache this instance.
      this.repositories[resource] = instance;
    }

    return instance;
  }

  /**
   * Resolve given resource value to an entityReference
   *
   * @param {Entity|string} resource
   *
   * @return {Entity}
   * @throws {Error}
   */
  resolveEntityReference(resource) {
    let entityReference = resource;

    if (typeof resource === 'string') {
      entityReference = this.entities[resource] || Entity;
    }

    if (typeof entityReference === 'function') {
      return entityReference;
    }

    throw new Error('Unable to resolve to entity reference. Expected string or function.');
  }

  /**
   * Get an instance for `entity`
   *
   * @param {string|Entity} entity
   *
   * @return {Entity}
   */
  getEntity(entity) {
    let reference = this.resolveEntityReference(entity);
    let instance  = this.container.get(reference);
    let resource  = reference.getResource();

    if (!resource) {
      if (typeof entity !== 'string') {
        throw new Error('Unable to find resource for entity.');
      }

      resource = entity;
    }

    // Set the validator.
    if (instance.hasValidation() && !(instance.getValidator())) {
      let validator = this.container.get(OrmMetadata.forTarget(reference).fetch('validation'));

      instance.setValidator(validator);
    }

    return instance.setResource(resource).setRepository(this.getRepository(resource));
  }
}

/**
 * Set the 'resource' metadata and enables validation on the entity
 *
 * @param {string} resourceName The name of the resource
 * @param {[function]} ValidatorClass = Validator
 *
 * @return {function}
 *
 * @decorator
 */
export function validatedResource(resourceName, ValidatorClass) {
  return function(target, propertyName) {
    resource(resourceName)(target);
    validation(ValidatorClass)(target, propertyName);
  };
}

// added for bundling
// eslint-disable-line no-unused-vars
// eslint-disable-line no-unused-vars

/**
 * Plugin configure
 *
 * @export
 * @param {*} frameworkConfig
 * @param {*} configCallback
 */
export function configure(frameworkConfig, configCallback) {
  // add hasAssociation custom validation rule
  ValidationRules.customRule(
    'hasAssociation',
    value => !!((value instanceof Entity && typeof value.id === 'number') || typeof value === 'number'),
    `\${$displayName} must be an association.`    // eslint-disable-line quotes
  );

  let entityManagerInstance = frameworkConfig.container.get(EntityManager);

  configCallback(entityManagerInstance);

  frameworkConfig.globalResources('./component/association-select');
  frameworkConfig.globalResources('./component/paged');
}

export const logger = getLogger('aurelia-orm');

/**
* Set generic 'data' metadata.
*
 * @param {{}} metaData The data to set
 *
 * @returns {function}
 *
 * @decorator
 */
export function data(metaData) {
  /**
   * @param {function} target
   * @param {string} propertyName
   */
  return function(target, propertyName) {
    if (typeof metaData !== 'object') {
      logger.error('data must be an object, ' + typeof metaData + ' given.');
    }

    OrmMetadata.forTarget(target.constructor).put('data', propertyName, metaData);
  };
}

/**
 * Set the 'endpoint' metadta of an entity. Needs a set resource
 *
 * @param {string} entityEndpoint The endpoint name to use
 *
 * @return {function}
 *
 * @decorator
 */
export function endpoint(entityEndpoint) {
  return function(target) {
    if (!OrmMetadata.forTarget(target).fetch('resource')) {
      logger.warn('Need to set the resource before setting the endpoint!');
    }

    OrmMetadata.forTarget(target).put('endpoint', entityEndpoint);
  };
}

// fix for babels property decorator
export function ensurePropertyIsConfigurable(target, propertyName, descriptor) {
  if (descriptor && descriptor.configurable === false) {
    descriptor.configurable = true;

    if (!Reflect.defineProperty(target, propertyName, descriptor)) {
      logger.warn(`Cannot make configurable property '${propertyName}' of object`, target);
    }
  }
}

/**
 * Associate a property with an entity (toOne) or a collection (toMany)
 *
 * @param {undefined|string|{}} associationData undefined={entity:propertyName}, string={entity:string}, Object={entity: string, collection: string}
 *
 * @return {function}
 *
 * @decorator
 */
export function association(associationData) {
  return function(target, propertyName, descriptor) {
    ensurePropertyIsConfigurable(target, propertyName, descriptor);

    if (!associationData) {
      associationData = {entity: propertyName};
    } else if (typeof associationData === 'string') {
      associationData = {entity: associationData};
    }

    OrmMetadata.forTarget(target.constructor).put('associations', propertyName, {
      type  : associationData.entity ? 'entity' : 'collection',
      entity: associationData.entity || associationData.collection
    });
  };
}

/**
 * Registers the 'enumerations' for an attribute's values
 *
 * @param {*[]} values - a list of valid values for the entity's attribute
 *
 * @return {Function}
 *
 * @decorator
 */
export function enumeration(values) {
  return function(target, propertyName, descriptor) {
    ensurePropertyIsConfigurable(target, propertyName, descriptor);

    OrmMetadata.forTarget(target.constructor).put('enumerations', propertyName, values);
  };
}

/**
 * Set the 'types' metadata on the entity
 *
 * @param {string} typeValue The type(text,string,date,datetime,integer,int,number,float,boolean,bool,smart,autodetect (based on value)) to use for this property using typer
 *
 * @return {function}
 *
 * @decorator
 */
export function type(typeValue) {
  return function(target, propertyName, descriptor) {
    ensurePropertyIsConfigurable(target, propertyName, descriptor);

    OrmMetadata.forTarget(target.constructor).put('types', propertyName, typeValue);
  };
}


text:
package com.avast.cactus.grpc.server

import cats.MonadError
import cats.data.EitherT
import cats.syntax.all._
import com.avast.cactus.grpc._
import io.grpc._

import scala.collection.immutable
import scala.language.higherKinds
import scala.util.control.NonFatal
class ServerInterceptorsWrapper[F[_]](interceptors: immutable.Seq[ServerAsyncInterceptor[F]])(implicit F: MonadError[F, Throwable]) {
  def withInterceptors[Resp](serverCall: => F[Either[StatusException, Resp]]): F[Either[StatusException, Resp]] = {

    val context = Context.current()

    // load headers previously stored in context
    Option(MetadataContextKey.get(context)) match {
      case Some(headers) =>
        try {
          val resolvedInterceptors = {
            val s = EitherT[F, StatusException, GrpcMetadata] {
              F.pure(Right(GrpcMetadata(context, headers)))
            }

            interceptors
              .foldLeft(s) { case (prev, int) => prev.flatMap(r => EitherT(int(r)).leftMap(new StatusException(_))) }
              .value
          }

          resolvedInterceptors
            .flatMap {
              case Right(GrpcMetadata(ctx, _)) =>
                ctx
                  .call(() => { serverCall })

              case Left(statusException) => F.raiseError[Either[StatusException, Resp]](statusException)
            }
            .recover(ServerCommonMethods.recoverWithStatus)
        } catch {
          case NonFatal(e) =>
            F.pure {
              Left(new StatusException(Status.INTERNAL.withCause(e).withDescription("Request could not been processed")))
            }
        }

      case None =>
        F.pure {
          Left(new StatusException(Status.INTERNAL.withDescription("Could not extract metadata from the context, possible bug?")))
        }
    }

  }
}

redpajama_set_name: RedPajamaGithub


text:
package acme;

public interface iSuperToon {
  void pouet();
  void clap();

}


text:
layout: post
title:  "hybris如何加载property文件"
date:   2016-05-11 14:39:00
categories: hybris
author: eli
tags: property configuration
excerpt: property优先级以及在hybris中如何读取property文件
---
* content
{:toc}

## hybris中是如何加载property文件的?

众所周知,hybris是基于spring的,so 它也是利用spring来加载的。

### 那么spring是怎么加载的呢?

它可以这样做:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-4.2.xsd">

      <context:property-placeholder location="classpath:foo.properties" />

</beans>
```

也可以这样干:

```xml
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
    <list>
      <value>classpath:foo.properties</value>
    </list>
  </property>
  <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
```
或者这样也行:

```java

@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {

   @Bean
   public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
      return new PropertySourcesPlaceholderConfigurer();
   }
}

```

### spring又是如何读取的呢?

在xml中你可以这样做:

```xml

<bean id="dataSource">
  <property name="url" value="${jdbc.url}" />
</bean>

```

在javabean中你需要这样做:

```java

@Value( "${jdbc.url}" )
private String jdbcUrl;
```

### hybris 又是如何做的?

跟spring类似,你只需要这样:

```xml
<bean class="Foo">
  <property name="bar" value="${key_of_property}"/>
</bean>

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="properties" ref="hybrisProperties"/>
</bean>

```
你也可以自定义它:

```xml
bean id="testBean" class="org.training.TestBean">
    <property name="value" value="${custom.property}"/>
</bean>
<bean id="customPropertyPlaceholderConfigurer" class="org.training.CustomPropertyPlaceholderConfigurer">
    <property name="properties" ref="hybrisProperties"/>
    <property name="order" value="1000"/>
</bean>
```

**需要注意的是 order 的值必须小于 99999**

```java

package org.training;

import java.util.Properties;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class CustomPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer
{
    @Override
    protected String resolvePlaceholder(final String placeholder, final Properties props, final int systemPropertiesMode)
    {
        if("custom.property".equals(placeholder)){
            return "custom.value";
        }
        return null;
    }
}
```

幸运的是hybris中有一个接口 **ConfigurationService**,通常情况下,我们可以直接使用它。它的默认实现是 **DefaultConfigurationService**.

你可以这样用:

```java
//fetch the commons configuration instance
Configuration cfg = configurationService.getConfiguration();

//there are various convenience methods
String strgValue = cfg.getString("key");
boolean boolValue = cfg.getBoolean("key");
int intValue = cfg.getInt("key");
BigDecimal bd = cfg.getBigDecimal("key");

//optional default values can be passed as a second parameter
strgValue = cfg.getString("key", "defaultValue");

//listeners can be registered
final ConfigurationListener listener = new ConfigurationListener()
{
    public void configurationChanged(final ConfigurationEvent event)
    {
        //listener gets invoked before and after the value gets changed
        boolean isBefore = event.isBeforeUpdate();
        Object value = event.getPropertyValue();
        String key = event.getPropertyName();
    }
};
((HybrisConfiguration)cfg).addConfigurationListener(listener);
```

###  hybris中有很多property文件,如local.property,project.property等等,那它们有优先级吗?

>当然有

--------------------------------

**place of definition**

local.properties file

**location**

${HYBRIS_CONFIG_DIR}

**Priority**

Highest

**Overrides**

* extension-specific
  * project.properties files
* project.properties files
* application code defaults

**Overridden by**

(N/A)

-------------------------------

**place of definition**

* extension-specific
  * project.properties file

**location**

${EXTENSION_DIR}

**Priority**

High

**Overrides**

* project.properties file
* application code defaults

**Overridden by**

local.properties file

-----------------------------------

**place of definition**

hybris Platform project.properties file

**location**

${HYBRIS_BIN_DIR}/platform

**Priority**

Medium

**Overrides**

application code defaults

**Overridden by**

* local.properties file
* extension-specific
  * project.properties files

------------------------------

**place of definition**

Application code

**location**

Application code
When a property is not configured, a default value from the application code is used.

**Priority**

Low

**Overrides**

(N/A)

**Overridden by**

* local.properties file
* extension-specific
  * project.properties files
* project.properties file

-------------------------------------------


text:
package io.fabric8.agent.repository;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import io.fabric8.common.util.json.JsonReader;

/**
 */
public class HttpMetadataProvider implements MetadataProvider {

    public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
    public static final String HEADER_CONTENT_ENCODING = "Content-Encoding";
    public static final String GZIP = "gzip";

    private final String url;
    private long lastModified;
    private Map<String, Map<String, String>> metadatas;

    public HttpMetadataProvider(String url) {
        this.url = url;
    }

    @Override
    public long getLastModified() {
        return lastModified;
    }

    @Override
    public Map<String, Map<String, String>> getMetadatas() {
        try {
            HttpURLConnection.setFollowRedirects(false);
            HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
            if (lastModified > 0) {
                con.setIfModifiedSince(lastModified);
            }
            con.setRequestProperty(HEADER_ACCEPT_ENCODING, GZIP);
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                lastModified = con.getLastModified();
                InputStream is = con.getInputStream();
                if (GZIP.equals(con.getHeaderField(HEADER_CONTENT_ENCODING))) {
                    is = new GZIPInputStream(is);
                }
                metadatas = verify(JsonReader.read(is));
            } else if (con.getResponseCode() != HttpURLConnection.HTTP_NOT_MODIFIED) {
                throw new IOException("Unexpected http response: "
                        + con.getResponseCode() + " " + con.getResponseMessage());
            }
            return metadatas;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private Map<String, Map<String, String>> verify(Object value) {
        Map<?,?> obj = Map.class.cast(value);
        for (Map.Entry<?,?> entry : obj.entrySet()) {
            String.class.cast(entry.getKey());
            Map<?,?> child = Map.class.cast(entry.getValue());
            for (Map.Entry<?,?> ce : child.entrySet()) {
                String.class.cast(ce.getKey());
                String.class.cast(ce.getValue());
            }
        }
        return (Map<String, Map<String, String>>) obj;
    }

}


text:
import sqlite3
import urllib
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup, NavigableString
from phyllo.phyllo_logger import logger
import nltk
from itertools import cycle

nltk.download('punkt')

from nltk import sent_tokenize

global chapter

def parseRes2(soup, title, url, cur, author, date, collectiontitle):
    chapter = 'COSMO MEDICES II'
    [e.extract() for e in soup.find_all('br')]
    getp = soup.find_all('p')[:-1]
    j=1
    for p in getp:
        # make sure it's not a paragraph without the main text
        try:
            if p['class'][0].lower() in ['border', 'pagehead', 'shortborder', 'smallboarder', 'margin',
                                         'internal_navigation']:  # these are not part of the main t
                continue
        except:
            pass
        sen=p.text
        if sen.startswith('Magna equidem in hac'):
            chapter='ASTRONOMICUS NUNCIUS'
        i=1
        for s in sent_tokenize(sen):
            sentn=s.strip()
            num=i
            cur.execute("INSERT INTO texts VALUES (?,?,?,?,?,?,?, ?, ?, ?, ?)",
                        (None, collectiontitle, title, 'Latin', author, date, chapter,
                         num, sentn, url, 'prose'))
            i+=1
        j+=1

def main():
    # get proper URLs
    siteURL = 'http://www.thelatinlibrary.com'
    biggsURL = 'http://www.thelatinlibrary.com/galileo/galileo.sid.html'
    biggsOPEN = urllib.request.urlopen(biggsURL)
    biggsSOUP = BeautifulSoup(biggsOPEN, 'html5lib')
    textsURL = []

    # remove some unnecessary urls
    while ("http://www.thelatinlibrary.com/index.html" in textsURL):
        textsURL.remove("http://www.thelatinlibrary.com/index.html")
        textsURL.remove("http://www.thelatinlibrary.com/classics.html")
        textsURL.remove("http://www.thelatinlibrary.com/neo.html")
    logger.info("\n".join(textsURL))

    title='SERENISSIMO'

    author = 'Galileo Galilei'
    author = author.strip()
    collectiontitle='SIDEREUS NUNCIUS'
    date = '1610'

    with sqlite3.connect('texts.db') as db:
        c = db.cursor()
        c.execute(
        'CREATE TABLE IF NOT EXISTS texts (id INTEGER PRIMARY KEY, title TEXT, book TEXT,'
        ' language TEXT, author TEXT, date TEXT, chapter TEXT, verse TEXT, passage TEXT,'
        ' link TEXT, documentType TEXT)')
        c.execute("DELETE FROM texts WHERE author = 'Galileo Galilei'")
        parseRes2(biggsSOUP, title, biggsURL, c, author, date, collectiontitle)

if __name__ == '__main__':
    main()


text:
package io.aeron.cluster.service;

import org.agrona.DirectBuffer;
import org.agrona.concurrent.status.CountersReader;

import static org.agrona.concurrent.status.CountersReader.NULL_COUNTER_ID;
import static org.agrona.concurrent.status.CountersReader.RECORD_ALLOCATED;
import static org.agrona.concurrent.status.CountersReader.TYPE_ID_OFFSET;

/**
 * The counter that represent the role a node is playing in a cluster.
 */
public class ClusterNodeRole
{
    /**
     * Counter type id for the cluster node role.
     */
    public static final int CLUSTER_NODE_ROLE_TYPE_ID = 201;

    /**
     * Find the active counter id for a cluster node role.
     *
     * @param counters to search within.
     * @return the counter id if found otherwise {@link CountersReader#NULL_COUNTER_ID}.
     */
    public static int findCounterId(final CountersReader counters)
    {
        final DirectBuffer buffer = counters.metaDataBuffer();

        for (int i = 0, size = counters.maxCounterId(); i < size; i++)
        {
            if (counters.getCounterState(i) == RECORD_ALLOCATED)
            {
                final int recordOffset = CountersReader.metaDataOffset(i);

                if (buffer.getInt(recordOffset + TYPE_ID_OFFSET) == CLUSTER_NODE_ROLE_TYPE_ID)
                {
                    return i;
                }
            }
        }

        return NULL_COUNTER_ID;
    }
}


text:
ALDynamicBuffer::ALDynamicBuffer(size_t originSize)
{
    ALASSERT(originSize>0);
    mSize = 0;
    mContent = (char*)::malloc(originSize*sizeof(char));
    ALASSERT(NULL!=mContent);
    mCapacity = originSize;
}

ALDynamicBuffer::~ALDynamicBuffer()
{
    ::free(mContent);
}
void ALDynamicBuffer::load(const char* src, size_t len)
{
    ALASSERT(NULL!=src);
    ALASSERT(len>0);
    if (mCapacity < len + mSize)
    {
        int enlargeNumber = (len+mSize+mCapacity-1)/mCapacity;
        char* newContent = (char*)malloc(mCapacity*enlargeNumber*sizeof(char));
        mCapacity = mCapacity*enlargeNumber;
        ::memcpy(newContent, mContent, mSize*sizeof(char));
        ::free(mContent);
        mContent = newContent;
    }
    ALASSERT(mCapacity >= len + mSize);
    ::memcpy(mContent+mSize, src, len*sizeof(char));
    mSize+=len;
}
void ALDynamicBuffer::reset()
{
    mSize = 0;
}


text:
package com.tfc.library;

import android.app.Application;

import com.tfc.library.ui.widget.BaseToast;

/**
 * author @Fobid
 */
public class BaseApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        BaseToast.init(this);
    }
}


text:
'use strict'

let { red, bold, gray, options: colorette } = require('colorette')

let terminalHighlight = require('./terminal-highlight')

class CssSyntaxError extends Error {
  constructor (message, line, column, source, file, plugin) {
    super(message)
    this.name = 'CssSyntaxError'
    this.reason = message

    if (file) {
      this.file = file
    }
    if (source) {
      this.source = source
    }
    if (plugin) {
      this.plugin = plugin
    }
    if (typeof line !== 'undefined' && typeof column !== 'undefined') {
      this.line = line
      this.column = column
    }

    this.setMessage()

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CssSyntaxError)
    }
  }

  setMessage () {
    this.message = this.plugin ? this.plugin + ': ' : ''
    this.message += this.file ? this.file : '<css input>'
    if (typeof this.line !== 'undefined') {
      this.message += ':' + this.line + ':' + this.column
    }
    this.message += ': ' + this.reason
  }

  showSourceCode (color) {
    if (!this.source) return ''

    let css = this.source
    if (color == null) color = colorette.enabled
    if (terminalHighlight) {
      if (color) css = terminalHighlight(css)
    }

    let lines = css.split(/\r?\n/)
    let start = Math.max(this.line - 3, 0)
    let end = Math.min(this.line + 2, lines.length)

    let maxWidth = String(end).length

    let mark, aside
    if (color) {
      mark = text => bold(red(text))
      aside = text => gray(text)
    } else {
      mark = aside = str => str
    }

    return lines
      .slice(start, end)
      .map((line, index) => {
        let number = start + 1 + index
        let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | '
        if (number === this.line) {
          let spacing =
            aside(gutter.replace(/\d/g, ' ')) +
            line.slice(0, this.column - 1).replace(/[^\t]/g, ' ')
          return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^')
        }
        return ' ' + aside(gutter) + line
      })
      .join('\n')
  }

  toString () {
    let code = this.showSourceCode()
    if (code) {
      code = '\n\n' + code + '\n'
    }
    return this.name + ': ' + this.message + code
  }
}

module.exports = CssSyntaxError
CssSyntaxError.default = CssSyntaxError


text:
import org.hamcrest.CoreMatchers;
import org.jetbrains.annotations.Nullable;
import org.assertj.core.api.Assertions;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

class Contracts {

  private void checkNotNullValue(@Nullable Object o) {
    assertThat(o, CoreMatchers.<Object>notNullValue());
    System.out.println(o.hashCode());
  }

  private void checkIsNotNullValue(@Nullable Object o) {
    assertThat(o, CoreMatchers.is(CoreMatchers.<Object>notNullValue()));
    System.out.println(o.hashCode());
  }

  private void checkNotEqualToNull(@Nullable String test) {
    assertThat("String is null", test, not(equalTo(null)));
    int length = test.length();
  }

  public void checkAssertJ(@Nullable Object object, @Nullable Object object2) {
    Assertions.assertThat(object).isNotNull();
    System.out.println(object.toString());

    Assertions.assertThat(object2).describedAs("x").isNotNull();
    System.out.println(object2.toString());
  }

}


text:
'use strict';

angular.module('notifications').directive('notifications', [
	function() {
		return {
			restrict: 'E',
			templateUrl: 'modules/notifications/views/notifications.client.view.html'
		};
	}
]);


text:
<?php
include('dbconn.php');
Session_start();
$tref= $_POST['tref'];
$tac= $_POST['tac'];
$ubal= $_POST['bal'];
$uid= $_SESSION['id'];
$sql = mysql_query("select * from account where ac_number=".$tref);
$row= mysql_fetch_array($sql);
$t_cid= $row['customer_id'];
$row = mysql_num_rows($sql);
date_default_timezone_set('Asia/dhaka');
$t = time();
$t = date("Y-m-d H:i:s", $t);
if ($row == 1){
if ($ubal >= $tac ){
	$sql ="update account set balance=".$ubal."-".$tac." where customer_id=$uid" ;
	if (!mysql_query($sql)) {
	die('Error: ' . mysql_error());
	}
	$sql ="insert into transaction (transaction_type , amount, time, transaction_account, customer_id) values ('Wire Transfer-Out', $tac,'$t', $tref , $uid ) " ;
	if (!mysql_query($sql)) {
	die('Error: ' . mysql_error());
	}
	$sql ="update account set balance=balance+$tac where ac_number=$tref" ;
	if (!mysql_query($sql)) {
	die('Error: ' . mysql_error());
	}
	$sql ="insert into transaction (transaction_type , amount, time, transaction_account, customer_id) values ('Wire Transfer-IN', $tac, '$t' , $tref , $t_cid ) " ;
	if (!mysql_query($sql)) {
	die('Error: ' . mysql_error());
	}
}else{
	echo "insufficient fund";
}
}else{
	echo "invalid account";
}

mysql_close();

header ('location:send.php' );
?>


text:
<!doctype html>

<meta charset="utf-8">
<title>Page Not Found – Blog Title</title>
<meta name="description" content="Page not found. Your pixels are in another canvas.">

<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@aron_bordin">
<meta name="twitter:creator" content="@aron_bordin">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Page Not Found">
<meta property="og:description" content="Page not found. Your pixels are in another canvas.">
<meta property="og:url" content="http://aronbordin.com/neo-hpstr-jekyll-theme/404.html">
<meta property="og:site_name" content="Blog Title">
<meta property="og:image" content="http://aronbordin.com/neo-hpstr-jekyll-theme/images/images/logo.png">

<link rel="canonical" href="http://aronbordin.com/neo-hpstr-jekyll-theme/404.html">
<link href="http://aronbordin.com/neo-hpstr-jekyll-theme/feed.xml" type="application/atom+xml" rel="alternate" title="Blog Title Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>

<link rel="stylesheet" href="http://aronbordin.com/neo-hpstr-jekyll-theme/assets/css/main.css">
<link rel="stylesheet" href="http://aronbordin.com/neo-hpstr-jekyll-theme/assets/css/jquery.mmenu.all.css">
<link rel="stylesheet" href="http://aronbordin.com/neo-hpstr-jekyll-theme/assets/css/jquery.floating-social-share.min.css">

<link href="//fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic" rel="stylesheet" type="text/css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="http://aronbordin.com/neo-hpstr-jekyll-theme/favicon.ico">

<link rel="shortcut icon" href="http://aronbordin.com/neo-hpstr-jekyll-theme/favicon.png">

<link rel="apple-touch-icon-precomposed" href="http://aronbordin.com/neo-hpstr-jekyll-theme/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://aronbordin.com/neo-hpstr-jekyll-theme/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://aronbordin.com/neo-hpstr-jekyll-theme/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://aronbordin.com/neo-hpstr-jekyll-theme/images/apple-touch-icon-144x144-precomposed.png">

           Blog Title

Favorites

Code Highlighter

Sample Post

Categories

image

intro

sample

Tags

Install

Fork

Home

Page Not Found

<time> </time>

Home

Fork

Install

Tags

Categories

image

intro

sample

Favorites

Code Highlighter

Sample Post

    | Follow @aron_bordin

Sorry, but the page you were trying to view does not exist — perhaps you can try searching for it below.

    © 2016 Your name. Powered by Jekyll using the Neo-HPSTR Theme.


text:
package domain.models;

public class Jogador {
    private String nome;
    private String imagem;

    public Jogador(String nome, String imagem) {
        this.nome = nome;
        this.imagem = imagem;
    }

    public String getNome() {
        return nome;
    }

    public String getImagem() {
        return imagem;
    }
}


text:
/* @flow */

'use strict';

var _Object$defineProperty = require('babel-runtime/core-js/object/define-property')['default'];

var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];

_Object$defineProperty(exports, '__esModule', {
    value: true
});

exports['default'] = translateImplements;

var _assert = require('assert');

var _assert2 = _interopRequireDefault(_assert);

var _rx = require('rx');

var _rx2 = _interopRequireDefault(_rx);

var _extAttrs = require('./extAttrs');

var _extAttrs2 = _interopRequireDefault(_extAttrs);

var _type = require('./type');

var _type2 = _interopRequireDefault(_type);

var _concatIfAny = require('../concatIfAny');

var _concatIfAny2 = _interopRequireDefault(_concatIfAny);

var _FormattingToken = require('../FormattingToken');

var _FormattingToken2 = _interopRequireDefault(_FormattingToken);

var literal = _rx2['default'].Observable.of;

function translateImplements(node) {
    (0, _assert2['default'])(node.type === 'implements', 'Expected IdlImplements, found ' + node.type);

    return (0, _concatIfAny2['default'])((0, _extAttrs2['default'])(node), literal(_FormattingToken2['default'].newlineIndent)).concat(literal(_FormattingToken2['default'].enterComment), (0, _type2['default'])(node.target), literal(' implements '), (0, _type2['default'])(node['implements']), literal(_FormattingToken2['default'].exitComment));
}

module.exports = exports['default'];
//# sourceMappingURL=implements.js.map


text:
package com.github.vedenin.project_parser.crawlers;

import com.github.vedenin.project_parser.containers.ProjectContainer;

import java.util.List;
import java.util.Map;

/**
 * Returns Programming Projects from awesome lists or useful links
 *
 * Created by Slava Vedenin on 6/6/2016.
 */
public interface DownloadProjects {
    /**
     * Returns sections that has non-projects links (like websites or articles)
     *
     * @return list of sections that has non-projects links (like websites or articles)
     */
    List<String> getSkippedSections(String url);

    /**
     * Return list of java projects from awesome lists or useful links:
     *
     * @param url - url's from useful-java-links
     * @return java projects
     */
    Map<String, ProjectContainer> getProjects(String url);
}


text:
package xyz.vsngamer.elevatorid.client.gui;

import net.minecraft.client.gui.components.Checkbox;
import net.minecraft.network.chat.Component;

class FunctionalCheckbox extends Checkbox {

    private final Toggleable onPress;

    FunctionalCheckbox(int xIn, int yIn, int widthIn, int heightIn, Component text, boolean defaultValue, Toggleable onPress) {
        super(xIn, yIn, widthIn, heightIn, text, defaultValue);

        this.onPress = onPress;
    }

    @Override
    public void onPress() {
        super.onPress();
        onPress.onPress(selected());
    }

    @FunctionalInterface
    public interface Toggleable {
        void onPress(boolean value);
    }
}


text:
import * as React from 'react';
import styles from './Themes.module.scss';
import { IThemesProps } from './IThemesProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { DetailsList, DetailsListLayoutMode } from 'office-ui-fabric-react';

interface Window {
  __themeState__: any;
}

declare var window: Window;

export default class Themes extends React.Component<IThemesProps, void> {

  public render(): React.ReactElement<IThemesProps> {
    let _columns = [
      {
        key: 'column1',
        name: 'Name',
        fieldName: 'name',
        minWidth: 100,
        maxWidth: 200,
        isResizable: true
      },
      {
        key: 'column2',
        name: 'Value',
        fieldName: 'value',
        minWidth: 100,
        maxWidth: 400,
        isResizable: true
      },
    ];

    const items = this.getThemeVariablesItems();

    return (

{'This web part shows usage of SharePoint Themes.'}

{'Background color of paragraphs is set to "primaryBackgroud", variables list backogrud color is set to "themePrimary", font color is set to "primaryText"'}

{'Full list of available theme variables is available in windows.__themeState__.theme property and listed below'}

{'You can use theme variables in your .scss files like $yourVariable:"[theme:primaryBackground, default:#0273eb]"'}

{'Change the theme (Site Settings -> Change the look) and see what\'s happenning'}

        <DetailsList
        className={styles.themePrimary}
          items={items}
          columns={_columns}
          layoutMode={DetailsListLayoutMode.justified}
          viewport={{
            width: 750,
            height: 500
          }}
        />

    );
  }

  private getThemeVariablesItems(): Array<any> {
    const variables: any = window.__themeState__.theme;
    const items = [];

    for (let varName in variables) {
      if (!variables.hasOwnProperty(varName))
        continue;

      items.push({
        key: varName,
        name: varName,
        value: variables[varName]
      });
    }

    return items;
  }
}


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [PDFMargin](./puppeteer.pdfmargin.md) > [top](./puppeteer.pdfmargin.top.md)

## PDFMargin.top property

<b>Signature:</b>

```typescript
top?: string | number;
```


text:
package ru.job4j.tracker;

import java.util.ArrayList;

/**
 * Class Item суперкласс для трекера. Содержит конструктор,
 * методы геторы и сеторы, поле коментариев и создания.
 * @author bobrov
 * @since 30.09.17
 */
public class Item {
    private int id;
    private String name;
    private String desc;
    private String created;

    private ArrayList<String> comments;

    Item() { }

    Item(int id, String name, String desc) {
        this.id = id;
        this.name = name;
        this.desc = desc;
    }

    Item(int id, String name, String desc, String created, ArrayList<String> comments) {
        this.id = id;
        this.name = name;
        this.desc = desc;
        this.created = created;
        this.comments = comments;
    }

    int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }

    String getName() {
        return this.name;
    }

    String getDesc() {
        return this.desc;
    }

    public String getCreated() {
        return this.created;
    }

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

    public ArrayList<String> getComments() {
        return this.comments;
    }

    @Override
    public boolean equals(Object obj) {
        return this.name.equals(((Item) obj).name) && this.desc.equals(((Item) obj).desc);
    }
}


text:
namespace blink {

uint32_t AtomicStringToFourByteTag(AtomicString tag) {
  DCHECK_EQ(tag.length(), 4u);
  return (((tag[0]) << 24) | ((tag[1]) << 16) | ((tag[2]) << 8) | (tag[3]));
}

AtomicString FourByteTagToAtomicString(uint32_t tag) {
  constexpr size_t tag_size = 4;
  LChar tag_string[tag_size] = {(tag >> 24) & 0xFF, (tag >> 16) & 0xFF,
                                (tag >> 8) & 0xFF, tag & 0xFF};
  return AtomicString(tag_string, tag_size);
}

unsigned FontVariationSettings::GetHash() const {
  unsigned computed_hash = size() ? 5381 : 0;
  unsigned num_features = size();
  for (unsigned i = 0; i < num_features; ++i) {
    StringHasher string_hasher;
    const AtomicString& tag = at(i).Tag();
    for (unsigned j = 0; j < tag.length(); j++) {
      string_hasher.AddCharacter(tag[j]);
    }
    WTF::AddIntToHash(computed_hash, string_hasher.GetHash());
    WTF::AddFloatToHash(computed_hash, at(i).Value());
  }
  return computed_hash;
}

}  // namespace blink


text:
<?php
	class Circleflip_recent_post_widget extends WP_Widget {
		function __construct() {
			parent::__construct(false, 'CF Recent Posts Thumbnails');
		}
		function form($instance) {
			// outputs the options form on admin
			$title = isset($instance['title']) ? ($instance['title']) : 'Recent Posts';
			$number = isset($instance['number']) ? ($instance['number']) : '6';
		 	?>

<label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php _e('Title:','circleflip'); ?> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr($title); ?>" />

<label for="<?php echo esc_attr($this->get_field_id('number')); ?>"><?php _e('Number of posts to show:','circleflip'); ?> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('number')); ?>" name="<?php echo esc_attr($this->get_field_name('number')); ?>" type="text" value="<?php echo esc_attr($number); ?>" />

		 	<?php
		}
		function update($new_instance, $old_instance) {
			// processes widget options to be saved
			$instance = $old_instance;
			$instance['title'] = strip_tags($new_instance['title']);
			$instance['number'] = strip_tags($new_instance['number']);
			return $instance;
		}
		function widget($args, $instance) {
			// outputs the content of the widget
			wp_enqueue_style('recent_posts',get_template_directory_uri() . "/css/widgets/recent_posts.css",'2.0.3');
			extract( $args );
			$title = apply_filters('widget_title', $instance['title']);
			$number = apply_filters('widget_number', $instance['number']);
			if($args['id'] == 'sidebar-footerwidgetarea')
				 $footer_width = 'span'.circleflip_calculate_widget_width();
			else
				$footer_width = '';
			 ?>
				<li class="recentPost widget customWidget <?php echo esc_attr($footer_width) ?>">
					<?php if($title != null) { ?>

<?php echo esc_html($title);?>

					<?php }
					 $args = array(
						'numberposts' => -1,
				       	'orderby' => 'date',
				       	'order' => 'DESC',
						 'suppress_filters' => false,
				    );
						$posts = get_posts($args);
						$x = 0;
						$y = 0;
						$numberPost = 0;
						foreach ($posts as $post) {
							if(get_the_post_thumbnail($post->ID, 'cf-recent-posts') != null) {
								if($number < count($posts) ){
									if($numberPost == $number){
										break;
									}
									$numberPost++;
								}
							if($x == $y+6 || $x == 0){
								$x = $y;

								?>

						 <?php	} ?>

								<a href="<?php echo esc_url(get_permalink($post->ID)); ?>"><?php echo get_the_post_thumbnail($post->ID, 'cf-recent-posts'); ?>

							<?php
							$x++;
							if($x == $y+6){
							?>

							<?php }
							}
						}
					?>

			<?php }
		}
	register_widget('Circleflip_recent_post_widget');


text:
<?php

namespace Jumph\Bundle\EmailBundle\Filter\Subscriber;

use Lexik\Bundle\FormFilterBundle\Event\ApplyFilterEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class FilterSubscriber implements EventSubscriberInterface
{
    /**
     * Events to listen to.
     *
     * @return Array An array with events to listen to
     */
    public static function getSubscribedEvents()
    {
        return array(
            // if a Doctrine\ORM\QueryBuilder is passed to the lexik_form_filter.query_builder_updater service
            'lexik_form_filter.apply.orm.email_filter_name' => array('filterName'),

            // if a Doctrine\DBAL\Query\QueryBuilder is passed to the lexik_form_filter.query_builder_updater service
            'lexik_form_filter.apply.dbal.email_filter_name' => array('filterName'),
        );
    }

    /**
     * A listener for the filter type filterName.
     *
     * @param ApplyFilterEvent $event A LexikFormFilter event
     */
    public function filterName(ApplyFilterEvent $event)
    {
        $qb     = $event->getQueryBuilder();
        $expr   = $event->getFilterQuery()->getExpr();
        $values = $event->getValues();

        if (!empty($values['value'])) {
            $qb->andWhere(
                $expr->orX()
                    ->add($expr->like('e.subject', "'%".$values['value']."%'"))
            );
        }

    }
}


text:
'use strict';

module.exports = function(app) {
	//var users = require('../../app/controllers/users.server.controller');
	var boards = require('../../app/controllers/boards.server.controller');

	// Boards Routes
	app.route('/boards')
		.get(boards.list);

	app.route('/boards/:boardName')
		.post(boards.create)
		.get(boards.listArticles);

	app.route('/boards/write/:boardName')
		.get(boards.read)
		.post(boards.writeArticle);

	app.route('/boards/edit/:boardName')
		.put(boards.update);

	app.route('/boards/destroy/:boardName')
		.delete(boards.destroy);

	app.route('/boards/:boardName/:articleTitle')
		.get(boards.readArticle);

	app.route('/boards/:boardName/:articleTitle/edit')
		.put(boards.updateArticle);

	app.route('/boards/:boardName/:articleTitle/delete')
		.delete(boards.deleteArticle);

	app.route('/comment/create')
		.post(boards.createComment);

	app.route('/comment/delete')
		.delete(boards.deleteComment);

	app.route('/comment/update')
		.put(boards.updateComment);

	app.route('/tags')
		.get(boards.listTags);

	// Finish by binding the Board middleware
	app.param('boardId', boards.boardByID);
};


text:
package alltests;
import java.util.*;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MTMOrgDAO extends SquallDAO<MTMOrg> {

    // in construcorMethod.ftl
    protected MTMOrgDAO()
    {

        try {
            createPreparedStatements();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    void createPreparedStatements() throws SQLException {
    }
	// writeTransforms
	@Override
	protected MTMOrg _transformSingleResultSet(ResultSet rs )   throws SQLException {
		MTMOrg  mtmorg = new MTMOrg();
		mtmorg.id = rs.getLong("id");
		// writeTransforms - specified relations
		mtmorg.name = rs.getString("name");
		// writeTransforms - oppositeRelations
		mtmorg.isDirty = false;
		return mtmorg;
	}

	// writeTransforms
	@Override
	protected List<MTMOrg> _transformResultSet(ResultSet rs)  throws SQLException {
		List<MTMOrg> ret = new ArrayList<MTMOrg>();
		while ( rs.next() ) {
			ret.add(_transformSingleResultSet(rs));
		}
		return ret;
	}
    // in storeMethod.ftl
    @Override
    protected Long _store( MTMOrg mtmorg ) throws SQLException
    {
        List<String> updates = new ArrayList<String>();
        Long id = null;
        String query = "INSERT INTO MTMOrg ( name ) values (" +
	"" + sanitizeValue(mtmorg.name)+ ")";
        if ( PRINT_SQL ) log(query);
        // Get row id, special case for SQLite
        if (vendor.equals(DatabaseVendor.SQLITE)) {
        SquallQueryResult queryResult = this.executeQuery("SELECT last_insert_rowid()");
            if (queryResult.resultSet.next()) {
                id = queryResult.resultSet.getLong(1);
                queryResult.close();
            }
        } else {
            id = this.executeUpdateAndReturnId(query);

        }

        mtmorg.id = id;

		//Writing first class relations
		//Writing opposite relations
		if (mtmorg.mtmuser != null ) {
			updates.add("DELETE FROM MTMOrg_MTMUser WHERE MTMOrg_id = " + mtmorg.id );
			for ( MTMUser x : mtmorg.mtmuser) {
				if ( x.isDirty ) {
					//if ( !x.orgs.contains(mtmorg) ) { x.orgs.add(mtmorg); }
					MTMUserDAO.upsert(x);
				}
				updates.add("INSERT INTO MTMOrg_MTMUser ( MTMOrg_id , MTMUser_id ) VALUES ( " + mtmorg.id + "," + x.id + ")" );
			}
		}
		for ( String update : updates ) { log(update); this.executeUpdate(update); }
		mtmorg.isDirty = false;
		mtmorg.id = id;
		return id;
	}
	// in updateMethod.ftl
	@Override
	protected Long _update(MTMOrg mtmorg) throws  SQLException {
		String query =  "UPDATE  MTMOrg SET " +
	"name = " + sanitizeValue(mtmorg.name)+ " WHERE id = " + mtmorg.id + "";
		List<String> updates = new ArrayList<String>();
		if ( PRINT_SQL ) log(query);
		this.executeUpdate(query);		//Writing first class relations
		//Writing opposite relations
			if ( mtmorg.mtmuser != null ) {
				updates.add("DELETE FROM MTMOrg_MTMUser WHERE MTMOrg_id = " + mtmorg.id );
				for ( MTMUser x : mtmorg.mtmuser) {
					if ( x.isDirty ) {
						// if ( !x.orgs.contains(mtmorg) ) { x.orgs.add(mtmorg); }
						MTMUserDAO.upsert(x);
					}
				updates.add("INSERT INTO MTMOrg_MTMUser ( MTMOrg_id , MTMUser_id ) VALUES ( " + mtmorg.id + "," + x.id + ")" );
				}
			}
		for ( String update : updates ) { log(update); this.executeUpdate(update); }
		mtmorg.isDirty = false;
		return mtmorg.id;
	}

    // Here we fake static inheritance through some helper methods, got to be a better way than this.
    protected static Long update(MTMOrg mtmorg) throws  SQLException { return getInstance()._update(mtmorg); }
    public static Long upsert(MTMOrg mtmorg) throws  SQLException { return getInstance()._upsert(mtmorg); }

    public static List<MTMOrg> find(String whereClause, String sortColumn, Integer lowerLimit, Integer upperLimit) throws SQLException { return getInstance()._find(whereClause, sortColumn, lowerLimit, upperLimit); }
    public static List<MTMOrg> find(String whereClause, String sortColumn) throws SQLException { return getInstance()._find(whereClause, sortColumn); }
    public static List<MTMOrg> find(String whereClause) throws SQLException { return getInstance()._find(whereClause); }

    // These are only for ManyToMany lookups.
    public static List<MTMOrg> findRelated(String relatedClass, Long id) throws SQLException { return getInstance()._findRelated(relatedClass, id); }
    public static List<MTMOrg> findRelated(String relatedClass, Long id, String whereClause) throws SQLException { return getInstance()._findRelated(relatedClass, id, whereClause); }
    public static List<MTMOrg> findRelated(String relatedClass, Long id, String whereClause, String sortColumn) throws SQLException { return getInstance()._findRelated(relatedClass, id, whereClause, sortColumn); }
    public static List<MTMOrg> findRelated(String relatedClass, Long id, String whereClause, String sortColumn, Integer lowerLimit, Integer upperLimit) throws SQLException { return getInstance()._findRelated(relatedClass, id, whereClause, sortColumn, lowerLimit, upperLimit ); }

    public static List<MTMOrg> findOppositeRelated(String relatedClass, Long id) throws SQLException { return getInstance()._findOppositeRelated(relatedClass, id); }
    public static List<MTMOrg> findOppositeRelated(String relatedClass, Long id, String whereClause) throws SQLException { return getInstance()._findOppositeRelated(relatedClass, id, whereClause); }
    public static List<MTMOrg> findOppositeRelated(String relatedClass, Long id, String whereClause, String sortColumn) throws SQLException { return getInstance()._findOppositeRelated(relatedClass, id, whereClause, sortColumn); }
    public static List<MTMOrg> findOppositeRelated(String relatedClass, Long id, String whereClause, String sortColumn, Integer lowerLimit, Integer upperLimit) throws SQLException { return getInstance()._findOppositeRelated(relatedClass, id, whereClause, sortColumn, lowerLimit, upperLimit ); }

    public static Boolean remove(Long id) throws SQLException { return getInstance()._remove(id);}

    public static MTMOrg findOne(String whereClause) throws SQLException { return getInstance()._findOne(whereClause); }
    public static MTMOrg load(Long id) throws SQLException { return getInstance()._load(id); }
    public static MTMOrg mtmorgFromResultSet(ResultSet rs )   throws SQLException {
   		return getInstance()._transformSingleResultSet(rs);
   	}
    private static MTMOrgDAO instance = null;
  	public static MTMOrgDAO getInstance() { if (instance != null ) return instance;  else { instance = new MTMOrgDAO();return instance; }}

    @Override
    public String _getTable() { return "MTMOrg"; }

}


text:
echo "invoker.sh -- going to start daemon process"
cd ./target
nohup sleep 60 &
echo "invoker.sh -- daemon process was started"


text:
//
//  YWConversationServiceDef.h
//
//
//  Created by huanglei on 14/12/18.
//  Copyright (c) 2014年 taobao. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "YWServiceDef.h"
@class YWPerson;

/**
 *  收到新消息的回调
 *  @param aMessages 收到的新消息,数组中包含的对象都遵循 IYWMessage 协议,您可以直接访问 IYWMessage 中的方法
 */
typedef void(^YWConversationOnNewMessageBlock)(NSArray *aMessages);

/**
 *  收到新消息的回调
 *  @param aMessages 收到的新消息,数组中包含的对象都遵循 IYWMessage 协议,您可以直接访问 IYWMessage 中的方法
 *  @param aIsOffline 是否离线消息
 */
typedef void(^YWConversationOnNewMessageBlockV2)(NSArray *aMessages, BOOL aIsOffline);

typedef NS_ENUM(NSInteger, YWConversationInputStatus) {
    YWConversationStopInputStatus = 0x0,
    YWConversationInputTextStatus = 0x1,
    YWConversationRecordingStatus = 0x2,
    YWConversationSelectImageStatus = 0x4,
    YWConversationTakePictureStatus = YWConversationSelectImageStatus,
};

/**
 *  输入状态改变的回调
 *  @param aMessages 收到的新消息
 */
typedef void(^YWConversationInputStatusChangeBlock)(YWPerson *person, YWConversationInputStatus status);

/**
 *  数据集发生变更的回调,用于变更前或者变更完成时
 */
typedef void (^YWContentChangeBlock)(void);

typedef void (^YWResetContentBlock)(void);
/**
 *  数据集变更的回调,用于变更过程。
 *  @param object 被变更的对象
 *  @param indexPath 对象原先的位置
 *  @param newIndexPath 对象的新位置
 *  @param type 变更的方式,参见: YWObjectChangeType。
 */
typedef void (^YWObjectChangeBlock)(id object, NSIndexPath *indexPath, YWObjectChangeType type, NSIndexPath *newIndexPath);

@interface YWConversationServiceDef : NSObject

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EnvDTE;

namespace SSDTDevPack.Common.VSPackage
{
    public static class DocumentExtensions
    {
        public static string GetText(this Document source)
        {
            if (source == null)
                return null;    //can this even happen?

            var doc = source.Object("TextDocument") as TextDocument;

            if (null == doc)
            {
                return null;
            }

            var ep = doc.StartPoint.CreateEditPoint();
            ep.EndOfDocument();

            var length = ep.AbsoluteCharOffset;
            ep.StartOfDocument();
            return ep.GetText(length);
        }

    }
}


text:
import GetFeed from '../utils/service'
import githubConfig from '../assets/conf/github'

const flickrFeed = new GetFeed(
  'githubData',
  `https://api.github.com/users/${
    githubConfig.user.username
  }/events?type=owner&per_page=30&sort=created&direction=desc?page=1`,
)
  .getFeed()
  .then(data => {
    const normalizedOutput = []
    const filter = ['PushEvent', 'CreateEvent']
    let i = 0
    let date = ''

    for (i; i < data.length; i += 1) {
      const d = data[i]
      // Believe it or not the fastest: https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key
      const message = (((d.payload || {}).commits || [])[0] || {}).message || '' // d.payload.commits[0].message
      const desc = message !== '' ? `${d.type} - ${message}` : d.type

      if (filter.includes(d.type)) {
        // SEE normalize() comment above for re-use in other feeds
        date = new Date(d.created_at).getTime()
        normalizedOutput.push({
          title: d.repo.name.replace(`${d.actor.login}/`, ''),
          date,
          embed_url: d.repo.url,
          type: 'text',
          site_url: d.expanded_url,
          image_url: d.actor.avatar_url,
          description: desc,
        })
      }
    }

    return normalizedOutput
  })
  .catch(e => {
    console.log(e)
    return []
  })

export default flickrFeed


text:
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Authors: wan@google.com (Zhanyong Wan), eefacm@gmail.com (Sean Mcafee)
//
// The Google C++ Testing Framework (Google Test)
//
// This header file declares the String class and functions used internally by
// Google Test.  They are subject to change without notice. They should not used
// by code external to Google Test.
//
// This header file is #included by <gtest/internal/gtest-internal.h>.
// It should not be #included by other files.

#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_

#ifdef __BORLANDC__
// string.h is not guaranteed to provide strcpy on C++ Builder.
# include <mem.h>
#endif

#include <string.h>
#include <string>

#include "gtest/internal/gtest-port.h"

namespace testing {
namespace internal {

// String - an abstract class holding static string utilities.
class GTEST_API_ String {
 public:
  // Static utility methods

  // Clones a 0-terminated C string, allocating memory using new.  The
  // caller is responsible for deleting the return value using
  // delete[].  Returns the cloned string, or NULL if the input is
  // NULL.
  //
  // This is different from strdup() in string.h, which allocates
  // memory using malloc().
  static const char* CloneCString(const char* c_str);

#if GTEST_OS_WINDOWS_MOBILE
  // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
  // able to pass strings to Win32 APIs on CE we need to convert them
  // to 'Unicode', UTF-16.

  // Creates a UTF-16 wide string from the given ANSI string, allocating
  // memory using new. The caller is responsible for deleting the return
  // value using delete[]. Returns the wide string, or NULL if the
  // input is NULL.
  //
  // The wide string is created using the ANSI codepage (CP_ACP) to
  // match the behaviour of the ANSI versions of Win32 calls and the
  // C runtime.
  static LPCWSTR AnsiToUtf16(const char* c_str);

  // Creates an ANSI string from the given wide string, allocating
  // memory using new. The caller is responsible for deleting the return
  // value using delete[]. Returns the ANSI string, or NULL if the
  // input is NULL.
  //
  // The returned string is created using the ANSI codepage (CP_ACP) to
  // match the behaviour of the ANSI versions of Win32 calls and the
  // C runtime.
  static const char* Utf16ToAnsi(LPCWSTR utf16_str);
#endif

  // Compares two C strings.  Returns true iff they have the same content.
  //
  // Unlike strcmp(), this function can handle NULL argument(s).  A
  // NULL C string is considered different to any non-NULL C string,
  // including the empty string.
  static bool CStringEquals(const char* lhs, const char* rhs);

  // Converts a wide C string to a String using the UTF-8 encoding.
  // NULL will be converted to "(null)".  If an error occurred during
  // the conversion, "(failed to convert from wide string)" is
  // returned.
  static std::string ShowWideCString(const wchar_t* wide_c_str);

  // Compares two wide C strings.  Returns true iff they have the same
  // content.
  //
  // Unlike wcscmp(), this function can handle NULL argument(s).  A
  // NULL C string is considered different to any non-NULL C string,
  // including the empty string.
  static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);

  // Compares two C strings, ignoring case.  Returns true iff they
  // have the same content.
  //
  // Unlike strcasecmp(), this function can handle NULL argument(s).
  // A NULL C string is considered different to any non-NULL C string,
  // including the empty string.
  static bool CaseInsensitiveCStringEquals(const char* lhs,
                                           const char* rhs);

  // Compares two wide C strings, ignoring case.  Returns true iff they
  // have the same content.
  //
  // Unlike wcscasecmp(), this function can handle NULL argument(s).
  // A NULL C string is considered different to any non-NULL wide C string,
  // including the empty string.
  // NB: The implementations on different platforms slightly differ.
  // On windows, this method uses _wcsicmp which compares according to LC_CTYPE
  // environment variable. On GNU platform this method uses wcscasecmp
  // which compares according to LC_CTYPE category of the current locale.
  // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
  // current locale.
  static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
                                               const wchar_t* rhs);

  // Returns true iff the given string ends with the given suffix, ignoring
  // case. Any string is considered to end with an empty suffix.
  static bool EndsWithCaseInsensitive(
      const std::string& str, const std::string& suffix);

  // Formats an int value as "%02d".
  static std::string FormatIntWidth2(int value);  // "%02d" for width == 2

  // Formats an int value as "%X".
  static std::string FormatHexInt(int value);

  // Formats a byte as "%02X".
  static std::string FormatByte(unsigned char value);

 private:
  String();  // Not meant to be instantiated.
};  // class String

// Gets the content of the stringstream's buffer as an std::string.  Each '\0'
// character in the buffer is replaced with "\\0".
GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);

}  // namespace internal
}  // namespace testing

#endif  // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_


text: puts 'nice spec helper'


text:
import tkinter as tk

class Todo(tk.Tk):
    def __init__(self, tasks=None):
        super().__init__()
        if not tasks:
            self.tasks = []
        else:
            self.tasks = tasks
        self.title("To-Do App v1")
        self.geometry("300x400")
        todo1 = tk.Label(self, text="--- Add Items Here ---", bg="lightgrey", fg="black", pady=10)
        self.tasks.append(todo1)
        for task in self.tasks:
            task.pack(side=tk.TOP, fill=tk.X)
        self.task_create = tk.Text(self, height=3, bg="white", fg="black")
        self.task_create.pack(side=tk.BOTTOM, fill=tk.X)
        self.task_create.focus_set()
        self.bind("<Return>", self.add_task)
        self.colour_schemes = [{"bg": "lightgrey", "fg": "black"}, {"bg": "grey", "fg": "white"}]

    def add_task(self, event=None):
        task_text = self.task_create.get(1.0, tk.END).strip()
        print(task_text)
        if len(task_text) > 0:
            new_task = tk.Label(self, text=task_text, pady=10)
            _, task_style_choice = divmod(len(self.tasks), 2)
            print(task_style_choice)
            my_scheme_choice = self.colour_schemes[task_style_choice]
            print(my_scheme_choice, my_scheme_choice["bg"], my_scheme_choice["fg"])
            new_task.configure(bg=my_scheme_choice["bg"])
            new_task.configure(fg=my_scheme_choice["fg"])
            new_task.pack(side=tk.TOP, fill=tk.X)
            self.tasks.append(new_task)
        self.task_create.delete(1.0, tk.END)

if __name__ == "__main__":
    todo = Todo()
    todo.mainloop()


text:
const co = require('co');

const logger = global.dawan.logger;

const userTable = 'drop table users';
const roleTable = 'drop table roles';
const userRoleTable = 'drop table user_role';
const menuTable = 'drop table menus';
const roleMenuTable = 'drop table role_menu';

module.exports = function (connection) {
    co(function* () {
        yield connection.execute(userTable);
        logger.info('user table drop success!');
        yield connection.execute(roleTable);
        logger.info('role table drop success!');
        yield connection.execute(userRoleTable);
        logger.info('user_role table drop success!');
        yield connection.execute(menuTable);
        logger.info('menu table drop success!');
        yield connection.execute(roleMenuTable);
        logger.info('role_menu table drop success!');
    });
};


text:
package org.dolphin.http.server.sniffer;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by hanyanan on 2015/11/6.
 */
public class BroadCastTest {

    public static void main(String args[]) throws Exception {
        new Thread(){
            public void run(){
                try {
                    receiveBroadcast();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        Thread.sleep(100);
        sendBroadcast();
//        receiveBroadcast();
    }

    public static void sendBroadcast() throws Exception {
        DatagramSocket socket;
        DatagramPacket packet;
        byte[] data ;

        socket = new DatagramSocket();

        for (int i = 0; i < 50; i++) {
            socket.setBroadcast(true); //有没有没啥不同
            //send端指定接受端的端口,自己的端口是随机的
            data = (""+System.nanoTime()).getBytes();
            packet = new DatagramPacket(data, data.length, InetAddress.getByName("255.255.255.255"), 8300);
            socket.send(packet);
            socket.receive(packet);
            String s = new String(packet.getData(), 0, packet.getLength());
            System.out.println("Client "+packet.getAddress() + " at port " + packet.getPort() + " says " + s);
            Thread.sleep(1000);

        }
    }

    public static void receiveBroadcast() throws Exception {
        byte[] buffer = new byte[65507];
        DatagramSocket server = new DatagramSocket(8300);
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        for (; ; ) {
            server.receive(packet);
            String s = new String(packet.getData(), 0, packet.getLength());
            System.out.println("Server "+packet.getAddress() + " at port " + packet.getPort() + " says " + s);
            byte[] res = "ewfwefwefweff".getBytes();
            packet = new DatagramPacket(res, res.length, packet.getAddress(), packet.getPort());
            server.send(packet);
        }
    }

}


text:
<?php

namespace IonXLab\JacksonPhp\annotation;

/**
 * Class JacksonAnnotationArgument
 * @package IonXLab\JacksonPhp\annotation
 *
 * Defines an JacksonAnnotation argument (parameter or variable)
 */
class JacksonAnnotationArgument {

    /**
     * The argument index name or id
     * @var string|int
     */
    private $argumentKey;
    /**
     * The argument type ("boolean"|"integer"|"double"|"string"|"array"|"MyClassName")
     * @var string
     */
    private $argumentType;

    /**
     * @var array
     */
    private $argumentPossibleValues;

    /**
     * @param string|int $argumentKey the name or id of the argument (name only available for annotation parameters)
     * @param string $argumentType ("boolean"|"integer"|"double"|"string"|"array"|"MyClassName") the argument type
     * @param array $argumentPossibleValues optional: restrain accepted values for the argument
     * @throws \Exception If given type is not defined basic type misspelled or unknown class/namespace
     */
    public function __construct($argumentKey, $argumentType, $argumentPossibleValues=array()) {
        $this->argumentKey = $argumentKey;
        if($argumentType==("boolean"
                || "integer"
                || "double"
                || "string"
                || "array")) {
            $this->argumentType = $argumentType;
        } elseif(class_exists($argumentType)) {
            $this->argumentType = $argumentType;
        } else {
            throw new \Exception("Given Type is not defined. Misspelled or forgotten include ?");
        }
        $this->argumentPossibleValues = $argumentPossibleValues;
    }

    /**
     * @return int|string
     */
    public function getArgumentKey() {
        return $this->argumentKey;
    }

    /**
     * @return string
     */
    public function getArgumentType() {
        return $this->argumentType;
    }

    /**
     * @return array
     */
    public function getArgumentPossibleValues() {
        return $this->argumentPossibleValues;
    }
}


text:
class AboutLayout < MK::Layout
  def layout
    add UIScrollView, :scroll_view do
      background_color rmq.color.background_gray
      target.scrollEnabled = true

      add UIView, :content_container do
        add UILabel, :hi_there do
          color rmq.color.black
          font rmq.font.medium
          text "Hi There."
        end

        add UILabel, :about_app do
          base_settings
          text "The Calagator IOS app is a community supported calander of technology related meetups, events, and happenings in and around Portland OR. Events are synced automatically with all events listed on the calagator website. The IOS app is sponsored and published by Notch8, a Portland based ruby and mobile software shop.  It is maintained and updated by the awesome local Ruby community.  The app is built with love using the equally awesome Ruby Motion platform."
        end

        add UILabel, :about_calagator_heading do
          base_settings
          font rmq.font.small
          text "About Calagator"
        end

        add UILabel, :about_calagator do
          base_settings
          text "Calagator is a unified calendar for the technology community of Portland, Oregon. We are an all-volunteer effort and encourage anyone to import, create, and edit events."
        end

        add UIButton, :calagator_url do
          title "http://www.calagator.org"
          background_color rmq.color.battleship_gray
          size_to_fit
        end

        add UILabel, :about_notch8_heading do
          base_settings
          font rmq.font.small
          text "About Notch8"
        end

        add UILabel, :about_notch8 do
          base_settings
          text "Notch8 is a web and mobile application software shop located in Portland, OR and San Diego, CA.  Their team of software professionals build and ship high value client applications and projects that foster a thriving technology community."
        end

        add UIButton, :notch8_url do
          background_color rmq.color.battleship_gray
          size_to_fit
          title "http://www.notch8.com"
        end

      end
    end
  end

  def base_settings
    color rmq.color.battleship_gray
    font rmq.font.small
    target.numberOfLines = 0
    size_to_fit
  end

  def add_constraints
    constraints(:scroll_view) do
      top_left x:0, y: 0
      leading 0
      trailing 0
      width.equals(:superview)
      height.equals(:superview)
    end

    constraints(:content_container) do
      top 0
      bottom 0
      leading 0
      trailing 0
      width.equals(:superview)
    end

    constraints(:hi_there) do
      top 40
      left 20
      width.equals(:superview).minus(40)
    end

    constraints(:about_app) do
      top.equals(:hi_there, NSLayoutAttributeBottom).plus(40)
      left.equals(:hi_there)
      width.equals(:superview).minus(40)
    end

    constraints(:about_calagator_heading) do
      top.equals(:about_app, NSLayoutAttributeBottom).plus(40)
      left.equals(:hi_there)
      width.equals(:superview).minus(40)
    end

    constraints(:about_calagator) do
      top.equals(:about_calagator_heading, NSLayoutAttributeBottom).plus(10)
      left.equals(:hi_there)
      width.equals(:superview).minus(40)
    end

    constraints(:calagator_url) do
      top.equals(:about_calagator, NSLayoutAttributeBottom).plus(10)
      left 0
      width.equals(:superview)
    end

    constraints(:about_notch8_heading) do
      top.equals(:calagator_url, NSLayoutAttributeBottom).plus(40)
      left.equals(:hi_there)
      width.equals(:superview).minus(40)
    end

    constraints(:about_notch8) do
      top.equals(:about_notch8_heading, NSLayoutAttributeBottom).plus(10)
      left.equals(:hi_there)
      width.equals(:superview).minus(40)
    end

    constraints(:notch8_url) do
      top.equals(:about_notch8, NSLayoutAttributeBottom).plus(10)
      left.equals(:calagator_url)
      width.equals(:calagator_url)
      bottom -20
    end
  end
end


text:
package javax.mail;

import java.util.Properties;

public class Session {
    public static Session getInstance(Properties props, Authenticator auth) {
        return null;
    }
    public static Session getInstance(Properties props) {
        return null;
    }
}