text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Namespace
var importer = importer || {};

/**
 * A persistent data store for Cloud Import history information.
 *
 * @interface
 */
importer.ImportHistory = function() {};

/**
 * @return {!Promise<!importer.ImportHistory>} Resolves when history
 *     has been fully loaded.
 */
importer.ImportHistory.prototype.whenReady;

/**
 * @param {!FileEntry} entry
 * @param {!importer.Destination} destination
 * @return {!Promise<boolean>} Resolves with true if the FileEntry
 *     was previously copied to the device.
 */
importer.ImportHistory.prototype.wasCopied;

/**
 * @param {!FileEntry} entry
 * @param {!importer.Destination} destination
 * @return {!Promise<boolean>} Resolves with true if the FileEntry
 *     was previously imported to the specified destination.
 */
importer.ImportHistory.prototype.wasImported;

/**
 * @param {!FileEntry} entry
 * @param {!importer.Destination} destination
 * @param {string} destinationUrl
 */
importer.ImportHistory.prototype.markCopied;

/**
 * List urls of all files that are marked as copied, but not marked as synced.
 * @param {!importer.Destination} destination
 * @return {!Promise<!Array<string>>}
 */
importer.ImportHistory.prototype.listUnimportedUrls;

/**
 * @param {!FileEntry} entry
 * @param {!importer.Destination} destination
 * @return {!Promise<?>} Resolves when the operation is completed.
 */
importer.ImportHistory.prototype.markImported;

/**
 * @param {string} destinationUrl
 * @return {!Promise<?>} Resolves when the operation is completed.
 */
importer.ImportHistory.prototype.markImportedByUrl;

/**
 * Adds an observer, which will be notified when cloud import history changes.
 *
 * @param {!importer.ImportHistory.Observer} observer
 */
importer.ImportHistory.prototype.addObserver;

/**
 * Remove a previously registered observer.
 *
 * @param {!importer.ImportHistory.Observer} observer
 */
importer.ImportHistory.prototype.removeObserver;

/** @enum {string} */
importer.ImportHistory.State = {
  'COPIED': 'copied',
  'IMPORTED': 'imported'
};

/**
 * @typedef {{
 *   state: !importer.ImportHistory.State,
 *   entry: !FileEntry
 * }}
 */
importer.ImportHistory.ChangedEvent;

/** @typedef {function(!importer.ImportHistory.ChangedEvent)} */
importer.ImportHistory.Observer;

/**
 * An dummy {@code ImportHistory} implementation. This class can conveniently
 * be used when cloud import is disabled.
 * @param {boolean} answer The value to answer all {@code wasImported}
 *     queries with.
 *
 * @constructor
 * @implements {importer.HistoryLoader}
 * @implements {importer.ImportHistory}
 */
importer.DummyImportHistory = function(answer) {
  /** @private {boolean} */
  this.answer_ = answer;
};

/** @override */
importer.DummyImportHistory.prototype.whenReady = function() {
  return Promise.resolve(/** @type {!importer.ImportHistory} */ (this));
};

/** @override */
importer.DummyImportHistory.prototype.getHistory = function() {
  return this.whenReady();
};

/** @override */
importer.DummyImportHistory.prototype.wasCopied =
    function(entry, destination) {
  return Promise.resolve(this.answer_);
};

/** @override */
importer.DummyImportHistory.prototype.wasImported =
    function(entry, destination) {
  return Promise.resolve(this.answer_);
};

/** @override */
importer.DummyImportHistory.prototype.markCopied =
    function(entry, destination, destinationUrl) {
  return Promise.resolve();
};

/** @override */
importer.DummyImportHistory.prototype.listUnimportedUrls =
    function(destination) {
  return Promise.resolve([]);
};

/** @override */
importer.DummyImportHistory.prototype.markImported =
    function(entry, destination) {
  return Promise.resolve();
};

/** @override */
importer.DummyImportHistory.prototype.markImportedByUrl =
    function(destinationUrl) {
  return Promise.resolve();
};

/** @override */
importer.DummyImportHistory.prototype.addHistoryLoadedListener =
    function(listener) {};

/** @override */
importer.DummyImportHistory.prototype.addObserver = function(observer) {};

/** @override */
importer.DummyImportHistory.prototype.removeObserver = function(observer) {};

/**
 * @private @enum {number}
 */
importer.RecordType_ = {
  COPY: 0,
  IMPORT: 1
};

/**
 * @typedef {{
 *   sourceUrl: string,
 *   destinationUrl: string
 * }}
 */
importer.Urls;

/**
 * An {@code ImportHistory} implementation that reads from and
 * writes to a storage object.
 *
 * @constructor
 * @implements {importer.ImportHistory}
 * @struct
 *
 * @param {function(!FileEntry): !Promise<string>} hashGenerator
 * @param {!importer.RecordStorage} storage
 */
importer.PersistentImportHistory = function(hashGenerator, storage) {
  /** @private {function(!FileEntry): !Promise<string>} */
  this.createKey_ = hashGenerator;

  /** @private {!importer.RecordStorage} */
  this.storage_ = storage;

  /**
   * An in-memory representation of local copy history.
   * The first value is the "key" (as generated internally
   * from a file entry).
   * @private {!Object<!Object<!importer.Destination, importer.Urls>>}
   */
  this.copiedEntries_ = {};

  /**
   * An in-memory index from destination URL to key.
   *
   * @private {!Object<string>}
   */
  this.copyKeyIndex_ = {};

  /**
   * An in-memory representation of import history.
   * The first value is the "key" (as generated internally
   * from a file entry).
   * @private {!Object<!Array<importer.Destination>>}
   */
  this.importedEntries_ = {};

  /** @private {!Array<!importer.ImportHistory.Observer>} */
  this.observers_ = [];

  /** @private {Promise.<!importer.PersistentImportHistory>} */
  this.whenReady_ = this.load_();
};

/**
 * Reloads history from disk. Should be called when the file
 * is changed by an external source.
 *
 * @return {!Promise<!importer.PersistentImportHistory>} Resolves when
 *     history has been refreshed.
 * @private
 */
importer.PersistentImportHistory.prototype.load_ = function() {
  return this.storage_.readAll(this.updateInMemoryRecord_.bind(this))
      .then(
          /**
           * @return {!importer.PersistentImportHistory}
           * @this {importer.PersistentImportHistory}
           */
          function() {
            return this;
          }.bind(this))
      .catch(importer.getLogger().catcher('import-history-load'));
};

/**
 * @return {!Promise<!importer.ImportHistory>}
 */
importer.PersistentImportHistory.prototype.whenReady = function() {
  return /** @type {!Promise<!importer.ImportHistory>} */ (this.whenReady_);
};

/**
 * Detects record type and expands records to appropriate arguments.
 *
 * @param {!Array<*>} record
 * @this {importer.PersistentImportHistory}
 */
importer.PersistentImportHistory.prototype.updateInMemoryRecord_ =
    function(record) {
  switch (record[0]) {
    case importer.RecordType_.COPY:
      if (record.length !== 5) {
        importer.getLogger().error(
            'Skipping copy record with wrong number of fields: ' +
            record.length);
        break;
      }
      this.updateInMemoryCopyRecord_(
          /** @type {string} */ (
              record[1]),  // key
          /** @type {!importer.Destination} */ (
              record[2]),
          /** @type {string } */ (
              record[3]),  // sourceUrl
          /** @type {string } */ (
              record[4])); // destinationUrl
      return;
    case importer.RecordType_.IMPORT:
      if (record.length !== 3) {
        importer.getLogger().error(
            'Skipping import record with wrong number of fields: ' +
            record.length);
        break;
      }
      this.updateInMemoryImportRecord_(
          /** @type {string } */ (
              record[1]),  // key
          /** @type {!importer.Destination} */ (
              record[2]));
      return;
    default:
      assertNotReached('Ignoring record with unrecognized type: ' + record[0]);
  }
};

/**
 * Adds an import record to the in-memory history model.
 *
 * @param {string} key
 * @param {!importer.Destination} destination
 *
 * @return {boolean} True if a record was created.
 * @private
 */
importer.PersistentImportHistory.prototype.updateInMemoryImportRecord_ =
    function(key, destination) {
  if (!this.importedEntries_.hasOwnProperty(key)) {
    this.importedEntries_[key] = [destination];
    return true;
  } else if (this.importedEntries_[key].indexOf(destination) === -1) {
    this.importedEntries_[key].push(destination);
    return true;
  }
  return false;
};

/**
 * Adds a copy record to the in-memory history model.
 *
 * @param {string} key
 * @param {!importer.Destination} destination
 * @param {string} sourceUrl
 * @param {string} destinationUrl
 *
 * @return {boolean} True if a record was created.
 * @private
 */
importer.PersistentImportHistory.prototype.updateInMemoryCopyRecord_ =
    function(key, destination, sourceUrl, destinationUrl) {
  this.copyKeyIndex_[destinationUrl] = key;
  if (!this.copiedEntries_.hasOwnProperty(key)) {
    this.copiedEntries_[key] = {};
  }
  if (!this.copiedEntries_[key].hasOwnProperty(destination)) {
    this.copiedEntries_[key][destination] = {
      sourceUrl: sourceUrl,
      destinationUrl: destinationUrl
    };
    return true;
  }
  return false;
};

/** @override */
importer.PersistentImportHistory.prototype.wasCopied =
    function(entry, destination) {
  return this.whenReady_
      .then(this.createKey_.bind(this, entry))
      .then(
          /**
           * @param {string} key
           * @return {boolean}
           * @this {importer.PersistentImportHistory}
           */
          function(key) {
            return key in this.copiedEntries_ &&
                destination in this.copiedEntries_[key];
          }.bind(this))
      .catch(importer.getLogger().catcher('import-history-was-imported'));
};

/** @override */
importer.PersistentImportHistory.prototype.wasImported =
    function(entry, destination) {
  return this.whenReady_
      .then(this.createKey_.bind(this, entry))
      .then(
          /**
           * @param {string} key
           * @return {boolean}
           * @this {importer.PersistentImportHistory}
           */
          function(key) {
            return this.getDestinations_(key).indexOf(destination) >= 0;
          }.bind(this))
      .catch(importer.getLogger().catcher('import-history-was-imported'));
};

/** @override */
importer.PersistentImportHistory.prototype.markCopied =
    function(entry, destination, destinationUrl) {
  return this.whenReady_
      .then(this.createKey_.bind(this, entry))
      .then(
          /**
           * @param {string} key
           * @return {!Promise<?>}
           * @this {importer.ImportHistory}
           */
          function(key) {
            return this.storeRecord_([
                importer.RecordType_.COPY,
                key,
                destination,
                importer.deflateAppUrl(entry.toURL()),
                importer.deflateAppUrl(destinationUrl)]);
          }.bind(this))
      .then(this.notifyObservers_.bind(
          this,
          importer.ImportHistory.State.COPIED,
          entry,
          destination,
          destinationUrl))
      .catch(importer.getLogger().catcher('import-history-mark-copied'));
};

/** @override */
importer.PersistentImportHistory.prototype.listUnimportedUrls =
    function(destination) {
  return this.whenReady_.then(
      function() {
        // TODO(smckay): Merge copy and sync records for simpler
        // unimported file discovery.
        var unimported = [];
        for (var key in this.copiedEntries_) {
          var imported = this.importedEntries_[key];
          for (var destination in this.copiedEntries_[key]) {
            if (!imported || imported.indexOf(destination) === -1) {
              var url = importer.inflateAppUrl(
                  this.copiedEntries_[key][destination].destinationUrl);
              unimported.push(url);
            }
          }
        }
        return unimported;
      }.bind(this))
      .catch(
          importer.getLogger().catcher('import-history-list-unimported-urls'));
};

/** @override */
importer.PersistentImportHistory.prototype.markImported =
    function(entry, destination) {
  return this.whenReady_
      .then(this.createKey_.bind(this, entry))
      .then(
          /**
           * @param {string} key
           * @return {!Promise<?>}
           * @this {importer.ImportHistory}
           */
          function(key) {
            return this.storeRecord_([
                importer.RecordType_.IMPORT,
                key,
                destination]);
          }.bind(this))
      .then(this.notifyObservers_.bind(
          this,
          importer.ImportHistory.State.IMPORTED,
          entry,
          destination))
      .catch(importer.getLogger().catcher('import-history-mark-imported'));
};

/** @override */
importer.PersistentImportHistory.prototype.markImportedByUrl =
    function(destinationUrl) {
  var deflatedUrl = importer.deflateAppUrl(destinationUrl);
  var key = this.copyKeyIndex_[deflatedUrl];
  if (!!key) {
    var copyData = this.copiedEntries_[key];

    // We could build an index of this as well, but it seems
    // unnecessary given the fact that there will almost always
    // be just one destination for a file (assumption).
    for (var destination in copyData) {
      if (copyData[destination].destinationUrl === deflatedUrl) {
        return this.storeRecord_([
          importer.RecordType_.IMPORT,
          key,
          destination])
            .then(
                /** @this {importer.PersistentImportHistory} */
                function() {
                  var sourceUrl = importer.inflateAppUrl(
                      copyData[destination].sourceUrl);
                  // Here we try to create an Entry for the source URL.
                  // This will allow observers to update the UI if the
                  // source entry is in view.
                  util.urlToEntry(sourceUrl).then(
                      /**
                       * @param {Entry} entry
                       * @this {importer.PersistentImportHistory}
                       */
                      function(entry) {
                        if (entry.isFile) {
                          this.notifyObservers_(
                                importer.ImportHistory.State.IMPORTED,
                                /** @type {!FileEntry} */ (entry),
                                destination);
                        }
                      }.bind(this),
                      function() {
                        console.log(
                            'Unable to find original entry for: ' + sourceUrl);
                        return;
                      })
                      .catch(importer.getLogger().catcher(
                          'notify-listeners-on-import'));
                }.bind(this))
            .catch(importer.getLogger().catcher('mark-imported-by-url'));
      }
    }
  }

  return Promise.reject(
      'Unable to match destination URL to import record > ' + destinationUrl);
};

/** @override */
importer.PersistentImportHistory.prototype.addObserver =
    function(observer) {
  this.observers_.push(observer);
};

/** @override */
importer.PersistentImportHistory.prototype.removeObserver =
    function(observer) {
  var index = this.observers_.indexOf(observer);
  if (index > -1) {
    this.observers_.splice(index, 1);
  } else {
    console.warn('Ignoring request to remove observer that is not registered.');
  }
};

/**
 * @param {!importer.ImportHistory.State} state
 * @param {!FileEntry} entry
 * @param {!importer.Destination} destination
 * @param {string=} opt_destinationUrl
 * @private
 */
importer.PersistentImportHistory.prototype.notifyObservers_ =
    function(state, entry, destination, opt_destinationUrl) {
  this.observers_.forEach(
      /**
       * @param {!importer.ImportHistory.Observer} observer
       * @this {importer.PersistentImportHistory}
       */
      function(observer) {
        observer({
          state: state,
          entry: entry,
          destination: destination,
          destinationUrl: opt_destinationUrl
        });
      }.bind(this));
};

/**
 * @param {!Array<*>} record
 *
 * @return {!Promise<?>} Resolves once the write has been completed.
 * @private
 */
importer.PersistentImportHistory.prototype.storeRecord_ = function(record) {
  this.updateInMemoryRecord_(record);
  return this.storage_.write(record);
};

/**
 * @param {string} key
 * @return {!Array<string>} The list of previously noted
 *     destinations, or an empty array, if none.
 * @private
 */
importer.PersistentImportHistory.prototype.getDestinations_ = function(key) {
  return key in this.importedEntries_ ? this.importedEntries_[key] : [];
};

/**
 * Provider of lazy loaded importer.ImportHistory. This is the main
 * access point for a fully prepared {@code importer.ImportHistory} object.
 *
 * @interface
 */
importer.HistoryLoader = function() {};

/**
 * Instantiates an {@code importer.ImportHistory} object and manages any
 * necessary ongoing maintenance of the object with respect to
 * its external dependencies.
 *
 * @see importer.SynchronizedHistoryLoader for an example.
 *
 * @return {!Promise<!importer.ImportHistory>} Resolves when history instance
 *     is ready.
 */
importer.HistoryLoader.prototype.getHistory;

/**
 * Adds a listener to be notified when history is fully loaded for the first
 * time. If history is already loaded...will be called immediately.
 *
 * @param {function(!importer.ImportHistory)} listener
 */
importer.HistoryLoader.prototype.addHistoryLoadedListener;

/**
 * Class responsible for lazy loading of {@code importer.ImportHistory},
 * and reloading when the underlying data is updated (via sync).
 *
 * @constructor
 * @implements {importer.HistoryLoader}
 * @struct
 *
 * @param {function(): !Promise<!Array<!FileEntry>>} filesProvider
 * @param {!analytics.Tracker} tracker
 */
importer.SynchronizedHistoryLoader = function(filesProvider, tracker) {
  /**
   * @return {!Promise<!Array<!FileEntry>>} History files. Will always
   *     have at least one file (the "primary file"). When other devices
   *     have been used for import, additional files may be present
   *     as well. In all cases the primary file will be used for write
   *     operations and all non-primary files are read-only.
   * @private
   */
  this.getHistoryFiles_ = filesProvider;

  /** @private {!analytics.Tracker} */
  this.tracker_ = tracker;

  /** @private {boolean} */
  this.needsInitialization_ = true;

  /** @private {!importer.Resolver} */
  this.historyResolver_ = new importer.Resolver();
};

/** @override */
importer.SynchronizedHistoryLoader.prototype.getHistory = function() {
  if (this.needsInitialization_) {
    this.needsInitialization_ = false;
    this.getHistoryFiles_()
        .then(
            /**
             * @param {!Array<!FileEntry>} fileEntries
             * @return {!Promise<!importer.ImportHistory>}
             * @this {importer.SynchronizedHistoryLoader}
             */
            function(fileEntries) {
              var storage = new importer.FileBasedRecordStorage(
                  fileEntries,
                  this.tracker_);
              var history = new importer.PersistentImportHistory(
                  importer.createMetadataHashcode,
                  storage);
              new importer.DriveSyncWatcher(history);
              history.whenReady().then(
                  /** @this {importer.SynchronizedHistoryLoader} */
                  function() {
                    this.historyResolver_.resolve(history);
                  }.bind(this));
            }.bind(this))
        .catch(importer.getLogger().catcher('history-load-chain'));
  }

  return this.historyResolver_.promise;
};

/** @override */
importer.SynchronizedHistoryLoader.prototype.addHistoryLoadedListener =
    function(listener) {
  this.historyResolver_.promise.then(listener);
};

/**
 * An simple record storage mechanism.
 *
 * @interface
 */
importer.RecordStorage = function() {};

/**
 * Adds a new record.
 *
 * @param {!Array<*>} record
 * @return {!Promise<?>} Resolves when record is added.
 */
importer.RecordStorage.prototype.write;

/**
 * Reads all records.
 *
 * @param {function(!Array<*>)} recordCallback Callback called once
 *     for each record loaded.
 */
importer.RecordStorage.prototype.readAll;

/**
 * A {@code RecordStore} that persists data in a {@code FileEntry}.
 *
 * @param {!Array<!FileEntry>} fileEntries The first entry is the
 *     "primary" file for read-write, all other are read-only
 *     sources of data (presumably synced from other machines).
 *
 * @constructor
 * @implements {importer.RecordStorage}
 * @struct
 *
 * @param {!analytics.Tracker} tracker
 */
importer.FileBasedRecordStorage = function(fileEntries, tracker) {
  /** @private {!Array<!importer.PromisingFileEntry>} */
  this.inputFiles_ = fileEntries.map(
      importer.PromisingFileEntry.create);

  /** @private {!importer.PromisingFileEntry} */
  this.outputFile_ = this.inputFiles_[0];

  /** @private {!analytics.Tracker} */
  this.tracker_ = tracker;

  /**
   * Serializes all writes and reads on the primary file.
   * @private {!Promise<?>}
   * */
  this.latestOperation_ = Promise.resolve(null);
};

/** @override */
importer.FileBasedRecordStorage.prototype.write = function(record) {
  return this.latestOperation_ = this.latestOperation_
      .then(
          /**
           * @param {?} ignore
           * @this {importer.FileBasedRecordStorage}
           */
          function(ignore) {
            return this.outputFile_.createWriter();
          }.bind(this))
      .then(this.writeRecord_.bind(this, record))
      .catch(importer.getLogger().catcher('file-record-store-write'));
};

/**
 * Appends a new record to the end of the file.
 *
 * @param {!Object} record
 * @param {!FileWriter} writer
 * @return {!Promise<?>} Resolves when write is complete.
 * @private
 */
importer.FileBasedRecordStorage.prototype.writeRecord_ =
    function(record, writer) {
  var blob = new Blob(
      [JSON.stringify(record) + ',\n'],
      {type: 'text/plain; charset=UTF-8'});

  return new Promise(
      /**
       * @param {function()} resolve
       * @param {function()} reject
       * @this {importer.FileBasedRecordStorage}
       */
      function(resolve, reject) {
        writer.onwriteend = resolve;
        writer.onerror = reject;

        writer.seek(writer.length);
        writer.write(blob);
      }.bind(this));
};

/** @override */
importer.FileBasedRecordStorage.prototype.readAll = function(recordCallback) {
  var processTiming = this.tracker_.startTiming(
      metrics.Categories.ACQUISITION,
      metrics.timing.Variables.HISTORY_LOAD);

  return this.latestOperation_ = this.latestOperation_
      .then(
          /**
           * @param {?} ignored
           * @this {importer.FileBasedRecordStorage}
           */
          function(ignored) {
            var filePromises = this.inputFiles_.map(
                /**
                 * @param {!importer.PromisingFileEntry} entry
                 * @this {importer.FileBasedRecordStorage}
                 */
                function(entry) {
                  return entry.file();
                });
            return Promise.all(filePromises);
          }.bind(this))
      .then(
          /**
           * @return {!Array<!File>}
           * @this {importer.FileBasedRecordStorage}
           */
          function(files) {
            var contentPromises = files.map(
                this.readFileAsText_.bind(this));
            return Promise.all(contentPromises);
          }.bind(this),
          /**
           * @return {string}
           * @this {importer.FileBasedRecordStorage}
           */
          function() {
            console.error('Unable to read from one of history files.');
            return '';
          }.bind(this))
      .then(
          /**
           * @param {!Array<string>} fileContents
           * @this {importer.FileBasedRecordStorage}
           */
          function(fileContents) {
            var parsePromises = fileContents.map(
                this.parse_.bind(this));
            return Promise.all(parsePromises);
          }.bind(this))
      .then(
          /** @param {!Array<!Array<*>>} parsedContents */
          function(parsedContents) {
            parsedContents.forEach(
                /** @param {!Array<!Array<*>>} recordSet */
                function(recordSet) {
                  recordSet.forEach(recordCallback);
                });

            processTiming.send();

            var fileCount = this.inputFiles_.length;
            this.tracker_.send(
                metrics.ImportEvents.HISTORY_LOADED
                    .value(fileCount)
                    .dimension(fileCount === 1
                        ? metrics.Dimensions.MACHINE_USE_SINGLE
                        : metrics.Dimensions.MACHINE_USE_MULTIPLE));
          }.bind(this))
      .catch(importer.getLogger().catcher('file-record-store-read-all'));
};

/**
 * Reads the entire entry as a single string value.
 *
 * @param {!File} file
 * @return {!Promise<string>}
 * @private
 */
importer.FileBasedRecordStorage.prototype.readFileAsText_ = function(file) {
  return new Promise(
      /**
       * @param {function()} resolve
       * @param {function()} reject
       * @this {importer.FileBasedRecordStorage}
       */
      function(resolve, reject) {
        var reader = new FileReader();

        reader.onloadend = function() {
          if (reader.error) {
            console.error(reader.error);
            reject();
          } else {
            resolve(reader.result);
          }
        }.bind(this);

        reader.onerror = function(error) {
          console.error(error);
          reject(error);
        }.bind(this);

        reader.readAsText(file);
      }.bind(this))
      .catch(importer.getLogger().catcher(
      'file-record-store-read-file-as-text'));
};

/**
 * Parses the text.
 *
 * @param {string} text
 * @return {!Array<!Array<*>>}
 * @private
 */
importer.FileBasedRecordStorage.prototype.parse_ = function(text) {
  if (text.length === 0) {
    return [];
  } else {
    // Dress up the contents of the file like an array,
    // so the JSON object can parse it using JSON.parse.
    // That means we need to both:
    //   1) Strip the trailing ',\n' from the last record
    //   2) Surround the whole string in brackets.
    // NOTE: JSON.parse is WAY faster than parsing this
    // ourselves in javascript.
    var json = '[' + text.substring(0, text.length - 2) + ']';
    return /** @type {!Array<!Array<*>>} */ (JSON.parse(json));
  }
};

/**
 * This class makes the "drive" badges appear by way of marking entries as
 * imported in history when a previously imported file is fully synced to drive.
 *
 * @constructor
 * @struct
 *
 * @param {!importer.ImportHistory} history
 */
importer.DriveSyncWatcher = function(history) {
  /** @private {!importer.ImportHistory} */
  this.history_ = history;

  this.history_.addObserver(
      this.onHistoryChanged_.bind(this));

  this.history_.whenReady()
      .then(
          function() {
            this.history_.listUnimportedUrls(importer.Destination.GOOGLE_DRIVE)
                .then(this.updateSyncStatus_.bind(
                    this,
                    importer.Destination.GOOGLE_DRIVE));
          }.bind(this))
      .catch(importer.getLogger().catcher('drive-sync-watcher-constructor'));

  // Listener is only registered once the history object is initialized.
  // No need to register synchonously since we don't want to be
  // woken up to respond to events.
  chrome.fileManagerPrivate.onFileTransfersUpdated.addListener(
      this.onFileTransfersUpdated_.bind(this));
  // TODO(smckay): Listen also for errors on onDriveSyncError.
};

/** @const {number} */
importer.DriveSyncWatcher.UPDATE_DELAY_MS = 3500;

/**
 * @param {!importer.Destination} destination
 * @param {!Array<string>} unimportedUrls
 * @private
 */
importer.DriveSyncWatcher.prototype.updateSyncStatus_ =
    function(destination, unimportedUrls) {
  // TODO(smckay): Chunk processing of urls...to ensure we're not
  // blocking interactive tasks. For now, we just defer the update
  // for a few seconds.
  setTimeout(
      function() {
        unimportedUrls.forEach(
            function(url) {
              this.checkSyncStatus_(destination, url);
            }.bind(this));
      }.bind(this),
      importer.DriveSyncWatcher.UPDATE_DELAY_MS);
};

/**
 * @param {!FileTransferStatus} status
 * @private
 */
importer.DriveSyncWatcher.prototype.onFileTransfersUpdated_ =
    function(status) {
  // If the synced file it isn't one we copied,
  // the call to mark by url will just fail...fine by us.
  if (status.transferState === 'completed') {
    this.history_.markImportedByUrl(status.fileUrl);
  }
};

/**
 * @param {!importer.ImportHistory.ChangedEvent} event
 * @private
 */
importer.DriveSyncWatcher.prototype.onHistoryChanged_ =
    function(event) {
  if (event.state === importer.ImportHistory.State.COPIED) {
    // Check sync status incase the file synced *before* it was able
    // to mark be marked as copied.
    this.checkSyncStatus_(
        event.destination,
        event.destinationUrl,
        event.entry);
  }
};

/**
 * @param {!importer.Destination} destination
 * @param {string} url
 * @param {!FileEntry=} opt_entry Pass this if you have an entry
 *     on hand, else, we'll jump through some extra hoops to
 *     make do without it.
 * @private
 */
importer.DriveSyncWatcher.prototype.checkSyncStatus_ =
    function(destination, url, opt_entry) {
  console.assert(
      destination === importer.Destination.GOOGLE_DRIVE,
      'Unsupported destination: ' + destination);

  this.getSyncStatus_(url)
      .then(
          /**
           * @param {boolean} synced True if file is synced
           * @this {importer.DriveSyncWatcher}
           */
          function(synced) {
            if (synced) {
              if (opt_entry) {
                this.history_.markImported(opt_entry, destination);
              } else {
                this.history_.markImportedByUrl(url);
              }
            }
          }.bind(this))
      .catch(
          importer.getLogger().catcher(
              'drive-sync-watcher-check-sync-status'));
};

/**
 * @param {string} url
 * @return {!Promise<boolean>} Resolves with true if the
 *     file has been synced to the named destination.
 * @private
 */
importer.DriveSyncWatcher.prototype.getSyncStatus_ = function(url) {
  util.URLsToEntries([url])
    .then(
        /** @this {importer.DriveSyncWatcher} */
        function(results) {
          if (results.entries.length)
            return Promise.reject();
          return new Promise(
              /** @this {importer.DriveSyncWatcher} */
              function(resolve, reject) {
                // TODO(smckay): User Metadata Cache...once it is available
                // in the background.
                chrome.fileManagerPrivate.getEntryProperties(
                    [results.entries[0]],
                    ['dirty'],
                    /**
                     * @param {!Array<Object>} propertiesList
                     * @this {importer.DriveSyncWatcher}
                     */
                    function(propertiesList) {
                      console.assert(
                          propertiesList.length === 1,
                          'Got an unexpected number of results.');
                      if (chrome.runtime.lastError) {
                        reject(chrome.runtime.lastError);
                      } else {
                        var data = propertiesList[0];
                        resolve(!data['dirty']);
                      }
                    }.bind(this));
              }.bind(this));
        })
    .catch(importer.getLogger().catcher('drive-sync-watcher-get-sync-status'));
};

/**
 * History loader that provides an ImportHistorty appropriate
 * to user settings (if import history is enabled/disabled).
 *
 * TODO(smckay): Use SynchronizedHistoryLoader directly
 *     once cloud-import feature is enabled by default.
 *
 * @constructor
 * @implements {importer.HistoryLoader}
 * @struct
 *
 * @param {!analytics.Tracker} tracker
 */
importer.RuntimeHistoryLoader = function(tracker) {

  /** @return {!importer.HistoryLoader} */
  this.createRealHistoryLoader_ = function() {
    return new importer.SynchronizedHistoryLoader(
        importer.getHistoryFiles,
        tracker);
  };

  /** @private {boolean} */
  this.needsInitialization_ = true;

  /** @private {!importer.Resolver.<!importer.ImportHistory>} */
  this.historyResolver_ = new importer.Resolver();
};

/** @override */
importer.RuntimeHistoryLoader.prototype.getHistory = function() {
  if (this.needsInitialization_) {
    this.needsInitialization_ = false;
    importer.importEnabled()
        .then(
            /**
             * @param {boolean} enabled
             * @return {!importer.HistoryLoader}
             * @this {importer.RuntimeHistoryLoader}
             */
            function(enabled) {
              return enabled ?
                  this.createRealHistoryLoader_() :
                  new importer.DummyImportHistory(false);
            }.bind(this))
        .then(
            /**
             * @param {!importer.HistoryLoader} loader
             * @this {importer.RuntimeHistoryLoader}
             */
            function(loader) {
              return this.historyResolver_.resolve(loader.getHistory());
            }.bind(this))
        .catch(
            importer.getLogger().catcher(
                'runtime-history-loader-get-history'));
  }

  return this.historyResolver_.promise;
};

/** @override */
importer.RuntimeHistoryLoader.prototype.addHistoryLoadedListener =
    function(listener) {
  this.historyResolver_.promise.then(listener);
};


text:
module HGraph.Graph where

import           Control.Applicative
import           Control.Monad.State
import qualified Data.ByteString     as BS
import qualified Data.Map            as M
import           Data.Maybe
import qualified Data.Serialize      as Se
import qualified Data.Set            as S
import           HGraph.GraphConfig
import           HGraph.Types

emptyGraph :: Graph
emptyGraph = Graph emptyGraphConfig (M.empty, M.empty) (M.empty, M.empty) M.empty M.empty M.empty

alterGraphConfig :: GraphConfig -> GS ()
alterGraphConfig gc = modify (\g -> Graph gc (labelIndexMaps g) (labelMaps g) (nodeLabelInstances g) (nodes g) (edges g))

alterLabelIndexMaps :: LabelIndexMaps -> GS ()
alterLabelIndexMaps lim = modify (\g -> Graph (graphConfig g) lim (labelMaps g) (nodeLabelInstances g) (nodes g) (edges g))

alterLabelMaps :: LabelMaps -> GS ()
alterLabelMaps lm = modify (\g -> Graph (graphConfig g) (labelIndexMaps g) lm (nodeLabelInstances g) (nodes g) (edges g))

alterLabelInstances :: LabelInstances -> GS ()
alterLabelInstances li = modify (\g-> Graph (graphConfig g) (labelIndexMaps g) (labelMaps g) li (nodes g) (edges g))

alterAddLabelInstance :: LabelInstances -> LabelIndex -> Node -> GS ()
alterAddLabelInstance lins li n = alterLabelInstances $ M.alter aux li lins
    where
        i            = nodeId n
        aux Nothing  = Just $ S.singleton i
        aux (Just x) = Just $ S.insert i x

alterAddLabelInstances :: LabelInstances -> S.Set LabelIndex -> Node -> GS ()
alterAddLabelInstances lins lis n = S.foldl aux (return ()) lis
    where
        aux _ li = alterAddLabelInstance lins li n

alterRemoveLabelInstance :: LabelInstances -> LabelIndex -> Node -> GS ()
alterRemoveLabelInstance lins li n = alterLabelInstances $ M.alter aux li lins
    where
        i            = nodeId n
        aux Nothing  = Nothing
        aux (Just x) = Just $ S.delete i x

alterRemoveLabelInstances :: LabelInstances -> S.Set LabelIndex -> Node -> GS ()
alterRemoveLabelInstances lins lis n = S.foldl aux (return ()) lis
    where
        aux _ li = alterRemoveLabelInstance lins li n

alterNodes :: Nodes -> GS ()
alterNodes n = modify (\g -> Graph (graphConfig g) (labelIndexMaps g) (labelMaps g) (nodeLabelInstances g) n (edges g))

alterEdges :: Edges -> GS ()
alterEdges e = modify (\g -> Graph (graphConfig g) (labelIndexMaps g) (labelMaps g) (nodeLabelInstances g) (nodes g) e)

incrementNodeLabelIndex :: GS LabelIndex
incrementNodeLabelIndex = do g <- get
                             let li = nextNodeLabelIndex $ graphConfig g
                             alterGraphConfig $ incrementNodeLabelIndex' $ graphConfig g
                             return li

incrementEdgeLabelIndex :: GS LabelIndex
incrementEdgeLabelIndex = do g <- get
                             let li = nextNodeLabelIndex $ graphConfig g
                             alterGraphConfig $ incrementEdgeLabelIndex' $ graphConfig g
                             return li

incrementNodeId :: GS Id
incrementNodeId = do g <- get
                     let i = nextNodeId $ graphConfig g
                     alterGraphConfig $ incrementNodeId' $ graphConfig g
                     return i

incrementEdgeId :: GS Id
incrementEdgeId = do g <- get
                     let i = nextEdgeId $ graphConfig g
                     alterGraphConfig $ incrementEdgeId' $ graphConfig g
                     return i

getNodeLabels :: GS [Label]
getNodeLabels = do g <- get
                   return $ M.keys $ fst $ labelMaps g

getEdgeLabels :: GS [Label]
getEdgeLabels = do g <- get
                   return $ M.keys $ snd $ labelMaps g

getNodeCount :: GS Int
getNodeCount = do g <- get
                  return $ M.size $ nodes g

getEdgeCount :: GS Int
getEdgeCount = do g <- get
                  return $ M.size $ edges g

getNodeById :: Id -> GS (Maybe Node)
getNodeById i = M.lookup i . nodes <$> get

getNodeByIdUnsafe :: Id -> GS Node
getNodeByIdUnsafe i = fromJust . M.lookup i . nodes <$> get

getEdgeById :: Id -> GS (Maybe Edge)
getEdgeById i = M.lookup i . edges <$> get

getEdgeByIdUnsafe :: Id -> GS Edge
getEdgeByIdUnsafe i = fromJust . M.lookup i . edges <$> get

saveToDisk :: Graph -> FilePath -> IO ()
saveToDisk g fp = BS.writeFile fp $ Se.encode g

loadFromDisk :: FilePath -> IO Graph
loadFromDisk fp = do eg <- Se.decode <$> BS.readFile fp
                     return $ either (error "error reading from disk") id eg

redpajama_set_name: RedPajamaGithub


text:
import zof

APP = zof.Application(__name__)

def role_request(role, generation_id):
    return {
        'type': 'ROLE_REQUEST',
        'msg': {
            'role': role,
            'generation_id': generation_id
        }
    }

@APP.message('CHANNEL_UP')
def channel_up(event):
    ofmsg = role_request('ROLE_MASTER', 1)
    zof.compile(ofmsg).send()

if __name__ == '__main__':
    zof.run()


text:
/* Site-specific javascript */

// Notifications that can both dismiss and point to a separate URL
module.exports.handle_notification_dismiss = function () {
  $(document).ready(function () {
    $('ul.notifications li.notification > a').click(function (ev) {
      var url = $(this).attr('href');
      var dismiss_url = $(this).parent().attr('data-dismiss-url');
      if (dismiss_url) {
        ev.preventDefault();
        $.get(dismiss_url, function (data, text_status, xhr) {
          window.location.href = url;
        });
      }
      else {
        $(this).hide();
      }
    });
  });
}


text:
____
## Features
- [x] User signs up through Eventful (implemented)
- [x] User signs in through Eventful
- [x] User signs out
- [ ] User adds email
- [x] User views their dashboard
- [ ] User adds an item for rent
- [ ] User searches for items
- [ ] User views an available item
- [ ] User views an unavailable item
- [ ] User rents an item

____
## Stories

____
### User signs up through Eventful
> As a user, I want to sign up using Eventful in order to avoid setting up with
> an email & password

* #### Usage:
  * On homepage, click "Sign Up with Eventful"
  * User sees their dashboard

* #### Acceptance Criteria:
  * User is redirected to authorize app
  * User is saved to database with:
    * Name
    * Location

### User signs in through Eventful
> As a user, I want to sign in using Eventful in order to avoid remembering
> an email & password

* #### Usage:
  * On homepage, click "Sign In with Eventful"
  * User sees their dashboard

* #### Acceptance Criteria:
  * User is redirected to authorize app
  * User is logged in

### User signs out
> As a user, I want to sign out in order to leave the app

* #### Usage:
  * On any page, click "Sign Out"
  * User sees homepage

* #### Acceptance Criteria:
  * User is logged out

### User adds email
> As a user, I want to add email in order to rent items

* #### Usage:
  * On dashboard, click "Add Email"
  * User enters email
  * User clicks "Submit"
  * User sees dashboard with no "Add Contact" link

* #### Acceptance Criteria:
  * User is logged in
  * Input must be filled in
  * "Add Contact Info" is not visible if info has been entered

### User views their dashboard
> As a user, I want to view my dashboard in order to see all my rentals

* #### Usage:
  * On any page, user clicks "Dashboard"
  * User sees their dashboard

* #### Acceptance Criteria:
  * User must be logged in
  * User sees their own dashboard

### User adds an item for rent
> As a user, I want to add an item in order to rent it out

* #### Usage:
  * On dashboard, user clicks "Add an Item"
  * User fills in "name", "price", "location" & "description"
  * User uploads a photo
  * User clicks "Add item"
  * User sees their dashboard with new item listed

* #### Acceptance Criteria:
  * User must be logged in
  * User must fill in all inputs

### User searches for items
> As a user, I want to search in order to find items I want to rent

* #### Usage:
  * From search page, user selects a location
  * User selects a category
  * User clicks "Search"
  * User sees all applicable items

* #### Acceptance Criteria:
  * User must be logged in
  * User must select a location
  * User must select a category

### User views an available item
> As a user, I want to view an item in order to find out more information

* #### Usage:
  * User clicks on desired item
  * User sees item view page

* #### Acceptance Criteria:
  * User must be logged in
  * View page must contain photo, "name", "price", "location", & description
  * View page must have a button to rent the item

### User views an unavailable item
> As a user, I want to view an item in order to find out more information

* #### Usage:
  * User clicks on desired item
  * User sees item view page

* #### Acceptance Criteria:
  * User must be logged in
  * View page must contain photo, "name", "price", "location", & description
  * View page must have a notification that item is currently rented

### User rents an item
> As a user, I want to rent an item in order to use it

* #### Usage:
  * From the item view page, user clicks "Rent"
  * User sees dashboard with rented item listed

* #### Acceptance Criteria:
  * User must be logged in
  * User must have contact information in profile


text:
An experiment to try to build an audiovisual live coding environment running in the browser

Since this was built for the very specific purpose of jamming with other musicians, it is a very opinionated tool at the moment. I'm not sure what it will be evolve into, but here's what it is right now:

* A simple, code based pattern sequencer that has up to 16 steps, shuffle and allows you to express the beat in either declarate
* A set of tools, currently crudely exposed through a global object, that allow for sample playing, synthesizer type stuff and a fixed set of predefined effects
* A fullscreen, initialized 2D canvas that can be drawn on in requestAnimationFrame speed.
* Automatic collection of Samples (for Audio) and Images (for canvas)

Documentation is sparse, please look at the examples.

Currently, the live code contains two methods:

draw(canvasContext,state, analyzerData)
* draw will be called within the canvas loop that is based on requestAnimationFrame
* canvasContext is the 2d context of the full screen canvas element (only 2d is supported ATM)
* state is a magical state object you can use to store data that should persist between loop runs
  * state has an init-function that let's you init values if they are not yes existent.
* analyserData is a 16 element float32array of fft data from the sound source. do your thang.

pattern(context, outlet, start_times, step_time, state, data)
* pattern will be called once every time the pattern loops. The pattern is (currently) a 16 step
* pattern with every step matching a 1/16 note.
* *context* is the audioContext
* *outlet* is the audio destination your webaudio objects should ultimately connect to
* *start_times* is an array of start times for the notes in the pattern
* *step_time* is the length of a single step
* *state* is the beforementioned state object (note that the canvas loop and the pattern loop indeed share this object)
* *data* is unused and will most probably contain prefabbed samples etc.

### License

Liv3c0der is released under MIT License. See [LICENSE.txt](LICENSE.txt) for the full license.

### Sample Server

liv3c0der does no longer have any audio assets included. You need to start a seperate compontent to serve assets.

The idea is that hosting samples, especially in high quality, non-lossy-compressed versions on remote servers is possible but not desirable.

Also this makes using your own samples in liv3c0der really, really easy.

I have a working proof-of-concept written in ruby using sinatra at https://github.com/halfbyte/sample-server.

I would love to turn this into a npm binary or something. Any takers?

#### Protocol

Just serve an index at (this is configurable) http://localhost:4567/index.json that looks like this:

{
  "sample_name": "http://sample-url",
  "sample-name": "..."
}

The only other requirement that you set the "Access-Control-Allow-Origin" header to "*" or wherever you serve liv3c0der, because of CORS.

liv3c0der will then load the index and will try to load all urls specified in the index. You can then access the sample list at AE.S.

### Sound Tools

AudioEngine is both responsible for scheduling the events and a growing collection of more high level building blocks.

This is an almost complete list of the high level bulding blocks, but you probably need to read the source to learn how to use each one.

* AE.NOTES contains the MIDI array of note frequencies, so LC.NOTES[0] gives you the lowest C
* AE.LEnv is an Envelope generator created with linearRamps.
  * Signature is (param,time,length,min, max,attack,decay,sustain,release)
  * a,d,r are expressed as fractions of length
  * sustain as fraction of max

* AE.S is an object containing all loaded samples. See above.
* All samples willl be loaded automatically and can be played as soon as they are completely decoded.
* AE.S['<samplename>'] or AE.S.<samplename> is a sample object that has three public methods:
  * play(outlet, time, length, rate)
  * playGrain(outlet, time, offset, length, rate)
  * playShot(outlet, time, rate, volume)
* AE.DelayLine - a configurable delay line that can be used as an output
  * DelayLine.delayTime
  * DelayLine.filterFrequency
  * DelayLine.feedback
* AE.ReverbLine - a configurable reverb line that can be used as an output
  * ReverbLine.mix - mix ratio between original and reverb signal. This is the AudioParam
* AE.DubLine - A combination of delay and reverb, as often used in dub and dubtechno.

* AE.DEL, AE.DUB and AE.REV are shortcuts for the inputs of DelayLine, DubLine and ReverbLine.
* AE.SpreadSynth (will be renamed!) is a dual oscillator synth with full ENVs for amp and filter
* AE.AcidSynth is a single osc synth with a double filter for enhanced squeakability. It has a more simple envelope.
* AE.SawSynth is a configurable "Super Saw" synth with a large number or Sawtooth oscillators all slightly detuned.
* AE.WubSynth is your one-stop-shop Dubstep synth. You wish. It's just a square wave with a lfo driven lowpass.

* AE.DrumSynth is a single oscillator drum synthesizer capable of rendering convincing synthetic bass drums but also toms and random bleeps.
* AE.SnareSynth is a DrumSynth with filtered white noise on top to generate simple snares
* AE.NoiseHat is a simple noise based hihat/cymbal synth that sounds best with high resonance.

* AE.Instance.tempo can be set to the desired tempo in BPM.
* AE.Instance.groove can be set to any value between 0 and 1 to delay each second step in a pattern by a certain percentage to create a shuffled rythm.

* AE.Tuna. See [here](https://github.com/Dinahmoe/tuna), please let it be Tuna. AE.Tuna is an initialized Tuna instance.

### Canvas Tools

This also needs a way to serve images from the outside. Currently the image list is still hardcoded.

* LC.I.<imagename> is an Image() instance that can be used for context.drawImage
* LC.hsla is a simple utility to not deal with string concatenation when creating colors for the canvas
* LC.cls clears the canvas
* LC.centerText centers a given text on the screen


text:
All notable changes to Prologue Alerts will be documented in this file. This file follows the *[Keep a CHANGELOG](http://keepachangelog.com/)* standards.

## [0.4.0-beta.3] - 2015-03-29

### Fixed

- Moved publishes and merge config calls to correct locations

## [0.4.0-beta.2] - 2015-03-29

### Fixed

- Moved merging of config to boot method in service provider

## [0.4.0-beta.1] - 2015-03-29

### Added

- Laravel 5 support

### Changed

- Now requires PHP >=5.4
- All code converted to PSR-2
- Now using PSR-4 auto loading
- Ported Prologue's support MessageBag functionality and removed the dependency

### Removed

- Laravel 4 support

## [0.3.0] - 2014-05-23

### Added

- Add an array of messages to an alert level ([#8](https://github.com/prologuephp/alerts/issues/8))
- Get the alert levels from the MessageBag ([#7](https://github.com/prologuephp/alerts/issues/7))

## [0.2.0] - 2013-08-04

### Added

- Unit tests

### Changed

- Migrated over to Prologue Support's MessageBag class ([#2](https://github.com/prologuephp/alerts/issues/2))

### Fixed

- Some minor bug fixes

### Fixed

- Fixed a bug where only array data could be passed to the `PermissionFactory`
- Fixed a bug where a action alias got denied but was still accepted

## [0.1.1] - 2013-07-19

### Fixed

- Move config folder one folder higher ([#1](https://github.com/prologuephp/alerts/issues/1))

## [0.1.0] - 2013-07-19

First public alpha release.


text:
/*global define*/
/*jslint white:true,browser:true*/

define([
    'bluebird',
    // CDN
    'kb_common/html',
    // LOCAL
    'common/ui',
    'common/events',
    'common/props',
    // Wrapper for inputs
    './inputWrapperWidget',
    'widgets/appWidgets/fieldWidget',
    'widgets/appWidgets/paramInputResolver',

    'common/runtime'
        // All the input widgets

], function (
    Promise,
    html,
    UI,
    Events,
    Props,
    //Wrappers
    RowWidget,
    FieldWidget,
    ParamResolver,
    Runtime

    // Input widgets
    ) {
    'use strict';

    var t = html.tag,
        form = t('form'), span = t('span'), div = t('div');

    function factory(config) {
        var runtime = Runtime.make(),
            parentBus = config.bus,
            workspaceInfo = config.workspaceInfo,
            container,
            ui,
            bus,
            places,
            model = Props.make(),
            inputBusses = [],
            paramResolver = ParamResolver.make(),
            settings = {
                showAdvanced: null
            },
        widgets = [];

        // DATA
        /*
         *
         * Evaluates the parameter spec to determine which input widget needs to be
         * invoked, but doesn't know what the widget does.
         * Provides the communication bus for each input to route info to the widget
         * and out of it.
         *
         *  In terms of widgets it looks like this:
         *
         *  InputCellWidget
         *    inputWidgets
         *      FieldWidget
         *        textInputWidget
         *      FieldWidget
         *        objectInputWidget
         *      FieldWidget
         *        newObjectInputWidget
         *      FieldWidget
         *        integerInputWidget
         *      FieldWidget
         *        floatInputWidget
         */

        /*
         * The input control widget is selected based on these parameters:
         * - data type - (text, int, float, workspaceObject (ref, name)
         * - input app - input, select
         */

        // RENDERING

        function makeFieldWidget(appSpec, parameterSpec, value) {
            var fieldBus = runtime.bus().makeChannelBus(null, 'A field widget'),
                inputWidget = paramResolver.getInputWidgetFactory(parameterSpec);

            inputBusses.push(fieldBus);

            // Forward all changed parameters to the controller. That is our main job!
            fieldBus.on('changed', function (message) {
                parentBus.emit('parameter-changed', {
                    parameter: parameterSpec.id(),
                    newValue: message.newValue
                });
            });

            // An input widget may ask for the current model value at any time.
            fieldBus.on('sync', function () {
                parentBus.emit('parameter-sync', {
                    parameter: parameterSpec.id()
                });
            });

            fieldBus.on('sync-params', function (message) {
                console.log('request sync params', message);
                parentBus.emit('sync-params', {
                    parameters: message.parameters
                });
            });

            /*
             * Or in fact any parameter value at any time...
             */
            fieldBus.on('get-parameter-value', function (message) {
                parentBus.request({
                    parameter: message.parameter
                }, {
                    key: 'get-parameter-value'
                })
                    .then(function (message) {
                        bus.emit('parameter-value', {
                            parameter: message.parameter
                        });
                    });
            });

            //bus.on('parameter-value', function (message) {
            //    bus.emit('parameter-value', message);
            //});

            fieldBus.respond({
                key: {
                    type: 'get-parameter'
                },
                handle: function (message) {
                    console.log('GOT?', message);
                    if (message.parameterName) {
                        return parentBus.request(message, {
                            key: {
                                type: 'get-parameter'
                            }
                        });
                    } else {
                        return null;
                    }
                }
            });

            // Just pass the update along to the input widget.
            parentBus.listen({
                key: {
                    type: 'update',
                    parameter: parameterSpec.id()
                },
                handle: function (message) {
                    fieldBus.emit('update', {
                        value: message.value
                    });
                }
            });

            // just forward...
            //bus.on('newstate', function (message) {
            //    inputWidgetBus.send(message);
            //});
            return {
                bus: bus,
                widget: FieldWidget.make({
                    inputControlFactory: inputWidget,
                    showHint: true,
                    useRowHighight: true,
                    initialValue: value,
                    appSpec: appSpec,
                    parameterSpec: parameterSpec,
                    bus: fieldBus,
                    workspaceId: workspaceInfo.id
                })
            };
        }

        function renderAdvanced(area) {

            // area is either "input" or "parameter"

            var areaElement = area + '-area',
                areaSelector = '[data-element="' + areaElement + '"]',
                advancedInputs = container.querySelectorAll(areaSelector + ' [data-advanced-parameter]');
            if (advancedInputs.length === 0) {
                ui.setContent([areaElement, 'advanced-hidden-message'], '');
                // ui.disableButton('toggle-advanced');
                return;
            }

//            ui.enableButton('toggle-advanced');

            var removeClass = (settings.showAdvanced ? 'advanced-parameter-hidden' : 'advanced-parameter-showing'),
                addClass = (settings.showAdvanced ? 'advanced-parameter-showing' : 'advanced-parameter-hidden');
            for (var i = 0; i < advancedInputs.length; i += 1) {
                var input = advancedInputs[i];
                input.classList.remove(removeClass);
                input.classList.add(addClass);
            }
//
//            // How many advanaced?
//
//            // Also update the button
//            var button = container.querySelector('[data-button="toggle-advanced"]');
//            button.innerHTML = (settings.showAdvanced ? 'Hide Advanced' : 'Show Advanced (' + advancedInputs.length + ' hidden)');

            // Also update the count in the paramters.
            var events = Events.make({node: container});

            var message;
            if (settings.showAdvanced) {
                if (advancedInputs.length > 1) {
                    message = String(advancedInputs.length) + ' advanced parameters showing';
                } else {
                    message = String(advancedInputs.length) + ' advanced parameter showing';
                }
                var showAdvancedButton = ui.buildButton({
                    label: 'hide advanced',
                    type: 'link',
                    name: 'advanced-parameters-toggler',
                    event: {
                        type: 'toggle-advanced'
                    },
                    events: events
                });

                ui.setContent([areaElement, 'advanced-hidden-message'], '(' + message + ') ' + showAdvancedButton);
            } else {
                if (advancedInputs.length > 1) {
                    message = String(advancedInputs.length) + ' advanced parameters hidden';
                } else {
                    message = String(advancedInputs.length) + ' advanced parameter hidden';
                }
                var showAdvancedButton = ui.buildButton({
                    label: 'show advanced',
                    type: 'link',
                    name: 'advanced-parameters-toggler',
                    event: {
                        type: 'toggle-advanced'
                    },
                    events: events
                });

                ui.setContent([areaElement, 'advanced-hidden-message'], '(' + message + ') ' + showAdvancedButton);
            }

            events.attachEvents();
        }

        function renderLayout() {
            var events = Events.make(),
                content = form({dataElement: 'input-widget-form'}, [
                    ui.buildPanel({
                        type: 'default',
                        body: [
                            // ui.makeButton('Show Advanced', 'toggle-advanced', {events: events}),
                            div({
                                class: 'btn-toolbar pull-right'
                            }, [
                                ui.buildButton({
                                    events: events,
                                    name: 'reset-to-defaults',
                                    icon: {
                                        name: 'recycle'
                                    },
                                    label: 'Reset'
                                })
                                // ui.makeButton('Reset to Defaults', 'reset-to-defaults', {events: events})
                            ])
                        ],
                        classes: ['kb-panel-light']
                    }),
                    ui.buildPanel({
                        title: span(['Input Objects', span({dataElement: 'advanced-hidden-message', style: {marginLeft: '6px', fontStyle: 'italic'}})]),
                        name: 'input-objects-area',
                        body: div({dataElement: 'input-fields'}),
                        classes: ['kb-panel-light']
                    }),
                    // ui.makePanel('Input Objects', 'input-fields'),
                    ui.buildPanel({
                        title: span(['Parameters', span({dataElement: 'advanced-hidden-message', style: {marginLeft: '6px', fontStyle: 'italic'}})]),
                        name: 'parameters-area',
                        body: div({dataElement: 'parameter-fields'}),
                        classes: ['kb-panel-light']
                    }),
                    ui.buildPanel({
                        title: 'Output Objects',
                        name: 'output-objects-area',
                        body: div({dataElement: 'output-fields'}),
                        classes: ['kb-panel-light']
                    })
                        // ui.makePanel('Output Report', 'output-report')
                ]);

            return {
                content: content,
                events: events
            };
        }

        // MESSAGE HANDLERS

        function doAttach(node) {
            container = node;
            ui = UI.make({
                node: container,
                bus: bus
            });
            var layout = renderLayout();
            container.innerHTML = layout.content;
            layout.events.attachEvents(container);
            places = {
                inputFields: ui.getElement('input-fields'),
                outputFields: ui.getElement('output-fields'),
                parameterFields: ui.getElement('parameter-fields'),
                advancedParameterFields: ui.getElement('advanced-parameter-fields')
            };
        }

        // EVENTS

        function attachEvents() {
            bus.on('reset-to-defaults', function () {
                inputBusses.forEach(function (inputBus) {
                    inputBus.emit('reset-to-defaults');
                });
            });
            bus.on('toggle-advanced', function () {
                // we can just do that here? Or defer to the inputs?
                // I don't know ...
                //inputBusses.forEach(function (bus) {
                //    bus.send({
                //        type: 'toggle-advanced'
                //    });
                //});
                settings.showAdvanced = !settings.showAdvanced;
                renderAdvanced('input-objects');
                renderAdvanced('parameters');
            });
            runtime.bus().on('workspace-changed', function () {
                // tell each input widget about this amazing event!
                widgets.forEach(function (widget) {
                    widget.bus.emit('workspace-changed');
                });
            });
        }

        // Maybe
        function validateParameterSpec(spec) {
            // ensure that inputs are consistent with inputs

            // and outputs with output

            // and params with param

            // validate type

            return spec;
        }

        function validateParameterSpecs(params) {
            return params.map(function (spec) {
                return validateParameterSpec(spec);
            });
        }

        // LIFECYCLE API

        function renderParameters(params) {
            // First get the app specs, which is stashed in the model,
            // with the parameters returned.
            // Separate out the params into the primary groups.
            var appSpec = model.getItem('appSpec');

            return Promise.try(function () {
                var params = validateParameterSpecs(model.getItem('parameters')),
                    inputParams = params.filter(function (spec) {
                        return (spec.paramClass() === 'input');
                    }),
                    outputParams = params.filter(function (spec) {
                        return (spec.paramClass() === 'output');
                    }),
                    parameterParams = params.filter(function (spec) {
                        return (spec.paramClass() === 'parameter');
                    });

                return Promise.resolve()
                    .then(function () {
                        if (inputParams.length === 0) {
                            places.inputFields.innerHTML = span({style: {fontStyle: 'italic'}}, 'No input objects for this app');
                        } else {
                            return Promise.all(inputParams.map(function (spec) {
                                try {
                                    var result = makeFieldWidget(appSpec, spec, model.getItem(['params', spec.name()])),
                                        rowWidget = RowWidget.make({widget: result.widget, spec: spec}),
                                        rowNode = document.createElement('div');
                                    places.inputFields.appendChild(rowNode);
                                    widgets.push({
                                        widget: rowWidget,
                                        bus: result.bus
                                    });
                                    rowWidget.attach(rowNode);
                                } catch (ex) {
                                    console.error('Error making input field widget', ex);
                                    // TRY Throwing up
                                    // or not: throw new Error('Error making input field widget: ' + ex.message);
                                    var errorDisplay = div({style: {border: '1px red solid'}}, [
                                        ex.message
                                    ]);
                                    places.inputFields.appendChild(ui.createNode(errorDisplay));
                                }
                            }));
                        }
                    })
                    .then(function () {
                        if (outputParams.length === 0) {
                            places.outputFields.innerHTML = span({style: {fontStyle: 'italic'}}, 'No output objects for this app');
                        } else {
                            return Promise.all(outputParams.map(function (spec) {
                                try {
                                    var result = makeFieldWidget(appSpec, spec, model.getItem(['params', spec.name()])),
                                        rowWidget = RowWidget.make({widget: result.widget, spec: spec}),
                                        rowNode = document.createElement('div');
                                    places.outputFields.appendChild(rowNode);
                                    widgets.push({
                                        widget: rowWidget,
                                        bus: result.bus
                                    });
                                    rowWidget.attach(rowNode);
                                } catch (ex) {
                                    console.error('Error making output field widget', ex);
                                    // throw new Error('Error making output field widget: ' + ex.message);
                                    var errorDisplay = div({style: {border: '1px red solid'}}, [
                                        ex.message
                                    ]);
                                    places.outputFields.appendChild(ui.createNode(errorDisplay));
                                }
                            }));
                        }
                    })
                    .then(function () {
                        // Show the user that a report object will be created. Otherwise it may seem weird that there is
                        // no way to specify the output object
                        //if (env.appSpec) {
                        //    +++
                        // }
                    })
                    .then(function () {
                        if (parameterParams.length === 0) {
                            // TODO: should be own node
                            ui.setContent('parameter-fields', span({style: {fontStyle: 'italic'}}, 'No parameters for this app'));
                        } else {
                            return Promise.all(parameterParams.map(function (spec) {
                                try {
                                    var result = makeFieldWidget(appSpec, spec, model.getItem(['params', spec.name()])),
                                        rowWidget = RowWidget.make({widget: result.widget, spec: spec}),
                                        rowNode = document.createElement('div');
                                    places.parameterFields.appendChild(rowNode);
                                    widgets.push({
                                        widget: rowWidget,
                                        bus: result.bus
                                    });
                                    rowWidget.attach(rowNode);
                                } catch (ex) {
                                    console.error('Error making parameter field widget', ex);
                                    var errorDisplay = div({style: {border: '1px red solid'}}, [
                                        ex.message
                                    ]);
                                    places.parameterFields.appendChild(ui.createNode(errorDisplay));
                                }
                            }));
                        }
                    })
                    .then(function () {
                        return Promise.all(widgets.map(function (widget) {
                            return widget.widget.start();
                        }));
                    })
                    .then(function () {
                        return Promise.all(widgets.map(function (widget) {
                            return widget.widget.run(params);
                        }));
                    })
                    .then(function () {
                        renderAdvanced('input-objects');
                        renderAdvanced('parameters');
                    });
            });
        }

        function start() {

            return Promise.try(function () {
                // send parent the ready message
                parentBus.emit('ready');

                // parent will send us our initial parameters
                parentBus.on('run', function (message) {
                    doAttach(message.node);

                    model.setItem('appSpec', message.appSpec);
                    model.setItem('parameters', message.parameters);

                    // we then create our widgets
                    renderParameters()
                        .then(function () {
                            // do something after success
                            attachEvents();
                        })
                        .catch(function (err) {
                            // do somethig with the error.
                            console.error('ERROR in start', err);
                        });
                });

                parentBus.on('parameter-changed', function (message) {
                    // Also, tell each of our inputs that a param has changed.
                    // TODO: use the new key address and subscription
                    // mechanism to make this more efficient.
                    inputBusses.forEach(function (bus) {
                        bus.send(message, {
                            key: {
                                type: 'parameter-changed',
                                parameter: message.parameter
                            }
                        });
                        // bus.emit('parameter-changed', message);
                    });
                });
            });
        }

        function stop() {
            return Promise.try(function () {
                // really unhook things here.
            });
        }

        // CONSTRUCTION

        bus = runtime.bus().makeChannelBus(null, 'A app params widget');

        return {
            start: start,
            stop: stop,
            bus: function () {
                return bus;
            }
        };
    }

    return {
        make: function (config) {
            return factory(config);
        }
    };
});


text:
<?php

namespace Magento\User\Controller\Adminhtml\Auth;

class Forgotpassword extends \Magento\User\Controller\Adminhtml\Auth
{
    /**
     * Forgot administrator password action
     *
     * @return void
     */
    public function execute()
    {
        $email = (string)$this->getRequest()->getParam('email');
        $params = $this->getRequest()->getParams();

        if (!empty($email) && !empty($params)) {
            // Validate received data to be an email address
            if (\Zend_Validate::is($email, 'EmailAddress')) {
                $collection = $this->_objectManager->get('Magento\User\Model\ResourceModel\User\Collection');
                /** @var $collection \Magento\User\Model\ResourceModel\User\Collection */
                $collection->addFieldToFilter('email', $email);
                $collection->load(false);

                if ($collection->getSize() > 0) {
                    foreach ($collection as $item) {
                        /** @var \Magento\User\Model\User $user */
                        $user = $this->_userFactory->create()->load($item->getId());
                        if ($user->getId()) {
                            $newPassResetToken = $this->_objectManager->get(
                                'Magento\User\Helper\Data'
                            )->generateResetPasswordLinkToken();
                            $user->changeResetPasswordLinkToken($newPassResetToken);
                            $user->save();
                            $user->sendPasswordResetConfirmationEmail();
                        }
                        break;
                    }
                }
                // @codingStandardsIgnoreStart
                $this->messageManager->addSuccess(__('We\'ll email you a link to reset your password.'));
                // @codingStandardsIgnoreEnd
                $this->getResponse()->setRedirect(
                    $this->_objectManager->get('Magento\Backend\Helper\Data')->getHomePageUrl()
                );
                return;
            } else {
                $this->messageManager->addError(__('Please correct this email address:'));
            }
        } elseif (!empty($params)) {
            $this->messageManager->addError(__('Please enter an email address.'));
        }
        $this->_view->loadLayout();
        $this->_view->renderLayout();
    }
}


text:
function m=genmatrix1(dmat)
echo off
% genereert een generieke random matrix
a = rand(dmat);
x = randi(100,dmat,1)-1;
m = [a a*x];


text:
using Aliencube.CryptoService.Interfaces;

namespace Aliencube.CryptoService
{
    /// <summary>
    /// This represents the base class for cryption service entities. This must be inherited.
    /// </summary>
    public abstract class CryptoServiceBase : ICryptoServiceBase
    {
        /// <summary>
        /// Transforms the value.
        /// </summary>
        /// <param name="value">Value to transform.</param>
        /// <param name="direction">Direction to transform.</param>
        /// <returns>Returns the value transformed.</returns>
        public abstract string Transform(string value, CryptoDirection direction);

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public virtual void Dispose()
        {
        }
    }
}


text:
> New as of 0.3.1

```
apps:clone <old-app> <new-app>                 # Clones an app
apps:create <app>                              # Create a new app
apps:destroy <app>                             # Permanently destroy an app
apps:exists <app>                              # Checks if an app exists
apps:list                                      # List your apps
apps:lock <app>                                # Locks an app for deployment
apps:locked <app>                              # Checks if an app is locked for deployment
apps:rename <old-app> <new-app>                # Rename an app
apps:report [<app>] [<flag>]                   # Display report about an app
apps:unlock <app>                              # Unlocks an app for deployment
```

## Usage

### Listing applications

> New as of 0.8.1. Use the `apps` command for older versions.

You can easily list all available applications using the `apps:list` command:

```shell
dokku apps:list
```

```
=====> My Apps
node-js-app
python-app
```

Note that you can easily hide extra output from Dokku commands by using the `--quiet` flag, which makes it easier to parse on the command line.

```shell
dokku --quiet apps:list
```

```
node-js-app
python-app
```

### Checking if an application exists

For CI/CD pipelines, it may be useful to see if an application exists before creating a "review" application for a specific branch. You can do so via the `apps:exists` command:

```shell
dokku apps:exists  node-js-app
```

```
App does not exist
```

The `apps:exists` command will return non-zero if the application does not exist, and zero if it does.

### Manually creating an application

A common pattern for deploying applications to Dokku is to configure an application before deploying it. You can do so via the `apps:create` command:

```shell
dokku apps:create node-js-app
```

```
Creating node-js-app... done
```

Once created, you can configure the application as normal, and deploy the application whenever ready. This is useful for cases where you may wish to do any of the following kinds of tasks:

- Configure domain names and SSL certificates.
- Create and link datastores.
- Set environment variables.

### Removing a deployed app

In some cases, you may need to destroy an application, whether it is because the application is temporary or because it was misconfigured. In these cases, you can use the `apps:destroy` command. Performing any destructive actions in Dokku requires confirmation, and this command will ask for the name of the application being deleted before doing so.

```shell
dokku apps:destroy node-js-app
```

```
 !     WARNING: Potentially Destructive Action
 !     This command will destroy node-js-app (including all add-ons).
 !     To proceed, type "node-js-app"

> node-js-app
Destroying node-js-app (including all add-ons)
```

This will prompt you to verify the application's name before destroying it. You may also use the `--force` flag to circumvent this verification process:

```shell
dokku --force apps:destroy node-js-app
```

```
Destroying node-js-app (including all add-ons)
```

The `--force` flag can also be specified on the command vs globally:

```shell
dokku apps:destroy --force node-js-app
```

```
Destroying node-js-app (including all add-ons)
```

Destroying an application will unlink all linked services and destroy any config related to the application. Note that linked services will retain their data for later use (or removal).

### Renaming a deployed app

> New as of 0.4.7

You can rename a deployed app using the `apps:rename` command. Note that the application *must* have been deployed at least once, or the rename will not complete successfully:

```shell
dokku apps:rename node-js-app io-js-app
```

```
Destroying node-js-app (including all add-ons)
-----> Cleaning up...
-----> Building io-js-app from herokuish...
-----> Adding BUILD_ENV to build environment...
-----> Node.js app detected

-----> Creating runtime environment

...

=====> Application deployed:
       http://io-js-app.ci.dokku.me

Renaming node-js-app to io-js-app... done
```

This will copy all of your app's contents into a new app directory with the name of your choice, delete your old app, then rebuild the new version of the app and deploy it. All of your config variables, including database urls, will be preserved.

By default, Dokku will deploy the renamed app, though you can skip the deploy by using the `--skip-deploy` flag:

```shell
dokku apps:rename --skip-deploy node-js-app io-js-app
```

Remember to also change your git remote on your local machine in order to make `git push dokku main:master` work again. For this you can use `git remote set-url`.

```shell
git remote set-url dokku dokku@dokku.me:io-js-app
```

### Cloning an existing app

> New as of 0.11.5

You can clone an existing app using the `apps:clone` command.  Note that the application *must* have been deployed at least once, or cloning will not complete successfully:

```shell
dokku apps:clone node-js-app io-js-app
```

```
Cloning node-js-app to io-js-app... done
```

This will copy all of your app's contents into a new app directory with the name of your choice and then rebuild the new version of the app and deploy it with the following caveats:

- All of your environment variables, including database urls, will be preserved.
- Custom domains are not applied to the new app.
- SSL certificates will not be copied to the new app.
- Port mappings with the scheme `https` and host-port `443` will be skipped.

> Warning: If you have exposed specific ports via `docker-options` plugin, or performed anything that cannot be done against multiple applications, `apps:clone` may result in errors.

By default, Dokku will deploy this new app, though you can skip the deploy by using the `--skip-deploy` flag:

```shell
dokku apps:clone --skip-deploy node-js-app io-js-app
```

Finally, if the application already exists, you may wish to ignore errors resulting from attempting to clone over it. To do so, you can use the `--ignore-existing` flag. A warning will be emitted, but the command will return `0`.

```shell
dokku apps:clone --ignore-existing node-js-app io-js-app
```

### Locking app deploys

> New as of 0.11.6

If you wish to disable deploying for a period of time, this can be done via deploy locks. Normally, deploy locks exist only for the duration of a deploy so as to avoid deploys from colliding, but a deploy lock can be created by running the `apps:lock` command.

```shell
dokku apps:lock node-js-app
```

```
-----> Deploy lock created
```

### Unlocking app deploys

> New as of 0.11.6

In some cases, it may be necessary to remove an existing deploy lock. This can be performed via the `apps:unlock` command.

> Warning: Removing the deploy lock *will not* stop in progress deploys. At this time, in progress deploys will need to be manually terminated by someone with server access.

```shell
dokku apps:unlock node-js-app
```

```
 !     A deploy may be in progress.
 !     Removing the app lock will not stop in progress deploys.
-----> Deploy lock removed.
```

### Checking lock status

> New as of 0.13.0

In some cases, you may wish to inspect the state of an app lock. To do so, you can issue an `apps:lock` command. This will exit non-zero if there is no app lock in place.

```shell
dokku apps:locked node-js-app
```

```
Deploy lock does not exist
```

### Displaying reports for an app

> New as of 0.8.1

You can get a report about the deployed apps using the `apps:report` command:

```shell
dokku apps:report
```

```
=====> node-js-app app information
       App created at:              1635126111
       App dir:                     /home/dokku/node-js-app
       App deploy source:           git
       App deploy source metadata:  cd7b8afccb202f222e7dc7b427553e71ba5ddafd
       App locked:                  false
=====> python-sample app information
       App created at:              1635126000
       App dir:                     /home/dokku/python-sample
       App deploy source:
       App deploy source metadata:
       App locked:                  false
=====> ruby-sample app information
       App created at:              1635122462
       App dir:                     /home/dokku/ruby-sample
       App deploy source:           git
       App deploy source metadata:  c60921ea2799ca108276414b95ea197f16798d51
       App locked:                  false
```

You can run the command for a specific app also.

```shell
dokku apps:report node-js-app
```

```
=====> node-js-app app information
       App dir:                     /home/dokku/node-js-app
       App deploy source:           git
       App deploy source metadata:  cd7b8afccb202f222e7dc7b427553e71ba5ddafd
       App locked:                  false
```

You can pass flags which will output only the value of the specific information you want. For example:

```shell
dokku apps:report node-js-app --app-dir
```


text:
<!DOCTYPE HTML>
<html>
<head>
<style>
#autosize {
  font-size: 10px;
}
</style>
<script src="resources/autosizingTest.js"></script>
<script>
  function test() {
    var autosizeContainer = document.getElementById('autosize');
    var forceLayout = autosizeContainer.offsetWidth;
    var computedFontSize = parseInt(window.getComputedStyle(autosizeContainer).fontSize);
    if (computedFontSize > 10)
      document.write('PASS');
    else
      document.write('FAIL. Expected a font size above 10, got ' + computedFontSize);
    if (window.testRunner)
      testRunner.dumpAsText();
  }
</script>
</head>
<body onload="test()">
  <div id="autosize">
    This test passes if this text is autosized, the font size change is observable from javascript, and FAIL is not printed. I'm just adding lines so this text is long enough to autosize. I'm just adding lines so this text is long enough to autosize. I'm just adding lines so this text is long enough to autosize. I'm just adding lines so this text is long enough to autosize. I'm just adding lines so this text is long enough to autosize. I'm just adding lines so this text is long enough to autosize.
  </div>
</body>
</html>


text:
package com.github.javarch.jsf.mbeans;

import javax.inject.Named;

import com.github.javarch.persistence.Persistable;

@Named
public abstract class AbstractCreateManagedBean <T extends Persistable<?>> extends AbstractFormManagedBean<T>{

	private static final long serialVersionUID = 241528714229926461L;

	@Override
	public void onAction(T entidade) {
		log.debug("Exectando default action");
		repository.saveOrUpdate( entidade );
	}
}


text:
        <input type="text" class="form-control" id="usernamefield" placeholder="{{ 'SEARCH' | translate }}" [(ngModel)]="query" />

      {{ 'USERS' | translate }}:

            {{user.name}}
            <button id="deleteBtn" type="button" class="btn btn-danger btn-xs deleteBtn" aria-label="Left Align" data-toggle="modal"
              data-target="#myModal" data-backdrop="static" *ngIf="shouldApplySelectedUserLayout(user)">

            </button>

          {{ 'LOGIN' | translate }}

          {{ 'CREATE_USER' | translate }}

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

{{ 'DELETE_USER_TITLE' | translate }}

            {{ 'DELETE_USER_QUESTION' | translate }}

              {{selectedUser.name}}

            <button type="button" id="yesBtn" class="btn btn-danger" data-dismiss="modal" (click)="deleteUser()">{{ 'YES' | translate }}</button>
            <button type="button" id="noBtn" class="btn btn-default" data-dismiss="modal" (click)="deleteCancelled()">{{ 'NO' | translate }}</button>


text:
const React = require('react')

const CompLibrary = require('../../core/CompLibrary.js')
const Container = CompLibrary.Container
const GridBlock = CompLibrary.GridBlock

const siteConfig = require(process.cwd() + '/siteConfig.js')

function docUrl(doc, language) {
  return siteConfig.baseUrl + 'docs/' + (language ? language + '/' : '') + doc
}

class Help extends React.Component {
  render() {
    let language = this.props.language || ''
    const supportLinks = [
      {
        content: `Learn more about rest-hapi using the [documentation on this site.](${docUrl(
          'quick-start.html',
          null
        )})`,
        title: 'Browse the docs'
      },
      {
        content:
          'Ask questions about the documentation and project. Join the conversation on [gitter](https://gitter.im/rest-hapi/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)!',
        title: 'Gitter'
      },
      {
        content:
          'You can follow and contact us on [Twitter](https://twitter.com/resthapi).',
        title: 'Twitter'
      },
      {
        content:
          'At our [GitHub repo](https://github.com/JKHeadley/rest-hapi) Browse and submit [issues](https://github.com/JKHeadley/rest-hapi/issues) or [pull requests](https://github.com/JKHeadley/rest-hapi/pulls) for bugs you find or any new features you may want implemented. Be sure to also check out our [contributing information](https://github.com/JKHeadley/rest-hapi/blob/master/CONTRIBUTING.md).',
        title: 'GitHub'
      }
    ]

    return (

        <Container className="mainContainer documentContainer postContainer">

Need help?

              If you need help with rest-hapi, you can try one of the mechanisms
              below.

            <GridBlock contents={supportLinks} layout="fourColumn" />

        </Container>

    )
  }
}

module.exports = Help


text:
package org.openhubframework.openhub.component.circuitbreaker;

import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.impl.DefaultComponent;
import org.apache.camel.util.StringHelper;
import org.openhubframework.openhub.spi.circuitbreaker.CircuitBreaker;
import org.openhubframework.openhub.spi.circuitbreaker.CircuitConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

/**
 * Custom component for simple use of circuit breaker.
 *
 * Usage:
 * .to("circuit:<circuit-name>:<uri-to-call>"),
 * where:
 *  <circuit-name> is unique name of circuit, recommended granularity
 *  is one circuit per target system.
 *  <uri-to-call> is uri to be invoked if circuit is up.
 * Configuration:
 *  {@link CircuitConfiguration} in Exchange property {@link CircuitBreaker#CONFIGURATION_PROPERTY}
 *
 * @author Karel Kovarik
 * @see CircuitBreaker
 * @since 2.2
 */
public class CircuitComponent extends DefaultComponent {

    /**
     * CircuitBreaker interface implementation.
     * If none is provided, component cannot be used.
     */
    @Autowired
    private CircuitBreaker circuitBreaker;

    /**
     * Camel producer template.
     */
    @Produce
    private ProducerTemplate producerTemplate;

    /**
     * CamelContext.
     */
    @Autowired
    private CamelContext camelContext;

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        final CircuitEndpoint endpoint = new CircuitEndpoint(uri, this);

        final String endpointURI = StringHelper.after(uri, ":");
        Assert.hasText(endpointURI, "the endpointURI must not be empty");

        final String name = StringHelper.before(endpointURI, ":");
        Assert.hasText(name, "the circuitName must not be empty.");
        final String trimmedName = name.replaceAll("/", "").trim();
        Assert.hasText(trimmedName, "the trimmed circuitName must not be empty.");
        final String targetUri = StringHelper.after(endpointURI, ":");
        Assert.hasText(targetUri, "the targetUri must not be empty.");

        endpoint.setCircuitName(trimmedName);
        endpoint.setTargetUri(targetUri);
        return endpoint;
    }

    /**
     * Get instance of CircuitBreaker implementation.
     */
    protected CircuitBreaker getCircuitBreaker() {
        return circuitBreaker;
    }

    /**
     * Get instance of producerTemplate.
     */
    protected ProducerTemplate getProducerTemplate() {
        return producerTemplate;
    }

    @Override
    protected void validateParameters(String uri, Map<String, Object> parameters, String optionPrefix) {
        // do nothing, do not call validation from parent - DefaultComponent
    }
}


text:
package org.apache.flink.test.iterative.nephele.customdanglingpagerank;

import java.util.Set;

import org.apache.flink.api.common.functions.AbstractRichFunction;
import org.apache.flink.api.common.functions.GenericCollectorMap;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.test.iterative.nephele.ConfigUtils;
import org.apache.flink.test.iterative.nephele.customdanglingpagerank.types.VertexWithRankAndDangling;
import org.apache.flink.test.iterative.nephele.danglingpagerank.PageRankStats;
import org.apache.flink.util.Collector;

@SuppressWarnings("deprecation")
public class CustomCompensatingMap extends AbstractRichFunction implements GenericCollectorMap<VertexWithRankAndDangling, VertexWithRankAndDangling> {

	private static final long serialVersionUID = 1L;

	private boolean isFailureIteration;

	private boolean isFailingWorker;

	private double uniformRank;

	private double rescaleFactor;

	@Override
	public void open(Configuration parameters) throws Exception {
		int currentIteration = getIterationRuntimeContext().getSuperstepNumber();
		int failingIteration = ConfigUtils.asInteger("compensation.failingIteration", parameters);
		isFailureIteration = currentIteration == failingIteration + 1;

		int workerIndex = getRuntimeContext().getIndexOfThisSubtask();
		Set<Integer> failingWorkers = ConfigUtils.asIntSet("compensation.failingWorker", parameters);
		isFailingWorker = failingWorkers.contains(workerIndex);

		long numVertices = ConfigUtils.asLong("pageRank.numVertices", parameters);

		if (currentIteration > 1) {

			PageRankStats stats = (PageRankStats) getIterationRuntimeContext().getPreviousIterationAggregate(CustomCompensatableDotProductCoGroup.AGGREGATOR_NAME);

			uniformRank = 1d / (double) numVertices;
			double lostMassFactor = (numVertices - stats.numVertices()) / (double) numVertices;
			rescaleFactor = (1 - lostMassFactor) / stats.rank();
		}
	}

	@Override
	public void map(VertexWithRankAndDangling pageWithRank, Collector<VertexWithRankAndDangling> out) throws Exception {

		if (isFailureIteration) {
			double rank = pageWithRank.getRank();

			if (isFailingWorker) {
				pageWithRank.setRank(uniformRank);
			} else {
				pageWithRank.setRank(rank * rescaleFactor);
			}
		}
		out.collect(pageWithRank);
	}
}


text:
<?php

namespace SkyaTura\EloquentREST\Traits;

use Illuminate\Http\Request;
use SkyaTura\EloquentREST\Classes\ResponseDataClass;

trait ResponseTrait
{
    private function responseAs($obj, $type = 'json', $code = 200)
    {
        $response = new ResponseDataClass($obj);
        return response()->$type($response->toArray(), $code);
    }

    public function responseError($msg = 'Unknown error', $code = 500, $type = 'json')
    {
        return response()->$type(['error' => $msg], $code);
    }

    public function responseEmpty($type = 'json')
    {
        return response()->$type([], 204);
    }

    public function response($object, $type = 'json')
    {
        return $this->responseAs($object, $type);
    }
}


text:
// scalastyle:off println
package org.apache.spark.examples

import java.util.Random

import scala.math.exp

import breeze.linalg.{DenseVector, Vector}

import org.apache.spark.sql.SparkSession

/**
 * Logistic regression based classification.
 *
 * This is an example implementation for learning how to use Spark. For more conventional use,
 * please refer to org.apache.spark.ml.classification.LogisticRegression.
 */
object SparkHdfsLR {
  val D = 10   // Number of dimensions
  val rand = new Random(42)

  case class DataPoint(x: Vector[Double], y: Double)

  def parsePoint(line: String): DataPoint = {
    val tok = new java.util.StringTokenizer(line, " ")
    val y = tok.nextToken.toDouble
    val x = new Array[Double](D)
    var i = 0
    while (i < D) {
      x(i) = tok.nextToken.toDouble; i += 1
    }
    DataPoint(new DenseVector(x), y)
  }

  def showWarning() {
    System.err.println(
      """WARN: This is a naive implementation of Logistic Regression and is given as an example!
        |Please use org.apache.spark.ml.classification.LogisticRegression
        |for more conventional use.
      """.stripMargin)
  }

  def main(args: Array[String]) {

    if (args.length < 2) {
      System.err.println("Usage: SparkHdfsLR <file> <iters>")
      System.exit(1)
    }

    showWarning()

    val spark = SparkSession
      .builder
      .appName("SparkHdfsLR")
      .getOrCreate()

    val inputPath = args(0)
    val lines = spark.read.textFile(inputPath).rdd

    val points = lines.map(parsePoint).cache()
    val ITERATIONS = args(1).toInt

    // Initialize w to a random value
    val w = DenseVector.fill(D) {2 * rand.nextDouble - 1}
    println(s"Initial w: $w")

    for (i <- 1 to ITERATIONS) {
      println(s"On iteration $i")
      val gradient = points.map { p =>
        p.x * (1 / (1 + exp(-p.y * (w.dot(p.x)))) - 1) * p.y
      }.reduce(_ + _)
      w -= gradient
    }

    println(s"Final w: $w")
    spark.stop()
  }
}
// scalastyle:on println