text:
package com.cjmalloy.torrentfs.editor.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import com.cjmalloy.torrentfs.editor.core.*;
import com.cjmalloy.torrentfs.editor.event.*;
import com.cjmalloy.torrentfs.editor.event.DoExport.ExportCallback;
import com.cjmalloy.torrentfs.editor.event.DoOpenFolder.OpenFolderCallback;
import com.cjmalloy.torrentfs.editor.model.ExportSettings;
import com.cjmalloy.torrentfs.editor.model.document.MainDocument;
import com.cjmalloy.torrentfs.editor.ui.*;
import com.cjmalloy.torrentfs.model.*;
import com.cjmalloy.torrentfs.util.TfsUtil;
import com.google.common.eventbus.Subscribe;
import com.turn.ttorrent.common.Torrent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MainController extends Controller<MainDocument> {

  private static final Logger logger = LoggerFactory.getLogger(MainController.class);
  private static final ResourceBundle R = ResourceBundle.getBundle("com.cjmalloy.torrentfs.editor.i18n.MessageBundle");

  private static final String CREATOR_ID = "tfs-gui";
  private static final Encoding DEFAULT_ENCODING = Encoding.BENCODE_BASE64;

  private static MainController instance = new MainController();

  static {
    instance.model = new MainDocument();

    instance.fileSystem = new FileSystemController(instance.model.fileSystemModel);
    instance.editor = new EditorController(instance.model.editorModel);
    instance.loadMeta();
  }

  private static ExceptionHandler ioExceptionHandler = new ExceptionHandler() {
    @Override
    public void handleException(Exception e) {
      Controller.EVENT_BUS.post(new DoMessage(R.getString("errorAccessingFilesystem") + e.getLocalizedMessage()));
    }
  };

  public FileSystemController fileSystem;
  public EditorController editor;

  /**
   * Ignore file system updates while this class is writing to the
   * file system.
   */
  private boolean ignoreFsUpdates = false;

  protected MainController() {
  }

  public Nested createNested(File f) throws IOException {
    Nested parent = getParentNested(f);

    Meta parentMeta;
    File parentAbsPath;
    if (parent == null) {
      // parent is root
      parentAbsPath = model.fileSystemModel.workspace.toFile();
      if (parentAbsPath.equals(f)) return null;
      if (model.metadata == null) {
        createTfs(parentAbsPath);
      }
      parentMeta = model.metadata;
    } else {
      if (parent.absolutePath.equals(f)) return parent;
      if (parent.meta == null) createTfs(parent.absolutePath);
      parentMeta = parent.meta;
      parentAbsPath = parent.absolutePath;
    }

    Nested result = new Nested();
    result.mount = parentAbsPath.toPath().relativize(f.toPath()).toString();
    result.encoding = DEFAULT_ENCODING;
    result.absolutePath = f;
    if (parentMeta.nested == null) parentMeta.nested = new ArrayList<>();
    parentMeta.nested.add(result);
    rebaseSiblings(parentMeta, result);
    return result;
  }

  public Meta createTfs(File f) throws IOException {
    if (f.isDirectory()) f = Paths.get(f.toString(), ".tfs").toFile();
    Nested parent = createNested(f.getParentFile());
    if (parent != null && parent.meta != null) return parent.meta;

    Meta meta = new Meta();
    if (parent == null) {
      // parent is root
      model.metadata = meta;
    } else {
      parent.meta = meta;
    }
    return meta;
  }

  /**
   * Prompt the user to export the torrent files for this tfs.
   * This will update any nested torrent data if it has changed.
   */
  public void export() {
    editor.saveCancelContinue(new Continuation() {
      @Override
      public void next() {
        EVENT_BUS.post(new DoExport(new ExportCallback() {
          @Override
          public void withSettings(ExportSettings settings) {
            exportWithSettings(settings);
          }
        }));
      }
    });
  }

  @Subscribe
  public void fileModified(FileModificationEvent event) {
    if (ignoreFsUpdates) return;

    //TODO: try to only load files that have changed
    if (event.file.toString().endsWith(".tfs")) {
      loadMeta();
    }
  }

  /**
   * Get the context menu for this file.
   */
  public List<MenuItem> getMenu(final File f) {
    List<MenuItem> ret = new ArrayList<>();
    ret.add(new MenuItem(R.getString("edit"), new Continuation() {
      @Override
      public void next() {
        editor.openFile(f);
      }
    }));
    if (isLocked(f)) {
      if (isNested(f)) {
        ret.add(new MenuItem(R.getString("unlock"), new ThrowsContinuation() {
          @Override
          public void next() throws IOException {
            unlock(f);
            writeMeta();
          }
        }, ioExceptionHandler));
      }
    } else {
      if (isNested(f)) {
        ret.add(new MenuItem(R.getString("lock"), new ThrowsContinuation() {
          @Override
          public void next() throws IOException {
            lock(f);
            writeMeta();
          }
        }, ioExceptionHandler));
      }
      if (isTfs(f) || isTfsRootDir(f)) {
        ret.add(new MenuItem(R.getString("removeTfs"), new ThrowsContinuation() {
          @Override
          public void next() throws IOException {
            removeTfs(f);
            writeMeta();
          }
        }, ioExceptionHandler));
      } else {
        if (f.isDirectory()) {
          ret.add(new MenuItem(R.getString("createTfs"), new ThrowsContinuation() {
            @Override
            public void next() throws IOException {
              createTfs(f);
              writeMeta();
            }
          }, ioExceptionHandler));
        }
        if (isNested(f)) {
          ret.add(new MenuItem(R.getString("removeNested"), new ThrowsContinuation() {
            @Override
            public void next() throws IOException {
              removeNested(f);
              writeMeta();
            }
          }, ioExceptionHandler));
        } else {
          ret.add(new MenuItem(R.getString("createNested"), new ThrowsContinuation() {
            @Override
            public void next() throws IOException {
              createNested(f);
              writeMeta();
            }
          }, ioExceptionHandler));
        }
      }
    }
    return ret;
  }

  /**
   * Get the metadata for this nested torrent mount location.
   */
  public Nested getNested(File f) throws IOException {
    if (model.metadata == null) return null;
    return getNestedFromRoot(model.fileSystemModel.workspace.toFile(), model.metadata, f);
  }

  /**
   * Get the torrent that contains this file. If this is part of the root
   * tfs then return null.
   */
  public Nested getParentNested(File f) throws IOException {
    if (model.metadata == null) return null;
    return getParentNestedFromRoot(model.fileSystemModel.workspace.toFile(), model.metadata, f);
  }

  /**
   * Check if this file is under a nested torrent that is locked.
   */
  public boolean isLocked(File f) {
    try {
      Nested n;
      while ((n = getParentNested(f)) != null) {
        if (n.readOnly) return true;
        f = f.getParentFile();
      }
    } catch (IOException e) {
      logger.warn(e.getMessage());
    }
    return false;
  }

  /**
   * Check if this folder is a torrent mount point.
   */
  public boolean isMountPoint(File f) throws IOException {
    return f.equals(model.fileSystemModel.workspace.toFile())
      || isNested(f);
  }

  /**
   * Check if this folder or file is a mount point for a nested torrent.
   */
  public boolean isNested(File f) {
    try {
      return getNested(f) != null;
    } catch (IOException e) {
      return false;
    }
  }

  /**
   * Check if this is a valid .tfs file.
   */
  public boolean isTfs(File f) {
    try {
      return f.exists()
        && f.toString().endsWith(".tfs")
        && isMountPoint(f.getParentFile());
    } catch (IOException e) {
      return false;
    }
  }

  /**
   * Check if this is a root directory for a nested tfs.
   */
  public boolean isTfsRootDir(File f) {
    return isTfs(Paths.get(f.toString(), ".tfs").toFile());
  }

  /**
   * Read all tfs metadata from the filesystem.
   */
  public void loadMeta() {
    if (model.fileSystemModel.workspace == null) return;

    try {
      File rootTfs = Paths.get(model.fileSystemModel.workspace.toString(), ".tfs").toFile();
      if (!rootTfs.exists()) {
        model.metadata = null;
        return;
      }

      model.metadata = Meta.load(rootTfs);
      loadMetaFromRoot(model.fileSystemModel.workspace.toFile(), model.metadata);
    } catch (IOException e) {
      Controller.EVENT_BUS.post(new DoMessage(R.getString("errorAccessingFilesystem") + e.getLocalizedMessage()));
    }
  }

  /**
   * Load the metadata for this nested torrent. If this nested torrent is
   * a legacy torrent and not a tfs torrent, return null.
   */
  public Meta loadTfs(Nested n) throws IllegalStateException, IOException {
    if (!n.absolutePath.isDirectory()) return null;

    File tfs = Paths.get(n.absolutePath.toString(), ".tfs").toFile();
    if (!tfs.exists()) return null;

    return Meta.load(tfs);
  }

  public void lock(File f) throws IOException {
    getNested(f).readOnly = true;
  }

  /**
   * Prompt the user to choose a new workspace.
   */
  public void open() {
    editor.closeAll(new Continuation() {
      @Override
      public void next() {
        EVENT_BUS.post(new DoOpenFolder(new OpenFolderCallback() {
          @Override
          public void withFolder(Path folder) {
            openWorkspace(folder);
          }
        }));
      }
    });
  }

  public void removeNested(File f) throws IOException {
    getParentNested(f.getParentFile()).meta.nested.remove(getNested(f));
  }

  public void removeTfs(File f) throws IOException {
    if (f.isDirectory()) f = Paths.get(f.toString(), ".tfs").toFile();
    getParentNested(f).meta = null;
    f.delete();
  }

  public void requestExit() {
    editor.closeAll(new Continuation() {
      @Override
      public void next() {
        EVENT_BUS.post(new DoShutdownNow());
        update();
      }
    });
  }

  public void unlock(File f) throws IOException {
    Nested n;
    while ((n = getParentNested(f)) != null) {
      n.readOnly = false;
      f = f.getParentFile();
    }
  }

  @Override
  public void updateAll() {
    fileSystem.update();
    editor.update();
    update();
  }

  public void writeMeta() throws IOException {
    writeMetaToFile(model.fileSystemModel.workspace.toFile(), model.metadata);
  }

  private void exportWithSettings(final ExportSettings settings) {
    if (!settings.valid()) {
      EVENT_BUS.post(new DoErrorMessage(R.getString("errorInvalidExportSettings")));
      return;
    }

    ignoreFsUpdates = true;

    EVENT_BUS.post(new ProgressStartEvent());
    WorkerExecutor.get().execute(new Worker<Void>() {
      @Override
      public Void doInBackground(WorkerContext context) throws Exception {
        try {
          context.updateProgress(0.1);
          List<Torrent> torrents = TfsUtil.generateTorrentFromTfs(
              fileSystem.model.workspace.toFile(),
              Encoding.BENCODE_BASE64,
              settings.getAnnounce(),
              CREATOR_ID,
              settings.cache,
              settings.useLinks
          );
          context.updateProgress(0.5);
          TfsUtil.saveTorrents(settings.torrentSaveDir, torrents);
        } catch (Exception e) {
          e.printStackTrace();
        }
        return null;
      }

      @Override
      public void done(WorkerContext context) {
        EVENT_BUS.post(new ProgressEndEvent());
        EVENT_BUS.post(new DoMessage("done!"));
        ignoreFsUpdates = false;
        loadMeta();
      }

      @Override
      public void updateProgress(WorkerContext context, double progress) {
        EVENT_BUS.post(new ProgressUpdateEvent(progress));
      }
    });
  }

  private Nested getNestedFromRoot(File metaRoot, Meta meta, File f) throws IOException {
    if (meta.nested == null) return null;

    // Breadth-first search
    for (Nested n : meta.nested) {
      if (Paths.get(metaRoot.toString(), n.mount).toFile().getCanonicalFile().equals(f)) return n;
    }
    for (Nested n : meta.nested) {
      if (n.meta == null) continue;

      Nested result = getNestedFromRoot(Paths.get(metaRoot.toString(), n.mount).toFile(), n.meta, f);
      if (result != null) return result;
    }
    return null;
  }

  private Nested getParentNestedFromRoot(File metaRoot, Meta meta, File f) throws IOException {
    if (!f.toString().startsWith(metaRoot.toString())) return null;
    if (meta.nested == null) return null;

    for (Nested n : meta.nested) {
      if (!f.toString().startsWith(Paths.get(metaRoot.toString(), n.mount).toFile().getCanonicalFile().toString())) {
        continue;
      }

      if (n.meta == null) return n;

      Nested result = getParentNestedFromRoot(Paths.get(metaRoot.toString(), n.mount).toFile(), n.meta, f);
      if (result != null) return result;
      return n;
    }
    return null;
  }

  private void loadMetaFromRoot(File metaRoot, Meta meta) throws IllegalStateException, IOException {
    if (meta.nested == null) return;

    for (Nested n : meta.nested) {
      n.absolutePath = Paths.get(metaRoot.toString(), n.mount).toFile().getCanonicalFile();
      n.meta = loadTfs(n);
      if (n.meta == null) continue;

      loadMetaFromRoot(n.absolutePath, n.meta);
    }
  }

  /**
   * Change the current workspace.
   */
  private void openWorkspace(Path workspace) {
    editor.closeAll();
    fileSystem.setWorkspace(workspace);
    loadMeta();
  }

  private void rebaseSiblings(Meta parent, Nested child) throws IOException {
    List<Nested> toMove = new ArrayList<>();
    for (int i = parent.nested.size() - 1; i >= 0; i--) {
      Nested n = parent.nested.get(i);
      if (n == child) continue;

      if (n.absolutePath.toString().startsWith(child.absolutePath.toString())) {
        parent.nested.remove(i);
        toMove.add(n);
      }
    }
    if (toMove.size() == 0) return;

    createTfs(child.absolutePath);
    for (Nested n : toMove) {
      n.mount = child.absolutePath.toPath().relativize(n.absolutePath.toPath()).toString();
    }
    if (child.meta.nested == null) child.meta.nested = new ArrayList<>();
    child.meta.nested.addAll(toMove);
  }

  private void writeMetaToFile(File f, Meta meta) throws IOException {
    if (meta == null) return;

    TfsUtil.writeTfs(Paths.get(f.toString(), ".tfs").toFile(), meta);
    if (meta.nested == null) return;

    for (Nested n : meta.nested) {
      if (n.meta == null) continue;
      writeMetaToFile(n.absolutePath, n.meta);
    }
  }

  public static MainController get() {
    return instance;
  }
}


text:
package eu.bcvsolutions.idm.acc.domain;

import eu.bcvsolutions.idm.core.api.event.EventType;

/**
 * Active provisioning operation type
 *
 * @author Radek Tomiška
 *
 */
public enum ProvisioningEventType implements EventType {

	CREATE,
	UPDATE,
	DELETE,
	CANCEL,
	START, // Used in a uniform password to prevent end of sync too soon.
	END;
}

redpajama_set_name: RedPajamaGithub


text:
goog.provide('shaka.player.DrmInfo');

goog.require('shaka.asserts');
goog.require('shaka.util.ArrayUtils');
goog.require('shaka.util.Uint8ArrayUtils');

/**
 * Creates a DrmInfo, which represents a set of DRM configuration options.
 * DrmInfo is an internal class, please see
 * {@link shaka.player.DashVideoSource.ContentProtectionCallback},
 * {@link shaka.player.HttpVideoSource}, and
 * {@link shaka.player.DrmInfo.Config} for information on how to configure the
 * key system from the application.
 *
 * @constructor
 * @struct
 * @see {shaka.player.DashVideoSource.ContentProtectionCallback}
 * @see {shaka.player.DrmInfo.Config}
 * @exportDoc
 */
shaka.player.DrmInfo = function() {
  /**
   * An empty string indicates no key system.
   * @type {string}
   */
  this.keySystem = '';

  /** @type {string} */
  this.licenseServerUrl = '';

  /** @type {boolean} */
  this.withCredentials = false;

  /** @type {?shaka.player.DrmInfo.LicensePostProcessor} */
  this.licensePostProcessor = null;

  /** @type {?shaka.player.DrmInfo.LicensePreProcessor} */
  this.licensePreProcessor = null;

  /** @type {boolean} */
  this.distinctiveIdentifierRequired = false;

  /** @type {boolean} */
  this.persistentStateRequired = false;

  /** @type {string} */
  this.audioRobustness = '';

  /** @type {string} */
  this.videoRobustness = '';

  /** @type {Uint8Array} */
  this.serverCertificate = null;

  /** @type {!Array.<shaka.player.DrmInfo.InitData>} */
  this.initDatas = [];
};

/**
 * @typedef {{initData: !Uint8Array, initDataType: string}}
 * @exportDoc
 */
shaka.player.DrmInfo.InitData;

/**
 *

 * An object which represents a set of application provided DRM configuration
 * options.
 *

 *
 *

 * For encrypted content, an application must provide one or more DrmInfo.Config
 * objects to its VideoSource. For DASH content, the application can provide
 * Config objects to {@link shaka.player.DashVideoSource} via a callback
 * (see {@link shaka.player.DashVideoSource.ContentProtectionCallback}),
 * and for HTTP content, the application can provide a single Config object to
 * {@link shaka.player.HttpVideoSource} via HttpVideoSource's constructor.
 *

 *
 * The following options are supported:
 *

 *

 *   keySystem: string (required)

 *   The key system, e.g., "com.widevine.alpha".
 *   A blank string indicates unencrypted content.
 *
 *

 *   licenseServerUrl: string (required for streaming encrypted content)
 *

 *   The license server URL.
 *
 *

 *   withCredentials: boolean

 *   True if license requests should include cookies when sent cross-domain
 *   (see {@link http://goo.gl/pzY9F7}). Defaults to false.
 *
 *

 *   licensePostProcessor: shaka.player.DrmInfo.LicensePostProcessor

 *   A license post-processor that does application-specific post-processing on
 *   license responses.
 *
 *

 *   licensePreProcessor: shaka.player.DrmInfo.LicensePreProcessor

 *   A license pre-processor that does application-specific pre-processing on
 *   license requests.
 *
 *

 *   distinctiveIdentifierRequired: boolean

 *   True if the application requires the key system to support distinctive
 *   identifiers. Defaults to false.
 *
 *

 *   persistentStateRequired: boolean

 *   True if the application requires the key system to support persistent
 *   state, e.g., for persistent license storage. Defaults to false.
 *
 *

 *   audioRobustness: string

 *   A key system specific string that specifies an audio decrypt/decode
 *   security level.
 *
 *

 *   videoRobustness: string

 *   A key system specific string that specifies a video decrypt/decode
 *   security level.
 *
 *

 *   serverCertificate: Uint8Array

 *   An key system specific server certificate for authenticating license
 *   requests.
 *
 *

 *   initData: shaka.player.DrmInfo.InitData

 *   Explicit key system initialization data (initData value), which overrides
 *   both the initData given in the manifest, if any, and the initData in the
 *   actual content (which may be inspected via an EME 'encrypted' event).  The
 *   initDataType values and the formats that they correspond to are specified
 *   {@link http://goo.gl/hKBdff here}.
 *

 *
 * @typedef {Object.<string, *>}
 * @exportDoc
 */
shaka.player.DrmInfo.Config;

/**
 *

 * A callback which does application-specific post-processing on license
 * responses before they are passed to the key system. The application can
 * set this callback in a {@link shaka.player.DrmInfo.Config} object.
 *

 *
 *

 * The parameter is the license response from the license server.
 * Must return the raw license.
 *

 *
 * @example
 *     // Suppose the license server provides a JSON encoded license response
 *     // with the format {"header": header_string, "license": license_string}.
 *     // The application would need to use a license post-processor like
 *     // the following:
 *     var postProcessor = function(serverResponse) {
 *       // serverResponse is a Uint8Array, so decode it into an object.
 *       var json = String.fromCharCode.apply(null, serverResponse);
 *       var obj = JSON.parse(json);
 *
 *       var headerString = obj['header'];
 *       // Do something with the header...
 *
 *       // obj['license'] is a string, so encode it into a Uint8Array.
 *       var licenseString = obj['license'];
 *       var license = new Uint8Array(licenseString.split('').map(
 *           function(ch) { return ch.charCodeAt(0); }));
 *       return license;
 *     };
 *
 * @typedef {function(!Uint8Array):!Uint8Array}
 * @exportDoc
 */
shaka.player.DrmInfo.LicensePostProcessor;

/**
 * An object that describes a license request for license request
 * pre-processing (see {@link shaka.player.DrmInfo.LicensePreProcessor}).
 *

 *
 * The following options are supported:
 *

 *

 *   url: string (required)

 *   The license server URL.
 *
 *

 *   body: (ArrayBuffer|?string)

 *   The license request's body.
 *
 *

 *   method: string (required)

 *   The HTTP request method, which must be either 'GET' or 'POST'.
 *
 *

 *   headers: Object.<string, string>

 *   Extra HTTP request headers as key-value pairs.
 *

 *
 * @typedef {Object.<string, *>}
 * @exportDoc
 */
shaka.player.DrmInfo.LicenseRequestInfo;

/**
 *

 * A callback which does application-specific pre-processing on license
 * requests before they are sent to the license server. The application can
 * set this callback in a {@link shaka.player.DrmInfo.Config} object.
 *

 *
 *

 * The parameter is a {@link shaka.player.DrmInfo.LicenseRequestInfo}
 * object. The callback may modify the object's fields as it requires; some
 * fields are set to initial values:
 *

 *

 *   The |url| field is initially set to the license server URL provided by the
 *   license request pre-processor's corresponding DrmInfo; it may be set
 *   to an arbitrary URL, or may be extended with extra query parameters.
 *
 *

 *   The |body| field is initially set to the raw license request (an
 *   ArrayBuffer) emitted by the browser; it may be replaced (to another
 *   ArrayBuffer or string) or be removed entirely (e.g., if the server expects
 *   the raw license to be encoded in the URL).
 *
 *

 *   The |method| field is initially set to 'POST', but may be set to 'GET'.
 *
 *

 *   The |headers| field is initially an empty map; arbitrary request headers
 *   may be added as key-value pairs, e.g.,
 *   headers['Content-Type'] = 'application/x-www-form-urlencoded';
 *

 *

 *
 * @example
 *     // Suppose the license server expects a license request to use a
 *     // base64 encoded payload and include special query parameters.
 *     // The application would need to use a license pre-processor like
 *     // the following:
 *     var preProcessor = function(requestInfo) {
 *       // Add query parameters.
 *       requestInfo.url += '?session=123&token=abc'
 *       // Encode the payload as base64.
 *       requestInfo.body = window.btoa(
 *           String.fromCharCode.apply(null, new Uint8Array(requestInfo.body)));
 *     };
 * @typedef {function(!shaka.player.DrmInfo.LicenseRequestInfo)}
 * @exportDoc
 */
shaka.player.DrmInfo.LicensePreProcessor;

/**
 * Creates a DrmInfo object from a Config object.
 *
 * @param {shaka.player.DrmInfo.Config} config
 * @throws TypeError if a configuration option has the wrong type.
 * @throws Error if the application fails to provide any required fields.
 * @return {!shaka.player.DrmInfo}
 */
shaka.player.DrmInfo.createFromConfig = function(config) {
  var drmInfo = new shaka.player.DrmInfo();

  if (!config) return drmInfo;

  // Alias.
  var MapUtils = shaka.util.MapUtils;

  var keySystem = MapUtils.getString(config, 'keySystem');
  if (keySystem != null) {
    drmInfo.keySystem = keySystem;
  } else {
    throw new Error('\'keySystem\' cannot be null.');
  }

  var licenseServerUrl = MapUtils.getString(config, 'licenseServerUrl');
  if (licenseServerUrl != null) {
    drmInfo.licenseServerUrl = licenseServerUrl;
  } else if (keySystem) {
    throw new Error('For encrypted streaming content, \'licenseServerUrl\' ' +
                    'cannot be null or empty.');
  }

  var withCredentials = MapUtils.getBoolean(config, 'withCredentials');
  if (withCredentials != null) {
    drmInfo.withCredentials = withCredentials;
  }

  var licensePostProcessor = MapUtils.getAsInstanceType(
      config, 'licensePostProcessor', Function);
  if (licensePostProcessor != null) {
    drmInfo.licensePostProcessor = licensePostProcessor;
  }

  var licensePreProcessor = MapUtils.getAsInstanceType(
      config, 'licensePreProcessor', Function);
  if (licensePreProcessor != null) {
    drmInfo.licensePreProcessor = licensePreProcessor;
  }

  var distinctiveIdentifierRequired = MapUtils.getBoolean(
      config, 'distinctiveIdentifierRequired');
  if (distinctiveIdentifierRequired != null) {
    drmInfo.distinctiveIdentifierRequired = distinctiveIdentifierRequired;
  }

  var persistentStateRequired = MapUtils.getBoolean(
      config, 'persistentStateRequired');
  if (persistentStateRequired != null) {
    drmInfo.persistentStateRequired = persistentStateRequired;
  }

  var audioRobustness = MapUtils.getString(config, 'audioRobustness');
  if (audioRobustness != null) {
    drmInfo.audioRobustness = audioRobustness;
  }

  var videoRobustness = MapUtils.getString(config, 'videoRobustness');
  if (videoRobustness != null) {
    drmInfo.videoRobustness = videoRobustness;
  }

  var serverCertificate = MapUtils.getAsInstanceType(
      config, 'serverCertificate', Uint8Array);
  if (serverCertificate != null) {
    drmInfo.serverCertificate = serverCertificate;
  }

  var initData = MapUtils.getAsInstanceType(config, 'initData', Object);
  if (initData) {
    var data = MapUtils.getAsInstanceType(initData, 'initData', Uint8Array);
    if (data == null) {
      throw new Error('\'initData.initData\' cannot be null.');
    }

    var dataType = MapUtils.getString(initData, 'initDataType');
    if (dataType == null) {
      throw new Error('\'initData.initDataType\' cannot be null.');
    }

    drmInfo.initDatas.push({
      'initData': new Uint8Array(data.buffer),
      'initDataType': dataType
    });
  }

  return drmInfo;
};

/**
 * Combines this DrmInfo object with another DrmInfo object to create a new
 * DrmInfo object.
 *
 * @param {!shaka.player.DrmInfo} other The other DrmInfo object, which should
 *     be compatible with this DrmInfo object.
 * @return {!shaka.player.DrmInfo}
 */
shaka.player.DrmInfo.prototype.combine = function(other) {
  if (!COMPILED && !this.isCompatible(other)) {
    shaka.log.warning(
        'combine() should only be called with a compatible DrmInfo object:',
        'this', this,
        'other', other);
  }

  var drmInfo = new shaka.player.DrmInfo();

  drmInfo.keySystem = this.keySystem;
  drmInfo.licenseServerUrl = this.licenseServerUrl;
  drmInfo.withCredentials = this.withCredentials;
  drmInfo.licensePostProcessor = this.licensePostProcessor;
  drmInfo.licensePreProcessor = this.licensePreProcessor;
  drmInfo.distinctiveIdentifierRequired = this.distinctiveIdentifierRequired;
  drmInfo.persistentStateRequired = this.persistentStateRequired;
  drmInfo.audioRobustness = this.audioRobustness;
  drmInfo.videoRobustness = this.videoRobustness;

  drmInfo.serverCertificate =
      this.serverCertificate ?
      new Uint8Array(this.serverCertificate.buffer) :
      null;

  drmInfo.addInitDatas(this.initDatas);
  drmInfo.addInitDatas(other.initDatas);

  return drmInfo;
};

/**
 * @param {!shaka.player.DrmInfo} other
 * @return {boolean} True if this DrmInfo is compatible with |other|;
 *     otherwise, return false.
 */
shaka.player.DrmInfo.prototype.isCompatible = function(other) {
  return (this.keySystem == other.keySystem) &&
         (this.licenseServerUrl == other.licenseServerUrl) &&
         (this.withCredentials == other.withCredentials) &&
         (this.licensePostProcessor == other.licensePostProcessor) &&
         (this.licensePreProcessor == other.licensePreProcessor) &&
         (this.distinctiveIdentifierRequired ==
          other.distinctiveIdentifierRequired) &&
         (this.persistentStateRequired == other.persistentStateRequired) &&
         (this.audioRobustness == other.audioRobustness) &&
         (this.videoRobustness == other.videoRobustness) &&
         (shaka.util.Uint8ArrayUtils.equal(this.serverCertificate,
                                           other.serverCertificate));
};

/**
 * Adds the given initDatas (removing duplicates).
 *
 * @param {!Array.<shaka.player.DrmInfo.InitData>} otherInitDatas
 */
shaka.player.DrmInfo.prototype.addInitDatas = function(
    otherInitDatas) {
  var unfilteredInitDatas =
      this.initDatas.concat(otherInitDatas.map(
          function(initData) {
            return {
              'initData': new Uint8Array(initData.initData.buffer),
              'initDataType': initData.initDataType
            };
          }));

  this.initDatas = shaka.util.ArrayUtils.removeDuplicates(
      unfilteredInitDatas, shaka.player.DrmInfo.compareInitDatas_);
};

/**
 * @param {!shaka.player.DrmInfo.InitData} initDataA
 * @param {!shaka.player.DrmInfo.InitData} initDataB
 * @return {boolean}
 * @private
 */
shaka.player.DrmInfo.compareInitDatas_ =
    function(initDataA, initDataB) {
  return initDataA.initDataType == initDataB.initDataType &&
         shaka.util.Uint8ArrayUtils.equal(initDataA.initData,
                                          initDataB.initData);
};


text:
var specHelper = require('../../spec-helper');
var HistogramWidgetModel = require('../../../../../javascripts/deep-insights/widgets/histogram/histogram-widget-model');

describe('widgets/histogram/histogram-widget-model', function () {
  beforeEach(function () {
    var vis = specHelper.createDefaultVis();
    var source = vis.analysis.findNodeById('a0');
    this.layerModel = vis.map.layers.first();
    this.dataviewModel = vis.dataviews.createHistogramModel({
      column: 'col',
      source: source
    });
    this.widgetModel = new HistogramWidgetModel({}, {
      dataviewModel: this.dataviewModel,
      layerModel: this.layerModel
    }, {autoStyleEnabled: true});
  });

  describe('when model is set to collapsed', function () {
    beforeEach(function () {
      this.widgetModel.set('collapsed', true);
    });

    it('should disable dataview', function () {
      expect(this.widgetModel.dataviewModel.get('enabled')).toBe(false);
    });

    describe('when model is expanded', function () {
      beforeEach(function () {
        this.widgetModel.set('collapsed', false);
      });

      it('should enable dataview', function () {
        expect(this.widgetModel.dataviewModel.get('enabled')).toBe(true);
      });
    });
  });
});


text:
<?php

namespace Mesd\ReportDemoBundle\Services;

use Mesd\Jasper\ReportBundle\Interfaces\AbstractOptionsHandler;
use Mesd\Jasper\ReportBundle\InputControl\AbstractReportBundleInputControl;
use Mesd\Jasper\ReportBundle\InputControl\Option;

class ReportFormOptionsHandler extends AbstractOptionsHandler
{
    ///////////////
    // VARIABLES //
    ///////////////

    /**
     * Map that maps input control ids to the function to generate their option list
     * @var array
     */
    private $methodMap;

    //////////////////
    // BASE METHODS //
    //////////////////

    /**
     * Constructor
     */
    public function __construct() {
        //This where stuff from the dependency injector will come in and class variables will be set
        //Things such as the entity manager and security context will probably be the most common

        //Call the register methods method
        $this->registerMethods();
    }

    /////////////////////////
    // IMPLEMENTED METHODS //
    /////////////////////////

    /**
     * The method that takes a input control and generates a list of options for it
     *   NOTE: this should either
     *           A: return an array of Option objects for the user to select from
     *           B: return an empty array to give the user no options to select from
     *           C: return null to inidicate that this method does not handle the requested input type (such that fallback can takeover)
     *
     * @param  string     $inputControl The id of the input control to check for options of
     *
     * @return array|null               The array of options or null
     */
    public function getList($inputControlId) {
        //Check if the input control id is in the function map
        if (array_key_exists($inputControlId, $this->methodMap)) {
            //call the function
            $options = call_user_func(array($this, $this->methodMap[$inputControlId]));
        } else {
            //Set options to null (this way fallback mode will know to go ask Jasper for the options)
            $options = null;
        }

        //Return the options array or null
        return $options;
    }

    ///////////////////
    // CLASS METHODS //
    ///////////////////

    /**
     * A little simple method I use to centralize which input control ids call which option generating method
     */
    public function registerMethods() {
        //Init the array
        $this->methodMap = array();

        //nothing for now
    }

    ////////////////////
    // OPTION METHODS //
    ////////////////////

    //None here yet
}


text:
<div class="base" style="height: <%= podium.baseHeight %>">

<%= podium.achievement %>

        <%= _.each(contributors, function(contributor){ %>
            <li style="width:<%= contributor.get('picWidth') %>; height: <%= contributor.get('picWidth') %>">
                <div class="contributor" id="<%= contributor.get('name') %>" style="width:<%= contributor.get('picWidth') %>; height: <%= contributor.get('picWidth') %>">

                       <li class="pic" style="background-color: <%= contributor.get('medalHex') %>; width:<%= contributor.get('picWidth')%>; height: <%= contributor.get('picWidth')%>">

                               <a href="<%= contributor.get('githubPath') %>" style="width:<%= contributor.get('picWidth')%>; height: <%= contributor.get('picWidth')%>; background: url(<%= contributor.get('avatar_url') %>) no-repeat center; background-size: <%= String( Number(contributor.get('picWidth').split("px")[0] ) - 40) + 'px' %> <%= String( Number(contributor.get('picWidth').split("px")[0] ) - 40) + 'px'  %>">

                        <li class="username" style="width:<%= contributor.get('picWidth') %>">

<a href="<%= contributor.get('githubPath') %>"><%= contributor.get("login") %>

                        <li class="contributions" style="width:<%= contributor.get('picWidth') %>; height: <%= contributor.get('picWidth') %>">
                            <p style="background-color:<%= contributor.get('medalHex') %>"><%= contributor.get("contributions") %>

        <%= }); %>


text:
import { useSelector } from './internal/WebChatReduxContext';

export default function useSendTypingIndicator() {
  return [useSelector(({ sendTypingIndicator }) => sendTypingIndicator)];
}


text:
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Test {
  boolean isEmpty(Stream<String> stream) {
    return stream.peek(System.out::println).collect(Collectors.toList()).stream().limit(42).findAny().isPresent();
  }
}


text:
export default function promiseMiddleware({ dispatch, getState }) {

  return next => action => {
    const { promise, types, params } = action;

    if (!promise) return next(action);

    const [REQUEST, SUCCESS, FAILURE] = types;
    next({params, type: REQUEST});

    promise.then(
      payload => next({params, payload, type: SUCCESS}),
      payload => next({params, payload, type: FAILURE})
    );
  };
}


text:
var express = require('express');
var config = require("../config");
var sessionUtils = require("./session-utils");

var view;

var pageUtils = {
    configure: function (app) {
        if (config.view) {
            for (viewName in config.view) {
                view = config.view[viewName];
                if (view.method && view.route && view.content_template) {
                    (function () {     // run this in a function so that the router's callback will see variables appropriate for this iteration
                        var v = view;
                        var vname = viewName;
                        var options = v.render_options || {};
                        app[v.method](v.route, function (req, res, next) {
                            var now = Date.now();
                            // allocateSessionId() is used for cookie-session, where there is no sessionId.
                            // It should not be called if you are using express-session.
                            sessionUtils.allocateSessionId(req, now);
                            sessionUtils.keepSessionTimes(req, now);
                            sessionUtils.countPageHits(req);
                            sessionUtils.trackBreadcrumbs(req, res, vname);
                            sessionUtils.makeLocals(req, res);
                            // console.log("pageUtils.handler() req.sessionID", req.sessionID);
                            // console.log("pageUtils.handler() req.session", req.session);
                            // console.log("pageUtils.handler() res.locals", res.locals);
                            res.render(v.content_template, options);
                        });
                    })();
                }
            }
        }
    }
};

module.exports = pageUtils;


text:
//---------------------------------------------------------------------
// <copyright file="LinqQueryGenerationVisitor.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.Query.Linq
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    using Microsoft.Test.Taupo.Common;
    using Microsoft.Test.Taupo.Contracts;
    using Microsoft.Test.Taupo.Contracts.EntityModel;
    using Microsoft.Test.Taupo.Query.Contracts;
    using Microsoft.Test.Taupo.Query.Contracts.CommonExpressions;
    using Microsoft.Test.Taupo.Query.Contracts.Linq;
    using Microsoft.Test.Taupo.Query.Contracts.Linq.Expressions;

    /// <summary>
    /// The visitor that creates System.Linq.Expressions.Expression tree that represents a Linq query.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Coupling is temporarily allowed until further refactoring of current design.")]
    public abstract class LinqQueryGenerationVisitor : ILinqExpressionVisitor<Expression>
    {
#if WIN8
        private Type expressionGeneratorType = typeof(Enumerable);
#else
        private Type expressionGeneratorType = typeof(Queryable);
#endif
        private List<object> closures;
        private IAnonymousTypeBuilder anonymousTypeBuilder;
        private Dictionary<LinqParameterExpression, ParameterExpression> parametersInScope;

        /// <summary>
        /// Initializes a new instance of the LinqQueryGenerationVisitor class.
        /// </summary>
        /// <param name="context">Context for the query.</param>
        /// <param name="closures">Closures that are in scope. Properties of the type should match free variable names.</param>
        /// <param name="anonymousTypeBuilder">The anonymous type builder.</param>
        protected LinqQueryGenerationVisitor(object context, IEnumerable<object> closures, IAnonymousTypeBuilder anonymousTypeBuilder)
        {
            this.Context = context;
            this.parametersInScope = new Dictionary<LinqParameterExpression, ParameterExpression>();
            this.closures = new List<object>(closures);
            this.anonymousTypeBuilder = anonymousTypeBuilder;
        }

        /// <summary>
        /// Gets the context for the linq query.
        /// </summary>
        protected object Context { get; private set; }

        /// <summary>
        /// Gets or sets the the query provider for the linq query.
        /// </summary>
        protected IQueryProvider QueryProvider { get; set; }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression GenerateLinqExpression(QueryExpression expression)
        {
            return expression.Accept(this);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqAllExpression expression)
        {
            return this.GenerateAnyAllQueryCallExpression(expression, "All");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqAnyExpression expression)
        {
            return this.GenerateAnyAllQueryCallExpression(expression, "Any");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqAsEnumerableExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Type sourceTypeArgument = this.GetCollectionTypeArgument(source);

            return Expression.Call(typeof(Enumerable), "AsEnumerable", new Type[] { sourceTypeArgument }, source);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqBitwiseAndExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.And);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqBitwiseOrExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.Or);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqBuiltInFunctionCallExpression expression)
        {
            var type = Type.GetType(expression.LinqBuiltInFunction.ClassName);
            ExceptionUtilities.CheckObjectNotNull(type, "Cannot find type '{0}' to find method {1}", expression.LinqBuiltInFunction.ClassName, expression.LinqBuiltInFunction.MethodName);

            var expressionArguments = expression.Arguments.Select(a => this.GenerateLinqExpression(a)).ToList();
            var expressionArgumentTypes = expressionArguments.Select(a => a.Type).ToList();

            if (expression.LinqBuiltInFunction.BuiltInFunctionKind == LinqBuiltInFunctionKind.InstanceMethod)
            {
                ExceptionUtilities.Assert(expressionArguments.Count > 0, "Need at least one argument");

                var instanceExpression = expressionArguments.First();

                expressionArguments.Remove(instanceExpression);
                expressionArgumentTypes.Remove(expressionArgumentTypes.First());
                var methodInfo = type.GetMethod(expression.LinqBuiltInFunction.MethodName, expressionArgumentTypes.ToArray(), true, false);

                return Expression.Call(instanceExpression, methodInfo, expressionArguments);
            }
            else if (expression.LinqBuiltInFunction.BuiltInFunctionKind == LinqBuiltInFunctionKind.InstanceProperty)
            {
                ExceptionUtilities.Assert(expressionArguments.Count == 1, "Invalid test expression, cannot use a function that is an InstanceProperty type with multiple arguments");

                var instanceExpression = expressionArguments.Single();

                var propertyGetMethod = type.GetProperty(expression.LinqBuiltInFunction.MethodName).GetGetMethod();
                return Expression.Call(instanceExpression, propertyGetMethod);
            }
            else
            {
                var methodInfo = type.GetMethod(expression.LinqBuiltInFunction.MethodName, expressionArgumentTypes.ToArray(), true, true);
                return Expression.Call(methodInfo, expressionArguments.ToArray());
            }
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqCastExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);

            Type type = this.GetClrType(expression.TypeToOperateAgainst);
            MethodInfo methodInfo = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(type);
            return Expression.Call(methodInfo, source);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqConcatExpression expression)
        {
            Expression outer = this.GenerateLinqExpression(expression.Outer);
            Expression inner = this.GenerateLinqExpression(expression.Inner);

            Type typeArgument = this.GetCollectionTypeArgument(outer);

            return Expression.Call(this.expressionGeneratorType, "Concat", new Type[] { typeArgument }, outer, inner);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqContainsExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Expression value = this.GenerateLinqExpression(expression.Value);
            Type sourceTypeArgument = this.GetCollectionTypeArgument(source);

            return Expression.Call(this.expressionGeneratorType, "Contains", new Type[] { sourceTypeArgument }, source, value);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqCountExpression expression)
        {
            return this.GenerateQueryMethodWithLambda(expression, "Count");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqDefaultIfEmptyExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Type sourceTypeArgument = this.GetCollectionTypeArgument(source);

            if (expression.DefaultValue != null)
            {
                Expression defaultValue = this.GenerateLinqExpression(expression.DefaultValue);
                return Expression.Call(this.expressionGeneratorType, "DefaultIfEmpty", new Type[] { sourceTypeArgument }, source, defaultValue);
            }
            else
            {
                return Expression.Call(this.expressionGeneratorType, "DefaultIfEmpty", new Type[] { sourceTypeArgument }, source);
            }
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqDistinctExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Type sourceTypeArgument = this.GetCollectionTypeArgument(source);

            return Expression.Call(this.expressionGeneratorType, "Distinct", new Type[] { sourceTypeArgument }, source);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqExceptExpression expression)
        {
            Expression outer = this.GenerateLinqExpression(expression.Outer);
            Expression inner = this.GenerateLinqExpression(expression.Inner);

            Type typeArgument = this.GetCollectionTypeArgument(outer);

            return Expression.Call(this.expressionGeneratorType, "Except", new Type[] { typeArgument }, outer, inner);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqExclusiveOrExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.ExclusiveOr);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqFirstExpression expression)
        {
            return this.GenerateQueryMethodWithLambda(expression, "First");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqFirstOrDefaultExpression expression)
        {
            return this.GenerateQueryMethodWithLambda(expression, "FirstOrDefault");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqFreeVariableExpression expression)
        {
            // find closure object which has a property matching the free variable name
            object closure = this.closures.Where(c => c.GetType().GetProperty(expression.Name) != null).SingleOrDefault();

            if (closure == null)
            {
                throw new TaupoInvalidOperationException("Could not find closure with property matching free variable name: " + expression.Name);
            }

            PropertyInfo propertyInfo = closure.GetType().GetProperty(expression.Name);
            ExceptionUtilities.Assert(propertyInfo != null, "PropertyInfo should not be null");

            return Expression.Property(Expression.Constant(closure), propertyInfo);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqGroupByExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Expression keySelector = this.GenerateLinqExpression(expression.KeySelector);
            Expression elementSelector = expression.ElementSelector != null ? this.GenerateLinqExpression(expression.ElementSelector) : null;
            Expression resultSelector = expression.ResultSelector != null ? this.GenerateLinqExpression(expression.ResultSelector) : null;

            var genericArguments = new List<Type>(keySelector.Type.GetGenericArguments());
            var arguments = new List<Expression>(new[] { source, keySelector });
            if (elementSelector != null)
            {
                genericArguments.Add(elementSelector.Type.GetGenericArguments()[1]);
                arguments.Add(elementSelector);
            }

            if (resultSelector != null)
            {
                genericArguments.Add(resultSelector.Type.GetGenericArguments()[2]);
                arguments.Add(resultSelector);
            }

            return Expression.Call(this.expressionGeneratorType, "GroupBy", genericArguments.ToArray(), arguments.ToArray());
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqGroupJoinExpression expression)
        {
            return this.VisitJoinExpressionBase(expression, "GroupJoin");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqJoinExpression expression)
        {
            return this.VisitJoinExpressionBase(expression, "Join");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqLambdaExpression expression)
        {
            ParameterExpression[] parameters = expression.Parameters.Select(p => this.GenerateLinqExpression(p)).Cast<ParameterExpression>().ToArray();
            Expression body = this.GenerateLinqExpression(expression.Body);
            return Expression.Lambda(body, parameters);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqLengthPropertyExpression expression)
        {
            var instance = this.GenerateLinqExpression(expression.Instance);

            return Expression.Property(instance, "Length");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqLongCountExpression expression)
        {
            return this.GenerateQueryMethodWithLambda(expression, "LongCount");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqMaxExpression expression)
        {
            // Max must take an extra generic type argument when a lamba is given, otherwise Max will throw
            if (expression.Lambda != null)
            {
                return this.GenerateQueryMethodWithLambda(expression, "Max", new Type[] { ((IQueryClrType)expression.Lambda.Body.ExpressionType).ClrType });
            }
            else
            {
                return this.GenerateQueryMethodWithLambda(expression, "Max", new Type[] { });
            }
        }

        /// <summary>
        /// Visits a QueryExpression tree whose root node is the LinqMemeberMethodExpression.
        /// </summary>
        /// <param name="expression">The root node of the expression tree being visited.</param>
        /// <returns>The result of visiting this expression.</returns>
        public virtual Expression Visit(LinqMemberMethodExpression expression)
        {
            var instance = this.GenerateLinqExpression(expression.Source);
            string methodName = expression.MemberMethod.Name;
            var arguments = expression.Arguments.Select(a => this.GenerateLinqExpression(a)).ToArray();

            return this.BuildMethodCallExpression(instance, methodName, arguments);
        }

        /// <summary>
        /// Visits a QueryExpression tree whose root node is the LinqMinExpression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqMinExpression expression)
        {
            // Min must take an extra generic type argument when a lamba is given, otherwise Min will throw
            if (expression.Lambda != null)
            {
                return this.GenerateQueryMethodWithLambda(expression, "Min", new Type[] { ((IQueryClrType)expression.Lambda.Body.ExpressionType).ClrType });
            }
            else
            {
                return this.GenerateQueryMethodWithLambda(expression, "Min", new Type[] { });
            }
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public virtual Expression Visit(LinqNewArrayExpression expression)
        {
            List<Expression> linqExpressions = new List<Expression>();
            foreach (var childExpression in expression.Expressions)
            {
                linqExpressions.Add(this.GenerateLinqExpression(childExpression));
            }

            var collectionType = expression.ExpressionType as QueryCollectionType;
            ExceptionUtilities.CheckObjectNotNull(collectionType, "Expecting expression type to be a collection.");

            var queryClrType = collectionType.ElementType as IQueryClrType;
            ExceptionUtilities.CheckObjectNotNull(queryClrType, "In order to make a New Array we need to have a clrType, the queryType'{0}' does not implement IQueryClrType", expression.ExpressionType);

            return Expression.NewArrayInit(queryClrType.ClrType, linqExpressions.ToArray());
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public virtual Expression Visit(LinqNewExpression expression)
        {
            Expression[] members = expression.Members.Select(this.GenerateLinqExpression).ToArray();
            Type anonymousClrType = null;
            if (expression.ExpressionType is QueryAnonymousStructuralType)
            {
                anonymousClrType = this.anonymousTypeBuilder.GetAnonymousType(((QueryAnonymousStructuralType)expression.ExpressionType).Properties.Select(c => c.Name).ToArray());
            }

            ExceptionUtilities.CheckObjectNotNull(anonymousClrType, "could not discover type of new Expression");
            Type[] genericTypeArguments = members.Select(m => m.Type).ToArray();
            Type concreteClrType = anonymousClrType.MakeGenericType(genericTypeArguments);
            ConstructorInfo ctorInfo = concreteClrType.GetInstanceConstructor(true, genericTypeArguments);

            return Expression.New(ctorInfo, members);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqNewInstanceExpression expression)
        {
            var queryClrType = expression.ExpressionType as IQueryClrType;

            ExceptionUtilities.Assert(queryClrType != null, "could not discover type of new Expression");

            Type clrType = queryClrType.ClrType;

            // If we are creating an instance of a specific type, we need to prepare the memberbind expressions for the binding the values of the
            // properties of the type to input values
            var memberBindExpressions = new List<MemberBinding>();

            // entity=>
            for (int index = 0; index < expression.Members.Count; index++)
            {
                string propertyName = expression.MemberNames[index];
                Expression memberExpression = this.GenerateLinqExpression(expression.Members[index]);

                // .PropertyName = PropertyExpression1(entity.PropertyName)
                MemberInfo propertyInfo = clrType.GetProperty(propertyName);
                MemberBinding binding = Expression.Bind(propertyInfo, memberExpression);
                memberBindExpressions.Add(binding);
            }

            ExceptionUtilities.Assert(expression.ConstructorArguments.Count == 0, "Cannot create typed instances with non-default constructor");

            // Since we are creating an instance of a known type, we get the default parameter-less constructor
            ConstructorInfo ctorInfo = clrType.GetInstanceConstructor(true, PlatformHelper.EmptyTypes);
            ExceptionUtilities.CheckObjectNotNull(ctorInfo, "Type '{0}' does not have a default , parameter-less constructor", clrType.FullName);

            // entity => new EntityType( constructorArgs )
            NewExpression newExpression = Expression.New(ctorInfo, Enumerable.Empty<Expression>());

            // entity => new EntityType( constructorArgs ) { Property1 = PropertyExpression1(entity.Property1) }
            Expression objectWithPropertiesSet = Expression.MemberInit(newExpression, memberBindExpressions);
            return objectWithPropertiesSet;
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqOrderByExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);

            Expression result = source;
            for (int i = 0; i < expression.KeySelectors.Count; i++)
            {
                var keySelector = this.GenerateLinqExpression(expression.KeySelectors[i]);
                Type[] keySelectorGenericArguments = keySelector.Type.GetGenericArguments();

                var isDescending = expression.AreDescending[i];

                string methodName = i == 0 ? "OrderBy" : "ThenBy";

                if (isDescending)
                {
                    methodName += "Descending";
                }

                result = Expression.Call(this.expressionGeneratorType, methodName, new[] { keySelectorGenericArguments[0], keySelectorGenericArguments[1] }, result, keySelector);
            }

            return result;
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqParameterExpression expression)
        {
            ParameterExpression result;
            if (!this.parametersInScope.TryGetValue(expression, out result))
            {
                result = Expression.Parameter(this.GetClrType(expression.ExpressionType), expression.Name);
                this.parametersInScope.Add(expression, result);
            }

            return result;
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqSelectExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Expression selector = this.GenerateLinqExpression(expression.Lambda);

            Type[] selectorGenericArguments = selector.Type.GetGenericArguments();

            return Expression.Call(this.expressionGeneratorType, "Select", new[] { selectorGenericArguments[0], selectorGenericArguments[1] }, source, selector);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqSelectManyExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);

            // a bit of LINQ rocket-science. Basically we need to fake the type of collectionSelector to be always IEnumerable<Foo>
            // even if the body is something else, like IList<Foo>. Otherwise Expression.Call will not work cause it won't be able to find appropriate overload
            // compiler does similar thing when it's constructing Expression from method syntax or comprehension
            // fakeCollectionSelector is used to get generic type arguments, which are then used to generate delegate type that we need.
            Expression fakeCollectionSelector = this.GenerateLinqExpression(expression.CollectionSelector);
            Type[] collectionSelectorGenericArguments = fakeCollectionSelector.Type.GetGenericArguments();
            var sourceTypeArgument = collectionSelectorGenericArguments[0];
            var collectionTypeArgument = collectionSelectorGenericArguments[1].GetInterfaces()
                .Where(i => i.IsGenericType() && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)).Single().GetGenericArguments().Single();

            ParameterExpression[] collectionSelectorParameters = expression.CollectionSelector.Parameters.Select(p => this.GenerateLinqExpression(p)).Cast<ParameterExpression>().ToArray();
            Expression collectionSelectorBody = this.GenerateLinqExpression(expression.CollectionSelector.Body);
            var delegateType = typeof(Func<,>).MakeGenericType(sourceTypeArgument, typeof(IEnumerable<>).MakeGenericType(collectionTypeArgument));
            var collectionSelector = Expression.Lambda(delegateType, collectionSelectorBody, collectionSelectorParameters);
            var resultSelector = expression.ResultSelector != null ? this.GenerateLinqExpression(expression.ResultSelector) : null;

            if (resultSelector == null)
            {
                return Expression.Call(this.expressionGeneratorType, "SelectMany", new[] { sourceTypeArgument, collectionTypeArgument }, source, collectionSelector);
            }
            else
            {
                var resultTypeArgument = resultSelector.Type.GetGenericArguments().Last();

                return Expression.Call(this.expressionGeneratorType, "SelectMany", new[] { sourceTypeArgument, collectionTypeArgument, resultTypeArgument }, source, collectionSelector, resultSelector);
            }
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqSingleExpression expression)
        {
            return this.GenerateQueryMethodWithLambda(expression, "Single");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqSingleOrDefaultExpression expression)
        {
            return this.GenerateQueryMethodWithLambda(expression, "SingleOrDefault");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqSkipExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Expression skipCount = this.GenerateLinqExpression(expression.SkipCount);

            Type sourceTypeArgument = this.GetCollectionTypeArgument(source);

            return Expression.Call(this.expressionGeneratorType, "Skip", new[] { sourceTypeArgument }, source, skipCount);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqTakeExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Expression takeCount = this.GenerateLinqExpression(expression.TakeCount);

            Type sourceTypeArgument = this.GetCollectionTypeArgument(source);

            return Expression.Call(this.expressionGeneratorType, "Take", new[] { sourceTypeArgument }, source, takeCount);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqUnionExpression expression)
        {
            Expression firstSource = this.GenerateLinqExpression(expression.FirstSource);
            Expression secondSource = this.GenerateLinqExpression(expression.SecondSource);

            Type sourceType = firstSource.Type.GetGenericArguments()[0];

            return Expression.Call(this.expressionGeneratorType, "Union", new[] { sourceType }, firstSource, secondSource);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(LinqWhereExpression expression)
        {
            return this.GenerateQueryMethodWithLambda(expression, "Where");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryAddExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.Add);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryAndExpression expression)
        {
            Expression left = this.GenerateLinqExpression(expression.Left);
            Expression right = this.GenerateLinqExpression(expression.Right);

            return Expression.And(left, right);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryAsExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Type type = this.GetClrType(expression.TypeToOperateAgainst);
            return Expression.TypeAs(source, type);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryCastExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Type type = this.GetClrType(expression.TypeToOperateAgainst);
            return Expression.Convert(source, type);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryConstantExpression expression)
        {
            return Expression.Constant(expression.ScalarValue.Value, this.GetClrType(expression.ExpressionType));
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public virtual Expression Visit(QueryCustomFunctionCallExpression expression)
        {
            throw new TaupoNotSupportedException("Not implemented yet.");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryDivideExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.Divide);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryEqualToExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.Equal);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public virtual Expression Visit(QueryFunctionImportCallExpression expression)
        {
            throw new TaupoNotSupportedException("Not implemented yet.");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryFunctionParameterReferenceExpression expression)
        {
            throw new TaupoNotSupportedException("Not implemented yet.");
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryGreaterThanExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.GreaterThan);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryGreaterThanOrEqualToExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.GreaterThanOrEqual);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryIsNotNullExpression expression)
        {
            var argument = this.GenerateLinqExpression(expression.Argument);

            return Expression.NotEqual(argument, Expression.Constant(null));
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryIsNullExpression expression)
        {
            var argument = this.GenerateLinqExpression(expression.Argument);

            return Expression.Equal(argument, Expression.Constant(null));
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryIsOfExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Type type = this.GetClrType(expression.TypeToOperateAgainst);
            return Expression.TypeIs(source, type);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryLessThanExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.LessThan);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryLessThanOrEqualToExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.LessThanOrEqual);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryModuloExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.Modulo);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryMultiplyExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.Multiply);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryNotEqualToExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.NotEqual);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryNotExpression expression)
        {
            Expression left = this.GenerateLinqExpression(expression.Argument);

            return Expression.Not(left);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryNullExpression expression)
        {
            return Expression.Constant(null, this.GetClrType(expression.ExpressionType));
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryOfTypeExpression expression)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);

            Type type = this.GetClrType(expression.TypeToOperateAgainst);
            MethodInfo methodInfo = typeof(Queryable).GetMethod("OfType").MakeGenericMethod(type);
            return Expression.Call(methodInfo, source);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryOrExpression expression)
        {
            Expression left = this.GenerateLinqExpression(expression.Left);
            Expression right = this.GenerateLinqExpression(expression.Right);

            return Expression.Or(left, right);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryPropertyExpression expression)
        {
            Expression instance = this.GenerateLinqExpression(expression.Instance);

            return Expression.Property(instance, expression.Name);
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QueryRootExpression expression)
        {
            PropertyInfo propertyInfo = this.Context.GetType().GetProperty(expression.Name);
            IQueryable queryRoot = propertyInfo.GetValue(this.Context, null) as IQueryable;
            ExceptionUtilities.CheckObjectNotNull(queryRoot, "The root of the query should be an IQueryable");
            return queryRoot.Expression;
        }

        /// <summary>
        /// Generates System.Linq.Expressions.Expression from the given expression.
        /// </summary>
        /// <param name="expression">Expression to generate System.Linq.Expressions.Expression from.</param>
        /// <returns>Generated System.Linq.Expressions.Expression.</returns>
        public Expression Visit(QuerySubtractExpression expression)
        {
            return this.VisitBinaryExpression(expression, Expression.Subtract);
        }

        /// <summary>
        /// Builds a method call expression.
        /// </summary>
        /// <param name="instance">The instance expression.</param>
        /// <param name="methodInfo">The method info.</param>
        /// <param name="arguments">The argument expressions.</param>
        /// <returns>The method call expression</returns>
        protected static Expression BuildMethodCallExpression(Expression instance, MethodInfo methodInfo, params Expression[] arguments)
        {
            if (methodInfo.IsStatic)
            {
                return Expression.Call(methodInfo, arguments);
            }
            else
            {
                return Expression.Call(instance, methodInfo, arguments);
            }
        }

        /// <summary>
        /// Builds a method call expression.
        /// </summary>
        /// <param name="instance">The instance expression.</param>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="arguments">The argument expressions.</param>
        /// <returns>The method call expression</returns>
        protected virtual Expression BuildMethodCallExpression(Expression instance, string methodName, params Expression[] arguments)
        {
            MethodInfo methodInfo = instance.Type.GetMethod(methodName);
            ExceptionUtilities.CheckObjectNotNull(methodInfo, "Could not find method '{0}' on type of expression '{1}'", methodName, instance);

            return BuildMethodCallExpression(instance, methodInfo, arguments);
        }

        /// <summary>
        /// Visits the binary expression.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <param name="builderMethodCall">The builder method call.</param>
        /// <returns>The result of visiting the expression</returns>
        protected virtual Expression VisitBinaryExpression(QueryBinaryExpression expression, Func<Expression, Expression, BinaryExpression> builderMethodCall)
        {
            Expression left = this.GenerateLinqExpression(expression.Left);
            Expression right = this.GenerateLinqExpression(expression.Right);

            return builderMethodCall(left, right);
        }

        private Type GetClrType(QueryType queryType)
        {
            var queryClrType = queryType as IQueryClrType;
            if (queryClrType != null)
            {
                return queryClrType.ClrType;
            }

            var queryCollectionType = queryType as QueryCollectionType;
            if (queryCollectionType != null)
            {
                var elementType = queryCollectionType.ElementType as IQueryClrType;
                if (elementType != null)
                {
                    Type enumerableType = typeof(IEnumerable<>).MakeGenericType(elementType.ClrType);
                    return enumerableType;
                }
            }

            throw new TaupoInvalidOperationException("Unable to determine CLR type for " + queryType + ".");
        }

        private Type GetCollectionTypeArgument(Expression expression)
        {
#if WIN8
            var interfaces = expression.Type.GetInterfaces().Where(i => i.IsGenericType() && i.GetGenericTypeDefinition() == typeof(IEnumerable<>));
            if (interfaces.Any())
            {
                Type enumerableInterface = interfaces.Single();
                return enumerableInterface.GetGenericArguments()[0];
            }

            if (expression.Type.IsGenericType())
            {
                var genericTypeDefinition = expression.Type.GetGenericTypeDefinition();
                if (genericTypeDefinition == typeof(IEnumerable<>))
                {
                    return expression.Type.GetGenericArguments()[0];
                }
            }

            throw new TaupoArgumentException("Type of expression is not a collection.");
#else
            Type enumerableInterface = expression.Type.GetInterfaces().Where(i => i.IsGenericType() && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)).Single();

            return enumerableInterface.GetGenericArguments()[0];
#endif
        }

        private Expression GenerateQueryMethodWithLambda(LinqQueryMethodWithLambdaExpression expression, string queryMethodName)
        {
            return this.GenerateQueryMethodWithLambda(expression, queryMethodName, new Type[] { });
        }

        private Expression GenerateQueryMethodWithLambda(LinqQueryMethodWithLambdaExpression expression, string queryMethodName, Type[] additionalTypeArguments)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Type sourceTypeArgument = this.GetCollectionTypeArgument(source);
            Type[] typeArguments = new Type[] { sourceTypeArgument };

            // Some expressions e.g min and max require additional generic type arguments
            typeArguments = typeArguments.Concat(additionalTypeArguments).ToArray();

            if (expression.Lambda == null)
            {
                return Expression.Call(this.expressionGeneratorType, queryMethodName, typeArguments, source);
            }
            else
            {
                Expression predicate = this.GenerateLinqExpression(expression.Lambda);
                return Expression.Call(this.expressionGeneratorType, queryMethodName, typeArguments, source, predicate);
            }
        }

        private Expression GenerateAnyAllQueryCallExpression(LinqQueryMethodWithLambdaExpression expression, string methodName)
        {
            Expression source = this.GenerateLinqExpression(expression.Source);
            Type sourceTypeArgument = this.GetCollectionTypeArgument(source);
            Type[] typeArguments = new Type[] { sourceTypeArgument };

            if (expression.Lambda == null)
            {
                return Expression.Call(typeof(Enumerable), methodName, typeArguments, source);
            }
            else
            {
                Expression predicate = this.GenerateLinqExpression(expression.Lambda);
                return Expression.Call(typeof(Enumerable), methodName, typeArguments, source, predicate);
            }
        }

        private Expression VisitJoinExpressionBase(LinqJoinExpressionBase expression, string methodName)
        {
            Expression outer = this.GenerateLinqExpression(expression.Outer);
            Expression inner = this.GenerateLinqExpression(expression.Inner);
            Expression outerKeySelector = this.GenerateLinqExpression(expression.OuterKeySelector);
            Expression innerKeySelector = this.GenerateLinqExpression(expression.InnerKeySelector);
            Expression resultSelector = this.GenerateLinqExpression(expression.ResultSelector);

            var outerType = outerKeySelector.Type.GetGenericArguments()[0];
            var innerType = innerKeySelector.Type.GetGenericArguments()[0];
            var keyType = outerKeySelector.Type.GetGenericArguments()[1];
            var resultType = resultSelector.Type.GetGenericArguments().Last();

            return Expression.Call(typeof(Queryable), methodName, new Type[] { outerType, innerType, keyType, resultType }, outer, inner, outerKeySelector, innerKeySelector, resultSelector);
        }
    }
}


text:
/*
  =require twitter-bootstrap-static/bootstrap

  Use Font Awesome icons (default)
  To use Glyphicons sprites instead of Font Awesome, replace with "require twitter-bootstrap-static/sprites"
  =require twitter-bootstrap-static/fontawesome
*/

/* User sign in and sign forms. */
.border-form-div {
  max-width: 300px;
  padding: 19px 29px 29px;
  margin: 0 auto 20px;
  background-color: #fff;
  border: 1px solid #e5e5e5;
  -webkit-border-radius: 5px;
     -moz-border-radius: 5px;
          border-radius: 5px;
  -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
     -moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
          box-shadow: 0 1px 2px rgba(0,0,0,.05);
}
.border-form-div .form-signin-heading,
.border-form-div .checkbox {
  margin-bottom: 10px;
}
.border-form-div input[type="text"],
.border-form-div input[type="email"],
.border-form-div input[type="password"] {
  font-size: 16px;
  height: auto;
  margin-bottom: 15px;
  padding: 7px 9px;
}

.note{
  font-size: 12px;
  color: red;
}

/*
tfoot {
  background-color: #D9EDF7;
  color: #000000;
  border-top: 2px solid #428BCA;
  border-bottom: 2px solid #428BCA;
}

thead {
  background-color: #000000;
  color: #FFFFFF;
  border-top: 2px solid #428BCA;
  border-bottom: 2px solid #428BCA;
}
*/


text:
package com.thirdpart.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;

public class CustomScrollView extends ScrollView {

	public CustomScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

//	@Override
//    public boolean onInterceptTouchEvent(MotionEvent ev) {
//            return false;
//    }
}


text:
namespace GMap.NET
{
   public delegate void CurrentPositionChanged(PointLatLng point);
   public delegate void NeedInvalidation();

   public delegate void TileLoadComplete();
   public delegate void TileLoadStart();

   public delegate void MapDrag();
   public delegate void MapZoomChanged();
   public delegate void MapTypeChanged(MapType type);

   public delegate void EmptyTileError(int zoom, Point pos);
}