text:
// Copyright (c) 2012 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.

/**
 * Represents each volume, such as "drive", "download directory", each "USB
 * flush storage", or "mounted zip archive" etc.
 *
 * @constructor
 * @struct
 *
 * @param {VolumeManagerCommon.VolumeType} volumeType The type of the volume.
 * @param {string} volumeId ID of the volume.
 * @param {FileSystem} fileSystem The file system object for this volume.
 * @param {(string|undefined)} error The error if an error is found.
 * @param {(string|undefined)} deviceType The type of device
 *     ('usb'|'sd'|'optical'|'mobile'|'unknown') (as defined in
 *     chromeos/disks/disk_mount_manager.cc). Can be undefined.
 * @param {(string|undefined)} devicePath Identifier of the device that the
 *     volume belongs to. Can be undefined.
 * @param {boolean} isReadOnly True if the volume is read only.
 * @param {!{displayName:string, isCurrentProfile:boolean}} profile Profile
 *     information.
 * @param {string} label Label of the volume.
 * @param {(string|undefined)} extensionId Id of the extension providing this
 *     volume. Empty for native volumes.
 * @param {boolean} hasMedia When true the volume has been identified
 *     as containing media such as photos or videos.
 * @param {boolean} configurable When true, then the volume can be configured.
 * @param {VolumeManagerCommon.Source} source Source of the volume's data.
 */
function VolumeInfo(
    volumeType,
    volumeId,
    fileSystem,
    error,
    deviceType,
    devicePath,
    isReadOnly,
    profile,
    label,
    extensionId,
    hasMedia,
    configurable,
    watchable,
    source) {
  this.volumeType_ = volumeType;
  this.volumeId_ = volumeId;
  this.fileSystem_ = fileSystem;
  this.label_ = label;
  this.displayRoot_ = null;

  /** @type {Object<!FakeEntry>} */
  this.fakeEntries_ = {};

  /** @type {Promise.<!DirectoryEntry>} */
  this.displayRootPromise_ = null;

  if (volumeType === VolumeManagerCommon.VolumeType.DRIVE) {
    // TODO(mtomasz): Convert fake entries to DirectoryProvider.
    this.fakeEntries_[VolumeManagerCommon.RootType.DRIVE_OFFLINE] = {
      isDirectory: true,
      rootType: VolumeManagerCommon.RootType.DRIVE_OFFLINE,
      toURL: function() { return 'fake-entry://drive_offline'; }
    };
    this.fakeEntries_[VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME] = {
      isDirectory: true,
      rootType: VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME,
      toURL: function() { return 'fake-entry://drive_shared_with_me'; }
    };
    this.fakeEntries_[VolumeManagerCommon.RootType.DRIVE_RECENT] = {
      isDirectory: true,
      rootType: VolumeManagerCommon.RootType.DRIVE_RECENT,
      toURL: function() { return 'fake-entry://drive_recent'; }
    };
  }

  // Note: This represents if the mounting of the volume is successfully done
  // or not. (If error is empty string, the mount is successfully done).
  // TODO(hidehiko): Rename to make this more understandable.
  this.error_ = error;
  this.deviceType_ = deviceType;
  this.devicePath_ = devicePath;
  this.isReadOnly_ = isReadOnly;
  this.profile_ = Object.freeze(profile);
  this.extensionId_ = extensionId;
  this.hasMedia_ = hasMedia;
  this.configurable_ = configurable;
  this.watchable_ = watchable;
  this.source_ = source;
}

VolumeInfo.prototype = /** @struct */ {
  /**
   * @return {VolumeManagerCommon.VolumeType} Volume type.
   */
  get volumeType() {
    return this.volumeType_;
  },
  /**
   * @return {string} Volume ID.
   */
  get volumeId() {
    return this.volumeId_;
  },
  /**
   * @return {FileSystem} File system object.
   */
  get fileSystem() {
    return this.fileSystem_;
  },
  /**
   * @return {DirectoryEntry} Display root path. It is null before finishing to
   * resolve the entry.
   */
  get displayRoot() {
    return this.displayRoot_;
  },
  /**
   * @return {Object<!FakeEntry>} Fake entries.
   */
  get fakeEntries() {
    return this.fakeEntries_;
  },
  /**
   * @return {(string|undefined)} Error identifier.
   */
  get error() {
    return this.error_;
  },
  /**
   * @return {(string|undefined)} Device type identifier.
   */
  get deviceType() {
    return this.deviceType_;
  },
  /**
   * @return {(string|undefined)} Device identifier.
   */
  get devicePath() {
    return this.devicePath_;
  },
  /**
   * @return {boolean} Whether read only or not.
   */
  get isReadOnly() {
    return this.isReadOnly_;
  },
  /**
   * @return {!{displayName:string, isCurrentProfile:boolean}} Profile data.
   */
  get profile() {
    return this.profile_;
  },
  /**
   * @return {string} Label for the volume.
   */
  get label() {
    return this.label_;
  },
  /**
   * @return {(string|undefined)} Id of an extennsion providing this volume.
   */
  get extensionId() {
    return this.extensionId_;
  },
  /**
   * @return {boolean} True if the volume contains media.
   */
  get hasMedia() {
    return this.hasMedia_;
  },
  /**
   * @return {boolean} True if the volume is configurable.
   */
  get configurable() {
    return this.configurable_;
  },
  /**
   * @return {boolean} True if the volume is watchable.
   */
  get watchable() {
    return this.watchable_;
  },
  /**
   * @return {VolumeManagerCommon.Source} Source of the volume's data.
   */
  get source() {
    return this.source_;
  }
};

/**
 * Starts resolving the display root and obtains it.  It may take long time for
 * Drive. Once resolved, it is cached.
 *
 * @param {function(!DirectoryEntry)=} opt_onSuccess Success callback with the
 *     display root directory as an argument.
 * @param {function(*)=} opt_onFailure Failure callback.
 * @return {!Promise.<!DirectoryEntry>}
 */
VolumeInfo.prototype.resolveDisplayRoot = function(opt_onSuccess,
                                                   opt_onFailure) {
  if (!this.displayRootPromise_) {
    // TODO(mtomasz): Do not add VolumeInfo which failed to resolve root, and
    // remove this if logic. Call opt_onSuccess() always, instead.
    if (this.volumeType !== VolumeManagerCommon.VolumeType.DRIVE) {
      if (this.fileSystem_)
        this.displayRootPromise_ = /** @type {Promise.<!DirectoryEntry>} */ (
            Promise.resolve(this.fileSystem_.root));
      else
        this.displayRootPromise_ = /** @type {Promise.<!DirectoryEntry>} */ (
            Promise.reject(this.error));
    } else {
      // For Drive, we need to resolve.
      var displayRootURL = this.fileSystem_.root.toURL() + '/root';
      this.displayRootPromise_ = new Promise(
          window.webkitResolveLocalFileSystemURL.bind(null, displayRootURL));
    }

    // Store the obtained displayRoot.
    this.displayRootPromise_.then(function(displayRoot) {
      this.displayRoot_ = displayRoot;
    }.bind(this));
  }
  if (opt_onSuccess)
    this.displayRootPromise_.then(opt_onSuccess, opt_onFailure);
  return this.displayRootPromise_;
};

/**
 * Utilities for volume manager implementation.
 */
var volumeManagerUtil = {};

/**
 * @const {string}
 */
volumeManagerUtil.TIMEOUT_STR_REQUEST_FILE_SYSTEM =
    'timeout(requestFileSystem)';

/**
 * @const {string}
 */
volumeManagerUtil.TIMEOUT_STR_RESOLVE_ISOLATED_ENTRIES =
    'timeout(resolveIsolatedEntries)';

/**
 * Throws an Error when the given error is not in
 * VolumeManagerCommon.VolumeError.
 *
 * @param {string} error Status string usually received from APIs.
 */
volumeManagerUtil.validateError = function(error) {
  for (var key in VolumeManagerCommon.VolumeError) {
    if (error === VolumeManagerCommon.VolumeError[key])
      return;
  }

  throw new Error('Invalid mount error: ' + error);
};

/**
 * Builds the VolumeInfo data from VolumeMetadata.
 * @param {VolumeMetadata} volumeMetadata Metadata instance for the volume.
 * @return {!Promise.<VolumeInfo>} Promise settled with the VolumeInfo instance.
 */
volumeManagerUtil.createVolumeInfo = function(volumeMetadata) {
  var localizedLabel;
  switch (volumeMetadata.volumeType) {
    case VolumeManagerCommon.VolumeType.DOWNLOADS:
      localizedLabel = str('DOWNLOADS_DIRECTORY_LABEL');
      break;
    case VolumeManagerCommon.VolumeType.DRIVE:
      localizedLabel = str('DRIVE_DIRECTORY_LABEL');
      break;
    default:
      // TODO(mtomasz): Calculate volumeLabel for all types of volumes in the
      // C++ layer.
      localizedLabel = volumeMetadata.volumeLabel ||
          volumeMetadata.volumeId.split(':', 2)[1];
      break;
  }

  console.debug('Requesting file system.');
  return util.timeoutPromise(
      new Promise(function(resolve, reject) {
        chrome.fileSystem.requestFileSystem(
            {
              volumeId: volumeMetadata.volumeId,
              writable: !volumeMetadata.isReadOnly
            },
            function(isolatedFileSystem) {
              if (chrome.runtime.lastError)
                reject(chrome.runtime.lastError.message);
              else
                resolve(isolatedFileSystem);
            });
      }),
      VolumeManager.TIMEOUT,
      volumeManagerUtil.TIMEOUT_STR_REQUEST_FILE_SYSTEM +
          ': ' + volumeMetadata.volumeId)
  .then(
      /**
       * @param {!FileSystem} isolatedFileSystem
       */
      function(isolatedFileSystem) {
        // Since File System API works on isolated entries only, we need to
        // convert it back to external one.
        // TODO(mtomasz): Make Files app work on isolated entries.
        return util.timeoutPromise(
            new Promise(function(resolve, reject) {
              chrome.fileManagerPrivate.resolveIsolatedEntries(
                  [isolatedFileSystem.root],
                  function(entries) {
                    if (chrome.runtime.lastError)
                      reject(chrome.runtime.lastError.message);
                    else if (!entries[0])
                      reject('Resolving for external context failed.');
                    else
                      resolve(entries[0].filesystem);
                  });
            }),
            VolumeManager.TIMEOUT,
            volumeManagerUtil.TIMEOUT_STR_RESOLVE_ISOLATED_ENTRIES +
                ': ' + volumeMetadata.volumeId);
       })
  .then(
      /**
       * @param {!FileSystem} fileSystem
       */
      function(fileSystem) {
        console.debug('File system obtained: ' + volumeMetadata.volumeId);
        if (volumeMetadata.volumeType ===
            VolumeManagerCommon.VolumeType.DRIVE) {
          // After file system is mounted, we "read" drive grand root
          // entry at first. This triggers full feed fetch on background.
          // Note: we don't need to handle errors here, because even if
          // it fails, accessing to some path later will just become
          // a fast-fetch and it re-triggers full-feed fetch.
          fileSystem.root.createReader().readEntries(
              function() { /* do nothing */ },
              function(error) {
                console.error(
                    'Triggering full feed fetch is failed: ' +
                    error.name);
              });
        }
        return new VolumeInfo(
            /** @type {VolumeManagerCommon.VolumeType} */
            (volumeMetadata.volumeType),
            volumeMetadata.volumeId,
            fileSystem,
            volumeMetadata.mountCondition,
            volumeMetadata.deviceType,
            volumeMetadata.devicePath,
            volumeMetadata.isReadOnly,
            volumeMetadata.profile,
            localizedLabel,
            volumeMetadata.extensionId,
            volumeMetadata.hasMedia,
            volumeMetadata.configurable,
            volumeMetadata.watchable,
            /** @type {VolumeManagerCommon.Source} */
            (volumeMetadata.source));
  })
  .catch(
      /**
       * @param {*} error
       */
      function(error) {
        console.error('Failed to mount a file system: ' +
            volumeMetadata.volumeId + ' because of: ' +
            (error.stack || error));
        volumeManagerUtil.reportMountError(volumeMetadata, error);

        return new VolumeInfo(
            /** @type {VolumeManagerCommon.VolumeType} */
            (volumeMetadata.volumeType),
            volumeMetadata.volumeId,
            null,  // File system is not found.
            volumeMetadata.mountCondition,
            volumeMetadata.deviceType,
            volumeMetadata.devicePath,
            volumeMetadata.isReadOnly,
            volumeMetadata.profile,
            localizedLabel,
            volumeMetadata.extensionId,
            volumeMetadata.hasMedia,
            volumeMetadata.configurable,
            volumeMetadata.watchable,
            /** @type {VolumeManagerCommon.Source} */
            (volumeMetadata.source));
      });
};

/**
 * Reports a mount error to analytics in the form of
 * "mount {errorType} {volumeType}", like
 * "mount timeout(resolveIsolatedEntries) provided:ZipUnpacker".
 * Note that errorType and volumeType must be an element of fixed set of strings
 * to avoid sending dynamic strings to analytics.
 *
 * @param {VolumeMetadata} volumeMetadata
 * @param {*} error
 */
volumeManagerUtil.reportMountError = function(volumeMetadata, error) {
  var errorType = 'error';
  if (error instanceof Error) {
    if (error.message.startsWith(
        volumeManagerUtil.TIMEOUT_STR_REQUEST_FILE_SYSTEM)) {
      errorType = volumeManagerUtil.TIMEOUT_STR_REQUEST_FILE_SYSTEM;
    }
    if (error.message.startsWith(
        volumeManagerUtil.TIMEOUT_STR_RESOLVE_ISOLATED_ENTRIES)) {
      errorType = volumeManagerUtil.TIMEOUT_STR_RESOLVE_ISOLATED_ENTRIES;
    }
  }
  var volumeType = volumeMetadata.volumeType;
  if (volumeMetadata.volumeType === VolumeManagerCommon.VolumeType.PROVIDED) {
    volumeType += ':' + metrics.getFileSystemProviderName(
        volumeMetadata.extensionId);
  }
  var description = 'mount ' + errorType + ' ' + volumeType;
  var fatal =
      volumeMetadata.volumeType === VolumeManagerCommon.VolumeType.DOWNLOADS ||
      volumeMetadata.volumeType === VolumeManagerCommon.VolumeType.DRIVE;

  if (window.background && window.background.tracker)
    window.background.tracker.sendException(description, fatal);
};

/**
 * The order of the volume list based on root type.
 * @type {Array<VolumeManagerCommon.VolumeType>}
 * @const
 * @private
 */
volumeManagerUtil.volumeListOrder_ = [
  VolumeManagerCommon.VolumeType.DRIVE,
  VolumeManagerCommon.VolumeType.DOWNLOADS,
  VolumeManagerCommon.VolumeType.ARCHIVE,
  VolumeManagerCommon.VolumeType.REMOVABLE,
  VolumeManagerCommon.VolumeType.MTP,
  VolumeManagerCommon.VolumeType.PROVIDED,
];

/**
 * Orders two volumes by volumeType and volumeId.
 *
 * The volumes at first are compared by volume type in the order of
 * volumeListOrder_.  Then they are compared by volume ID.
 *
 * @param {!VolumeInfo} volumeInfo1 Volume info to be compared.
 * @param {!VolumeInfo} volumeInfo2 Volume info to be compared.
 * @return {number} Returns -1 if volume1 < volume2, returns 1 if volume2 >
 *     volume1, returns 0 if volume1 === volume2.
 * @private
 */
volumeManagerUtil.compareVolumeInfo_ = function(volumeInfo1, volumeInfo2) {
  var typeIndex1 =
      volumeManagerUtil.volumeListOrder_.indexOf(volumeInfo1.volumeType);
  var typeIndex2 =
      volumeManagerUtil.volumeListOrder_.indexOf(volumeInfo2.volumeType);
  if (typeIndex1 !== typeIndex2)
    return typeIndex1 < typeIndex2 ? -1 : 1;
  if (volumeInfo1.volumeId !== volumeInfo2.volumeId)
    return volumeInfo1.volumeId < volumeInfo2.volumeId ? -1 : 1;
  return 0;
};

/**
 * The container of the VolumeInfo for each mounted volume.
 * @constructor
 */
function VolumeInfoList() {
  var field = 'volumeType,volumeId';

  /**
   * Holds VolumeInfo instances.
   * @type {cr.ui.ArrayDataModel}
   * @private
   */
  this.model_ = new cr.ui.ArrayDataModel([]);
  this.model_.setCompareFunction(field,
                                 /** @type {function(*, *): number} */
                                 (volumeManagerUtil.compareVolumeInfo_));
  this.model_.sort(field, 'asc');

  Object.freeze(this);
}

VolumeInfoList.prototype = {
  get length() { return this.model_.length; }
};

/**
 * Adds the event listener to listen the change of volume info.
 * @param {string} type The name of the event.
 * @param {function(Event)} handler The handler for the event.
 */
VolumeInfoList.prototype.addEventListener = function(type, handler) {
  this.model_.addEventListener(type, handler);
};

/**
 * Removes the event listener.
 * @param {string} type The name of the event.
 * @param {function(Event)} handler The handler to be removed.
 */
VolumeInfoList.prototype.removeEventListener = function(type, handler) {
  this.model_.removeEventListener(type, handler);
};

/**
 * Adds the volumeInfo to the appropriate position. If there already exists,
 * just replaces it.
 * @param {VolumeInfo} volumeInfo The information of the new volume.
 */
VolumeInfoList.prototype.add = function(volumeInfo) {
  var index = this.findIndex(volumeInfo.volumeId);
  if (index !== -1)
    this.model_.splice(index, 1, volumeInfo);
  else
    this.model_.push(volumeInfo);
};

/**
 * Removes the VolumeInfo having the given ID.
 * @param {string} volumeId ID of the volume.
 */
VolumeInfoList.prototype.remove = function(volumeId) {
  var index = this.findIndex(volumeId);
  if (index !== -1)
    this.model_.splice(index, 1);
};

/**
 * Obtains an index from the volume ID.
 * @param {string} volumeId Volume ID.
 * @return {number} Index of the volume.
 */
VolumeInfoList.prototype.findIndex = function(volumeId) {
  for (var i = 0; i < this.model_.length; i++) {
    if (this.model_.item(i).volumeId === volumeId)
      return i;
  }
  return -1;
};

/**
 * Searches the information of the volume that contains the passed entry.
 * @param {!Entry|!FakeEntry} entry Entry on the volume to be found.
 * @return {VolumeInfo} The volume's information, or null if not found.
 */
VolumeInfoList.prototype.findByEntry = function(entry) {
  for (var i = 0; i < this.length; i++) {
    var volumeInfo = this.item(i);
    if (volumeInfo.fileSystem &&
        util.isSameFileSystem(volumeInfo.fileSystem, entry.filesystem)) {
      return volumeInfo;
    }
    // Additionally, check fake entries.
    for (var key in volumeInfo.fakeEntries_) {
      var fakeEntry = volumeInfo.fakeEntries_[key];
      if (util.isSameEntry(fakeEntry, entry))
        return volumeInfo;
    }
  }
  return null;
};

/**
 * Searches the information of the volume that exists on the given device path.
 * @param {string} devicePath Path of the device to search.
 * @return {VolumeInfo} The volume's information, or null if not found.
 */
VolumeInfoList.prototype.findByDevicePath = function(devicePath) {
  for (var i = 0; i < this.length; i++) {
    var volumeInfo = this.item(i);
    if (volumeInfo.devicePath &&
        volumeInfo.devicePath == devicePath) {
      return volumeInfo;
    }
  }
  return null;
};

/**
 * Returns a VolumInfo for the volume ID, or null if not found.
 *
 * @param {string} volumeId
 * @return {VolumeInfo} The volume's information, or null if not found.
 * @private
 */
VolumeInfoList.prototype.findByVolumeId_ = function(volumeId) {
  var index = this.findIndex(volumeId);
  return (index !== -1) ?
      /** @type {VolumeInfo} */ (this.model_.item(index)) :
      null;
};

/**
 * Returns a promise that will be resolved when volume info, identified
 * by {@code volumeId} is created.
 *
 * @param {string} volumeId
 * @return {!Promise.<!VolumeInfo>} The VolumeInfo. Will not resolve
 *     if the volume is never mounted.
 */
VolumeInfoList.prototype.whenVolumeInfoReady = function(volumeId) {
  return new Promise(function(fulfill) {
    var handler = function() {
      var info = this.findByVolumeId_(volumeId);
      if (info) {
        fulfill(info);
        this.model_.removeEventListener('splice', handler);
      }
    }.bind(this);
    this.model_.addEventListener('splice', handler);
    handler();
  }.bind(this));
};

/**
 * @param {number} index The index of the volume in the list.
 * @return {!VolumeInfo} The VolumeInfo instance.
 */
VolumeInfoList.prototype.item = function(index) {
  return /** @type {!VolumeInfo} */ (this.model_.item(index));
};

/**
 * VolumeManager is responsible for tracking list of mounted volumes.
 *
 * @constructor
 * @implements {VolumeManagerCommon.VolumeInfoProvider}
 * @extends {cr.EventTarget}
 */
function VolumeManager() {
  /**
   * The list of archives requested to mount. We will show contents once
   * archive is mounted, but only for mounts from within this filebrowser tab.
   * @type {Object<Object>}
   * @private
   */
  this.requests_ = {};

  /**
   * The list of VolumeInfo instances for each mounted volume.
   * @type {VolumeInfoList}
   */
  this.volumeInfoList = new VolumeInfoList();

  /**
   * Queue for mounting.
   * @type {AsyncUtil.Queue}
   * @private
   */
  this.mountQueue_ = new AsyncUtil.Queue();

  // The status should be merged into VolumeManager.
  // TODO(hidehiko): Remove them after the migration.
  /**
   * Connection state of the Drive.
   * @type {VolumeManagerCommon.DriveConnectionState}
   * @private
   */
  this.driveConnectionState_ = {
    type: VolumeManagerCommon.DriveConnectionType.OFFLINE,
    reason: VolumeManagerCommon.DriveConnectionReason.NO_SERVICE,
    hasCellularNetworkAccess: false
  };

  chrome.fileManagerPrivate.onDriveConnectionStatusChanged.addListener(
      this.onDriveConnectionStatusChanged_.bind(this));
  this.onDriveConnectionStatusChanged_();
}

/**
 * Invoked when the drive connection status is changed.
 * @private
 */
VolumeManager.prototype.onDriveConnectionStatusChanged_ = function() {
  chrome.fileManagerPrivate.getDriveConnectionState(function(state) {
    this.driveConnectionState_ = state;
    cr.dispatchSimpleEvent(this, 'drive-connection-changed');
  }.bind(this));
};

/**
 * Returns the drive connection state.
 * @return {VolumeManagerCommon.DriveConnectionState} Connection state.
 */
VolumeManager.prototype.getDriveConnectionState = function() {
  return this.driveConnectionState_;
};

/**
 * VolumeManager extends cr.EventTarget.
 */
VolumeManager.prototype.__proto__ = cr.EventTarget.prototype;

/**
 * Time in milliseconds that we wait a response for. If no response on
 * mount/unmount received the request supposed failed.
 */
VolumeManager.TIMEOUT = 15 * 60 * 1000;

/**
 * The singleton instance of VolumeManager. Initialized by the first invocation
 * of getInstance().
 * @type {VolumeManager}
 * @private
 */
VolumeManager.instance_ = null;

/**
 * Returns instance of VolumeManager for debug purpose.
 * This method returns VolumeManager.instance_ which may not be initialized.
 *
 * @return {VolumeManager} Volume manager.
 */
VolumeManager.getInstanceForDebug = function() {
  return VolumeManager.instance_;
};

/**
 * @type {Promise}
 * @private
 */
VolumeManager.instancePromise_ = null;

/**
 * Returns the VolumeManager instance asynchronously. If it is not created or
 * under initialization, it will waits for the finish of the initialization.
 * @param {function(VolumeManager)=} opt_callback Called with the VolumeManager
 *     instance. TODO(hirono): Remove the callback and use Promise instead.
 * @return {Promise} Promise to be fulfilled with the volume manager.
 */
VolumeManager.getInstance = function(opt_callback) {
  if (!VolumeManager.instancePromise_) {
    VolumeManager.instance_ = new VolumeManager();
    VolumeManager.instancePromise_ = new Promise(function(fulfill) {
      VolumeManager.instance_.initialize_(function() {
        return fulfill(VolumeManager.instance_);
      });
    });
  }
  if (opt_callback)
    VolumeManager.instancePromise_.then(opt_callback);
  return VolumeManager.instancePromise_;
};

/**
 * Revokes the singleton instance for testing.
 */
VolumeManager.revokeInstanceForTesting = function() {
  VolumeManager.instancePromise_ = null;
  VolumeManager.instance_ = null;
};

/**
 * Adds new volume info from the given volumeMetadata. If the corresponding
 * volume info has already been added, the volumeMetadata is ignored.
 * @param {!VolumeMetadata} volumeMetadata
 * @return {!Promise<!VolumeInfo>}
 * @private
 */
VolumeManager.prototype.addVolumeMetadata_ = function(volumeMetadata) {
  return volumeManagerUtil.createVolumeInfo(volumeMetadata).then(
      /**
       * @param {!VolumeInfo} volumeInfo
       * @return {!VolumeInfo}
       */
      function(volumeInfo) {
        // We don't show Downloads and Drive on volume list if they have mount
        // error, since users can do nothing in this situation.
        // We show Removable and Provided volumes regardless of mount error so
        // that users can unmount or format the volume.
        // TODO(fukino): Once Files.app get ready, show erroneous Drive volume
        // so that users can see auth warning banner on the volume.
        // crbug.com/517772.
        var shouldShow = true;
        switch (volumeInfo.volumeType) {
          case VolumeManagerCommon.VolumeType.DOWNLOADS:
          case VolumeManagerCommon.VolumeType.DRIVE:
            shouldShow = !!volumeInfo.fileSystem;
            break;
        }
        if (shouldShow &&
            this.volumeInfoList.findIndex(volumeInfo.volumeId) === -1) {
          this.volumeInfoList.add(volumeInfo);

          // Update the network connection status, because until the drive is
          // initialized, the status is set to not ready.
          // TODO(mtomasz): The connection status should be migrated into
          // VolumeMetadata.
          if (volumeMetadata.volumeType ===
              VolumeManagerCommon.VolumeType.DRIVE) {
            this.onDriveConnectionStatusChanged_();
          }
        }
        return volumeInfo;
      }.bind(this));
};

/**
 * Initializes mount points.
 * @param {function()} callback Called upon the completion of the
 *     initialization.
 * @private
 */
VolumeManager.prototype.initialize_ = function(callback) {
  chrome.fileManagerPrivate.onMountCompleted.addListener(
      this.onMountCompleted_.bind(this));
  console.debug('Requesting volume list.');
  chrome.fileManagerPrivate.getVolumeMetadataList(function(volumeMetadataList) {
    console.debug('Volume list fetched with: ' + volumeMetadataList.length +
        ' items.');
    // We must subscribe to the mount completed event in the callback of
    // getVolumeMetadataList. crbug.com/330061.
    // But volumes reported by onMountCompleted events must be added after the
    // volumes in the volumeMetadataList are mounted. crbug.com/135477.
    this.mountQueue_.run(function(inCallback) {
      // Create VolumeInfo for each volume.
      Promise.all(
          volumeMetadataList.map(function(volumeMetadata) {
            console.debug(
                'Initializing volume: ' + volumeMetadata.volumeId);
            return this.addVolumeMetadata_(volumeMetadata).then(
                function(volumeInfo) {
                  console.debug('Initialized volume: ' + volumeInfo.volumeId);
                });
          }.bind(this)))
          .then(function() {
            console.debug('Initialized all volumes.');
            // Call the callback of the initialize function.
            callback();
            // Call the callback of AsyncQueue. Maybe it invokes callbacks
            // registered by mountCompleted events.
            inCallback();
          });
    }.bind(this));
  }.bind(this));
};

/**
 * Event handler called when some volume was mounted or unmounted.
 * @param {MountCompletedEvent} event Received event.
 * @private
 */
VolumeManager.prototype.onMountCompleted_ = function(event) {
  this.mountQueue_.run(function(callback) {
    switch (event.eventType) {
      case 'mount':
        var requestKey = this.makeRequestKey_(
            'mount',
            event.volumeMetadata.sourcePath || '');

        if (event.status === 'success' ||
            event.status ===
                VolumeManagerCommon.VolumeError.UNKNOWN_FILESYSTEM ||
            event.status ===
                VolumeManagerCommon.VolumeError.UNSUPPORTED_FILESYSTEM) {
          this.addVolumeMetadata_(event.volumeMetadata).then(
              function(volumeInfo) {
                this.finishRequest_(requestKey, event.status, volumeInfo);
                callback();
              }.bind(this));
        } else {
          console.warn('Failed to mount a volume: ' + event.status);
          this.finishRequest_(requestKey, event.status);
          callback();
        }
        break;

      case 'unmount':
        var volumeId = event.volumeMetadata.volumeId;
        var status = event.status;
        if (status === VolumeManagerCommon.VolumeError.PATH_UNMOUNTED) {
          console.warn('Volume already unmounted: ', volumeId);
          status = 'success';
        }
        var requestKey = this.makeRequestKey_('unmount', volumeId);
        var requested = requestKey in this.requests_;
        var volumeInfoIndex =
            this.volumeInfoList.findIndex(volumeId);
        var volumeInfo = volumeInfoIndex !== -1 ?
            this.volumeInfoList.item(volumeInfoIndex) : null;
        if (event.status === 'success' && !requested && volumeInfo) {
          console.warn('Mounted volume without a request: ' + volumeId);
          var e = new Event('externally-unmounted');
          e.volumeInfo = volumeInfo;
          this.dispatchEvent(e);
        }

        this.finishRequest_(requestKey, status);
        if (event.status === 'success')
          this.volumeInfoList.remove(event.volumeMetadata.volumeId);
        callback();
        break;
    }
  }.bind(this));
};

/**
 * Creates string to match mount events with requests.
 * @param {string} requestType 'mount' | 'unmount'. TODO(hidehiko): Replace by
 *     enum.
 * @param {string} argument Argument describing the request, eg. source file
 *     path of the archive to be mounted, or a volumeId for unmounting.
 * @return {string} Key for |this.requests_|.
 * @private
 */
VolumeManager.prototype.makeRequestKey_ = function(requestType, argument) {
  return requestType + ':' + argument;
};

/**
 * @param {string} fileUrl File url to the archive file.
 * @param {function(VolumeInfo)} successCallback Success callback.
 * @param {function(VolumeManagerCommon.VolumeError)} errorCallback Error
 *     callback.
 */
VolumeManager.prototype.mountArchive = function(
    fileUrl, successCallback, errorCallback) {
  chrome.fileManagerPrivate.addMount(fileUrl, function(sourcePath) {
    console.info(
        'Mount request: url=' + fileUrl + '; sourcePath=' + sourcePath);
    var requestKey = this.makeRequestKey_('mount', sourcePath);
    this.startRequest_(requestKey, successCallback, errorCallback);
  }.bind(this));
};

/**
 * Unmounts a volume.
 * @param {!VolumeInfo} volumeInfo Volume to be unmounted.
 * @param {function()} successCallback Success callback.
 * @param {function(VolumeManagerCommon.VolumeError)} errorCallback Error
 *     callback.
 */
VolumeManager.prototype.unmount = function(volumeInfo,
                                           successCallback,
                                           errorCallback) {
  chrome.fileManagerPrivate.removeMount(volumeInfo.volumeId);
  var requestKey = this.makeRequestKey_('unmount', volumeInfo.volumeId);
  this.startRequest_(requestKey, successCallback, errorCallback);
};

/**
 * Configures a volume.
 * @param {!VolumeInfo} volumeInfo Volume to be configured.
 * @return {!Promise} Fulfilled on success, otherwise rejected with an error
 *     message.
 */
VolumeManager.prototype.configure = function(volumeInfo) {
  return new Promise(function(fulfill, reject) {
    chrome.fileManagerPrivate.configureVolume(
        volumeInfo.volumeId,
        function() {
          if (chrome.runtime.lastError)
            reject(chrome.runtime.lastError.message);
          else
            fulfill();
        });
  });
};

/** @override */
VolumeManager.prototype.getVolumeInfo = function(entry) {
  return this.volumeInfoList.findByEntry(entry);
};

/**
 * Obtains volume information of the current profile.
 *
 * @param {VolumeManagerCommon.VolumeType} volumeType Volume type.
 * @return {VolumeInfo} Volume info.
 */
VolumeManager.prototype.getCurrentProfileVolumeInfo = function(volumeType) {
  for (var i = 0; i < this.volumeInfoList.length; i++) {
    var volumeInfo = this.volumeInfoList.item(i);
    if (volumeInfo.profile.isCurrentProfile &&
        volumeInfo.volumeType === volumeType)
      return volumeInfo;
  }
  return null;
};

/**
 * Obtains location information from an entry.
 *
 * @param {(!Entry|!FakeEntry)} entry File or directory entry. It can be a fake
 *     entry.
 * @return {EntryLocation} Location information.
 */
VolumeManager.prototype.getLocationInfo = function(entry) {
  var volumeInfo = this.volumeInfoList.findByEntry(entry);
  if (!volumeInfo)
    return null;

  if (util.isFakeEntry(entry)) {
    return new EntryLocation(
        volumeInfo,
        entry.rootType,
        true /* the entry points a root directory. */,
        true /* fake entries are read only. */);
  }

  var rootType;
  var isReadOnly;
  var isRootEntry;
  if (volumeInfo.volumeType === VolumeManagerCommon.VolumeType.DRIVE) {
    // For Drive, the roots are /root and /other, instead of /. Root URLs
    // contain trailing slashes.
    if (entry.fullPath == '/root' || entry.fullPath.indexOf('/root/') === 0) {
      rootType = VolumeManagerCommon.RootType.DRIVE;
      isReadOnly = volumeInfo.isReadOnly;
      isRootEntry = entry.fullPath === '/root';
    } else if (entry.fullPath == '/other' ||
               entry.fullPath.indexOf('/other/') === 0) {
      rootType = VolumeManagerCommon.RootType.DRIVE_OTHER;
      isReadOnly = true;
      isRootEntry = entry.fullPath === '/other';
    } else {
      // Accessing Drive files outside of /drive/root and /drive/other is not
      // allowed, but can happen. Therefore returning null.
      return null;
    }
  } else {
    switch (volumeInfo.volumeType) {
      case VolumeManagerCommon.VolumeType.DOWNLOADS:
        rootType = VolumeManagerCommon.RootType.DOWNLOADS;
        break;
      case VolumeManagerCommon.VolumeType.REMOVABLE:
        rootType = VolumeManagerCommon.RootType.REMOVABLE;
        break;
      case VolumeManagerCommon.VolumeType.ARCHIVE:
        rootType = VolumeManagerCommon.RootType.ARCHIVE;
        break;
      case VolumeManagerCommon.VolumeType.MTP:
        rootType = VolumeManagerCommon.RootType.MTP;
        break;
      case VolumeManagerCommon.VolumeType.PROVIDED:
        rootType = VolumeManagerCommon.RootType.PROVIDED;
        break;
      default:
        // Programming error, throw an exception.
        throw new Error('Invalid volume type: ' + volumeInfo.volumeType);
    }
    isReadOnly = volumeInfo.isReadOnly;
    isRootEntry = util.isSameEntry(entry, volumeInfo.fileSystem.root);
  }

  return new EntryLocation(volumeInfo, rootType, isRootEntry, isReadOnly);
};

/**
 * @param {string} key Key produced by |makeRequestKey_|.
 * @param {function(VolumeInfo)} successCallback To be called when the request
 *     finishes successfully.
 * @param {function(VolumeManagerCommon.VolumeError)} errorCallback To be called
 *     when the request fails.
 * @private
 */
VolumeManager.prototype.startRequest_ = function(key,
    successCallback, errorCallback) {
  if (key in this.requests_) {
    var request = this.requests_[key];
    request.successCallbacks.push(successCallback);
    request.errorCallbacks.push(errorCallback);
  } else {
    this.requests_[key] = {
      successCallbacks: [successCallback],
      errorCallbacks: [errorCallback],

      timeout: setTimeout(this.onTimeout_.bind(this, key),
                          VolumeManager.TIMEOUT)
    };
  }
};

/**
 * Called if no response received in |TIMEOUT|.
 * @param {string} key Key produced by |makeRequestKey_|.
 * @private
 */
VolumeManager.prototype.onTimeout_ = function(key) {
  this.invokeRequestCallbacks_(this.requests_[key],
                               VolumeManagerCommon.VolumeError.TIMEOUT);
  delete this.requests_[key];
};

/**
 * @param {string} key Key produced by |makeRequestKey_|.
 * @param {VolumeManagerCommon.VolumeError|string} status Status received
 *     from the API.
 * @param {VolumeInfo=} opt_volumeInfo Volume info of the mounted volume.
 * @private
 */
VolumeManager.prototype.finishRequest_ = function(key, status, opt_volumeInfo) {
  var request = this.requests_[key];
  if (!request)
    return;

  clearTimeout(request.timeout);
  this.invokeRequestCallbacks_(request, status, opt_volumeInfo);
  delete this.requests_[key];
};

/**
 * @param {Object} request Structure created in |startRequest_|.
 * @param {VolumeManagerCommon.VolumeError|string} status If status ===
 *     'success' success callbacks are called.
 * @param {VolumeInfo=} opt_volumeInfo Volume info of the mounted volume.
 * @private
 */
VolumeManager.prototype.invokeRequestCallbacks_ = function(
    request, status, opt_volumeInfo) {
  var callEach = function(callbacks, self, args) {
    for (var i = 0; i < callbacks.length; i++) {
      callbacks[i].apply(self, args);
    }
  };
  if (status === 'success') {
    callEach(request.successCallbacks, this, [opt_volumeInfo]);
  } else {
    volumeManagerUtil.validateError(status);
    callEach(request.errorCallbacks, this, [status]);
  }
};

/**
 * Returns current state of VolumeManager.
 * @return {string} Current state of VolumeManager.
 */
VolumeManager.prototype.toString = function() {
  return 'VolumeManager\n' +
      '- MountQueue_:\n' +
      '  ' + this.mountQueue_.toString().replace(/\n/g, '\n  ');
};

/**
 * Location information which shows where the path points in FileManager's
 * file system.
 *
 * @param {!VolumeInfo} volumeInfo Volume information.
 * @param {VolumeManagerCommon.RootType} rootType Root type.
 * @param {boolean} isRootEntry Whether the entry is root entry or not.
 * @param {boolean} isReadOnly Whether the entry is read only or not.
 * @constructor
 */
function EntryLocation(volumeInfo, rootType, isRootEntry, isReadOnly) {
  /**
   * Volume information.
   * @type {!VolumeInfo}
   */
  this.volumeInfo = volumeInfo;

  /**
   * Root type.
   * @type {VolumeManagerCommon.RootType}
   */
  this.rootType = rootType;

  /**
   * Whether the entry is root entry or not.
   * @type {boolean}
   */
  this.isRootEntry = isRootEntry;

  /**
   * Whether the location obtained from the fake entry correspond to special
   * searches.
   * @type {boolean}
   */
  this.isSpecialSearchRoot =
      this.rootType === VolumeManagerCommon.RootType.DRIVE_OFFLINE ||
      this.rootType === VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME ||
      this.rootType === VolumeManagerCommon.RootType.DRIVE_RECENT;

  /**
   * Whether the location is under Google Drive or a special search root which
   * represents a special search from Google Drive.
   * @type {boolean}
   */
  this.isDriveBased =
      this.rootType === VolumeManagerCommon.RootType.DRIVE ||
      this.rootType === VolumeManagerCommon.RootType.DRIVE_OTHER ||
      this.rootType === VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME ||
      this.rootType === VolumeManagerCommon.RootType.DRIVE_RECENT ||
      this.rootType === VolumeManagerCommon.RootType.DRIVE_OFFLINE;

  /**
   * Whether the given path can be a target path of folder shortcut.
   * @type {boolean}
   */
  this.isEligibleForFolderShortcut =
      !this.isSpecialSearchRoot &&
      !this.isRootEntry &&
      this.isDriveBased;

  /**
   * Whether the entry is read only or not.
   * @type {boolean}
   */
  this.isReadOnly = isReadOnly;

  Object.freeze(this);
}


text:
<?php

/* FdrAdminBundle:MissionAffretement:show.html.twig */
class __TwigTemplate_f635a4adfcd25c526a160e119026023095288bf628202be6b873b3086d3c00f9 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        try {
            $this->parent = $this->env->loadTemplate("::base.html.twig");
        } catch (Twig_Error_Loader $e) {
            $e->setTemplateFile($this->getTemplateName());
            $e->setTemplateLine(1);

            throw $e;
        }

        $this->blocks = array(
            'title' => array($this, 'block_title'),
            'body' => array($this, 'block_body'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_title($context, array $blocks = array())
    {
        echo "MissionAffretement|Show";
    }

    // line 3
    public function block_body($context, array $blocks = array())
    {
        // line 4
        echo "
MissionAffretement

                Id
                ";
        // line 10
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "id", array()), "html", null, true);
        echo "

                Ecc
                ";
        // line 14
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "ecc", array()), "html", null, true);
        echo "

                Ect
                ";
        // line 18
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "ect", array()), "html", null, true);
        echo "

                Ebl
                ";
        // line 22
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "ebl", array()), "html", null, true);
        echo "

                Espece
                ";
        // line 26
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "espece", array()), "html", null, true);
        echo "

                Autredoc
                ";
        // line 30
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "autredoc", array()), "html", null, true);
        echo "

                Valdeclassurance
                ";
        // line 34
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "valdeclassurance", array()), "html", null, true);
        echo "

                Bonlivraison
                ";
        // line 38
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "bonlivraison", array()), "html", null, true);
        echo "

                Numexpedition
                ";
        // line 42
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "numexpedition", array()), "html", null, true);
        echo "

                Dateramassage
                ";
        // line 46
        echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "dateramassage", array()), "Y-m-d H:i:s"), "html", null, true);
        echo "

                Lieuramassage
                ";
        // line 50
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "lieuramassage", array()), "html", null, true);
        echo "

                Nbrecolis
                ";
        // line 54
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "nbrecolis", array()), "html", null, true);
        echo "

                Naturemarchandise
                ";
        // line 58
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "naturemarchandise", array()), "html", null, true);
        echo "

                Datelivraison
                ";
        // line 62
        echo twig_escape_filter($this->env, twig_date_format_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "datelivraison", array()), "Y-m-d H:i:s"), "html", null, true);
        echo "

                Lieulivraison
                ";
        // line 66
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "lieulivraison", array()), "html", null, true);
        echo "

                Montantfacture
                ";
        // line 70
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "montantfacture", array()), "html", null, true);
        echo "

                Remise
                ";
        // line 74
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "remise", array()), "html", null, true);
        echo "

                Motifremise
                ";
        // line 78
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "motifremise", array()), "html", null, true);
        echo "

                Montantregle
                ";
        // line 82
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "montantregle", array()), "html", null, true);
        echo "

                Nombnq
                ";
        // line 86
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "nombnq", array()), "html", null, true);
        echo "

                Numcheque
                ";
        // line 90
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "numcheque", array()), "html", null, true);
        echo "

                Nom du responsable à contacter
                ";
        // line 94
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "nomresponsable", array()), "html", null, true);
        echo "

                Tel du responsable à contacter
                ";
        // line 98
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "telresponsable", array()), "html", null, true);
        echo "

        env->getExtension('routing')->getPath("missionaffretement");
        echo "\">
            Back to the list

        env, $this->env->getExtension('routing')->getPath("missionaffretement_edit", array("id" => $this->getAttribute((isset($context["entity"]) ? $context["entity"] : $this->getContext($context, "entity")), "id", array()))), "html", null, true);
        echo "\">
            Edit

";
        // line 114
        echo         $this->env->getExtension('form')->renderer->renderBlock((isset($context["delete_form"]) ? $context["delete_form"] : $this->getContext($context, "delete_form")), 'form');
        echo "

";
    }

    public function getTemplateName()
    {
        return "FdrAdminBundle:MissionAffretement:show.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  233 => 114,  226 => 110,  218 => 105,  208 => 98,  201 => 94,  194 => 90,  187 => 86,  180 => 82,  173 => 78,  166 => 74,  159 => 70,  152 => 66,  145 => 62,  138 => 58,  131 => 54,  124 => 50,  117 => 46,  110 => 42,  103 => 38,  96 => 34,  89 => 30,  82 => 26,  75 => 22,  68 => 18,  61 => 14,  54 => 10,  46 => 4,  43 => 3,  37 => 2,  11 => 1,);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package straightedge.test.benchmark;

import straightedge.test.benchmark.event.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import straightedge.geom.*;
import java.util.*;

/**
 *
 * @author Keith Woodward
 */
public class GameFrame extends JFrame{
	GameLoop loop;
	ViewPane view;
	JPanel botPanel;
	JCheckBox calcVisionButton;
	JCheckBox recalcPathEveryFrameButton;
	JCheckBox drawNodeConnectorsButton;
	JCheckBox drawGridButton;
	JLabel speedLabel;
	JTextField playerSpeedField;
	JLabel fixedConnectionDistLabel;
	JTextField fixedConnectionDistField;
	JLabel dynamicConnectionDistLabel;
	JTextField dynamicConnectionDistField;
	JLabel gridSizeLabel;
	JTextField gridSizeField;
	JButton reconnectButton;
	JButton newBlankMapButton;
	JButton newMapButton;
	JButton newSmallMazeButton;
	JButton newMediumMazeButton;
	JButton newBigMazeButton;

	Object mutex = new Object();

    public GameFrame(){
		super("Line of Sight and Path Finding");
		setSize(600, 600);
//		setExtendedState(JFrame.MAXIMIZED_BOTH);
		setLocationRelativeTo(null);
		addWindowListener(new WindowAdapter() {
			public void windowOpened(WindowEvent e) {
			}
			public void windowClosing(WindowEvent e) {
				close();
			}
		});
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(new BorderLayout());

		final GameFrame thisGameFrame = this;
		botPanel = new JPanel();

		calcVisionButton = new JCheckBox("Vision");
		calcVisionButton.setSelected(true);
		calcVisionButton.setToolTipText("If ticked, vision will be calculated every frame.");
		calcVisionButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				Player player = thisGameFrame.getLoop().getPlayer();
				int value = (calcVisionButton.isSelected() == true ? 1 : 0);
				PlayerStatusEvent playerStatusEvent = new PlayerStatusEvent(player, thisGameFrame.getLoop().getWorld().getTimeStampForEventNow(), PlayerStatusEvent.PLAYER_CALC_VISION, value);
				player.getView().getEventHandler().addNewEvent(playerStatusEvent);
			}
		});

		recalcPathEveryFrameButton = new JCheckBox("Path");
		recalcPathEveryFrameButton.setSelected(true);
		recalcPathEveryFrameButton.setToolTipText("If ticked, the path will be recalculated every frame rather than only when the path changes.
Useful for performance and robustness checking.");
		recalcPathEveryFrameButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				Player player = thisGameFrame.getLoop().getPlayer();
				int value = (recalcPathEveryFrameButton.isSelected() == true ? 1 : 0);
				PlayerStatusEvent playerStatusEvent = new PlayerStatusEvent(player, thisGameFrame.getLoop().getWorld().getTimeStampForEventNow(), PlayerStatusEvent.PLAYER_RECALC_PATH_EVERY_FRAME, value);
				player.getView().getEventHandler().addNewEvent(playerStatusEvent);
				if (drawNodeConnectorsButton.isSelected() && recalcPathEveryFrameButton.isSelected() == false){
					drawNodeConnectorsButton.doClick();
				}
			}
		});
		drawNodeConnectorsButton = new JCheckBox("Mesh");
		drawNodeConnectorsButton.setSelected(false);
		drawNodeConnectorsButton.setToolTipText("Shows the connections between nodes.");
		drawNodeConnectorsButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				thisGameFrame.getLoop().getWorld().setDrawNodeConnections(drawNodeConnectorsButton.isSelected());
				if (drawNodeConnectorsButton.isSelected() && recalcPathEveryFrameButton.isSelected() == false){
					recalcPathEveryFrameButton.doClick();
				}
			}
		});
		drawGridButton = new JCheckBox("Grid");
		drawGridButton.setSelected(false);
		drawGridButton.setToolTipText("Shows the grid used to store obstacles.");
		drawGridButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				thisGameFrame.getLoop().getWorld().setDrawGrid(drawGridButton.isSelected());
			}
		});
		speedLabel = new JLabel("Player speed: ");
		speedLabel.setToolTipText("Type a number in the text field and press enter.");
		playerSpeedField = new JTextField(""+0);
		playerSpeedField.setColumns(5);
		playerSpeedField.setToolTipText("Press enter after typing a number.");
		playerSpeedField.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				setPlayerSpeedFromTextField();
			}
		});
		playerSpeedField.addFocusListener(new FocusAdapter(){
			public void focusLost(FocusEvent e) {
				setPlayerSpeedFromTextField();
			}
		});
		fixedConnectionDistLabel = new JLabel("Obstacle max dist: ");
		fixedConnectionDistLabel.setToolTipText("For this to have an effect, click the 'Reconnect' button");
		fixedConnectionDistField = new JTextField(""+600);
		fixedConnectionDistField.setColumns(5);
		fixedConnectionDistField.setToolTipText("For this to have an effect, click the 'Reconnect' button");
		gridSizeLabel = new JLabel("Grid size: ");
		gridSizeLabel.setToolTipText("For this to have an effect, click the 'Reconnect' button");
		gridSizeField = new JTextField(""+150);
		gridSizeField.setColumns(5);
		gridSizeField.setToolTipText("For this to have an effect, click the 'Reconnect' button");
		dynamicConnectionDistLabel = new JLabel("End point max dist: ");
		dynamicConnectionDistLabel.setToolTipText("Max connection distance from the start node or end node to obstacle nodes.
Type a number in the text field and press enter.");
		dynamicConnectionDistField = new JTextField(""+600);
		dynamicConnectionDistField.setColumns(5);
		dynamicConnectionDistField.setToolTipText("Press enter after typing a number.");
		dynamicConnectionDistField.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				setDynamicConnectionDistFromTextField();
			}
		});
		dynamicConnectionDistField.addFocusListener(new FocusAdapter(){
			public void focusLost(FocusEvent e) {
				setDynamicConnectionDistFromTextField();
			}
		});
		reconnectButton = new JButton("Reconnect");
		reconnectButton.setToolTipText("Reconnects all obstacle nodes in the current map using the current settings.");
		reconnectButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				restartWithNewWorld(new BlankWorld(thisGameFrame.getLoop().getWorld().getOriginalPolygons()));
			}
		});
		newSmallMazeButton = new JButton("Maze");
		newSmallMazeButton.setToolTipText("Makes a small new random maze.");
		newSmallMazeButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				restartWithNewWorld(new MazeWorld(System.currentTimeMillis(), 30, 17, 12, 4f));
			}
		});
		newMediumMazeButton = new JButton("Medium maze");
		newMediumMazeButton.setToolTipText("Makes a medium new random maze.");
		newMediumMazeButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				//restartWithNewWorld(new MazeWorld(System.currentTimeMillis(), 13, 38, 26, 1f));
				restartWithNewWorld(new MazeWorld(0, 13, 38, 26, 1f));
			}
		});
		newBigMazeButton = new JButton("Pillars");
		newBigMazeButton.setToolTipText("Lots of little obstacles in a circle pattern");
//		newBigMazeButton = new JButton("Gigantic maze!");
//		newBigMazeButton.setToolTipText("Makes a massive new random maze.
Warning this could take a while to calculate
unless you set 'Obstacle max dist' very low (<40).");
		newBigMazeButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				restartWithNewWorld(new PillarWorld());
				//restartWithNewWorld(new MazeWorld(System.currentTimeMillis(), 13, 38, 26, 1f));
				//restartWithNewWorld(new MazeWorld(0, 13, 38, 26, 1f));
				//restartWithNewWorld(new MazeWorld(0, 13, 98, 66, 1f));
				//restartWithNewWorld(new MazeWorld(0, 6, 80, 60, 1f));
				//restartWithNewWorld(new MazeWorld(0, 6, 198, 133, 1f));
			}
		});
		newMapButton = new JButton("Obstacles");
		newMapButton.setToolTipText("Makes a new obstacles map which can be used for performance testing.");
		newMapButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				restartWithNewWorld(new ObstacleWorld());
			}
		});
		//newBlankMapButton = new JButton("Blank");
		//newBlankMapButton.setToolTipText("Makes a new blank map that you can fill with your own obstacles.");
		newBlankMapButton = new JButton("CornerCases");
		newBlankMapButton.setToolTipText("Problematic arrangement of obstacles which cause errors.");
		newBlankMapButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				//restartWithNewWorld(new BlankWorld());
				restartWithNewWorld(new CornerCaseWorld());
			}
		});
		JPanel q1 = new JPanel();
		JPanel p1 = new JPanel(new GridLayout(4,1));
		p1.add(speedLabel);
		p1.add(playerSpeedField);
		p1.add(dynamicConnectionDistLabel);
		p1.add(dynamicConnectionDistField);
		q1.add(p1);
		JPanel p2 = new JPanel(new GridLayout(3,1));
		p2.add(calcVisionButton);
		p2.add(recalcPathEveryFrameButton);
		p2.add(drawNodeConnectorsButton);
		//p2.add(drawGridButton);
		q1.add(p2);
		q1.setBorder(new javax.swing.border.TitledBorder("Player and View settings"));
		botPanel.add(q1);
		JPanel q2 = new JPanel();
		q2.setBorder(new javax.swing.border.TitledBorder("Obstacle and Map settings"));
		JPanel p3 = new JPanel(new GridLayout(4,1));
		p3.add(fixedConnectionDistLabel);
		p3.add(fixedConnectionDistField);
		p3.add(gridSizeLabel);
		p3.add(gridSizeField);
		q2.add(p3);
		JPanel p4 = new JPanel(new GridLayout(3,1));
		p4.add(reconnectButton);
		p4.add(newBlankMapButton);
		p4.add(newMapButton);
		q2.add(p4);
		JPanel p5 = new JPanel(new GridLayout(3,1));
		p5.add(newSmallMazeButton);
		p5.add(newMediumMazeButton);
		p5.add(newBigMazeButton);
		q2.add(p5);
		botPanel.add(q2);
		add(botPanel, BorderLayout.SOUTH);
		//restartWithNewWorld(new MazeWorld(0, 13, 38, 26, 1f));
		//restartWithNewWorld(new MazeWorld(0, 30, 17, 12, 4f));
		//restartWithNewWorld(new ObstacleWorld());
		restartWithNewWorld(new MazeWorld(0, 30, 17, 12, 4f));
	}
	boolean firstStart = true;
	public void restartWithNewWorld(final GameWorld newWorld){
		if (loop != null){
			// close the current loop
			loop.close();
		}
		if (view != null){
			// remove the old view
			remove(view);
		}
		// Remake the world.
		// Note that newWorld.init() can take ages, so we do that in another thread,
		// not on Swing's Event Dispatch Thread.
		// The below method just calls newWorld.init() after showing a progress dialog.
		showProgressDialog(newWorld);
		Player player = new Player();
		newWorld.addPlayer(player);
		view = new ViewPane();
		loop = new GameLoop(this, newWorld, player, view);
		view = loop.getView();
		newWorld.setLoop(loop);
		// reset the old settings:
		loop.getPlayer().setRecalcPathOnEveryUpdate(recalcPathEveryFrameButton.isSelected());
		loop.getPlayer().setCalcVision(calcVisionButton.isSelected());
		newWorld.setDrawNodeConnections(drawNodeConnectorsButton.isSelected());
		newWorld.setDrawGrid(drawGridButton.isSelected());
		loop.getPlayer().setSpeed(getPlayerSpeedFromTextField());
		loop.getPlayer().setMaxConnectionDist(this.getDynamicConnectionDistFromTextField());
		// add the new view and restart the loop.
		this.add(view, BorderLayout.CENTER);
		this.setVisible(true);
		loop.start();
		if (firstStart){
			JOptionPane.showConfirmDialog(this, "Left click to move the player.\nRight click to remove obstacles.\nRight press, drag then release to insert obstacles.\nTo insert shadow polygons at the mouse position press 'K'.\nHave fun!", "Instructions!", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
			firstStart = false;
		}
		view.requestFocus();
	}

	protected void showProgressDialog(final GameWorld newWorld){
		final JDialog dialog = new JDialog(this);
		dialog.setTitle("Progress");
		dialog.setModal(true);
		dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		// Need to implement cancelling the join process mid-way thru.
		dialog.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				close();
			}
		});
		//CustomProgressPane joinProgressPane = new CustomProgressPane(this, dialog);

		JPanel joinProgressPane = new JPanel();
		{
			JProgressBar progressBar = new JProgressBar();
			JButton cancelButton = new JButton("Quit");
			progressBar.setIndeterminate(true);
			progressBar.setString("   Just a few moments...");
			progressBar.setStringPainted(true);
			cancelButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent evt) {
					dialog.dispose();
					close();
				}
			});
			joinProgressPane.setLayout(new BorderLayout());
			joinProgressPane.add(progressBar);
			joinProgressPane.add(cancelButton, BorderLayout.SOUTH);
		}

		dialog.add(joinProgressPane);
		dialog.pack();
		dialog.setResizable(false);
		dialog.setLocationRelativeTo(this);
		synchronized(mutex){
			Thread t = new Thread(new Runnable(){
				public void run(){
					newWorld.init(getMaxConnectionDistFromTextField(), getTileWidthAndHeightFromTextField());
					try{
						SwingUtilities.invokeLater(new Runnable(){
							public void run(){
								// Should be done on the EDT.
								dialog.dispose();
							}
						});
					}catch(Exception e){
						e.printStackTrace();
					}

				}
			});
			t.start();
			dialog.setVisible(true);
		}
	}

	protected float getPlayerSpeedFromTextField(){
		String numString = playerSpeedField.getText();
		boolean invalid = false;
		float number = -1;
		try{
			number = Float.parseFloat(numString);
		}catch(NumberFormatException ex){
			ex.printStackTrace();
		}
		return number;
	}

	protected void setPlayerSpeedFromTextField(){
		float number = getPlayerSpeedFromTextField();
		Player player = getLoop().getPlayer();
		//System.out.println(this.getClass().getSimpleName()+" playerStatusEvent made. player == "+player);
		PlayerStatusEvent playerStatusEvent = new PlayerStatusEvent(player, getLoop().getWorld().getTimeStampForEventNow(), PlayerStatusEvent.PLAYER_SPEED_CHANGE, number);
		player.getView().getEventHandler().addNewEvent(playerStatusEvent);
	}

	protected float getDynamicConnectionDistFromTextField(){
		String numString = dynamicConnectionDistField.getText();
		boolean invalid = false;
		float number = -1;
		try{
			number = Float.parseFloat(numString);
		}catch(NumberFormatException ex){
			ex.printStackTrace();
		}
		return number;
	}
	protected void setDynamicConnectionDistFromTextField(){
		float number = getDynamicConnectionDistFromTextField();
		Player player = getLoop().getPlayer();
		PlayerStatusEvent playerStatusEvent = new PlayerStatusEvent(player, getLoop().getWorld().getTimeStampForEventNow(), PlayerStatusEvent.PLAYER_MAX_CONNECTION_DIST, number);
		player.getView().getEventHandler().addNewEvent(playerStatusEvent);
	}

	protected float getMaxConnectionDistFromTextField(){
		String numString = fixedConnectionDistField.getText();
		float number = 0;
		try{
			number = Float.parseFloat(numString);
		}catch(NumberFormatException ex){
			ex.printStackTrace();
		}
		if (number < 0){
			number = 0;
			fixedConnectionDistField.setText(""+number);
		}

		return number;
	}
	protected float getTileWidthAndHeightFromTextField(){
		String numString = gridSizeField.getText();
		float number = 0;
		try{
			number = Float.parseFloat(numString);
		}catch(NumberFormatException ex){
			ex.printStackTrace();
		}
		if (number < 0){
			number = 1;
			gridSizeField.setText(""+number);
		}
		return number;
	}

	public void close(){
		if (loop != null){
			loop.close();
		}
		this.dispose();
		// give everything some time to close, then exit the VM if it hasn't already exited.
		try{Thread.sleep(500);}catch(Exception e){}
		System.exit(0);
	}

	public static void main(String[] args) {
		// Should create swing components on Swing's Event Dispatch Thread:
		SwingUtilities.invokeLater(new Runnable(){
			public void run(){
				new GameFrame();
			}
		});
	}

	public GameLoop getLoop() {
		return loop;
	}

	public void setLoop(GameLoop loop) {
		if (this.loop != loop){
			this.loop = loop;
			loop.setFrame(this);
		}
	}

}


text:
package com.tomtop.exception;

@SuppressWarnings("serial")
public class IndexException extends Exception {

	public IndexException(){

	}

	public IndexException(String msg){
		 super(msg);
	}

}


text:
package com.anderspersson.xbmcwidget.xbmc;

import com.anderspersson.xbmcwidget.common.ErrorNotifier;
import android.app.IntentService;

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class XbmcService extends IntentService
{
    public static final String PLAYPAUSE_ACTION = "com.anderspersson.xbmcwidget.PLAY";
    public static final String PAUSE_ACTION = "com.anderspersson.xbmcwidget.PAUSE";
    public static final String UP_ACTION = "com.anderspersson.xbmcwidget.UP";
    public static final String DOWN_ACTION = "com.anderspersson.xbmcwidget.DOWN";
    public static final String LEFT_ACTION = "com.anderspersson.xbmcwidget.LEFT";
    public static final String RIGHT_ACTION = "com.anderspersson.xbmcwidget.RIGHT";
    public static final String SELECT_ACTION = "com.anderspersson.xbmcwidget.SELECT";
    public static final String BACK_ACTION = "com.anderspersson.xbmcwidget.BACK";
    public static final String STOP_ACTION = "com.anderspersson.xbmcwidget.STOP";
    public static final String TOGGLE_FULLSCREEN_ACTION = "com.anderspersson.xbmcwidget.TOGGLEFULLSCREEN";
    public static final String TOGGLE_OSD_ACTION = "com.anderspersson.xbmcwidget.TOGGLEOSD";
    public static final String HOME_ACTION = "com.anderspersson.xbmcwidget.HOME";
    public static final String CONTEXT_ACTION = "com.anderspersson.xbmcwidget.CONTEXT";
    public static final String PLAY_EPISODE_ACTION = "com.anderspersson.xbmcwidget.PLAY_EPISODE_ACTION";
    public static final String EXTRA_ITEM = "com.anderspersson.xbmcwidget.EXTRA_ITEM";

	public XbmcService() {
		super("XBMCService");
	}

	@Override
	public void onHandleIntent(Intent intent) {
		XbmcRequest command = getCommandForIntent(intent);

		if(command == null)
			return;

		try {
			command.executeObject();
		} catch(Exception e)
		{
			Log.w(XbmcService.class.getSimpleName(), e.getMessage() == null ? "Unknown error." : e.getMessage());
			ErrorNotifier.notify(this);
		}
	}

    private XbmcRequest getCommandForIntent(Intent intent)  {

    	String action = intent.getAction();

    	if(intent.getAction() == null)
			return null;

    	if(action.equals(PLAYPAUSE_ACTION)) return sendActionCommand("12");
    	if(action.equals(STOP_ACTION)) return sendActionCommand("229");
    	if(action.equals(UP_ACTION)) return sendKeyCommand("270");
    	if(action.equals(DOWN_ACTION)) return sendKeyCommand("271");
    	if(action.equals(RIGHT_ACTION)) return sendKeyCommand("273");
    	if(action.equals(LEFT_ACTION)) return sendKeyCommand("272");
    	if(action.equals(BACK_ACTION)) return sendKeyCommand("275");
    	if(action.equals(SELECT_ACTION)) return sendKeyCommand("256");
    	if(action.equals(CONTEXT_ACTION)) return sendCommand("ExecBuiltIn(Action(ContextMenu))");
    	if(action.equals(HOME_ACTION)) return sendCommand("ExecBuiltIn(ActivateWindow(10000))");
    	if(action.equals(TOGGLE_FULLSCREEN_ACTION)) return sendActionCommand("18");
    	if(action.equals(TOGGLE_OSD_ACTION)) return sendKeyCommand("0xF04D");
    	if(action.equals(PLAY_EPISODE_ACTION))
    		return new PlayVideoCommand(getPrefManager(), intent.getExtras().getString(EXTRA_ITEM));

    	return null;
    }

	private XbmcRequest sendActionCommand(String actionKey) {
		return new ActionCommand(getPrefManager(), actionKey);
	}

	private XbmcRequest sendKeyCommand(String key) {
		return new SendKeyCommand(getPrefManager(), key);
	}

	private XbmcRequest sendCommand(String command) {
		return new CustomCommand(getPrefManager(), command);
	}

	private SharedPreferences getPrefManager() {
		return PreferenceManager.getDefaultSharedPreferences(this);
	}
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.cdn.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.resourcemanager.cdn.models.ResourcesResponseCustomDomainsItem;
import com.azure.resourcemanager.cdn.models.ResourcesResponseEndpointsItem;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** Resources Response. */
@Fluent
public final class ResourcesResponseInner {
    /*
     * The endpoints property.
     */
    @JsonProperty(value = "endpoints")
    private List<ResourcesResponseEndpointsItem> endpoints;

    /*
     * The customDomains property.
     */
    @JsonProperty(value = "customDomains")
    private List<ResourcesResponseCustomDomainsItem> customDomains;

    /**
     * Get the endpoints property: The endpoints property.
     *
     * @return the endpoints value.
     */
    public List<ResourcesResponseEndpointsItem> endpoints() {
        return this.endpoints;
    }

    /**
     * Set the endpoints property: The endpoints property.
     *
     * @param endpoints the endpoints value to set.
     * @return the ResourcesResponseInner object itself.
     */
    public ResourcesResponseInner withEndpoints(List<ResourcesResponseEndpointsItem> endpoints) {
        this.endpoints = endpoints;
        return this;
    }

    /**
     * Get the customDomains property: The customDomains property.
     *
     * @return the customDomains value.
     */
    public List<ResourcesResponseCustomDomainsItem> customDomains() {
        return this.customDomains;
    }

    /**
     * Set the customDomains property: The customDomains property.
     *
     * @param customDomains the customDomains value to set.
     * @return the ResourcesResponseInner object itself.
     */
    public ResourcesResponseInner withCustomDomains(List<ResourcesResponseCustomDomainsItem> customDomains) {
        this.customDomains = customDomains;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (endpoints() != null) {
            endpoints().forEach(e -> e.validate());
        }
        if (customDomains() != null) {
            customDomains().forEach(e -> e.validate());
        }
    }
}


text:
/*
 * =====================================================================================
 *
 *       Filename:  main.cpp
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  04/04/2011 04:43:35 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Mathias Buhr (), buhr@apparatus.de
 *
 * =====================================================================================
 */

#include <iostream>
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include "RayTracer.h"
#include "Scene.h"
#include "ImageIO.h"
#include "Pixel.h"
#include "Texture.h"

/* some global variables */
/* that's not exactly a nice example for "good coding style" */
int img_width;
int img_height;
std::string filename;

void parseArguments(int argc, char **argv)
{
    if (argc == 1) {
        std::cout << "Usage: " << argv[0] << " [options]" << std::endl;
        std::cout << "   -o: output prefix for filename, e.g. \"output\"" << std::endl;
        std::cout << "   -w: width of image to be generated" << std::endl;
        std::cout << "   -h: height of image to be generated" << std::endl;
        return;
    }
    for (int i = 1; i < argc; i++) {

        if (strcmp(argv[i],"-o")==0) {
            filename.assign(argv[i + 1]);
        } else if (strcmp(argv[i],"-w")==0) {
            img_width = atoi(argv[i + 1]);
        } else if (strcmp(argv[i],"-h")==0) {
            img_height = atoi(argv[i + 1]);
        }
    }
}
int main(int argc, char **argv)
{
    img_width = IMG_WIDTH;
    img_height = IMG_HEIGHT;
    filename = "output";
    parseArguments(argc, argv);

    std::cout << "Raytracer " << VERSION << std::endl;
    std::cout << "Tracing " << img_width << "x" << img_height << " pixels"  << std::endl;
    // get an instance of the RayTracer
    ray::RayTracer tracer;
    ray::Scene scene;

    // create the default scene
    scene.createDefaultScene();
    // attach this scene to the tracer
    tracer.setScene(scene);
    // setup framebuffer etc.
    tracer.prepare(img_height, img_width);

    // trace!
    tracer.trace(0, img_height*img_width);

    // write the framebuffer to disk
    // 1st we need a ref to ImageIO interface
    ray::img::ImageIO& imgio = ray::img::ImageIO::getInstance();
    // tell the interface to use the PPM format
    imgio.getWriter().setFileFormat("ppm");
    // the file shall be named "output.XXX"
    imgio.getWriter().setFileNamePrefix(filename);

    // clamp pixel buffer as some pixels may reach invalid values
    ray::PixelBuffer buffer = ray::clampPixelBuffer(tracer.getFrameBuffer());
    // write the the file
    imgio.getWriter().write(buffer, img_height, img_width);
    //  tell the user that we're done
    std::cout << "Image has been written to " << imgio.getWriter().getOutputFilePath() << std::endl;
    return EXIT_SUCCESS;
}


text:
{-# OPTIONS_GHC -Wall -fwarn-tabs #-}
{-# LANGUAGE CPP
           , MultiParamTypeClasses
           , FlexibleContexts
           #-}

----------------------------------------------------------------
--                                                  ~ 2022.03.05
-- |
-- Module      :  Test.Main
-- Copyright   :  2008--2022 wren romano
-- License     :  BSD-3-Clause
-- Maintainer  :  wren@cpan.org
-- Stability   :  provisional
-- Portability :  semi-portable (MPTC,...)
--
-- Testing 'Trie's.
----------------------------------------------------------------
module Main (main) where

#if !(MIN_VERSION_base(4,11,0))
-- [GHC 8.4.1]: This guard is just to avoid an \"unused import\" warning.
import Shared.BaseCompat
#endif
import Test.Utils
import Test.Properties (smallcheckTests, quickcheckTests)

import qualified Data.Trie              as T
import qualified Data.ByteString        as S

import qualified System.Exit            as System (exitSuccess, exitFailure)
import qualified System.IO              as System (hPutStrLn, stderr)
import qualified Test.Tasty.Ingredients as Tasty (tryIngredients)
import qualified Test.Tasty.Options     as Tasty (singleOption, OptionSet)
import qualified Test.Tasty.Runners     as Tasty (installSignalHandlers, parseOptions)
import qualified Test.Tasty             as Tasty
import qualified Test.Tasty.SmallCheck  as SC
import qualified Test.Tasty.QuickCheck  as QC

----------------------------------------------------------------
----------------------------------------------------------------
-- We can't use 'Tasty.defaultMain' together with 'Tasty.localOption',
-- because what we want to do is to set new defaults but still allow
-- the commandline to override those defaults, and I don't see any
-- way to do that with 'Tasty.defaultMain'.
--
-- TODO: Still need some way to remove the few remaining
-- 'Tasty.localOption' calls that aren't global...
main :: IO ()
main = do
  let ins = Tasty.defaultIngredients
  Tasty.installSignalHandlers
  opts <- Tasty.parseOptions ins tests
  case Tasty.tryIngredients ins (globalOptions <> opts) tests of
    Nothing -> do
      System.hPutStrLn System.stderr
        "No ingredients agreed to run. Something is wrong."
      System.exitFailure
    Just act -> do
      ok <- act
      if ok
        then System.exitSuccess
        else System.exitFailure

-- We add the timeout for the sake of GithubActions CI, so we don't
-- accidentally blow our budget.  So far, even with HPC enabled,
-- each test takes less than 1sec (almost all of them taking less
-- than 0.5sec); so allowing 10s per test is more than generous.
-- Since the full suite takes around 20sec, that means the timeout
-- will cap the suite to take no more than 200sec / 3.3min.
globalOptions :: Tasty.OptionSet
globalOptions = mconcat
    [ Tasty.singleOption (Tasty.mkTimeout 10000000)  -- 10sec; in microsecs
    , Tasty.singleOption (QC.QuickCheckTests    500) -- QC.Args.maxSuccess
    , Tasty.singleOption (QC.QuickCheckMaxSize  400) -- QC.Args.maxSize
    , Tasty.singleOption (QC.QuickCheckMaxRatio 10)  -- QC.Args.maxDiscardRatio
    , Tasty.singleOption (SC.SmallCheckDepth    3)
    ]

-- We run the HUnit and smallcheck tests first, since they're the
-- fastest.  Thus, we only pay for the QuickCheck tests if we have to.
tests :: Tasty.TestTree
tests =
  Tasty.testGroup "All Tests"
  [ hunitTests
  , Tasty.testGroup "Properties"
    [ smallcheckTests
    , quickcheckTests
    ]
  ]

hunitTests :: Tasty.TestTree
hunitTests =
  Tasty.testGroup "HUnit"
  [ test_Union
  , test_Intersect
  , test_Submap
  , test_Insert
  , test_Delete
  ]

----------------------------------------------------------------
----------------------------------------------------------------
-- Because we avoid epsilons everywhere else, need to make sure
-- 'mergeBy' gets it right
test_Union :: Tasty.TestTree
test_Union =
    Tasty.testGroup "mergeBy"
    [ testEqual "unionL epsilon" (e1 `T.unionL` e2) e1
    , testEqual "unionR epsilon" (e1 `T.unionR` e2) e2
    , testEqual "unionL regression" (tLeft `T.unionL` tRight) tLeftResult
    , testEqual "unionR regression" (tLeft `T.unionR` tRight) tRightResult
    ]
    where
    e1 = T.singleton S.empty (4::Int)
    e2 = T.singleton S.empty (2::Int)

    -- Regression test against bug filed by Gregory Crosswhite on
    -- 2010.06.10 against version 0.2.1.1.
    a, b :: S.ByteString
    a = read "\"\231^\179\160Y\134Gr\158<)&\222\217#\156\""
    b = read "\"\172\193\GSp\222\174GE\186\151\DC1#P\213\147\SI\""
    tLeft, tRight, tRightResult, tLeftResult :: T.Trie Int
    tLeft        = T.fromList [(a,1), (b,0)]
    tRight       = T.fromList [(a,2)]
    tRightResult = T.fromList [(a,2), (b,0)]
    tLeftResult  = T.fromList [(a,1), (b,0)]

test_Intersect :: Tasty.TestTree
test_Intersect =
    Tasty.testGroup "intersectBy"
    [ testEqual "intersectL" (tLeft `T.intersectL` tRight) tLeftResult
    , testEqual "intersectR" (tLeft `T.intersectR` tRight) tRightResult
    ]
    where
    -- Trivial regression example
    a, b, c :: S.ByteString
    a = packC2W "a"
    b = packC2W "b"
    c = packC2W "c"
    tLeft, tRight, tRightResult, tLeftResult :: T.Trie Int
    tLeft        = T.fromList [(S.empty,0), (a,1), (b,3)]
    tRight       = T.fromList [             (a,2), (c,4)]
    tLeftResult  = T.fromList [(a,1)]
    tRightResult = T.fromList [(a,2)]
    -- TODO: better unit test for when one string is prefix of another.

----------------------------------------------------------------
test_Submap :: Tasty.TestTree
test_Submap =
    Tasty.testGroup "submap"
    [ nullSubmap "split on arc fails"    fi   True
    , nullSubmap "prefix of arc matches" fo   False
    , nullSubmap "suffix of empty fails" food True
    , nullSubmap "missing branch fails"  bag  True
    , nullSubmap "at a branch matches"   ba   False
    ]
    where
    t    = vocab2trie ["foo", "bar", "baz"]
    fi   = packC2W "fi"
    fo   = packC2W "fo"
    food = packC2W "food"
    ba   = packC2W "ba"
    bag  = packC2W "bag"

    nullSubmap s q b = testEqual s (T.null $ T.submap q t) b

----------------------------------------------------------------
-- requires Eq (Trie a) and, in case it fails, Show (Trie a)
test_Insert :: Tasty.TestTree
test_Insert =
    Tasty.testGroup "insert"
    [ testEqual "insertion is commutative for prefix/superfix"
        (T.insert aba o $ T.insert abaissed i $ T.empty)
        (T.insert abaissed i $ T.insert aba o $ T.empty)
    ]
    where
    aba      = packC2W "aba"
    abaissed = packC2W "abaissed"

    o = 0::Int
    i = 1::Int

test_Delete :: Tasty.TestTree
test_Delete =
    Tasty.testGroup "delete"
    [ testEqual "deleting epsilon from empty trie is empty"
        (T.delete epsilon T.empty) (T.empty :: T.Trie Int)
    ]
    where
    -- TODO: why not 'S.empty'?
    epsilon = packC2W ""

----------------------------------------------------------------
----------------------------------------------------------- fin.


text:
all:: git-credential-osxkeychain

CC = gcc
RM = rm -f
CFLAGS = -g -O2 -Wall

-include ../../../config.mak.autogen
-include ../../../config.mak

git-credential-osxkeychain: git-credential-osxkeychain.o
	$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS) -Wl,-framework -Wl,Security

git-credential-osxkeychain.o: git-credential-osxkeychain.c
	$(CC) -c $(CFLAGS) $<

clean:
	$(RM) git-credential-osxkeychain git-credential-osxkeychain.o


text:
package hudson.plugins.emailext.plugins.recipients;

import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.EnvVars;
import hudson.Extension;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.User;
import hudson.plugins.emailext.ExtendedEmailPublisherContext;
import hudson.plugins.emailext.ExtendedEmailPublisherDescriptor;
import hudson.plugins.emailext.Messages;
import hudson.plugins.emailext.plugins.RecipientProvider;
import hudson.plugins.emailext.plugins.RecipientProviderDescriptor;
import hudson.tasks.test.AbstractTestResultAction;
import hudson.tasks.test.TestResult;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.Set;
import jakarta.mail.internet.InternetAddress;
import jenkins.model.Jenkins;
import org.jenkinsci.Symbol;
import org.kohsuke.stapler.DataBoundConstructor;

/**
 * A recipient provider that assigns ownership of a failing test to the set of developers (including any initiator)
 * that committed changes that first broke the test.
 */
public class FailingTestSuspectsRecipientProvider extends RecipientProvider {

    @DataBoundConstructor
    public FailingTestSuspectsRecipientProvider() {
    }

    @Override
    public void addRecipients(final ExtendedEmailPublisherContext context, final EnvVars env,
        final Set<InternetAddress> to, final Set<InternetAddress> cc, final Set<InternetAddress> bcc) {

        final class Debug implements RecipientProviderUtilities.IDebug {
            private final ExtendedEmailPublisherDescriptor descriptor
                = Jenkins.get().getDescriptorByType(ExtendedEmailPublisherDescriptor.class);

            private final PrintStream logger = context.getListener().getLogger();

            public void send(final String format, final Object... args) {
                descriptor.debug(logger, format, args);
            }
        }
        final Debug debug = new Debug();

        Set<User> users = null;

        final Run<?, ?> currentRun = context.getRun();
        if (currentRun == null) {
            debug.send("currentRun was null");
        } else {
            final AbstractTestResultAction<?> testResultAction = currentRun.getAction(AbstractTestResultAction.class);
            if (testResultAction == null) {
                debug.send("testResultAction was null");
            } else {
                if (testResultAction.getFailCount() <= 0) {
                    debug.send("getFailCount() returned <= 0");
                } else {
                    users = new HashSet<>();
                    debug.send("Collecting builds where a test started failing...");
                    final HashSet<Run<?, ?>> buildsWhereATestStartedFailing = new HashSet<>();
                    for (final TestResult caseResult : testResultAction.getFailedTests()) {
                        final Run<?, ?> runWhereTestStartedFailing = caseResult.getFailedSinceRun();
                        if (runWhereTestStartedFailing != null) {
                            debug.send("  runWhereTestStartedFailing: %d", runWhereTestStartedFailing.getNumber());
                            buildsWhereATestStartedFailing.add(runWhereTestStartedFailing);
                        } else {
                            context.getListener().error("getFailedSinceRun returned null for %s", caseResult.getFullDisplayName());
                        }
                    }
                    // For each build where a test started failing, walk backward looking for build results worse than
                    // UNSTABLE. All of those builds will be used to find suspects.
                    debug.send("Collecting builds with suspects...");
                    final HashSet<Run<?, ?>> buildsWithSuspects = new HashSet<>();
                    for (final Run<?, ?> buildWhereATestStartedFailing : buildsWhereATestStartedFailing) {
                        debug.send("  buildWhereATestStartedFailing: %d", buildWhereATestStartedFailing.getNumber());
                        buildsWithSuspects.add(buildWhereATestStartedFailing);
                        Run<?, ?> previousBuildToCheck = buildWhereATestStartedFailing.getPreviousCompletedBuild();
                        if (previousBuildToCheck != null) {
                            debug.send("    previousBuildToCheck: %d", previousBuildToCheck.getNumber());
                        }
                        while (previousBuildToCheck != null) {
                            if (buildsWithSuspects.contains(previousBuildToCheck)) {
                                // Short-circuit if the build to check has already been checked.
                                debug.send("      already contained in buildsWithSuspects; stopping search");
                                break;
                            }
                            final Result previousResult = previousBuildToCheck.getResult();
                            if (previousResult == null) {
                                debug.send("      previousResult was null");
                            } else {
                                debug.send("      previousResult: %s", previousResult.toString());
                                if (previousResult.isBetterThan(Result.FAILURE)) {
                                    debug.send("      previousResult was better than FAILURE; stopping search");
                                    break;
                                } else {
                                    debug.send("      previousResult was not better than FAILURE; adding to buildsWithSuspects; continuing search");
                                    buildsWithSuspects.add(previousBuildToCheck);
                                    previousBuildToCheck = previousBuildToCheck.getPreviousCompletedBuild();
                                    if (previousBuildToCheck != null) {
                                        debug.send("    previousBuildToCheck: %d", previousBuildToCheck.getNumber());
                                    }
                                }
                            }
                        }
                    }
                    debug.send("Collecting suspects...");
                    users.addAll(RecipientProviderUtilities.getChangeSetAuthors(buildsWithSuspects, debug));
                    users.addAll(RecipientProviderUtilities.getUsersTriggeringTheBuilds(buildsWithSuspects, debug));
                }
            }
        }

        if (users != null) {
            RecipientProviderUtilities.addUsers(users, context, env, to, cc, bcc, debug);
        }
    }

    @Extension
    @Symbol("brokenTestsSuspects")
    public static final class DescriptorImpl extends RecipientProviderDescriptor {

        @NonNull
        @Override
        public String getDisplayName() {
            return Messages.FailingTestSuspectsRecipientProvider_DisplayName();
        }
    }
}


text:
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UserQuestionsType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('answers', 'collection', ['label'=>'','type' => new AnswersType($builder, $options)])
            ->add('submit', 'submit');
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Users'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'appbundle_users';
    }
}


text:
#include "Python.h"

#include "ipc_support.h"
#include <errno.h>
#include <sys/shm.h>
#include <sys/sem.h>

/* This union is not defined in sys/sem.h on some systems */
#if (!__APPLE__) && (!defined(__GNU_LIBRARY__) || defined(_SEM_SEMUN_UNDEFINED))
union semun {
  int val;               /* value for SETVAL */
  struct semid_ds* buf;  /* buffer for IPC_STAT, IPC_SET */
  unsigned short* array; /* array for GETALL, SETALL */
  struct seminfo* __buf; /* buffer for IPC_INFO; linux only */
};
#endif

#if __APPLE__
int semtimedop(int semid, struct sembuf *sops, unsigned nsops,
               struct timespec *timeout) {
  return semop(semid, sops, nsops);
}
#endif

int semarray_init(int size, unsigned short* init_vals) {
  union semun arg;
  int sem_id;

  arg.array = init_vals;
  sem_id = semget(IPC_PRIVATE, size, SHM_W | SHM_R);
  semctl(sem_id, 0, SETALL, arg);
  return sem_id;
}

int semarray_exists(int sem_id) {
  union semun arg;
  struct semid_ds statinfo;
  int ret;

  /* Is this the best way? */
  arg.buf = &statinfo;
  ret = semctl(sem_id, 0, IPC_STAT, arg);
  return ret >= 0 ? 1 : 0;
}

int semarray_delete(int sem_id) {
  return semctl(sem_id, 0, IPC_RMID, NULL);
}

int semarray_lock(int sem_id, int i, struct timespec *timeout) {
  struct sembuf buf;

  /* Decrement is locking */
  buf.sem_op = -1;
  buf.sem_num = i;
  buf.sem_flg = SEM_UNDO;
  return semtimedop(sem_id, &buf, 1, timeout);
}

int semarray_unlock(int sem_id, int i, struct timespec *timeout) {
  struct sembuf buf;

  /* Increment is unlocking */
  buf.sem_op = 1;
  buf.sem_num = i;
  buf.sem_flg = SEM_UNDO;
  return semtimedop(sem_id, &buf, 1, timeout);
}