text:
package com.jayantkrish.jklol.models.parametric;

import java.util.Iterator;

import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.jayantkrish.jklol.models.CoercionError;
import com.jayantkrish.jklol.models.DiscreteFactor;
import com.jayantkrish.jklol.models.DiscreteFactor.Outcome;
import com.jayantkrish.jklol.models.TableFactor;
import com.jayantkrish.jklol.models.VariableNumMap;
import com.jayantkrish.jklol.tensor.DenseTensor;
import com.jayantkrish.jklol.tensor.DenseTensorBuilder;
import com.jayantkrish.jklol.tensor.SparseTensor;
import com.jayantkrish.jklol.tensor.Tensor;
import com.jayantkrish.jklol.tensor.TensorBuilder;
import com.jayantkrish.jklol.util.Assignment;

/**
 * Stores sufficient statistics in a tensors. This implementation of
 * {@link SufficientStatistic} should be sufficient for most
 * {@link ParametricFactor}s.
 *
 * @author jayantk
 */
public class TensorSufficientStatistics implements SufficientStatistics {

  private static final long serialVersionUID = -888818836179147365L;

  private final VariableNumMap statisticNames;

  // This flag determines whether statisticsTensor or statistics
  // contains the current parameters.
  private boolean isDense;
  private Tensor statisticsTensor;
  private TensorBuilder statistics;

  /**
   * Copy constructor.
   *
   * @param toCopy
   */
  private TensorSufficientStatistics(TensorSufficientStatistics toCopy) {
    this.statisticNames = Preconditions.checkNotNull(toCopy.statisticNames);
    if (toCopy.isDense) {
      this.isDense = true;
      this.statistics = toCopy.statistics.getCopy();
      this.statisticsTensor = null;
    } else {
      this.isDense = false;
      this.statistics = null;
      // Tensors are immutable, so this tensor can be shared.
      this.statisticsTensor = toCopy.statisticsTensor;
    }
  }

  /**
   * Creates sufficient statistics represented by a dense tensor.
   *
   * @param statisticNames assigns names to the entries of {@code statistics}.
   * @param statistics
   */
  public TensorSufficientStatistics(VariableNumMap statisticNames, TensorBuilder statistics) {
    Preconditions.checkArgument(statisticNames.getDiscreteVariables().size() == statisticNames.size());
    Preconditions.checkArgument(Ints.asList(statistics.getDimensionNumbers()).equals(statisticNames.getVariableNums()));

    this.statisticNames = statisticNames;
    this.statistics = statistics;

    this.statisticsTensor = null;
    this.isDense = true;
  }

  private TensorSufficientStatistics(VariableNumMap statisticNames, Tensor statistics) {
      Preconditions.checkArgument(statisticNames.getDiscreteVariables().size() == statisticNames.size());
      Preconditions.checkArgument(Ints.asList(statistics.getDimensionNumbers()).equals(statisticNames.getVariableNums()));

    this.statisticNames = statisticNames;
    this.statistics = null;

    this.statisticsTensor = statistics;
    this.isDense = false;
  }

  /**
   * Creates a sufficient statistics vector represented using a sparse tensor.
   *
   * @param statisticNames
   * @param statistics
   * @return
   */
  public static TensorSufficientStatistics createSparse(VariableNumMap statisticNames, Tensor statistics) {
    return new TensorSufficientStatistics(statisticNames, statistics);
  }

  /**
   * Creates a sufficient statistics vector represented using a dense tensor.
   *
   * @param statisticNames
   * @param statistics
   * @return
   */
  public static TensorSufficientStatistics createDense(VariableNumMap statisticNames, TensorBuilder statistics) {
    return new TensorSufficientStatistics(statisticNames, statistics);
  }

  public static TensorSufficientStatistics createDense(VariableNumMap statisticNames) {
    return new TensorSufficientStatistics(statisticNames,
        new DenseTensorBuilder(statisticNames.getVariableNumsArray(), statisticNames.getVariableSizes()));
  }

  /**
   * Gets the tensor in {@code this}.
   * <p>
   * For efficiency, this method does not copy the parameters, and hence the
   * values in the returned tensor may be modified if {@code this} is updated.
   * This situation should be avoided.
   *
   * @return
   */
  public Tensor get() {
    if (isDense) {
      return statistics.buildNoCopy();
    } else {
      return statisticsTensor;
    }
  }

  private int[] getTensorDimensions() {
    if (isDense) {
      return statistics.getDimensionNumbers();
    } else {
      return statisticsTensor.getDimensionNumbers();
    }
  }

  private int[] getTensorSizes() {
    if (isDense) {
      return statistics.getDimensionSizes();
    } else {
      return statisticsTensor.getDimensionSizes();
    }
  }

  /**
   * Gets the tensor in {@code this}, wrapped in a factor that provides names
   * for the statistics/parameters. The returned factor provides an immutable
   * snapshot of the current values of the parameters, and will not reflect
   * future modifications.
   *
   * @return
   */
  public DiscreteFactor getFactor() {
    return new TableFactor(statisticNames, get());
  }

  /**
   * Gets the mapping from statistic/parameter names to tensor indexes.
   *
   * @return
   */
  public VariableNumMap getStatisticNames() {
    return statisticNames;
  }

  @Override
  public void increment(SufficientStatistics other, double multiplier) {
    Preconditions.checkArgument(other instanceof TensorSufficientStatistics);
    TensorSufficientStatistics otherStats = (TensorSufficientStatistics) other;
    increment(otherStats.get(), multiplier);
  }

  public void increment(Tensor other, double multiplier) {
    if (isDense) {
      statistics.incrementWithMultiplier(other, multiplier);
    } else {
      statisticsTensor = statisticsTensor.elementwiseAddition(other.elementwiseProduct(multiplier));
    }
  }

  public void incrementOuterProduct(Tensor leftTensor, Tensor rightTensor, double multiplier) {
    if (isDense) {
      statistics.incrementOuterProductWithMultiplier(leftTensor, rightTensor, multiplier);
    } else {
      Tensor other = leftTensor.outerProduct(rightTensor);
      statisticsTensor = statisticsTensor.elementwiseAddition(other.elementwiseProduct(multiplier));
    }
  }

  public void incrementInnerProduct(Tensor leftTensor, Tensor rightTensor, double multiplier) {
    if (isDense) {
      statistics.incrementInnerProductWithMultiplier(leftTensor, rightTensor, multiplier);
    } else {
      Tensor other = leftTensor.innerProduct(rightTensor);
      statisticsTensor = statisticsTensor.elementwiseAddition(other.elementwiseProduct(multiplier));
    }
  }

  /**
   * Increments the element of that corresponds to the statistic/parameter
   * featureAssignment.
   *
   * @param featureAssignment
   * @param amount
   */
  public void incrementFeature(Assignment featureAssignment, double amount) {
    if (isDense) {
      statistics.incrementEntry(amount, statisticNames.assignmentToIntArray(featureAssignment));
    } else {
      Tensor increment = SparseTensor.singleElement(getTensorDimensions(), getTensorSizes(),
          statisticNames.assignmentToIntArray(featureAssignment), amount);
      statisticsTensor = statisticsTensor.elementwiseAddition(increment);
    }
  }

  public void incrementFeatureByName(double amount, Object ... featureName) {
    Assignment assignment = statisticNames.outcomeArrayToAssignment(featureName);
    incrementFeature(assignment, amount);
  }

  /**
   * Increments the value of {@code index} by {@code amount}.
   *
   * @param index
   * @param amount
   */
  public void incrementFeatureByIndex(double amount, int... key) {
    if (isDense) {
      statistics.incrementEntry(amount, key);
    } else {
      Tensor increment = SparseTensor.singleElement(getTensorDimensions(), getTensorSizes(),
          key, amount);
      statisticsTensor = statisticsTensor.elementwiseAddition(increment);
    }
  }

  @Override
  public void transferParameters(SufficientStatistics other) {
    DiscreteFactor otherFactor = ((TensorSufficientStatistics) other).getFactor();

    Iterator<Outcome> outcomeIter = otherFactor.outcomeIterator();
    while (outcomeIter.hasNext()) {
      Outcome outcome = outcomeIter.next();

      Assignment assignment = outcome.getAssignment();
      if (statisticNames.isValidAssignment(assignment)) {
        incrementFeature(assignment, outcome.getProbability());
      }
    }
  }

  @Override
  public void increment(double amount) {
    if (isDense) {
      statistics.increment(amount);
    } else {
      statisticsTensor = statisticsTensor.elementwiseAddition(amount);
    }
  }

  @Override
  public void multiply(double amount) {
    if (isDense) {
      statistics.multiply(amount);
    } else {
      statisticsTensor = statisticsTensor.elementwiseProduct(amount);
    }
  }

  @Override
  public void softThreshold(double threshold) {
    if (isDense) {
      statistics.softThreshold(threshold);
    } else {
      statisticsTensor = statisticsTensor.softThreshold(threshold);
    }
  }

  @Override
  public void findEntriesLargerThan(double threshold) {
    if (isDense) {
      statistics.findEntriesLargerThan(threshold);
    } else {
      statisticsTensor = statisticsTensor.getEntriesLargerThan(threshold);
    }
  }

  @Override
  public void perturb(double stddev) {
    if (!isDense) {
      // Make the representation dense, since the random perturbation is dense.
      statistics = DenseTensorBuilder.copyOf(statisticsTensor);
      statisticsTensor = null;
      isDense = true;
    }

    Tensor perturbation = DenseTensor.random(getTensorDimensions(), getTensorSizes(), 0.0, stddev);
    statistics.increment(perturbation);
  }

  @Override
  public TensorSufficientStatistics duplicate() {
    return new TensorSufficientStatistics(this);
  }

  @Override
  public double innerProduct(SufficientStatistics other) {
    Preconditions.checkArgument(other instanceof TensorSufficientStatistics);
    Tensor otherStatistics = ((TensorSufficientStatistics) other).get();
    if (isDense) {
      return statistics.innerProduct(otherStatistics);
    } else {
      return statisticsTensor.innerProduct(otherStatistics).getByDimKey();
    }
  }

  @Override
  public double getL2Norm() {
    if (isDense) {
      return statistics.getL2Norm();
    } else {
      return statisticsTensor.getL2Norm();
    }
  }

  @Override
  public ListSufficientStatistics coerceToList() {
    throw new CoercionError("Cannot coerce TensorSufficientStatistics instance into ListSufficientStatistics.");
  }

  @Override
  public void makeDense() {
    if (!isDense) {
      statistics = DenseTensorBuilder.copyOf(statisticsTensor);
      statisticsTensor = null;
      isDense = true;
    }
  }

  @Override
  public void zeroOut() {
    if (isDense) {
      statistics.multiply(0);
    } else {
      statisticsTensor = statisticsTensor.elementwiseProduct(0);
    }
  }

  @Override
  public void incrementSquare(SufficientStatistics other, double multiplier) {
    Preconditions.checkArgument(other instanceof TensorSufficientStatistics);
    Tensor otherStatistics = ((TensorSufficientStatistics) other).get();
    if (isDense) {
      statistics.incrementSquare(otherStatistics, multiplier);
    } else {
      Tensor square = otherStatistics.elementwiseProduct(otherStatistics.elementwiseProduct(multiplier));
      statisticsTensor = statisticsTensor.elementwiseAddition(square);
    }
  }

  @Override
  public void incrementSquareAdagrad(SufficientStatistics gradient,
      SufficientStatistics currentParameters, double multiplier) {
    Preconditions.checkArgument(gradient instanceof TensorSufficientStatistics);
    Tensor gradientTensor = ((TensorSufficientStatistics) gradient).get();
    Preconditions.checkArgument(currentParameters instanceof TensorSufficientStatistics);
    Tensor parameterTensor = ((TensorSufficientStatistics) currentParameters).get();

    if (isDense) {
      statistics.incrementSquareAdagrad(gradientTensor, parameterTensor, multiplier);
    } else {
      Tensor increment = gradientTensor.elementwiseAddition(parameterTensor.elementwiseProduct(multiplier));
      increment = increment.elementwiseProduct(increment);
      statisticsTensor = statisticsTensor.elementwiseAddition(increment);
    }
  }

  @Override
  public void multiplyInverseAdagrad(SufficientStatistics sumSquares, double constant,
      double multiplier) {
    Preconditions.checkArgument(sumSquares instanceof TensorSufficientStatistics);
    Tensor sumSquaresTensor = ((TensorSufficientStatistics) sumSquares).get();

    if (isDense) {
      statistics.multiplyInverseAdagrad(sumSquaresTensor, constant, multiplier);
    } else {
      Tensor multiplierTensor = sumSquaresTensor.elementwiseSqrt().elementwiseInverse()
          .elementwiseProduct(multiplier).elementwiseAddition(constant);
      statisticsTensor = statisticsTensor.elementwiseProduct(multiplierTensor);
    }
  }

  @Override
  public void incrementAdagrad(SufficientStatistics gradient, SufficientStatistics sumSquares,
      double multiplier) {
    Preconditions.checkArgument(gradient instanceof TensorSufficientStatistics);
    Tensor gradientTensor = ((TensorSufficientStatistics) gradient).get();
    Preconditions.checkArgument(sumSquares instanceof TensorSufficientStatistics);
    Tensor squareTensor = ((TensorSufficientStatistics) sumSquares).get();

    if (isDense) {
      statistics.incrementAdagrad(gradientTensor, squareTensor, multiplier);
    } else {
      Tensor increment = gradientTensor.elementwiseProduct(squareTensor
        .elementwiseInverse().elementwiseSqrt()).elementwiseProduct(multiplier);
      statisticsTensor = statisticsTensor.elementwiseAddition(increment);
    }
  }

  @Override
  public String getDescription() {
    return getFactor().getParameterDescription();
  }

  public void getFeatureNames() {
    System.out.println("**** feature names *****" + this.statisticNames.getVariables().get(0).toString());
  }

  @Override
  public String toString() {
    return getFactor().toString();
  }
}


text:
#ifndef _LINUX_VIRTIO_PCI_H
#define _LINUX_VIRTIO_PCI_H

#include "linux/types.h"
#include "linux/virtio_config.h"

#ifndef VIRTIO_PCI_NO_LEGACY

/* A 32-bit r/o bitmask of the features supported by the host */
#define VIRTIO_PCI_HOST_FEATURES    0

/* A 32-bit r/w bitmask of features activated by the guest */
#define VIRTIO_PCI_GUEST_FEATURES   4

/* A 32-bit r/w PFN for the currently selected queue */
#define VIRTIO_PCI_QUEUE_PFN        8

/* A 16-bit r/o queue size for the currently selected queue */
#define VIRTIO_PCI_QUEUE_NUM        12

/* A 16-bit r/w queue selector */
#define VIRTIO_PCI_QUEUE_SEL        14

/* A 16-bit r/w queue notifier */
#define VIRTIO_PCI_QUEUE_NOTIFY     16

/* An 8-bit device status register.  */
#define VIRTIO_PCI_STATUS           18

/* An 8-bit r/o interrupt status register.  Reading the value will return the
* current contents of the ISR and will also clear it.  This is effectively
* a read-and-acknowledge. */
#define VIRTIO_PCI_ISR              19

/* MSI-X registers: only enabled if MSI-X is enabled. */
/* A 16-bit vector for configuration changes. */
#define VIRTIO_MSI_CONFIG_VECTOR    20
/* A 16-bit vector for selected queue notifications. */
#define VIRTIO_MSI_QUEUE_VECTOR     22

/* The remaining space is defined by each driver as the per-driver
* configuration space */
#define VIRTIO_PCI_CONFIG_OFF(msix_enabled) ((msix_enabled) ? 24 : 20)
/* Deprecated: please use VIRTIO_PCI_CONFIG_OFF instead */
#define VIRTIO_PCI_CONFIG(msix_enabled) VIRTIO_PCI_CONFIG_OFF(msix_enabled)

/* How many bits to shift physical queue address written to QUEUE_PFN.
* 12 is historical, and due to x86 page size. */
#define VIRTIO_PCI_QUEUE_ADDR_SHIFT 12

/* The alignment to use between consumer and producer parts of vring.
* x86 pagesize again. */
#define VIRTIO_PCI_VRING_ALIGN      4096

#endif /* VIRTIO_PCI_NO_LEGACY */

/* The bit of the ISR which indicates a device configuration change. */
#define VIRTIO_PCI_ISR_CONFIG       0x2
/* Vector value used to disable MSI for queue */
#define VIRTIO_MSI_NO_VECTOR        0xffff

/* IDs for different capabilities.  Must all exist. */

/* Common configuration */
#define VIRTIO_PCI_CAP_COMMON_CFG   1
/* Notifications */
#define VIRTIO_PCI_CAP_NOTIFY_CFG   2
/* ISR access */
#define VIRTIO_PCI_CAP_ISR_CFG      3
/* Device specific configuration */
#define VIRTIO_PCI_CAP_DEVICE_CFG   4
/* PCI configuration access */
#define VIRTIO_PCI_CAP_PCI_CFG      5

/* This is the PCI capability header: */
struct virtio_pci_cap {
    __u8 cap_vndr;      /* Generic PCI field: PCI_CAPABILITY_ID_VENDOR_SPECIFIC */
    __u8 cap_next;      /* Generic PCI field: next ptr. */
    __u8 cap_len;       /* Generic PCI field: capability length */
    __u8 cfg_type;      /* Identifies the structure. */
    __u8 bar;           /* Where to find it. */
    __u8 padding[3];    /* Pad to full dword. */
    __le32 offset;      /* Offset within bar. */
    __le32 length;      /* Length of the structure, in bytes. */
};

struct virtio_pci_notify_cap {
    struct virtio_pci_cap cap;
    __le32 notify_off_multiplier;   /* Multiplier for queue_notify_off. */
};

/* Fields in VIRTIO_PCI_CAP_COMMON_CFG: */
struct virtio_pci_common_cfg {
    /* About the whole device. */
    __le32 device_feature_select;   /* read-write */
    __le32 device_feature;          /* read-only */
    __le32 guest_feature_select;    /* read-write */
    __le32 guest_feature;           /* read-write */
    __le16 msix_config;             /* read-write */
    __le16 num_queues;              /* read-only */
    __u8 device_status;             /* read-write */
    __u8 config_generation;         /* read-only */

    /* About a specific virtqueue. */
    __le16 queue_select;            /* read-write */
    __le16 queue_size;              /* read-write, power of 2. */
    __le16 queue_msix_vector;       /* read-write */
    __le16 queue_enable;            /* read-write */
    __le16 queue_notify_off;        /* read-only */
    __le32 queue_desc_lo;           /* read-write */
    __le32 queue_desc_hi;           /* read-write */
    __le32 queue_avail_lo;          /* read-write */
    __le32 queue_avail_hi;          /* read-write */
    __le32 queue_used_lo;           /* read-write */
    __le32 queue_used_hi;           /* read-write */
};

#define MAX_QUEUES_PER_DEVICE_DEFAULT 8

typedef struct virtio_queue_info
{
    /* the actual virtqueue */
    struct virtqueue *vq;
    /* the number of entries in the queue */
    u16 num;
    /* the virtual address of the ring queue */
    void *queue;
} VirtIOQueueInfo;

typedef struct virtio_system_ops {
    // device register access
    u8 (*vdev_read_byte)(ULONG_PTR ulRegister);
    u16 (*vdev_read_word)(ULONG_PTR ulRegister);
    u32 (*vdev_read_dword)(ULONG_PTR ulRegister);
    void (*vdev_write_byte)(ULONG_PTR ulRegister, u8 bValue);
    void (*vdev_write_word)(ULONG_PTR ulRegister, u16 wValue);
    void (*vdev_write_dword)(ULONG_PTR ulRegister, u32 ulValue);

    // memory management
    void *(*mem_alloc_contiguous_pages)(void *context, size_t size);
    void (*mem_free_contiguous_pages)(void *context, void *virt);
    ULONGLONG (*mem_get_physical_address)(void *context, void *virt);
    void *(*mem_alloc_nonpaged_block)(void *context, size_t size);
    void (*mem_free_nonpaged_block)(void *context, void *addr);

    // PCI config space access
    int (*pci_read_config_byte)(void *context, int where, u8 *bVal);
    int (*pci_read_config_word)(void *context, int where, u16 *wVal);
    int (*pci_read_config_dword)(void *context, int where, u32 *dwVal);

    // PCI resource handling
    size_t (*pci_get_resource_len)(void *context, int bar);
    void *(*pci_map_address_range)(void *context, int bar, size_t offset, size_t maxlen);

    // misc
    u16 (*vdev_get_msix_vector)(void *context, int queue);
    void (*vdev_sleep)(void *context, unsigned int msecs);
} VirtIOSystemOps;

struct virtio_device;
typedef struct virtio_device VirtIODevice;

struct virtio_device_ops
{
    // read/write device config and read config generation counter
    void (*get_config)(VirtIODevice *vdev, unsigned offset, void *buf, unsigned len);
    void (*set_config)(VirtIODevice *vdev, unsigned offset, const void *buf, unsigned len);
    u32 (*get_config_generation)(VirtIODevice *vdev);

    // read/write device status byte and reset the device
    u8 (*get_status)(VirtIODevice *vdev);
    void (*set_status)(VirtIODevice *vdev, u8 status);
    void (*reset)(VirtIODevice *vdev);

    // get/set device feature bits
    u64 (*get_features)(VirtIODevice *vdev);
    NTSTATUS (*set_features)(VirtIODevice *vdev, u64 features);

    // set config/queue MSI interrupt vector, returns the new vector
    u16 (*set_config_vector)(VirtIODevice *vdev, u16 vector);
    u16 (*set_queue_vector)(struct virtqueue *vq, u16 vector);

    // query virtual queue size and memory requirements
    NTSTATUS (*query_queue_alloc)(VirtIODevice *vdev,
        unsigned index, unsigned short *pNumEntries,
        unsigned long *pRingSize,
        unsigned long *pHeapSize);

    // allocate and initialize a queue
    NTSTATUS (*setup_queue)(struct virtqueue **queue,
        VirtIODevice *vdev, VirtIOQueueInfo *info,
        unsigned idx, u16 msix_vec);

    // tear down and deallocate a queue
    void (*delete_queue)(VirtIOQueueInfo *info);
};

struct virtio_device
{
    // the I/O port BAR of the PCI device (legacy virtio devices only)
    ULONG_PTR addr;

    // true if the device uses MSI interrupts
    bool msix_used;

    // true if the VIRTIO_RING_F_EVENT_IDX feature flag has been negotiated
    bool event_suppression_enabled;

    // true if the VIRTIO_F_RING_PACKED feature flag has been negotiated
    bool packed_ring;

    // internal device operations, implemented separately for legacy and modern
    const struct virtio_device_ops *device;

    // external callbacks implemented separately by different driver model drivers
    const struct virtio_system_ops *system;

    // opaque context value passed as first argument to virtio_system_ops callbacks
    void *DeviceContext;

    // the ISR status field, reading causes the device to de-assert an interrupt
    volatile u8 *isr;

    // modern virtio device capabilities and related state
    volatile struct virtio_pci_common_cfg *common;
    volatile unsigned char *config;
    volatile unsigned char *notify_base;
    int notify_map_cap;
    u32 notify_offset_multiplier;

    size_t config_len;
    size_t notify_len;

    // maximum number of virtqueues that fit in the memory block pointed to by info
    ULONG maxQueues;

    // points to inline_info if not more than MAX_QUEUES_PER_DEVICE_DEFAULT queues
    // are used, or to an external allocation otherwise
    VirtIOQueueInfo *info;
    VirtIOQueueInfo inline_info[MAX_QUEUES_PER_DEVICE_DEFAULT];
};

/* Driver API: device init and shutdown
 * DeviceContext is a driver defined opaque value which will be passed to driver
 * supplied callbacks described in pSystemOps. pSystemOps must be non-NULL and all
 * its fields must be non-NULL. msix_used is true if and only if the device is
 * configured with MSI support.
 */
NTSTATUS virtio_device_initialize(VirtIODevice *vdev,
                                  const VirtIOSystemOps *pSystemOps,
                                  void *DeviceContext,
                                  bool msix_used);
void virtio_device_shutdown(VirtIODevice *vdev);

/* Driver API: device status manipulation
 * virtio_set_status should not be called by new drivers. Device status should only
 * be getting its bits set with virtio_add_status and reset all back to 0 with
 * virtio_device_reset. virtio_device_ready is a special version of virtio_add_status
 * which adds the VIRTIO_CONFIG_S_DRIVER_OK status bit.
 */
u8 virtio_get_status(VirtIODevice *vdev);
void virtio_set_status(VirtIODevice *vdev, u8 status);
void virtio_add_status(VirtIODevice *vdev, u8 status);

void virtio_device_reset(VirtIODevice *vdev);
void virtio_device_ready(VirtIODevice *vdev);

/* Driver API: device feature bitmap manipulation
 * Features passed to virtio_set_features should be a subset of features offered by
 * the device as returned from virtio_get_features. virtio_set_features sets the
 * VIRTIO_CONFIG_S_FEATURES_OK status bit if it is supported by the device.
 */
#define virtio_is_feature_enabled(FeaturesList, Feature)  (!!((FeaturesList) & (1ULL << (Feature))))
#define virtio_feature_enable(FeaturesList, Feature)      ((FeaturesList) |= (1ULL << (Feature)))
#define virtio_feature_disable(FeaturesList, Feature)     ((FeaturesList) &= ~(1ULL << (Feature)))

u64 virtio_get_features(VirtIODevice *dev);
NTSTATUS virtio_set_features(VirtIODevice *vdev, u64 features);

/* Driver API: device configuration access
 * Both virtio_get_config and virtio_set_config support arbitrary values of the len
 * parameter. Config items of length 1, 2, and 4 are read/written using one access,
 * length 8 is broken down to two 4 bytes accesses, and any other length is read or
 * written byte by byte.
 */
void virtio_get_config(VirtIODevice *vdev, unsigned offset,
                       void *buf, unsigned len);
void virtio_set_config(VirtIODevice *vdev, unsigned offset,
                       void *buf, unsigned len);

/* Driver API: virtqueue setup
 * virtio_reserve_queue_memory makes VirtioLib reserve memory for its virtqueue
 * bookkeeping. Drivers should call this function if they intend to set up queues
 * one by one with virtio_find_queue. virtio_find_queues (plural) internally takes
 * care of the reservation and virtio_reserve_queue_memory need not be called.
 * Note that in addition to queue interrupt vectors, virtio_find_queues also sets
 * up the device config vector as a convenience.
 * Drivers should treat the returned struct virtqueue pointers as opaque handles.
 */
NTSTATUS virtio_query_queue_allocation(VirtIODevice *vdev, unsigned index,
                                       unsigned short *pNumEntries,
                                       unsigned long *pRingSize,
                                       unsigned long *pHeapSize);

NTSTATUS virtio_reserve_queue_memory(VirtIODevice *vdev, unsigned nvqs);

NTSTATUS virtio_find_queue(VirtIODevice *vdev, unsigned index,
                           struct virtqueue **vq);
NTSTATUS virtio_find_queues(VirtIODevice *vdev, unsigned nvqs,
                            struct virtqueue *vqs[]);

/* Driver API: virtqueue shutdown
 * The device must be reset and re-initialized to re-setup queues after they have
 * been deleted.
 */
void virtio_delete_queue(struct virtqueue *vq);
void virtio_delete_queues(VirtIODevice *vdev);

/* Driver API: virtqueue query and manipulation
 * virtio_get_queue_descriptor_size
 * is useful in situations where the driver has to prepare for the memory allocation
 * performed by virtio_reserve_queue_memory beforehand.
 */

u32 virtio_get_queue_size(struct virtqueue *vq);
unsigned long virtio_get_indirect_page_capacity();

ULONG __inline virtio_get_queue_descriptor_size()
{
    return sizeof(VirtIOQueueInfo);
}

/* Driver API: interrupt handling
 * virtio_set_config_vector and virtio_set_queue_vector set the MSI vector used for
 * device configuration interrupt and queue interrupt, respectively. The driver may
 * choose to either return the vector from the vdev_get_msix_vector callback (called
 * as part of queue setup) or call these functions later. Note that setting the vector
 * may fail which is indicated by the return value of VIRTIO_MSI_NO_VECTOR.
 * virtio_read_isr_status returns the value of the ISR status register, note that it
 * is not idempotent, calling the function makes the device de-assert the interrupt.
 */
u16 virtio_set_config_vector(VirtIODevice *vdev, u16 vector);
u16 virtio_set_queue_vector(struct virtqueue *vq, u16 vector);

u8 virtio_read_isr_status(VirtIODevice *vdev);

/* Driver API: miscellaneous helpers
 * virtio_get_bar_index returns the corresponding BAR index given its physical address.
 * This tends to be useful to all drivers since Windows doesn't provide reliable BAR
 * indices as part of resource enumeration. The function returns -1 on failure.
 */
int virtio_get_bar_index(PPCI_COMMON_HEADER pPCIHeader, PHYSICAL_ADDRESS BasePA);

#endif

redpajama_set_name: RedPajamaGithub


text:
/**
 * Alexa module that spawns a new AlexaBot in botkit. It also registers all handlers to create a valid Alexa
 * Response.
 *
 * @module lib/bot-alexa
 */

'use strict';

const debug = require('debug')('wchbotserver:bot-alexa');
const AlexaBot = require('./botkit/Alexa-Bot');
const path = require('path');
const MongoStorage = require('botkit-storage-mongo');

const AlexaMessageHandling = require('./skills/alexaMessageHandling');

/**
 * Initalization of the alexa controller
 * @param  {Object} middleware - The conversation service middleware
 * @return {Object}            The initalized controller and bot object
 */
module.exports = function ({app, wchcore, appSettings}) {
  const env = wchcore.getService('env');
  const {channels: {alexa: alexaSettings}, dbService} = appSettings;
  const dbCreds = env.getService('db_config');
  const alexaService = env.getService('alexa_config');
  const isDbCredsSet = dbCreds && dbCreds.credentials && dbCreds.credentials.mongoUri;

  // Init facebook
  return new Promise((resolve, reject) => {
    if (alexaSettings.enabled) {
      const botOptions = {appid: alexaService.credentials.appid, debug: alexaSettings.debug};

      if (dbService.enabled && isDbCredsSet) {
        botOptions.storage = MongoStorage({mongoUri: dbCreds.credentials.mongoUri});
      }
      else if (alexaSettings.fileStore !== false) {
        if (dbService.enabled && !isDbCredsSet) {
          debug('WARN: No db set. Fallback to file storage.');
        }
        botOptions.json_file_store = path.join(__dirname, '.data', 'db'); // eslint-disable-line camelcase
      }

      const controller = new AlexaBot(botOptions);
      AlexaMessageHandling(controller, {wchcore, appSettings});
      const bot = controller.spawn();
      app.use('/alexaendpoint', bot.router);
      debug('Alexa bot is live...');
    }
    return resolve(wchcore);
  });

}


text:
package commands

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/bmizerany/assert"
)

func TestInit(t *testing.T) {
	repo := NewRepository(t, "empty")
	defer repo.Test()

	repo.AddPath(repo.Path, ".git")
	repo.AddPath(repo.Path, "subdir")

	cmd := repo.Command("init")
	cmd.Output = "git lfs initialized"

	prePushHookFile := filepath.Join(repo.Path, ".git", "hooks", "pre-push")

	cmd.Before(func() {
		err := os.RemoveAll(filepath.Join(repo.Path, ".git", "hooks"))
		assert.Equal(t, nil, err)
	})

	cmd.After(func() {
		// assert filter config
		configs := GlobalGitConfig(t)
		AssertIncludeString(t, "filter.lfs.clean=git lfs clean %f", configs)
		AssertIncludeString(t, "filter.lfs.smudge=git lfs smudge %f", configs)
		AssertIncludeString(t, "filter.lfs.required=true", configs)
		found := 0
		for _, line := range configs {
			if strings.HasPrefix(line, "filter.lfs") {
				found += 1
			}
		}
		assert.Equal(t, 3, found)

		// assert hooks
		stat, err := os.Stat(prePushHookFile)
		assert.Equal(t, nil, err)
		assert.Equal(t, false, stat.IsDir())
	})

	cmd = repo.Command("init")
	cmd.Output = "Hook already exists: pre-push\n\necho 'yo'\n\ngit lfs initialized"

	customHook := []byte("echo 'yo'")
	cmd.Before(func() {
		err := ioutil.WriteFile(prePushHookFile, customHook, 0755)
		assert.Equal(t, nil, err)
	})

	cmd.After(func() {
		by, err := ioutil.ReadFile(prePushHookFile)
		assert.Equal(t, nil, err)
		assert.Equal(t, string(customHook), string(by))
	})
}


text:
#ifndef RUBY_RUBY_BACKWARD_H
#define RUBY_RUBY_BACKWARD_H 1

#define RClass RClassDeprecated
#ifndef __cplusplus
DEPRECATED_TYPE(("RClass is internal use only"),
struct RClass {
    struct RBasic basic;
});
#endif

#define DECLARE_DEPRECATED_FEATURE(ver, func) \
    NORETURN(ERRORFUNC(("deprecated since "#ver), DEPRECATED(void func(void))))

/* complex.c */
DECLARE_DEPRECATED_FEATURE(2.2, rb_complex_set_real);
DECLARE_DEPRECATED_FEATURE(2.2, rb_complex_set_imag);

/* eval.c */
DECLARE_DEPRECATED_FEATURE(2.2, rb_disable_super);
DECLARE_DEPRECATED_FEATURE(2.2, rb_enable_super);

/* hash.c */
DECLARE_DEPRECATED_FEATURE(2.2, rb_hash_iter_lev);
DECLARE_DEPRECATED_FEATURE(2.2, rb_hash_ifnone);

/* string.c */
DECLARE_DEPRECATED_FEATURE(2.2, rb_str_associate);
DECLARE_DEPRECATED_FEATURE(2.2, rb_str_associated);

/* variable.c */
DEPRECATED(void rb_autoload(VALUE, ID, const char*));

/* vm.c */
DECLARE_DEPRECATED_FEATURE(2.2, rb_clear_cache);
DECLARE_DEPRECATED_FEATURE(2.2, rb_frame_pop);

#define DECLARE_DEPRECATED_INTERNAL_FEATURE(func) \
    NORETURN(ERRORFUNC(("deprecated internal function"), DEPRECATED(void func(void))))

/* error.c */
DECLARE_DEPRECATED_INTERNAL_FEATURE(rb_compile_error);
DECLARE_DEPRECATED_INTERNAL_FEATURE(rb_compile_error_with_enc);
DECLARE_DEPRECATED_INTERNAL_FEATURE(rb_compile_error_append);

/* struct.c */
DECLARE_DEPRECATED_INTERNAL_FEATURE(rb_struct_ptr);

/* variable.c */
DECLARE_DEPRECATED_INTERNAL_FEATURE(rb_generic_ivar_table);

/* vm.c */
DEPRECATED(int rb_frame_method_id_and_class(ID *idp, VALUE *klassp));

/* from version.c */
#ifndef RUBY_SHOW_COPYRIGHT_TO_DIE
# define RUBY_SHOW_COPYRIGHT_TO_DIE 1
#endif
#if RUBY_SHOW_COPYRIGHT_TO_DIE
/* for source code backward compatibility */
DEPRECATED(static inline int ruby_show_copyright_to_die(int));
static inline int
ruby_show_copyright_to_die(int exitcode)
{
    ruby_show_copyright();
    return exitcode;
}
#define ruby_show_copyright() /* defer EXIT_SUCCESS */ \
    (exit(ruby_show_copyright_to_die(EXIT_SUCCESS)))
#endif

#endif /* RUBY_RUBY_BACKWARD_H */


text:
<?php

function altertBoxSuccess(){
?>
<?php if (isset($_GET["alertMessage"])): ?>

<div data-alert class="alert-box <?php echo $_GET["alertMessageType"] ?> radius">
  <?php echo $_GET["alertMessage"] ?>
  ×

<?php endif ?>

<?php
}

add_action('foundationpress_before_content', 'altertBoxSuccess');


text:
DOA Utilities
=============

.. automodule:: pyroomacoustics.doa.utils
    :members:
    :undoc-members:
    :show-inheritance:


text:
using namespace std;

#if defined(_WIN32) || defined(_WIN64)
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) {
#endif
#ifdef __unix__
int main (int argc, char *argv[]){
#endif
    Game *game = new Game();
    game->newGame();
    delete game;
    return 0;
}


text:
<!DOCTYPE html>
<title>Test media element networkState value in an error corner case.</title>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<video></video>
<script>
async_test(function(t) {
    var video = document.querySelector("video");
    assert_equals(video.readyState, HTMLMediaElement.HAVE_NOTHING);
    video.onended = t.unreached_func();
    video.onerror = t.step_func(() => {
      assert_equals(video.readyState, HTMLMediaElement.HAVE_ENOUGH_DATA);
      assert_equals(video.networkState, HTMLMediaElement.NETWORK_IDLE);

      var source = document.createElement("source");
      video.removeAttribute("src");
      video.appendChild(source);  // Schedules load timer.
      video.removeChild(source);  // Good luck with that load.
      window.setTimeout(t.step_func_done(() => {
        // If we wait before removing the child, we will get HAVE_ENOUGH_DATA,
        // and NETWORK_NO_SOURCE. It's not really clear if that's correct, nor
        // is it clear whether removing the child immediately should change the
        // result. In any case, the load algorithm handles NETWORK_EMPTY as a
        // special case. For now we'll just test that we don't trigger that.
        assert_true(video.readyState != HTMLMediaElement.HAVE_ENOUGH_DATA ||
                    video.networkState != HTMLMediaElement.NETWORK_EMPTY);
      }), 0);
    });

    video.src = "content/corrupt.ogv";
    video.play();
});
</script>


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using grpc = global::Grpc.Core;

namespace HOLMS.Types.CRM.RPC {
  public static partial class GuestHistorySvc
  {
    static readonly string __ServiceName = "holms.types.crm.rpc.GuestHistorySvc";

    static readonly grpc::Marshaller<global::HOLMS.Types.CRM.Guests.GuestIndicator> __Marshaller_GuestIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.CRM.Guests.GuestIndicator.Parser.ParseFrom);
    static readonly grpc::Marshaller<global::HOLMS.Types.CRM.Guests.GuestHistorySummary> __Marshaller_GuestHistorySummary = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.CRM.Guests.GuestHistorySummary.Parser.ParseFrom);

    static readonly grpc::Method<global::HOLMS.Types.CRM.Guests.GuestIndicator, global::HOLMS.Types.CRM.Guests.GuestHistorySummary> __Method_GetGuestHistory = new grpc::Method<global::HOLMS.Types.CRM.Guests.GuestIndicator, global::HOLMS.Types.CRM.Guests.GuestHistorySummary>(
        grpc::MethodType.Unary,
        __ServiceName,
        "GetGuestHistory",
        __Marshaller_GuestIndicator,
        __Marshaller_GuestHistorySummary);

    /// Service descriptor
    public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
    {
      get { return global::HOLMS.Types.CRM.RPC.GuestHistorySvcReflection.Descriptor.Services[0]; }
    }

    /// Base class for server-side implementations of GuestHistorySvc
    public abstract partial class GuestHistorySvcBase
    {
      public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.CRM.Guests.GuestHistorySummary> GetGuestHistory(global::HOLMS.Types.CRM.Guests.GuestIndicator request, grpc::ServerCallContext context)
      {
        throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
      }

    }

    /// Client for GuestHistorySvc
    public partial class GuestHistorySvcClient : grpc::ClientBase<GuestHistorySvcClient>
    {
      /// Creates a new client for GuestHistorySvc
      /// <param name="channel">The channel to use to make remote calls.</param>
      public GuestHistorySvcClient(grpc::Channel channel) : base(channel)
      {
      }
      /// Creates a new client for GuestHistorySvc that uses a custom <c>CallInvoker</c>.
      /// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
      public GuestHistorySvcClient(grpc::CallInvoker callInvoker) : base(callInvoker)
      {
      }
      /// Protected parameterless constructor to allow creation of test doubles.
      protected GuestHistorySvcClient() : base()
      {
      }
      /// Protected constructor to allow creation of configured clients.
      /// <param name="configuration">The client configuration.</param>
      protected GuestHistorySvcClient(ClientBaseConfiguration configuration) : base(configuration)
      {
      }

      public virtual global::HOLMS.Types.CRM.Guests.GuestHistorySummary GetGuestHistory(global::HOLMS.Types.CRM.Guests.GuestIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
      {
        return GetGuestHistory(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      public virtual global::HOLMS.Types.CRM.Guests.GuestHistorySummary GetGuestHistory(global::HOLMS.Types.CRM.Guests.GuestIndicator request, grpc::CallOptions options)
      {
        return CallInvoker.BlockingUnaryCall(__Method_GetGuestHistory, null, options, request);
      }
      public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.Guests.GuestHistorySummary> GetGuestHistoryAsync(global::HOLMS.Types.CRM.Guests.GuestIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
      {
        return GetGuestHistoryAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
      }
      public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.CRM.Guests.GuestHistorySummary> GetGuestHistoryAsync(global::HOLMS.Types.CRM.Guests.GuestIndicator request, grpc::CallOptions options)
      {
        return CallInvoker.AsyncUnaryCall(__Method_GetGuestHistory, null, options, request);
      }
      /// Creates a new instance of client from given <c>ClientBaseConfiguration</c>.
      protected override GuestHistorySvcClient NewInstance(ClientBaseConfiguration configuration)
      {
        return new GuestHistorySvcClient(configuration);
      }
    }

    /// Creates service definition that can be registered with a server
    /// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
    public static grpc::ServerServiceDefinition BindService(GuestHistorySvcBase serviceImpl)
    {
      return grpc::ServerServiceDefinition.CreateBuilder()
          .AddMethod(__Method_GetGuestHistory, serviceImpl.GetGuestHistory).Build();
    }

  }
}
#endregion


text:
// .NAME vtkPUnstructuredGridConnectivity.h -- Unstructured grid connectivity.
//
// .SECTION Description
//  vtkPUnstructuredGridConnectivity implements functionality for generating
//  ghost zones for a distributed unstructured grid. Generating ghost zones is
//  implemented in two stages. First, we build the ghost zones, which amounts
//  to building the connectivity of the ghosted grid and communication links,
//  and second, we update the ghost zones by communicating the fields on the
//  ghost cells and nodes. The main steps involved in this process are as
//  follows:
//

//
 Each process computes a bounding box of the grid it owns.

//
 The bounding boxes are then distributed to all processes by
//         an AllGather collective call.

//
 Each process loops through the list of bounding boxes and
//         computes box intersections with its local bounding box.

//
 The list of intersecting bounding boxes, yields an abbreviated list
//         of candidate neighbors.

//
 Given the local grid, each process then extracts the boundary grid,
//         which consists of nodes/cells on the boundary, global node IDs and
//         the local cell IDs w.r.t. the local grid.

//
 Boundary grids are then exchanged among candidate neighbors using
//         point-to-point communication.

//
 Next, each process constructs the topology of the ghost zones and
//         communication links, using the local boundary grid and the list of
//         remote boundary grids.

//
 The communication links store a source/target pair for nodes/cells
//         among connected grids and remain persistent in memory.

//
 Last, the fields (node- and/or cell-centered) are updated, using
//         point-to-point communication by processing the communication
//         links.

//

// @deprecated Not maintained as of VTK 7.0 and will be removed eventually.
// Use vtkPUnstructuredGridGhostCellsGenerator instead.
//
// .SECTION Caveats
//

//
 The code currently assumes one grid per rank.

//
 GlobalID information must be available.

//
 The grid must be globally conforming, i.e., no hanging nodes.

//
 Only topologically face-adjacent ghost cells are considered.

//
 PointData and CellData must match across partitions/processes.

//

//
// .SECTION See Also
//  vtkPUnstructuredGridGhostDataGenerator vtkPUnstructuredGridGhostCellsGenerator

#ifndef vtkPUnstructuredGridConnectivity_h
#define vtkPUnstructuredGridConnectivity_h

#include "vtkFiltersParallelGeometryModule.h" // For export macro
#include "vtkObject.h"

#if !defined(VTK_LEGACY_REMOVE)

// Forward Declarations
class vtkCell;
class vtkCellData;
class vtkIdList;
class vtkIdTypeArray;
class vtkMPIController;
class vtkMultiProcessStream;
class vtkPointData;
class vtkPoints;
class vtkUnstructuredGrid;

// Forward Declaration of internal data-structures
namespace vtk
{
namespace details
{

struct GridInfo;
struct MeshLinks;
struct CommunicationLinks;

} // END namespace details
} // END namespace vkt

class VTKFILTERSPARALLELGEOMETRY_EXPORT vtkPUnstructuredGridConnectivity :
  public vtkObject
{
public:
  static vtkPUnstructuredGridConnectivity* New();
  vtkTypeMacro(vtkPUnstructuredGridConnectivity,vtkObject);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Set/Get the underlying MPI controller used for communication.
  vtkSetMacro(Controller,vtkMPIController*);
  vtkGetMacro(Controller,vtkMPIController*);

  // Description:
  // Set/Get the name of the GlobalID field. By default, "GlobalID" is assumed.
  vtkSetStringMacro(GlobalIDFieldName);
  vtkGetStringMacro(GlobalIDFieldName);

  // Description:
  // Returns the ghosted grid.
  vtkGetMacro(GhostedGrid,vtkUnstructuredGrid*);

  // Description:
  // Registers the grid in this process
  void RegisterGrid(vtkUnstructuredGrid* gridPtr);

  // Description:
  // Builds the ghost-zone connectivity. This method sets up the necessary
  // communication lists for updating the ghost zones.
  // NOTE: the local grid, must be registered, by calling RegisterGrid(),
  // prior to calling this method.
  void BuildGhostZoneConnectivity();

  // Description:
  // Exchanges ghost zone data (i.e., node-centered or cell-centered fields).
  // NOTE: This method must be called after BuildGhostZoneConnectivity.
  void UpdateGhosts();

protected:
  vtkPUnstructuredGridConnectivity();
  virtual ~vtkPUnstructuredGridConnectivity();

  char* GlobalIDFieldName;            // The field of the global IDs.
  vtkUnstructuredGrid* InputGrid;     // The input grid, to be ghosted.
  vtkUnstructuredGrid* GhostedGrid;   // This is the output from this class.
  vtkMPIController* Controller;       // Supplied MPI controller.

// BTX
  vtk::details::GridInfo* AuxiliaryData; // Data used to build the ghost zones.
  vtk::details::CommunicationLinks* CommLists; // Persistent comm lists.
// ETX

  // Description:
  // Given the deserialized cell-centered ghost data from the given neighboring
  // rank, this method fills in the cell-centered fields of the ghost zone.
  void FillGhostZoneCells(
        const int neiRank,
        vtkCellData* ghostData,
        vtkIdType* cellIdx,
        const unsigned int numGhostCells);

  // Description:
  // Given the deserialized node-centered ghost data from the given neighboring
  // rank, this method fills in the node-centered fields of the ghost zone.
  void FillGhostZoneNodes(
        const int neiRank,
        vtkPointData* ghostData,
        vtkIdType* globalIdx,
        const unsigned int numGhostNodes);

  // Description:
  // Deserializes the raw buffers received from each neighboring rank and
  // updates the ghosted grid instance by filling in the values for the
  // ghost zones.
  void DeSerializeGhostZones();

  // Description:
  // This method exchanges the buffer sizes among neighboring processes and
  // allocates a persistent buffer for the communication. This exchange and
  // memory allocation happens only the first time the data is exchanged
  void CreatePersistentRcvBuffers();

  // Description:
  // This method serializes the local data (node-centered and/or cell-centered)
  // for each rank that this process/grid communicates with.
  void SerializeGhostZones();

  // Description:
  // Synchs the data on the input grid in this process to the ghosted grid
  // instance.
  void SynchLocalData();

  // Description:
  // Loops through the nodes of the ghost cell and the local adjacent cell
  // and determines what
  void EnqueueNodeLinks(
        const int rmtRank,
        const vtkIdType ghostCell,
        const vtkIdType adjCell,
        vtkIdList* shared);

  // Description:
  // Given the cell, c, this method checks if it is connected to the grid
  // assigned to this process. The method will return -1, if the cell is
  // not connected. If the cell is connected, adjCell will hold the cell
  // index of the cell w.r.t. the input grid that the ghost cell is
  // face-adjacent to as well as the shared global Ids of the face between
  // the ghost and the face-adjacent, boundary cell.
  bool IsCellConnected(
      vtkCell* c,vtkIdType* globalId, const vtkIdType N,
      vtkIdType& adjCell,
      vtkIdList* sharedIds);

  // Description:
  // Inserts the ghost cell nodes in to the ghosted instance of the grid.
  void InsertGhostCellNodes(
        vtkCell* ghostCell,
        vtkIdTypeArray* ghostGridGlobalIdx,
        vtkIdType* globalIdArray,
        vtkUnstructuredGrid* bGrid,
        vtkIdType* cellPts);

  // Description:
  // Process the remote boundary grid and injects cells in to the ghosted
  // grid if a match is found.
  void ProcessRemoteGrid(
      const int rmtRank,vtkUnstructuredGrid* bGrid);

  // Description:
  // Builds the ghosted grid and communication lists
  void BuildGhostedGridAndCommLists();

  // Description:
  // Serializes the unstructured grid into a bytestream.
  void SerializeUnstructuredGrid(
      vtkUnstructuredGrid* g, vtkMultiProcessStream& bytestream);

  // Description:
  // De-serializes the unstructured grid from the given bytestream.
  void DeSerializeUnstructuredGrid(
      vtkUnstructuredGrid* g, vtkMultiProcessStream& bytestream);

  // Description:
  // Writes the given unstructured grid to an ASCII file.
  // NOTE: Used for debugging.
  void WriteUnstructuredGrid(vtkUnstructuredGrid* grid, const char* fileName);

  // Description:
  // Loops through the auxiliary FaceList, constructed in MarkFaces, and
  // extracts the faces and nodes on the boundary.
  void ExtractSurfaceMesh();

  // Description:
  // Loops through the input grid cell faces and updates the auxiliary
  // data-structures to associates a count with each face.
  void MarkFaces();

  // Description:
  // Extracts the boundary cell from the input grid and inserts it in to
  // the boundary grid.
  void ExtractBoundaryCell(
      const vtkIdType cellIdx,
      const vtkIdType numCellNodes,
      vtkIdType* cellNodes,
      vtkPoints* nodes,
      vtkIdTypeArray* localIdx,
      vtkIdTypeArray* globaIdx
      );

  // Description:
  // Checks if the cell, composed by the supplied nodes, is on the boundary.
  // A cell is on the boundary iff any of its nodes touch the boundary.
  bool IsCellOnBoundary(vtkIdType* cellNodes, vtkIdType N);

  // Description:
  // Exchanged the boundary grids among candidate ranks.
  void ExchangeBoundaryGrids();

  // Description:
  // Exchange boundary grid sizes
  void ExchangeBoundaryGridSizes(int size);

  // Description:
  // Collides the bounds of this process with the bounding boxes of all
  // other processes. The processes whose bounding boxes intersect yield
  // the list of candidate ranks with which boundary grids will be exchanged.
  void BoundingBoxCollision();

  // Description:
  // Exchanges the grid bounds of this process with all other processes.
  // Upon completion, each process will have the global grid bounds of
  // every process.
  void ExchangeGridBounds();

  // Description:
  // Extracts the boundary grid geometry from the input grid.
  // Note: this method only extract the mesh and global/local ID information.
  void ExtractBoundaryGrid();

private:
  vtkPUnstructuredGridConnectivity(const vtkPUnstructuredGridConnectivity&); // Not implemented
  void operator=(const vtkPUnstructuredGridConnectivity&); // Not implemented
};

#endif //VTK_LEGACY_REMOVE
#endif /* vtkPUnstructuredGridConnectivity_h */


text:
<?php
namespace GuzzleHttp\Tests;

use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Uri;
use Psr\Http\Message\ResponseInterface;

class ClientTest extends \PHPUnit_Framework_TestCase
{
    public function testUsesDefaultHandler()
    {
        $client = new Client();
        Server::enqueue([new Response(200, ['Content-Length' => 0])]);
        $response = $client->get(Server::$url);
        $this->assertEquals(200, $response->getStatusCode());
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Magic request methods require a URI and optional options array
     */
    public function testValidatesArgsForMagicMethods()
    {
        $client = new Client();
        $client->get();
    }

    public function testCanSendMagicAsyncRequests()
    {
        $client = new Client();
        Server::flush();
        Server::enqueue([new Response(200, ['Content-Length' => 2], 'hi')]);
        $p = $client->getAsync(Server::$url, ['query' => ['test' => 'foo']]);
        $this->assertInstanceOf(PromiseInterface::class, $p);
        $this->assertEquals(200, $p->wait()->getStatusCode());
        $received = Server::received(true);
        $this->assertCount(1, $received);
        $this->assertEquals('test=foo', $received[0]->getUri()->getQuery());
    }

    public function testCanSendSynchronously()
    {
        $client = new Client(['handler' => new MockHandler([new Response()])]);
        $request = new Request('GET', 'http://example.com');
        $r = $client->send($request);
        $this->assertInstanceOf(ResponseInterface::class, $r);
        $this->assertEquals(200, $r->getStatusCode());
    }

    public function testClientHasOptions()
    {
        $client = new Client([
            'base_uri' => 'http://foo.com',
            'timeout'  => 2,
            'headers'  => ['bar' => 'baz'],
            'handler'  => new MockHandler()
        ]);
        $base = $client->getConfig('base_uri');
        $this->assertEquals('http://foo.com', (string) $base);
        $this->assertInstanceOf(Uri::class, $base);
        $this->assertNotNull($client->getConfig('handler'));
        $this->assertEquals(2, $client->getConfig('timeout'));
        $this->assertArrayHasKey('timeout', $client->getConfig());
        $this->assertArrayHasKey('headers', $client->getConfig());
    }

    public function testCanMergeOnBaseUri()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client([
            'base_uri' => 'http://foo.com/bar/',
            'handler'  => $mock
        ]);
        $client->get('baz');
        $this->assertEquals(
            'http://foo.com/bar/baz',
            $mock->getLastRequest()->getUri()
        );
    }

    public function testCanMergeOnBaseUriWithRequest()
    {
        $mock = new MockHandler([new Response(), new Response()]);
        $client = new Client([
            'handler'  => $mock,
            'base_uri' => 'http://foo.com/bar/'
        ]);
        $client->request('GET', new Uri('baz'));
        $this->assertEquals(
            'http://foo.com/bar/baz',
            (string) $mock->getLastRequest()->getUri()
        );

        $client->request('GET', new Uri('baz'), ['base_uri' => 'http://example.com/foo/']);
        $this->assertEquals(
            'http://example.com/foo/baz',
            (string) $mock->getLastRequest()->getUri(),
            'Can overwrite the base_uri through the request options'
        );
    }

    public function testCanUseRelativeUriWithSend()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client([
            'handler'  => $mock,
            'base_uri' => 'http://bar.com'
        ]);
        $this->assertEquals('http://bar.com', (string) $client->getConfig('base_uri'));
        $request = new Request('GET', '/baz');
        $client->send($request);
        $this->assertEquals(
            'http://bar.com/baz',
            (string) $mock->getLastRequest()->getUri()
        );
    }

    public function testMergesDefaultOptionsAndDoesNotOverwriteUa()
    {
        $c = new Client(['headers' => ['User-agent' => 'foo']]);
        $this->assertEquals(['User-agent' => 'foo'], $c->getConfig('headers'));
        $this->assertInternalType('array', $c->getConfig('allow_redirects'));
        $this->assertTrue($c->getConfig('http_errors'));
        $this->assertTrue($c->getConfig('decode_content'));
        $this->assertTrue($c->getConfig('verify'));
    }

    public function testDoesNotOverwriteHeaderWithDefault()
    {
        $mock = new MockHandler([new Response()]);
        $c = new Client([
            'headers' => ['User-agent' => 'foo'],
            'handler' => $mock
        ]);
        $c->get('http://example.com', ['headers' => ['User-Agent' => 'bar']]);
        $this->assertEquals('bar', $mock->getLastRequest()->getHeaderLine('User-Agent'));
    }

    public function testDoesNotOverwriteHeaderWithDefaultInRequest()
    {
        $mock = new MockHandler([new Response()]);
        $c = new Client([
            'headers' => ['User-agent' => 'foo'],
            'handler' => $mock
        ]);
        $request = new Request('GET', Server::$url, ['User-Agent' => 'bar']);
        $c->send($request);
        $this->assertEquals('bar', $mock->getLastRequest()->getHeaderLine('User-Agent'));
    }

    public function testDoesOverwriteHeaderWithSetRequestOption()
    {
        $mock = new MockHandler([new Response()]);
        $c = new Client([
            'headers' => ['User-agent' => 'foo'],
            'handler' => $mock
        ]);
        $request = new Request('GET', Server::$url, ['User-Agent' => 'bar']);
        $c->send($request, ['headers' => ['User-Agent' => 'YO']]);
        $this->assertEquals('YO', $mock->getLastRequest()->getHeaderLine('User-Agent'));
    }

    public function testCanUnsetRequestOptionWithNull()
    {
        $mock = new MockHandler([new Response()]);
        $c = new Client([
            'headers' => ['foo' => 'bar'],
            'handler' => $mock
        ]);
        $c->get('http://example.com', ['headers' => null]);
        $this->assertFalse($mock->getLastRequest()->hasHeader('foo'));
    }

    public function testRewriteExceptionsToHttpErrors()
    {
        $client = new Client(['handler' => new MockHandler([new Response(404)])]);
        $res = $client->get('http://foo.com', ['exceptions' => false]);
        $this->assertEquals(404, $res->getStatusCode());
    }

    public function testRewriteSaveToToSink()
    {
        $r = Psr7\stream_for(fopen('php://temp', 'r+'));
        $mock = new MockHandler([new Response(200, [], 'foo')]);
        $client = new Client(['handler' => $mock]);
        $client->get('http://foo.com', ['save_to' => $r]);
        $this->assertSame($r, $mock->getLastOptions()['sink']);
    }

    public function testAllowRedirectsCanBeTrue()
    {
        $mock = new MockHandler([new Response(200, [], 'foo')]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);
        $client->get('http://foo.com', ['allow_redirects' => true]);
        $this->assertInternalType('array',  $mock->getLastOptions()['allow_redirects']);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage allow_redirects must be true, false, or array
     */
    public function testValidatesAllowRedirects()
    {
        $mock = new MockHandler([new Response(200, [], 'foo')]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);
        $client->get('http://foo.com', ['allow_redirects' => 'foo']);
    }

    /**
     * @expectedException \GuzzleHttp\Exception\ClientException
     */
    public function testThrowsHttpErrorsByDefault()
    {
        $mock = new MockHandler([new Response(404)]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);
        $client->get('http://foo.com');
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface
     */
    public function testValidatesCookies()
    {
        $mock = new MockHandler([new Response(200, [], 'foo')]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);
        $client->get('http://foo.com', ['cookies' => 'foo']);
    }

    public function testSetCookieToTrueUsesSharedJar()
    {
        $mock = new MockHandler([
            new Response(200, ['Set-Cookie' => 'foo=bar']),
            new Response()
        ]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler, 'cookies' => true]);
        $client->get('http://foo.com');
        $client->get('http://foo.com');
        $this->assertEquals('foo=bar', $mock->getLastRequest()->getHeaderLine('Cookie'));
    }

    public function testSetCookieToJar()
    {
        $mock = new MockHandler([
            new Response(200, ['Set-Cookie' => 'foo=bar']),
            new Response()
        ]);
        $handler = HandlerStack::create($mock);
        $client = new Client(['handler' => $handler]);
        $jar = new CookieJar();
        $client->get('http://foo.com', ['cookies' => $jar]);
        $client->get('http://foo.com', ['cookies' => $jar]);
        $this->assertEquals('foo=bar', $mock->getLastRequest()->getHeaderLine('Cookie'));
    }

    public function testCanDisableContentDecoding()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->get('http://foo.com', ['decode_content' => false]);
        $last = $mock->getLastRequest();
        $this->assertFalse($last->hasHeader('Accept-Encoding'));
        $this->assertFalse($mock->getLastOptions()['decode_content']);
    }

    public function testCanSetContentDecodingToValue()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->get('http://foo.com', ['decode_content' => 'gzip']);
        $last = $mock->getLastRequest();
        $this->assertEquals('gzip', $last->getHeaderLine('Accept-Encoding'));
        $this->assertEquals('gzip', $mock->getLastOptions()['decode_content']);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testValidatesHeaders()
    {
        $mock = new MockHandler();
        $client = new Client(['handler' => $mock]);
        $client->get('http://foo.com', ['headers' => 'foo']);
    }

    public function testAddsBody()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $request = new Request('PUT', 'http://foo.com');
        $client->send($request, ['body' => 'foo']);
        $last = $mock->getLastRequest();
        $this->assertEquals('foo', (string) $last->getBody());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testValidatesQuery()
    {
        $mock = new MockHandler();
        $client = new Client(['handler' => $mock]);
        $request = new Request('PUT', 'http://foo.com');
        $client->send($request, ['query' => false]);
    }

    public function testQueryCanBeString()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $request = new Request('PUT', 'http://foo.com');
        $client->send($request, ['query' => 'foo']);
        $this->assertEquals('foo', $mock->getLastRequest()->getUri()->getQuery());
    }

    public function testQueryCanBeArray()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $request = new Request('PUT', 'http://foo.com');
        $client->send($request, ['query' => ['foo' => 'bar baz']]);
        $this->assertEquals('foo=bar%20baz', $mock->getLastRequest()->getUri()->getQuery());
    }

    public function testCanAddJsonData()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $request = new Request('PUT', 'http://foo.com');
        $client->send($request, ['json' => ['foo' => 'bar']]);
        $last = $mock->getLastRequest();
        $this->assertEquals('{"foo":"bar"}', (string) $mock->getLastRequest()->getBody());
        $this->assertEquals('application/json', $last->getHeaderLine('Content-Type'));
    }

    public function testCanAddJsonDataWithoutOverwritingContentType()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $request = new Request('PUT', 'http://foo.com');
        $client->send($request, [
            'headers' => ['content-type' => 'foo'],
            'json'    => 'a'
        ]);
        $last = $mock->getLastRequest();
        $this->assertEquals('"a"', (string) $mock->getLastRequest()->getBody());
        $this->assertEquals('foo', $last->getHeaderLine('Content-Type'));
    }

    public function testAuthCanBeTrue()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->get('http://foo.com', ['auth' => false]);
        $last = $mock->getLastRequest();
        $this->assertFalse($last->hasHeader('Authorization'));
    }

    public function testAuthCanBeArrayForBasicAuth()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->get('http://foo.com', ['auth' => ['a', 'b']]);
        $last = $mock->getLastRequest();
        $this->assertEquals('Basic YTpi', $last->getHeaderLine('Authorization'));
    }

    public function testAuthCanBeArrayForDigestAuth()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->get('http://foo.com', ['auth' => ['a', 'b', 'digest']]);
        $last = $mock->getLastOptions();
        $this->assertEquals([
            CURLOPT_HTTPAUTH => 2,
            CURLOPT_USERPWD  => 'a:b'
        ], $last['curl']);
    }

    public function testAuthCanBeCustomType()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->get('http://foo.com', ['auth' => 'foo']);
        $last = $mock->getLastOptions();
        $this->assertEquals('foo', $last['auth']);
    }

    public function testCanAddFormParams()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->post('http://foo.com', [
            'form_params' => [
                'foo' => 'bar bam',
                'baz' => ['boo' => 'qux']
            ]
        ]);
        $last = $mock->getLastRequest();
        $this->assertEquals(
            'application/x-www-form-urlencoded',
            $last->getHeaderLine('Content-Type')
        );
        $this->assertEquals(
            'foo=bar+bam&baz%5Bboo%5D=qux',
            (string) $last->getBody()
        );
    }

    public function testFormParamsEncodedProperly()
    {
        $separator = ini_get('arg_separator.output');
        ini_set('arg_separator.output', '&');
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->post('http://foo.com', [
            'form_params' => [
                'foo' => 'bar bam',
                'baz' => ['boo' => 'qux']
            ]
        ]);
        $last = $mock->getLastRequest();
        $this->assertEquals(
            'foo=bar+bam&baz%5Bboo%5D=qux',
            (string) $last->getBody()
        );

        ini_set('arg_separator.output', $separator);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testEnsuresThatFormParamsAndMultipartAreExclusive()
    {
        $client = new Client(['handler' => function () {}]);
        $client->post('http://foo.com', [
            'form_params' => ['foo' => 'bar bam'],
            'multipart' => []
        ]);
    }

    public function testCanSendMultipart()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->post('http://foo.com', [
            'multipart' => [
                [
                    'name'     => 'foo',
                    'contents' => 'bar'
                ],
                [
                    'name'     => 'test',
                    'contents' => fopen(__FILE__, 'r')
                ]
            ]
        ]);

        $last = $mock->getLastRequest();
        $this->assertContains(
            'multipart/form-data; boundary=',
            $last->getHeaderLine('Content-Type')
        );

        $this->assertContains(
            'Content-Disposition: form-data; name="foo"',
            (string) $last->getBody()
        );

        $this->assertContains('bar', (string) $last->getBody());
        $this->assertContains(
            'Content-Disposition: form-data; name="foo"' . "\r\n",
            (string) $last->getBody()
        );
        $this->assertContains(
            'Content-Disposition: form-data; name="test"; filename="ClientTest.php"',
            (string) $last->getBody()
        );
    }

    public function testCanSendMultipartWithExplicitBody()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->send(
            new Request(
                'POST',
                'http://foo.com',
                [],
                new Psr7\MultipartStream(
                    [
                        [
                            'name' => 'foo',
                            'contents' => 'bar',
                        ],
                        [
                            'name' => 'test',
                            'contents' => fopen(__FILE__, 'r'),
                        ],
                    ]
                )
            )
        );

        $last = $mock->getLastRequest();
        $this->assertContains(
            'multipart/form-data; boundary=',
            $last->getHeaderLine('Content-Type')
        );

        $this->assertContains(
            'Content-Disposition: form-data; name="foo"',
            (string) $last->getBody()
        );

        $this->assertContains('bar', (string) $last->getBody());
        $this->assertContains(
            'Content-Disposition: form-data; name="foo"' . "\r\n",
            (string) $last->getBody()
        );
        $this->assertContains(
            'Content-Disposition: form-data; name="test"; filename="ClientTest.php"',
            (string) $last->getBody()
        );
    }

    public function testUsesProxyEnvironmentVariables()
    {
        $http = getenv('HTTP_PROXY');
        $https = getenv('HTTPS_PROXY');
        $no = getenv('NO_PROXY');
        $client = new Client();
        $this->assertNull($client->getConfig('proxy'));
        putenv('HTTP_PROXY=127.0.0.1');
        $client = new Client();
        $this->assertEquals(
            ['http' => '127.0.0.1'],
            $client->getConfig('proxy')
        );
        putenv('HTTPS_PROXY=127.0.0.2');
        putenv('NO_PROXY=127.0.0.3, 127.0.0.4');
        $client = new Client();
        $this->assertEquals(
            ['http' => '127.0.0.1', 'https' => '127.0.0.2', 'no' => ['127.0.0.3','127.0.0.4']],
            $client->getConfig('proxy')
        );
        putenv("HTTP_PROXY=$http");
        putenv("HTTPS_PROXY=$https");
        putenv("NO_PROXY=$no");
    }

    public function testRequestSendsWithSync()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->request('GET', 'http://foo.com');
        $this->assertTrue($mock->getLastOptions()['synchronous']);
    }

    public function testSendSendsWithSync()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $client->send(new Request('GET', 'http://foo.com'));
        $this->assertTrue($mock->getLastOptions()['synchronous']);
    }

    public function testCanSetCustomHandler()
    {
        $mock = new MockHandler([new Response(500)]);
        $client = new Client(['handler' => $mock]);
        $mock2 = new MockHandler([new Response(200)]);
        $this->assertEquals(
            200,
            $client->send(new Request('GET', 'http://foo.com'), [
                'handler' => $mock2
            ])->getStatusCode()
        );
    }

    public function testProperlyBuildsQuery()
    {
        $mock = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mock]);
        $request = new Request('PUT', 'http://foo.com');
        $client->send($request, ['query' => ['foo' => 'bar', 'john' => 'doe']]);
        $this->assertEquals('foo=bar&john=doe', $mock->getLastRequest()->getUri()->getQuery());
    }

    public function testSendSendsWithIpAddressAndPortAndHostHeaderInRequestTheHostShouldBePreserved()
    {
        $mockHandler = new MockHandler([new Response()]);
        $client = new Client(['base_uri' => 'http://127.0.0.1:8585', 'handler' => $mockHandler]);
        $request = new Request('GET', '/test', ['Host'=>'foo.com']);

        $client->send($request);

        $this->assertEquals('foo.com', $mockHandler->getLastRequest()->getHeader('Host')[0]);
    }

    public function testSendSendsWithDomainAndHostHeaderInRequestTheHostShouldBePreserved()
    {
        $mockHandler = new MockHandler([new Response()]);
        $client = new Client(['base_uri' => 'http://foo2.com', 'handler' => $mockHandler]);
        $request = new Request('GET', '/test', ['Host'=>'foo.com']);

        $client->send($request);

        $this->assertEquals('foo.com', $mockHandler->getLastRequest()->getHeader('Host')[0]);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testValidatesSink()
    {
        $mockHandler = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mockHandler]);
        $client->get('http://test.com', ['sink' => true]);
    }

    public function testHttpDefaultSchemeIfUriHasNone()
    {
        $mockHandler = new MockHandler([new Response()]);
        $client = new Client(['handler' => $mockHandler]);

        $client->request('GET', '//example.org/test');

        $this->assertSame('http://example.org/test', (string) $mockHandler->getLastRequest()->getUri());
    }
}


text:
@interface DetailViewController : UIViewController
@property (copy, nonatomic) NSString *identify;
@property (strong, nonatomic) UIImage *image;
@end


text:
package org.iotivity.base.examples;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import org.iotivity.base.EntityHandlerResult;
import org.iotivity.base.ModeType;
import org.iotivity.base.OcConnectivityType;
import org.iotivity.base.OcException;
import org.iotivity.base.OcHeaderOption;
import org.iotivity.base.OcPlatform;
import org.iotivity.base.OcRepresentation;
import org.iotivity.base.OcResource;
import org.iotivity.base.OcResourceHandle;
import org.iotivity.base.OcResourceRequest;
import org.iotivity.base.OcResourceResponse;
import org.iotivity.base.PlatformConfig;
import org.iotivity.base.QualityOfService;
import org.iotivity.base.ServiceType;
import org.iotivity.ca.CaEdrInterface;
import org.iotivity.ca.CaIpInterface;
import org.iotivity.ca.CaLeClientInterface;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This class is for messaging between the server and the client.
 * It can handle message manually.
 */
public class MessageFragment extends Fragment implements OcResource.OnGetListener,
                                                         OcResource.OnPutListener {

    private static final String TAG          = "OIC_SIMPLE_MESSAGE";
    private final String        EOL          = System.getProperties().getProperty("line.separator");
    private final double        MILLI_PER_SEC = 1000.0;

    private Activity            mActivity;
    private Context             mContext;

    OcPlatform.EntityHandler    mEntityHandler;
    private OcResourceHandle    mResourceHandle;
    private OcResource          mFoundResource;

    private QualityOfService    mQos         = QualityOfService.LOW;

    private LinearLayout        mServerLayout;
    private LinearLayout        mClientLayout;
    private TextView            mResourceText;
    private TextView            mActionLog;
    private TextView            mResultLog;
    private ToggleButton        mQosToggle;
    private Button              mRegisterButton;
    private Button              mGetButton;
    private Button              mPutButton;
    private Button              mLargeButton;
    private Button              mDiscoverIPButton;
    private Button              mDiscoverBTButton;
    private Button              mDiscoverLEButton;
    private Button              mDiscoverTCPButton;
    private Button              mDiscoverNFCButton;

    private String              mLargeData;
    private boolean             mState;
    private long                mStartTime;
    private long                mEndTime;

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

        mActivity = getActivity();
        mContext = mActivity.getBaseContext();
    }

    View.OnClickListener getButtonListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mFoundResource != null) {
                    mStartTime = System.currentTimeMillis();
                    sendGetToFoundResource(Common.STATE_GET);
                } else {
                    Common.showToast(mContext, "Please discovery first");
                    Log.e(TAG, "get() : resource is null");
                }
            }
        };
    }

    View.OnClickListener putButtonListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mFoundResource != null) {
                    mStartTime = System.currentTimeMillis();
                    sendPutToFoundResource();
                } else {
                    Common.showToast(mContext, "Please discovery first");
                    Log.e(TAG, "put() : resource is null");
                }
            }
        };
    }

    View.OnClickListener getLargeListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mFoundResource != null) {
                    mStartTime = System.currentTimeMillis();
                    sendGetToFoundResource(Common.LARGE_GET);
                } else {
                    Common.showToast(mContext, "Please discovery first");
                    Log.e(TAG, "large() : resource is null");
                }
            }
        };
    }

    View.OnClickListener discoverButtonListener(
            final OcConnectivityType connectivityType) {
        return new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initOcPlatform(ModeType.CLIENT);
                mFoundResource = null;

                if (OcConnectivityType.CT_ADAPTER_TCP == connectivityType) {
                    showTCPInput();
                } else {
                    try {
                        Log.i(TAG, "discoverButtonListener");
                        OcPlatform.findResource("",
                                                OcPlatform.WELL_KNOWN_QUERY,
                                                EnumSet.of(connectivityType),
                                                resourceFoundListener, mQos);

                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mActionLog.setText("[Action Log]" + EOL);
                                mActionLog.append("Find resource()" + EOL);
                                mActionLog.append("Connectivity : " + connectivityType + EOL);

                                mResultLog.setText("[Result Log]" + EOL);
                                mResultLog.append("Start Time : ");
                                mResultLog.append(Common.getDateCurrentTimeZone() + EOL);
                                mStartTime = System.currentTimeMillis();
                            }
                        });
                    } catch (OcException e) {
                        e.printStackTrace();
                    }
                }
                mServerLayout.setVisibility(View.GONE);
            }
        };
    }

    void makeTCPResource(String address) {

        List<String> resourceTypeList = new ArrayList<String>();
        List<String> resourceInterfaceList = new ArrayList<String>();
        resourceInterfaceList.add(Common.RESOURCE_INTERFACE);
        resourceTypeList.add(Common.RESOURCE_TYPE);
        try {
            mFoundResource = OcPlatform.constructResourceObject(address,
                    Common.RESOURCE_URI,
                    EnumSet.of(OcConnectivityType.CT_ADAPTER_TCP), false,
                    resourceTypeList, resourceInterfaceList);

            mActionLog.setText("[Action Log]" + EOL);
            mActionLog.append("Found resource()" + EOL);
            mActionLog.append("Connectivity : " + OcConnectivityType.CT_ADAPTER_TCP + EOL);
            mActionLog.append(mFoundResource.getHost() + Common.RESOURCE_URI);

            mResultLog.setText("[Result Log]" + EOL);

        } catch (OcException e) {
            e.printStackTrace();
        }
    }

    void sendGetToFoundResource(String command) {
        try {
            Log.i(TAG, "sendGetToFoundResource");

            Map<String, String> queryParameters = new HashMap<String, String>();
            queryParameters.put(Common.GET_COMMAND, command);

            mFoundResource.get(queryParameters, this, mQos);

            mActionLog.setText("[Action Log]" + EOL + "Send get()"+ EOL + "To : ");
            mActionLog.append(mFoundResource.getHost() + mFoundResource.getUri() + EOL);
        } catch (OcException e) {
            e.printStackTrace();
        }
    }

    void sendPutToFoundResource() {
        try {
            Log.i(TAG, "sendPutToFoundResource");

            OcRepresentation rep = new OcRepresentation();
            rep.setValue(Common.STATE_KEY, !mState);

            Map<String, String> queryParams = new HashMap<>();

            mFoundResource.put(rep, queryParams, this);
            mActionLog.setText("[Action Log]" + EOL);
            mActionLog.append("Send put()" + EOL + "To : ");
            mActionLog.append(mFoundResource.getHost() + mFoundResource.getUri() + EOL);
        } catch (OcException e) {
            e.printStackTrace();
        }
    }

    OcPlatform.OnResourceFoundListener resourceFoundListener =
                                           new OcPlatform.OnResourceFoundListener() {
        @Override
        public void onResourceFound(OcResource ocResource) {
            synchronized (mActivity) {
                final String resourceUri = ocResource.getUri();
                Log.i(TAG, "onResourceFound : " + ocResource.getUri());

                if (resourceUri.contains(Common.RESOURCE_URI)) {
                    mFoundResource = ocResource;
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mEndTime = System.currentTimeMillis();
                            double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
                            mResultLog.append("Discovery Time : ");
                            mResultLog.append(String.format("%.3f", flightTime) + "sec" + EOL);
                            mActionLog.append(mFoundResource.getHost() + resourceUri + EOL);
                        }
                    });
                }
            }
        }
    };

    @Override
    public void onGetCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
        String repUri = ocRepresentation.getUri();
        Log.i(TAG, "onGetCompleted : " + repUri);

        try {
            final String command = ocRepresentation.getValue(Common.GET_COMMAND);

            if (command == null || command.isEmpty()) {
                Log.e(TAG, "Get command is null");
                return;
            } else if (command.equals(Common.STATE_GET)) {
                mState = ocRepresentation.getValue(Common.STATE_KEY);
                mLargeData = "";
            } else if (command.equals(Common.LARGE_GET)) {
                mLargeData = ocRepresentation.getValue(Common.LARGE_KEY);
            }
        } catch (OcException e) {
            e.printStackTrace();
        }

        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mEndTime = System.currentTimeMillis();
                double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;

                if (mLargeData == null || mLargeData.isEmpty()) {
                    mResultLog.append(EOL + "Get Light State : " + mState + EOL);
                } else {
                    mResultLog.append(EOL + "Payload Size : " + mLargeData.length() + EOL);
                }

                mResultLog.append("Get Time : " + String.format("%.3f", flightTime) + "sec" + EOL);
            }
        });
    }

    @Override
    public void onGetFailed(Throwable throwable) {
        Log.e(TAG, "Get failed");
    }

    @Override
    public void onPutCompleted(List<OcHeaderOption> list, OcRepresentation ocRepresentation) {
        String repUri = ocRepresentation.getUri();
        Log.i(TAG, "onPutCompleted : " + repUri);

        try {
            mState = ocRepresentation.getValue(Common.STATE_KEY);
        } catch (OcException e) {
            e.printStackTrace();
        }

        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mEndTime = System.currentTimeMillis();
                double flightTime = (double) (mEndTime - mStartTime) / MILLI_PER_SEC;
                mResultLog.append(EOL + "Set Light State : " + !mState + EOL + "Put Time : ");
                mResultLog.append(String.format("%.3f", flightTime) + "sec" + EOL);
            }
        });
    }

    @Override
    public void onPutFailed(Throwable throwable) {
        Log.e(TAG, "Put failed");
    }

    // ******************************************************************************
    // End of the OCF Client specific code
    // ******************************************************************************

    private void createResource() {
        mEntityHandler = new OcPlatform.EntityHandler() {
            @Override
            public EntityHandlerResult handleEntity(
                    OcResourceRequest ocResourceRequest) {
                return mEntityHandler(ocResourceRequest);
            }
        };

        try {
            mResourceHandle = OcPlatform.registerResource(Common.RESOURCE_URI,
                                 Common.RESOURCE_TYPE, Common.RESOURCE_INTERFACE,
                                 mEntityHandler, Common.RESOURCE_PROPERTIES);

        } catch (OcException e) {
            String errString = "Error : " + e.getErrorCode().toString();
            Log.e(TAG, errString);
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();
            Log.e(TAG, exceptionAsString);
            mResourceText.setText(errString);
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < Common.DATA_SIZE; i++) {
            sb.append('j');
        }
        mLargeData = sb.toString();

        sb.setLength(0);
        sb.append("URI :   " + Common.RESOURCE_URI + EOL);
        sb.append("Type :   " + Common.RESOURCE_TYPE + EOL);
        sb.append("Interface :   " + Common.RESOURCE_INTERFACE + EOL);
        sb.append("Properties :   " + Common.RESOURCE_PROPERTIES.toString() + EOL);
        mResourceText.setText(sb.toString());
        mActionLog.setText("");
        mResultLog.setText("Created resource" + EOL);
    }

    protected EntityHandlerResult mEntityHandler(OcResourceRequest ocResourceRequest) {
        EntityHandlerResult result = EntityHandlerResult.ERROR;
        final StringBuilder sb = new StringBuilder();
        switch (ocResourceRequest.getRequestType()) {
            case GET:
                sb.append("Type :   GET");
                if (sendGetResponse(ocResourceRequest)) {
                    result = EntityHandlerResult.OK;
                }
                break;
            case PUT:
                sb.append("Type :   PUT");
                if (sendPutResponse(ocResourceRequest)) {
                    result = EntityHandlerResult.OK;
                }
                break;
            case DELETE:
                sb.append("Type :   DELETE");
                break;
            case POST:
                sb.append("Type :   POST");
                break;
            default:
                break;
        }
        sb.append(EOL + "Light State :   " + mState);
        sb.append(EOL + "Time :   " + Common.getDateCurrentTimeZone());
        if (result == EntityHandlerResult.ERROR) {
            sb.append(EOL + "!! Error occurred during sending the response !!");
        }

        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mResultLog.setText(sb.toString());
            }
        });

        return result;
    }

    private boolean sendGetResponse(OcResourceRequest ocResourceRequest) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Common.showToast(mContext, "received get command, send response");
            }
        });

        Map<String, String> queryParameters = ocResourceRequest.getQueryParameters();
        final String command = queryParameters.get(Common.GET_COMMAND);

        if (command == null
                || (!command.equals(Common.STATE_GET) && !command.equals(Common.LARGE_GET))) {
            return false;
        }

        OcRepresentation rep = new OcRepresentation();
        try {
            rep.setValue(Common.GET_COMMAND, command);
            if (command.equals(Common.STATE_GET)) {
                rep.setValue(Common.STATE_KEY, mState);
            } else if (command.equals(Common.LARGE_GET)) {
                rep.setValue(Common.LARGE_KEY, mLargeData);
            }
        } catch (OcException e) {
            e.printStackTrace();
        }

        OcResourceResponse response = new OcResourceResponse();

        response.setRequestHandle(ocResourceRequest.getRequestHandle());
        response.setResourceHandle(ocResourceRequest.getResourceHandle());
        response.setResourceRepresentation(rep);
        try {
            OcPlatform.sendResponse(response);
            return true;
        } catch (OcException e) {
            e.printStackTrace();
            return false;
        }
    }

    private boolean sendPutResponse(OcResourceRequest ocResourceRequest) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Common.showToast(mContext, "received put command, send response");
            }
        });

        try {
            OcRepresentation rep = ocResourceRequest.getResourceRepresentation();
            if (rep.hasAttribute(Common.STATE_KEY)) {
                mState = rep.getValue(Common.STATE_KEY);
            }
        } catch (OcException e) {
            e.printStackTrace();
        }

        OcResourceResponse response = new OcResourceResponse();
        OcRepresentation rep = new OcRepresentation();

        response.setRequestHandle(ocResourceRequest.getRequestHandle());
        response.setResourceHandle(ocResourceRequest.getResourceHandle());
        response.setResourceRepresentation(rep);
        try {
            OcPlatform.sendResponse(response);
            return true;
        } catch (OcException e) {
            e.printStackTrace();
            return false;
        }
    }

    // ******************************************************************************
    // End of the OCF Server specific code
    // ******************************************************************************

    private void initOcPlatform(ModeType type) {
        PlatformConfig cfg = new PlatformConfig(mActivity, mContext,
                                                ServiceType.IN_PROC,
                                                type,
                                                Common.IP_ADDRESS,
                                                Common.IP_PORT,
                                                mQos);
        OcPlatform.Configure(cfg);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_message, container, false);

        mServerLayout = (LinearLayout) rootView.findViewById(R.id.server_layout);
        mClientLayout = (LinearLayout) rootView.findViewById(R.id.client_layout);

        mResourceText = (TextView) rootView.findViewById(R.id.resource_view);
        mActionLog = (TextView) rootView.findViewById(R.id.action_log_view);
        mResultLog = (TextView) rootView.findViewById(R.id.result_log_view);

        mDiscoverIPButton = (Button) rootView.findViewById(R.id.ip_button);
        mDiscoverBTButton = (Button) rootView.findViewById(R.id.bt_button);
        mDiscoverLEButton = (Button) rootView.findViewById(R.id.le_button);
        mDiscoverTCPButton = (Button) rootView.findViewById(R.id.tcp_button);
        mDiscoverNFCButton = (Button) rootView.findViewById(R.id.nfc_button);

        mRegisterButton = (Button) rootView.findViewById(R.id.register_button);
        mGetButton = (Button) rootView.findViewById(R.id.get_button);
        mPutButton = (Button) rootView.findViewById(R.id.put_button);
        mLargeButton = (Button) rootView.findViewById(R.id.large_button);

        mQosToggle = (ToggleButton) rootView.findViewById(R.id.qos_toggle_button);

        mDiscoverIPButton.setOnClickListener(
                discoverButtonListener(OcConnectivityType.CT_ADAPTER_IP));
        mDiscoverBTButton.setOnClickListener(
                discoverButtonListener(OcConnectivityType.CT_ADAPTER_RFCOMM_BTEDR));
        mDiscoverLEButton.setOnClickListener(
                discoverButtonListener(OcConnectivityType.CT_ADAPTER_GATT_BTLE));
        mDiscoverTCPButton.setOnClickListener(
                discoverButtonListener(OcConnectivityType.CT_ADAPTER_TCP));
        mDiscoverNFCButton.setOnClickListener(
                discoverButtonListener(OcConnectivityType.CT_ADAPTER_NFC));

        mRegisterButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mResourceHandle == null) {
                    initOcPlatform(ModeType.SERVER);
                    createResource();
                    mClientLayout.setVisibility(View.GONE);
                } else {
                    Common.showToast(mContext, "Already created resource");
                }
            }
        });
        mGetButton.setOnClickListener(getButtonListener());
        mPutButton.setOnClickListener(putButtonListener());
        mLargeButton.setOnClickListener(getLargeListener());

        mQosToggle
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (b) {
                            mQos = QualityOfService.HIGH;
                        } else {
                            mQos = QualityOfService.LOW;
                        }
                    }
                });

        return rootView;
    }

    private void showTCPInput() {

        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        View inputView = layoutInflater.inflate(R.layout.tcp_input, null);
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
        alertDialogBuilder.setView(inputView);

        final EditText editText = (EditText) inputView.getRootView().findViewById(R.id.ipText);
        editText.setText(Common.TCP_ADDRESS);
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        if (editText.getText().length() != 0) {
                            Common.TCP_ADDRESS = editText.getText().toString();

                            StringBuilder sb = new StringBuilder();
                            sb.append(Common.COAP_TCP);
                            sb.append(Common.TCP_ADDRESS);
                            sb.append(Common.TCP_PORT);
                            makeTCPResource(sb.toString());
                        }
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.apache.fop.fonts.substitute Class Hierarchy (Apache FOP 2.1 API)
</TITLE>

<META NAME="date" CONTENT="2016-01-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package org.apache.fop.fonts.substitute

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

java.util.AbstractCollection<E> (implements java.util.Collection<E>)

java.util.AbstractList<E> (implements java.util.List<E>)

java.util.ArrayList<E> (implements java.lang.Cloneable, java.util.List<E>, java.util.RandomAccess, java.io.Serializable)

org.apache.fop.fonts.substitute.AttributeValue
org.apache.fop.fonts.substitute.FontSubstitutions

org.apache.fop.fonts.substitute.FontQualifier
org.apache.fop.fonts.substitute.FontSubstitution
org.apache.fop.fonts.substitute.FontSubstitutionsConfigurator
org.apache.fop.fonts.substitute.FontWeightRange

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.