text:
#ifndef MIRTK_VectorND_H
#define MIRTK_VectorND_H

#include "mirtk/Math.h"
#include "mirtk/Point.h"
#include "mirtk/Vector3.h"

namespace mirtk {

/// Represents a n-D vector of fixed dimensions
///
/// Must be a primitive type which can be treated as an array of n
/// values of type T such that sizeof(VectorND<n, T>) == n * sizeof(T).
/// Thus, this primitive vector type may not have any other data members
/// besides the n vector components. This is required especially
/// when VectorND is used as voxel type of an image and further an
/// externally allocated continuous block of n * sizeof(T) bytes used
/// internally by the image instance which only reinterprets the memory
/// as consecutive VectorND<n, T> instances, i.e.,
///
/// \code
/// const int X   = 256;
/// const int Y   = 256;
/// const int Z   = 128;
/// const int num = X * Y * Z;
/// const int dim = 9;
/// double *data = new double[dim * num];
/// GenericImage<VectorND<dim, double> > image(X, Y, Z, data);
/// \endcode
template <int N, typename T>
struct VectorND
{
  typedef T ComponentType;

  // ---------------------------------------------------------------------------
  // Attributes

  /// Vector components
  T _v[N];

  // ---------------------------------------------------------------------------
  // Construction/Destruction

  /// Construct from scalar
  VectorND(T = T(0));

  /// Construct from C array
  explicit VectorND(const T[N]);

  /// Construct from variable size vector type
  explicit VectorND(const Vector &);

  /// Copy constructor
  template <typename T2>
  VectorND(const VectorND<N, T2> &);

  // ---------------------------------------------------------------------------
  // Accessors

  /// Number of vector components
  static int Rows() { return N; }

  /// Set/get vector component at index
  T &operator ()(int);

  /// Get vector component at index
  T operator ()(int) const;

  /// Cast to C array pointer
  operator T *();

  /// Cast to C array pointer
  operator const T *() const;

  // ---------------------------------------------------------------------------
  // Vector/integral-valued scalar operators

  /// Assign integral valued scalar
  VectorND &operator =(int);

  /// Add integral valued scalar
  VectorND &operator +=(int);

  /// Subtract integral valued scalar
  VectorND &operator -=(int);

  /// Multiply by integral valued scalar
  VectorND &operator *=(int);

  /// Divide by integral valued scalar
  VectorND &operator /=(int);

  /// Add integral valued scalar to vector
  VectorND operator +(int) const;

  /// Subtract integral valued scalar to vector
  VectorND operator -(int) const;

  /// Multiply vector by integral valued scalar
  VectorND operator *(int) const;

  /// Divide vector by integral valued scalar
  VectorND operator /(int) const;

  // ---------------------------------------------------------------------------
  // Vector/real-valued scalar operators

  /// Assign real valued scalar
  VectorND &operator =(double);

  /// Add real valued scalar
  VectorND &operator +=(double);

  /// Subtract real valued scalar
  VectorND &operator -=(double);

  /// Multiply by real valued scalar
  VectorND &operator *=(double);

  /// Divide by real valued scalar
  VectorND &operator /=(double);

  /// Add real valued scalar to vector
  VectorND operator +(double) const;

  /// Subtract real valued scalar to vector
  VectorND operator -(double) const;

  /// Multiply vector by real valued scalar
  VectorND operator *(double) const;

  /// Divide vector by real valued scalar
  VectorND operator /(double) const;

  // ---------------------------------------------------------------------------
  // Vector/vector operators

  /// Unary negation operator
  VectorND operator -() const;

  /// Assignment from other vector
  template <typename T2> VectorND &operator =(const VectorND<N, T2> &);

  /// Addition of other vector
  template <typename T2> VectorND &operator +=(const VectorND<N, T2> &);

  /// Subtraction of other vector
  template <typename T2> VectorND &operator -=(const VectorND<N, T2> &);

  /// Element-wise multiplication with other vector
  template <typename T2> VectorND &operator *=(const VectorND<N, T2> &);

  /// Element-wise division by other vector
  template <typename T2> VectorND &operator /=(const VectorND<N, T2> &);

  /// Addition of two vectors
  template <typename T2> VectorND operator +(const VectorND<N, T2> &) const;

  /// Subtraction of two vectors
  template <typename T2> VectorND operator -(const VectorND<N, T2> &) const;

  /// Element-wise multiplication of two vectors
  template <typename T2> VectorND operator *(const VectorND<N, T2> &) const;

  /// Element-wise division of two vectors
  template <typename T2> VectorND operator /(const VectorND<N, T2> &) const;

  // ---------------------------------------------------------------------------
  // Vector/integral-valued scalar comparison

  /// Element-wise equality comparison with inegral-valued scalar
  bool operator ==(int) const;

  /// Element-wise inequality comparison with inegral-valued scalar
  bool operator !=(int) const;

  /// Element-wise less than comparison to inegral-valued scalar
  bool operator <(int) const;

  /// Element-wise greater than comparison to inegral-valued scalar
  bool operator >(int) const;

  /// Element-wise less or equal than comparison to inegral-valued scalar
  bool operator <=(int) const;

  /// Element-wise greater or equal than comparison to inegral-valued scalar
  bool operator >=(int) const;

  // ---------------------------------------------------------------------------
  // Vector/real-valued scalar comparison

  /// Element-wise equality comparison with real-valued scalar
  bool operator ==(double) const;

  /// Element-wise inequality comparison with real-valued scalar
  bool operator !=(double) const;

  /// Element-wise less than comparison to real-valued scalar
  bool operator <(double) const;

  /// Element-wise greater than comparison to real-valued scalar
  bool operator >(double) const;

  /// Element-wise less or equal than comparison to real-valued scalar
  bool operator <=(double) const;

  /// Element-wise greater or equal than comparison to real-valued scalar
  bool operator >=(double) const;

  // ---------------------------------------------------------------------------
  // Vector/vector comparison

  /// Operator for testing equality of two vectors
  template <typename T2> bool operator ==(const VectorND<N, T2> &) const;

  /// Operator for testing non-equality of two vector
  template <typename T2> bool operator !=(const VectorND<N, T2> &) const;

  /// Operator for ordering vectors
  template <typename T2> bool operator <(const VectorND<N, T2> &) const;

  /// Operator for ordering vectors
  template <typename T2> bool operator >(const VectorND<N, T2> &) const;

  /// Operator for ordering vectors
  template <typename T2> bool operator <=(const VectorND<N, T2> &) const;

  /// Operator for ordering vectors
  template <typename T2> bool operator >=(const VectorND<N, T2> &) const;

  // ---------------------------------------------------------------------------
  // Other vector functions

  /// Compute squared length of vector
  double SquaredLength() const;

  /// Compute length of vector
  double Length() const;

  /// Normalize vector to length one
  void Normalize();

  /// Dot-product with other vector
  double DotProduct(const VectorND &) const;

};

////////////////////////////////////////////////////////////////////////////////
// Inline definitions
////////////////////////////////////////////////////////////////////////////////

// =============================================================================
// Construction/Destruction
// =============================================================================

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>::VectorND(T s)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = s;
  }
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>::VectorND(const T v[N])
{
  for (int i = 0; i < N; ++i) {
    _v[i] = v[i];
  }
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>::VectorND(const Vector &v)
{
  if (v.Rows() != N) {
    Throw(ERR_InvalidArgument, __FUNCTION__, "Vector must have ", N, " components");
  }
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T>(v(i));
  }
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline VectorND<N, T1>::VectorND(const VectorND<N, T2> &v)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T1>(v._v[i]);
  }
}

// =============================================================================
// Accessors
// =============================================================================

// -----------------------------------------------------------------------------
template <int N, typename T>
inline T& VectorND<N, T>::operator ()(int i)
{
  return _v[i];
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline T VectorND<N, T>::operator ()(int i) const
{
  return _v[i];
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>::operator T *()
{
  return _v;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>::operator const T *() const
{
  return _v;
}

// =============================================================================
// Vector/integral-valued scalar operators
// =============================================================================

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>& VectorND<N, T>::operator =(int s)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T>(s);
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>& VectorND<N, T>::operator +=(int s)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T>(static_cast<double>(_v[i]) + static_cast<double>(s));
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>& VectorND<N, T>::operator -=(int s)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T>(static_cast<double>(_v[i]) - static_cast<double>(s));
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>& VectorND<N, T>::operator *=(int s)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T>(static_cast<double>(_v[i]) * static_cast<double>(s));
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>& VectorND<N, T>::operator /=(int s)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T>(static_cast<double>(_v[i]) / static_cast<double>(s));
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> VectorND<N, T>::operator +(int s) const
{
  VectorND<N, T> r(*this);
  r += s;
  return r;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> VectorND<N, T>::operator -(int s) const
{
  VectorND<N, T> r(*this);
  r -= s;
  return r;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> VectorND<N, T>::operator *(int s) const
{
  VectorND<N, T> r(*this);
  r *= s;
  return r;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> VectorND<N, T>::operator /(int s) const
{
  VectorND<N, T> r(*this);
  r /= s;
  return r;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> operator +(int s, const VectorND<N, T> &v)
{
  return v + s;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> operator -(int s, const VectorND<N, T> &v)
{
  return v - s;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> operator *(int s, const VectorND<N, T> &v)
{
  return v * s;
}

// =============================================================================
// Vector/real-valued scalar operators
// =============================================================================

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>& VectorND<N, T>::operator =(double s)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T>(s);
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>& VectorND<N, T>::operator +=(double s)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T>(static_cast<double>(_v[i]) + s);
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>& VectorND<N, T>::operator -=(double s)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T>(static_cast<double>(_v[i]) - s);
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>& VectorND<N, T>::operator *=(double s)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T>(static_cast<double>(_v[i]) * s);
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T>& VectorND<N, T>::operator /=(double s)
{
  for (int i = 0; i < N; ++i) {
    _v[i] = static_cast<T>(static_cast<double>(_v[i]) / s);
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> VectorND<N, T>::operator +(double s) const
{
  VectorND<N, T> r(*this);
  r += s;
  return r;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> VectorND<N, T>::operator -(double s) const
{
  VectorND<N, T> r(*this);
  r -= s;
  return r;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> VectorND<N, T>::operator *(double s) const
{
  VectorND<N, T> r(*this);
  r *= s;
  return r;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> VectorND<N, T>::operator /(double s) const
{
  VectorND<N, T> r(*this);
  r /= s;
  return r;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> operator +(double s, const VectorND<N, T> &v)
{
  return v + s;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> operator -(double s, const VectorND<N, T> &v)
{
  return v - s;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> operator *(double s, const VectorND<N, T> &v)
{
  return v * s;
}

// =============================================================================
// Vector/vector operators
// =============================================================================

// -----------------------------------------------------------------------------
template <int N, typename T>
inline VectorND<N, T> VectorND<N, T>::operator -() const
{
  VectorND<N, T> v(*this);
  for (int i = 0; i < N; ++i) {
    v._v[i] = -v._v[i];
  }
  return v;
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline VectorND<N, T1> &VectorND<N, T1>::operator =(const VectorND<N, T2> &v)
{
  for (int i = 0; i < N; ++i) {
    v._v[i] = static_cast<T1>(v._v[i]);
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline VectorND<N, T1> &VectorND<N, T1>::operator +=(const VectorND<N, T2>& v)
{
  for (int i = 0; i < N; ++i) {
   _v[i] = static_cast<T1>(static_cast<double>(_v[i]) + static_cast<double>(v._v[i]));
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline VectorND<N, T1> &VectorND<N, T1>::operator -=(const VectorND<N, T2> &v)
{
  for (int i = 0; i < N; ++i) {
   _v[i] = static_cast<T1>(static_cast<double>(_v[i]) - static_cast<double>(v._v[i]));
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline VectorND<N, T1> &VectorND<N, T1>::operator *=(const VectorND<N, T2> &v)
{
  for (int i = 0; i < N; ++i) {
   _v[i] = static_cast<T1>(static_cast<double>(_v[i]) * static_cast<double>(v._v[i]));
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline VectorND<N, T1> &VectorND<N, T1>::operator /=(const VectorND<N, T2> &v)
{
  for (int i = 0; i < N; ++i) {
   _v[i] = static_cast<T1>(static_cast<double>(_v[i]) / static_cast<double>(v._v[i]));
  }
  return *this;
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline VectorND<N, T1> VectorND<N, T1>::operator +(const VectorND<N, T2> &v) const
{
  VectorND<N, T1> r(*this);
  r += v;
  return r;
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline VectorND<N, T1> VectorND<N, T1>::operator -(const VectorND<N, T2> &v) const
{
  VectorND<N, T1> r(*this);
  r -= v;
  return r;
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline VectorND<N, T1> VectorND<N, T1>::operator *(const VectorND<N, T2> &v) const
{
  VectorND<N, T1> r(*this);
  r *= v;
  return r;
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline VectorND<N, T1> VectorND<N, T1>::operator /(const VectorND<N, T2> &v) const
{
  VectorND<N, T1> r(*this);
  r /= v;
  return r;
}

// =============================================================================
// Vector/real-valued scalar comparison
// =============================================================================

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator ==(double s) const
{
  for (int i = 0; i < N; ++i) {
    if (!AreEqual(static_cast<double>(_v[i]), s)) return false;
  }
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator !=(double s) const
{
  return !(*this == s);
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator <(double s) const
{
  for (int i = 0; i < N; ++i) {
    if (!(static_cast<double>(_v[i]) < s)) return false;
  }
  return true;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator >(double s) const
{
  for (int i = 0; i < N; ++i) {
    if (!(static_cast<double>(_v[i]) > s)) return false;
  }
  return true;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator <=(double s) const
{
  return !(*this > s);
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator >=(double s) const
{
  return !(*this < s);
}

// =============================================================================
// Vector/integral-valued scalar comparison
// =============================================================================

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator ==(int s) const
{
  return (*this == static_cast<double>(s));
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator !=(int s) const
{
  return !(*this == s);
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator <(int s) const
{
  return (*this < static_cast<double>(s));
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator >(int s) const
{
  return (*this > static_cast<double>(s));
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator <=(int s) const
{
  return !(*this > s);
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline bool VectorND<N, T>::operator >=(int s) const
{
  return !(*this < s);
}

// =============================================================================
// Vector/vector comparison
// =============================================================================

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline bool VectorND<N, T1>::operator ==(const VectorND<N, T2> &v) const
{
  for (int i = 0; i < N; ++i) {
    if (!AreEqual(static_cast<double>(_v[i]), static_cast<double>(v._v[i]))) return false;
  }
  return true;
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline bool VectorND<N, T1>::operator !=(const VectorND<N, T2> &v) const
{
  return !(*this == v);
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline bool VectorND<N, T1>::operator <(const VectorND<N, T2> &v) const
{
  for (int i = N - 1; i >= 0; --i) {
    if (static_cast<double>(_v[i]) < static_cast<double>(v._v[i])) return true;
    if (!AreEqual(static_cast<double>(_v[i]), static_cast<double>(v._v[i]))) break;
  }
  return false;
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline bool VectorND<N, T1>::operator >(const VectorND<N, T2> &v) const
{
  return !(*this == v) && !(*this < v);
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline bool VectorND<N, T1>::operator <=(const VectorND<N, T2> &v) const
{
  return (*this < v) || (*this == v);
}

// -----------------------------------------------------------------------------
template <int N, typename T1> template <typename T2>
inline bool VectorND<N, T1>::operator >=(const VectorND<N, T2> &v) const
{
  return (*this > v) || (*this == v);
}

// =============================================================================
// Vector functions
// =============================================================================

// -----------------------------------------------------------------------------
template <int N, typename T>
inline double VectorND<N, T>::DotProduct(const VectorND<N, T> &v) const
{
  double dp = 0.;
  for (int i = 0; i < N; ++i) {
    dp += static_cast<double>(_v[i]) * static_cast<double>(v._v[i]);
  }
  return dp;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline double VectorND<N, T>::SquaredLength() const
{
  return DotProduct(*this);
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline double VectorND<N, T>::Length() const
{
  return sqrt(SquaredLength());
}

// -----------------------------------------------------------------------------
template <int N, typename T>
inline void VectorND<N, T>::Normalize()
{
  const double length = Length();
  if (!IsZero(length)) (*this) /= length;
}

// =============================================================================
// Indexed element access
// =============================================================================

// -----------------------------------------------------------------------------
template <int N, class T>
inline T get(const VectorND<N, T> &v, int n)
{
  return v(n);
}

// -----------------------------------------------------------------------------
template <int N, class T>
inline void put(VectorND<N, T> &v, int n, const T &value)
{
  v(n) = value;
}

// =============================================================================
// Element-wise <cmath> functions
// =============================================================================

// -----------------------------------------------------------------------------
template <int N, typename T>
VectorND<N, T> pow(const VectorND<N, T> &v, int e)
{
  VectorND<N, T> w;
  for (int i = 0; i < N; ++i) {
    w._v[i] = pow(v._v[i], e);
  }
  return w;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
VectorND<N, T> pow(const VectorND<N, T> &v, double e)
{
  VectorND<N, T> w;
  for (int i = 0; i < N; ++i) {
    w._v[i] = pow(v._v[i], e);
  }
  return w;
}

// -----------------------------------------------------------------------------
template <int N, typename T>
VectorND<N, T> sqrt(const VectorND<N, T> &v)
{
  VectorND<N, T> w;
  for (int i = 0; i < N; ++i) {
    w._v[i] = sqrt(v._v[i]);
  }
  return w;
}

} // namespace mirtk

#endif // MIRTK_VectorND_H


text:
define(function() {
  var PathManager;
  return PathManager = (function() {
    function PathManager(options) {
      this.configure(options);
    }

    PathManager.prototype.configure = function(options) {
      return this.config = options.path;
    };

    PathManager.prototype.path = function(name) {
      var url;
      return url = this.config.baseUrl + name.replace(/\./g, '/') + '.js';
    };

    PathManager.prototype.moduleName = function(name) {
      var MODULE_NAME_REGEX;
      MODULE_NAME_REGEX = /(\S+?)\.(\S+)/;
      if (MODULE_NAME_REGEX.exec(name)) {
        return name.split('.').pop();
      }
      return name;
    };

    PathManager.prototype.fullModuleName = function(name) {
      return name;
    };

    return PathManager;

  })();
});

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ignite.jvmtest;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.LongAdder;
import org.apache.ignite.internal.util.GridTimer;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.testframework.GridTestUtils;

/**
 * Blocking queue performance benchmark.
 */
public class BlockingQueueTest {
    /** Number of retries. */
    private static final int RETRIES = 3;

    /** Number of attempts. */
    private static final int CNT = 1000000;

    /** Number of threads. */
    private static final int THREAD_CNT = Runtime.getRuntime().availableProcessors();

    /**
     * Main method.
     *
     * @param args Parameters.
     * @throws Exception If failed.
     */
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < RETRIES; i++) {
            X.println(">>>");
            X.println(">>> Executing single threaded attempt: " + i);
            X.println(">>>");

            testBlockingQueue("single-threaded-linked-queue", new LinkedBlockingQueue<>());
            testBlockingQueue("single-threaded-linked-deque", new LinkedBlockingDeque<>());
            testBlockingQueue("single-threaded-array-queue", new ArrayBlockingQueue<>(CNT + 10));
        }

        for (int i = 0; i < RETRIES; i++) {
            X.println(">>>");
            X.println(">>> Executing multi-threaded attempt: " + i);
            X.println(">>>");

            testBlockingQueueMultithreaded("multi-threaded-linked-queue", new LinkedBlockingQueue<>());
            testBlockingQueueMultithreaded("multi-threaded-linked-deque", new LinkedBlockingDeque<>());
            testBlockingQueueMultithreaded("multi-threaded-array-queue", new ArrayBlockingQueue<>(
                THREAD_CNT * CNT + 100));
        }
    }

    /**
     * @throws InterruptedException If interrupted.
     */
    private static void waitGc() throws InterruptedException {
        System.gc();
        System.gc();

        X.println(">>> Waiting for GC to complete...");

        Thread.sleep(1000);
    }

    /**
     * @param testName Test name.
     * @param q Queue to test.
     * @throws InterruptedException If interrupted.
     */
    private static void testBlockingQueue(String testName, BlockingQueue<Object> q) throws InterruptedException {
        waitGc();

        X.println(">>> Starting test for: " + testName);

        long dur = testBlockingQueue(q);

        X.println(">>> Tested queue [testName=" + testName + ", dur=" + dur + "ms]");

        assert q.isEmpty();
    }

    /**
     * @param testName Test name.
     * @param q Queue.
     * @throws Exception If failed.
     */
    private static void testBlockingQueueMultithreaded(String testName, final BlockingQueue<Object> q)
        throws Exception {
        waitGc();

        X.println(">>> Starting test for: " + testName);

        final LongAdder adder = new LongAdder();

        GridTestUtils.runMultiThreaded(new Callable<Object>() {
            @Override public Object call() throws Exception {
                adder.add(testBlockingQueue(q));

                return null;
            }
        }, THREAD_CNT, "queue-test-worker");

        X.println(">>> Tested queue [testName=" + testName + ", dur=" + adder.sum() + "ms]");

        assert q.isEmpty();
    }

    /**
     * @param q Queue to test.
     * @throws InterruptedException If interrupted.
     */
    private static long testBlockingQueue(BlockingQueue<Object> q) throws InterruptedException {
        GridTimer timer = new GridTimer("blocking-queue");

        for (int i = 0; i < CNT; i++)
            q.put(new Object());

        for (int i = 0; i < CNT; i++) {
            Object o = q.take();

            assert o != null;
        }

        timer.stop();

        return timer.duration();
    }
}


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

001
002
007
008package org.jsimpledb.parse.func;
009
010import com.google.common.collect.Iterables;
011
012import org.jsimpledb.parse.ParseSession;
013import org.jsimpledb.parse.expr.AbstractValue;
014import org.jsimpledb.parse.expr.EvalException;
015import org.jsimpledb.parse.expr.Value;
016
017@Function
018public class ConcatFunction extends SimpleFunction {
019
020    public ConcatFunction() {
021        super("concat", 1, 1);
022    }
023
024    @Override
025    public String getHelpSummary() {
026        return "concatenates the Iterables within an Iterable";
027    }
028
029    @Override
030    public String getUsage() {
031        return "concat(items)";
032    }
033
034    @Override
035    public String getHelpDetail() {
036        return "The concat() function takes an argument which must be an Iterable of Iterables (i.e., an instance of"
037          + " Iterable<? extends Iterable<?>>), and returns a new Iterable<?> which is the concatenation of the inner Iterables.";
038    }
039
040    @Override
041    protected Value apply(ParseSession session, Value[] params) {
042        final Value value = params[0];
043        return new AbstractValue() {
044            @Override
045            public Object get(final ParseSession session) {
046                return Iterables.concat(Iterables.transform((Iterable<?>)value.checkType(session, "concat()", Iterable.class),
047                  new com.google.common.base.Function<Object, Iterable<?>>() {
048                    @Override
049                    public Iterable<?> apply(Object item) {
050                        if (item == null)
051                            throw new EvalException("concat() operation encountered null Iterable");
052                        if (!(item instanceof Iterable)) {
053                            throw new EvalException("concat() operation encountered non-Iterable value of type "
054                              + item.getClass().getName());
055                        }
056                        return (Iterable<?>)item;
057                    }
058                }));
059            }
060        };
061    }
062}
063


text:
#!/usr/bin/env node

'use strict';

/* eslint-disable
  import/order,
  import/no-extraneous-dependencies,
  global-require,
  no-shadow,
  no-console,
  multiline-ternary,
  arrow-parens,
  array-bracket-spacing,
  space-before-function-paren
*/
const debug = require('debug')('webpack-dev-server');

const fs = require('fs');
const net = require('net');
const path = require('path');

const portfinder = require('portfinder');
const importLocal = require('import-local');

const yargs = require('yargs');
const webpack = require('webpack');

const options = require('./options');

const {
  colors,
  status,
  version,
  bonjour,
  defaultTo
} = require('./utils');

const Server = require('../lib/Server');

const addEntries = require('../lib/utils/addEntries');
const createDomain = require('../lib/utils/createDomain');
const createLogger = require('../lib/utils/createLogger');

let server;

const signals = [ 'SIGINT', 'SIGTERM' ];

signals.forEach((signal) => {
  process.on(signal, () => {
    if (server) {
      server.close(() => {
        // eslint-disable-next-line no-process-exit
        process.exit();
      });
    } else {
      // eslint-disable-next-line no-process-exit
      process.exit();
    }
  });
});

// Prefer the local installation of webpack-dev-server
if (importLocal(__filename)) {
  debug('Using local install of webpack-dev-server');

  return;
}

try {
  require.resolve('webpack-cli');
} catch (err) {
  console.error('The CLI moved into a separate package: webpack-cli');
  console.error('Please install \'webpack-cli\' in addition to webpack itself to use the CLI');
  console.error('-> When using npm: npm i -D webpack-cli');
  console.error('-> When using yarn: yarn add -D webpack-cli');

  process.exitCode = 1;
}

yargs.usage(
  `${version()}\nUsage:  https://webpack.js.org/configuration/dev-server/`
);

require('webpack-cli/bin/config-yargs')(yargs);
// It is important that this is done after the webpack yargs config,
// so it overrides webpack's version info.
yargs.version(version());
yargs.options(options);

const argv = yargs.argv;

const config = require('webpack-cli/bin/convert-argv')(yargs, argv, {
  outputFilename: '/bundle.js'
});
// Taken out of yargs because we must know if
// it wasn't given by the user, in which case
// we should use portfinder.
const DEFAULT_PORT = 8080;

function processOptions (config) {
  // processOptions {Promise}
  if (typeof config.then === 'function') {
    config.then(processOptions).catch((err) => {
      console.error(err.stack || err);
      // eslint-disable-next-line no-process-exit
      process.exit();
    });

    return;
  }

  const firstWpOpt = Array.isArray(config)
    ? config[0]
    : config;

  const options = config.devServer || firstWpOpt.devServer || {};

  if (argv.bonjour) {
    options.bonjour = true;
  }

  if (argv.host !== 'localhost' || !options.host) {
    options.host = argv.host;
  }

  if (argv['allowed-hosts']) {
    options.allowedHosts = argv['allowed-hosts'].split(',');
  }

  if (argv.public) {
    options.public = argv.public;
  }

  if (argv.socket) {
    options.socket = argv.socket;
  }

  if (argv.progress) {
    options.progress = argv.progress;
  }

  if (!options.publicPath) {
    // eslint-disable-next-line
    options.publicPath = firstWpOpt.output && firstWpOpt.output.publicPath || '';

    if (
      !/^(https?:)?\/\//.test(options.publicPath) &&
      options.publicPath[0] !== '/'
    ) {
      options.publicPath = `/${options.publicPath}`;
    }
  }

  if (!options.filename) {
    options.filename = firstWpOpt.output && firstWpOpt.output.filename;
  }

  if (!options.watchOptions) {
    options.watchOptions = firstWpOpt.watchOptions;
  }

  if (argv.stdin) {
    process.stdin.on('end', () => {
      // eslint-disable-next-line no-process-exit
      process.exit(0);
    });

    process.stdin.resume();
  }

  if (!options.hot) {
    options.hot = argv.hot;
  }

  if (!options.hotOnly) {
    options.hotOnly = argv['hot-only'];
  }

  if (!options.clientLogLevel) {
    options.clientLogLevel = argv['client-log-level'];
  }

  // eslint-disable-next-line
  if (options.contentBase === undefined) {
    if (argv['content-base']) {
      options.contentBase = argv['content-base'];

      if (Array.isArray(options.contentBase)) {
        options.contentBase = options.contentBase.map((p) => path.resolve(p));
      } else if (/^[0-9]$/.test(options.contentBase)) {
        options.contentBase = +options.contentBase;
      } else if (!/^(https?:)?\/\//.test(options.contentBase)) {
        options.contentBase = path.resolve(options.contentBase);
      }
      // It is possible to disable the contentBase by using
      // `--no-content-base`, which results in arg["content-base"] = false
    } else if (argv['content-base'] === false) {
      options.contentBase = false;
    }
  }

  if (argv['watch-content-base']) {
    options.watchContentBase = true;
  }

  if (!options.stats) {
    options.stats = {
      cached: false,
      cachedAssets: false
    };
  }

  if (
    typeof options.stats === 'object' &&
    typeof options.stats.colors === 'undefined'
  ) {
    options.stats = Object.assign(
      {},
      options.stats,
      { colors: argv.color }
    );
  }

  if (argv.lazy) {
    options.lazy = true;
  }

  if (!argv.info) {
    options.noInfo = true;
  }

  if (argv.quiet) {
    options.quiet = true;
  }

  if (argv.https) {
    options.https = true;
  }

  if (argv.cert) {
    options.cert = fs.readFileSync(
      path.resolve(argv.cert)
    );
  }

  if (argv.key) {
    options.key = fs.readFileSync(
      path.resolve(argv.key)
    );
  }

  if (argv.cacert) {
    options.ca = fs.readFileSync(
      path.resolve(argv.cacert)
    );
  }

  if (argv.pfx) {
    options.pfx = fs.readFileSync(
      path.resolve(argv.pfx)
    );
  }

  if (argv['pfx-passphrase']) {
    options.pfxPassphrase = argv['pfx-passphrase'];
  }

  if (argv.inline === false) {
    options.inline = false;
  }

  if (argv['history-api-fallback']) {
    options.historyApiFallback = true;
  }

  if (argv.compress) {
    options.compress = true;
  }

  if (argv['disable-host-check']) {
    options.disableHostCheck = true;
  }

  if (argv['open-page']) {
    options.open = true;
    options.openPage = argv['open-page'];
  }

  if (typeof argv.open !== 'undefined') {
    options.open = argv.open !== '' ? argv.open : true;
  }

  if (options.open && !options.openPage) {
    options.openPage = '';
  }

  if (argv.useLocalIp) {
    options.useLocalIp = true;
  }
  // Kind of weird, but ensures prior behavior isn't broken in cases
  // that wouldn't throw errors. E.g. both argv.port and options.port
  // were specified, but since argv.port is 8080, options.port will be
  // tried first instead.
  options.port = argv.port === DEFAULT_PORT
    ? defaultTo(options.port, argv.port)
    : defaultTo(argv.port, options.port);

  if (options.port != null) {
    startDevServer(config, options);

    return;
  }

  portfinder.basePort = DEFAULT_PORT;

  portfinder.getPort((err, port) => {
    if (err) {
      throw err;
    }

    options.port = port;

    startDevServer(config, options);
  });
}

function startDevServer(config, options) {
  const log = createLogger(options);

  addEntries(config, options);

  let compiler;

  try {
    compiler = webpack(config);
  } catch (err) {
    if (err instanceof webpack.WebpackOptionsValidationError) {
      log.error(colors.error(options.stats.colors, err.message));
      // eslint-disable-next-line no-process-exit
      process.exit(1);
    }

    throw err;
  }

  if (options.progress) {
    new webpack.ProgressPlugin({
      profile: argv.profile
    }).apply(compiler);
  }

  const suffix = (options.inline !== false || options.lazy === true ? '/' : '/webpack-dev-server/');

  try {
    server = new Server(compiler, options, log);
  } catch (err) {
    if (err.name === 'ValidationError') {
      log.error(colors.error(options.stats.colors, err.message));
      // eslint-disable-next-line no-process-exit
      process.exit(1);
    }

    throw err;
  }

  if (options.socket) {
    server.listeningApp.on('error', (e) => {
      if (e.code === 'EADDRINUSE') {
        const clientSocket = new net.Socket();

        clientSocket.on('error', (err) => {
          if (err.code === 'ECONNREFUSED') {
            // No other server listening on this socket so it can be safely removed
            fs.unlinkSync(options.socket);

            server.listen(options.socket, options.host, (error) => {
              if (error) {
                throw error;
              }
            });
          }
        });

        clientSocket.connect({ path: options.socket }, () => {
          throw new Error('This socket is already used');
        });
      }
    });

    server.listen(options.socket, options.host, (err) => {
      if (err) {
        throw err;
      }
      // chmod 666 (rw rw rw)
      const READ_WRITE = 438;

      fs.chmod(options.socket, READ_WRITE, (err) => {
        if (err) {
          throw err;
        }

        const uri = createDomain(options, server.listeningApp) + suffix;

        status(uri, options, log, argv.color);
      });
    });
  } else {
    server.listen(options.port, options.host, (err) => {
      if (err) {
        throw err;
      }

      if (options.bonjour) {
        bonjour(options);
      }

      const uri = createDomain(options, server.listeningApp) + suffix;

      status(uri, options, log, argv.color);
    });
  }
}

processOptions(config);


text:
namespace headless {

class HeadlessContentRendererClient : public content::ContentRendererClient {
 public:
  HeadlessContentRendererClient();
  ~HeadlessContentRendererClient() override;

  DISALLOW_COPY_AND_ASSIGN(HeadlessContentRendererClient);
};

}  // namespace headless

#endif  // HEADLESS_LIB_RENDERER_HEADLESS_CONTENT_RENDERER_CLIENT_H_


text:
app package
===========

Subpackages
-----------

.. toctree::

    app.tests

Submodules
----------

.. toctree::

   app.geolocator
   app.models
   app.nlp
   app.views
   app.weighter

Module contents
---------------

.. automodule:: app
    :members:
    :undoc-members:
    :show-inheritance:


text:
const {Range} = require('atom')

// endregion

// region getSelectionRange

const getSelectionRange = (editor, range) => {
	const endRow = range.end.column === 0
		? range.end.row - 1
		: range.end.row
	const endCol = editor.lineTextForBufferRow(endRow).length

	return new Range([
		range.start.row,
		0
	], [
		endRow,
		endCol
	])
}

// endregion

// region export

module.exports = getSelectionRange

// endregion


text:
(function($) {

  /**
   * Set all elements within the collection to have the same height.
   */
  $.fn.equalHeight = function(){
    var heights = [];
    $.each(this, function(i, element){
      $element = $(element);
      var element_height;
      // Should we include the elements padding in it's height?
      var includePadding = ($element.css('box-sizing') == 'border-box') || ($element.css('-moz-box-sizing') == 'border-box');
      if (includePadding) {
        element_height = $element.innerHeight();
      } else {
        element_height = $element.height();
      }
      heights.push(element_height);
    });
    this.height(Math.max.apply(window, heights));
    return this;
  }

  /**
   * Create a grid of equal height elements.
   */
  $.fn.equalHeightGrid = function(columns){
    var $tiles = this;
    $tiles.css('height', 'auto');
    for (var i = 0; i < $tiles.length; i++) {
      if (i % columns == 0) {
        var row = $($tiles[i]);
        for(var n = 1;n < columns;n++){
          row = row.add($tiles[i + n]);
        }
        row.equalHeight();
      }
    }
    return this;
  };

  /**
   * Detect how many columns there are in a given layout.
   */
  $.fn.detectGridColumns = function() {
    var offset = 0, cols = 0;
    this.each(function(i, elem) {
      var elem_offset = $(elem).offset().top;
      if (offset == 0 || elem_offset == offset) {
        cols++;
        offset = elem_offset;
      } else {
        return false;
      }
    });
    return cols;
  };

  /**
   * Ensure equal heights now, on ready, load and resize.
   */
  $.fn.responsiveEqualHeightGrid = function() {
    var _this = this;
    function syncHeights() {
      var cols = _this.detectGridColumns();
      console.log(cols);
      _this.equalHeightGrid(cols);
    }
    $(window).bind('resize load', syncHeights);
    syncHeights();
    return this;
  };

})(jQuery);


text:
"""
    Description:
        Watches and posts in channels with RSS feeds.

    Contributors:
        - Patrick Hennessy
"""
from bolt import Plugin
from bolt import interval
from bolt import parse_command
from bolt.utils import Timer
import feedparser
import html2text
import time
import datetime
import gevent

class RSS(Plugin):
    def activate(self):
        self.feed_url = "http://www.teamfortress.com/rss.xml"
        self.last_checked = time.gmtime()
        self.feeds = self.database.feed_channels

    @parse_command("feed {onoff}")
    def feed(self, event):
        args, kwargs = event.arguments
        toggle_status = kwargs['onoff']

        tf2_feed = self.feeds.find_one({"feed_url": self.feed_url})
        channel_id = event.message.channel_id

        if toggle_status == "on":
            if not tf2_feed:
                self.feeds.insert_one({"feed_url": self.feed_url, "channels": [channel_id]})
                self.say(channel_id, f"Subcribed this channel for updates to {self.feed_url}")
                return
            else:
                for channel in tf2_feed['channels']:
                    if channel == channel_id:
                        self.say(channel_id, f"This channel is already subcribed to {self.feed_url}")
                        break
                else:
                    self.feeds.update_one({"feed_url": self.feed_url}, {"$push": {"channels": channel_id}})
                    self.say(channel_id, f"Subcribed this channel for updates to {self.feed_url}")

        elif toggle_status == "off":
            if not tf2_feed:
                self.say(channel_id, f"I dont have any channels listed for {self.feed_url}")
            else:
                self.feeds.update_one({"feed_url": self.feed_url}, {"$pull": {"channels": channel_id}})
                self.say(channel_id, f"Unsubcribed this channel for updates to {self.feed_url}")

    @interval(60)
    def update(self):
        tf2_feed = self.feeds.find_one({"feed_url": self.feed_url})

        if not tf2_feed or not tf2_feed['channels']:
            return

        with Timer() as timer:
            # Get feed
            parsed_feed = feedparser.parse(self.feed_url)
            h = html2text.HTML2Text()
            h.ignore_images = True
            h.ignore_tables = True

            # Check last updated time
            last_checked = self.last_checked

            try:
                if last_checked > parsed_feed.feed['updated_parsed']:
                    return
            except KeyError:
                if last_checked > parsed_feed.updated_parsed:
                    return

            for post in parsed_feed.entries:
                # Ensure we're going to post something new
                if last_checked < post['published_parsed']:
                    summary = h.handle(post.summary)
                    summary = summary[:256]
                    timestamp = time.strftime("%a, %b %d %Y @ %I:%M %p", post['published_parsed'])

                    embed =  {
                        "title": f"__{post.title}__",
                        "url": f"{post.link}",
                        "author": {
                            "name": "Team Fortress 2 Updates",
                            "icon_url": "http://icons.iconarchive.com/icons/sicons/basic-round-social/512/rss-icon.png"
                        },
                        "description": f"*{timestamp}*\n\n{summary}",
                        "footer": {
                          "text": f"⏰ {timer.delta}ms | 🔌 RSS"
                        }
                    }

                    for channel in tf2_feed['channels']:
                        self.say(channel, embed=embed)
                        gevent.sleep(1)

                    self.last_checked = time.gmtime()
                    break


text:
<!-- Copyright (c) Microsoft Corporation. All rights reserved.
     Licensed under the MIT License. -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.azure</groupId>
    <artifactId>azure-client-sdk-parent</artifactId>
    <version>1.7.0</version> <!-- {x-version-update;com.azure:azure-client-sdk-parent;current} -->
    <relativePath>../../parents/azure-client-sdk-parent</relativePath>
  </parent>

  <groupId>com.azure</groupId>
  <artifactId>azure-communication-chat</artifactId>
  <version>1.4.0-beta.1</version> <!-- {x-version-update;com.azure:azure-communication-chat;current} -->

  <name>Microsoft Azure client library for chat application</name>
  <description>
    This package contains a Java SDK for Chat Azure Communication Service.
    For this release, see notes - https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/communication/azure-communication-chat/README.md and https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/communication/azure-communication-chat/CHANGELOG.md.
    Microsoft Azure Communication Chat quickstart - https://docs.microsoft.com/azure/communication-services/quickstarts/chat/get-started?pivots=programming-language-java
  </description>
  <url>https://github.com/Azure/azure-sdk-for-java</url>

  <distributionManagement>
    <site>
      <id>azure-java-build-docs</id>
      <url>${site.url}/site/${project.artifactId}</url>
    </site>
  </distributionManagement>

  <scm>
    <url>https://github.com/Azure/azure-sdk-for-java</url>
  </scm>

  <properties>
    <jacoco.min.linecoverage>0.70</jacoco.min.linecoverage>
    <jacoco.min.branchcoverage>0.45</jacoco.min.branchcoverage>
    <jacoco.skip>false</jacoco.skip>
    <!-- Configures the Java 9+ run to perform the required module exports, opens, and reads that are necessary for testing but shouldn't be part of the module-info. -->
    <javaModulesSurefireArgLine>
      --add-opens com.azure.communication.common/com.azure.communication.common.implementation=ALL-UNNAMED
    </javaModulesSurefireArgLine>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-core</artifactId>
      <version>1.34.0</version> <!-- {x-version-update;com.azure:azure-core;dependency} -->
    </dependency>
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-communication-common</artifactId>
      <version>1.2.3</version> <!-- {x-version-update;com.azure:azure-communication-common;dependency} -->
    </dependency>
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-communication-identity</artifactId>
      <version>1.4.1</version> <!-- {x-version-update;com.azure:azure-communication-identity;dependency} -->
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-core-test</artifactId>
      <version>1.13.0</version> <!-- {x-version-update;com.azure:azure-core-test;dependency} -->
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.nimbusds</groupId>
      <artifactId>nimbus-jose-jwt</artifactId>
      <version>9.22</version> <!-- {x-version-update;com.nimbusds:nimbus-jose-jwt;external_dependency} -->
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.9.1</version> <!-- {x-version-update;org.junit.jupiter:junit-jupiter-api;external_dependency} -->
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <version>5.9.1</version> <!-- {x-version-update;org.junit.jupiter:junit-jupiter-engine;external_dependency} -->
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-params</artifactId>
      <version>5.9.1</version> <!-- {x-version-update;org.junit.jupiter:junit-jupiter-params;external_dependency} -->
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-core-http-okhttp</artifactId>
      <version>1.11.4</version> <!-- {x-version-update;com.azure:azure-core-http-okhttp;dependency} -->
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>0.8.8</version> <!-- {x-version-update;org.jacoco:jacoco-maven-plugin;external_dependency} -->
        <configuration>
          <includes>
            <include>com/azure/communication/chat/*.class</include>
          </includes>
        </configuration>
        <executions>
          <execution>
            <id>coverage-report</id>
            <phase>verify</phase>
            <goals>
              <goal>report</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <version>3.0.0-M3</version> <!-- {x-version-update;org.apache.maven.plugins:maven-enforcer-plugin;external_dependency} -->
        <configuration>
          <rules>
            <bannedDependencies>
              <includes>
                <include>com.azure:*</include>
              </includes>
            </bannedDependencies>
          </rules>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII" />
    <title> Uninstalling Vagrant - Vagrant Documentation</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <link href="./../../stylesheets/bootstrap-2bdef9a2.css" media="screen" rel="stylesheet" />
    <link href="./../../stylesheets/vagrantup-d5d54c59.css" media="screen" rel="stylesheet" />

    <link href="./../..//fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet" />

        Vagrant Documentation

            Home

                  Contents

                    Overview

                    Why Vagrant?

                    Installation

                      Backwards Compatibility

                      Upgrading

                      Upgrading from 1.0.x

                      Uninstallation

                    Getting Started

                    Command-Line Interface

                    Vagrantfile

                    Boxes

                    Provisioning

                    Networking

                    Synced Folders

                    Multi-Machine

                    Providers

                    VirtualBox

                    VMware

                    Plugins

                    Debugging

Uninstalling Vagrant

Uninstalling Vagrant is easy and straightforward. You can either uninstall the Vagrant binary, the user data, or both. The sections below cover how to do this on every platform.

Removing the Vagrant Program

Removing the Vagrant program will remove the vagrant binary and all dependencies from your machine. After uninstalling the program, you can always reinstall again using standard methods.

On Windows, uninstall using the add/remove programs section of the control panel.

On Mac OS X, remove the /Applications/Vagrant directory and the /usr/bin/vagrant file.

On Linux, remove the /opt/vagrant directory and the /usr/bin/vagrant file.

Removing User Data

Removing the user data will remove all boxes, plugins, and any stored state that may be used by Vagrant. Removing the user data effectively makes Vagrant think it is once again a fresh install.

On every platform, remove the ~/.vagrant.d directory to delete the user data.

Running Vagrant will automatically regenerate any data necessary to run, so it is safe to remove the user data at any time.

                  Documentation

                  About

                  Support

Download

                  by

 © 2013 HashiCorp


text:
<!DOCTYPE HTML>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Galeria - ValeFut</title>
    <link rel="icon"
      type="image/png"
      href="images/vale-p.png" />

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700" rel="stylesheet" type="text/css">

    <link href="css/agency.min.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Voltar

                        Galeria de Fotos

Galeria

ValeFut

Clientes

Veja todos os nossos Clientes!

Ernaldo

PSG

Marcos Reis

Real Madrid

Fábio

São Paulo

Matheus

São Paulo

Tiago

PSG

Thiago Cruz

PSG

Leandro Cruz

Portugal e Bayern

Junior

Arsenal

Jackson

Corinthians

Rafael

Corinthians

Junior

Real Madrid

Rodrigo e Cris

Real Madrid e Barcelona

Allison

Calça Barcelona

Malan Junior

Flamengo

Anderson

Flamengo

Diego e Jaime

City e Flamengo

Rhones

Barcelona

Leandro e Emily

Portugal e Real Madrid

Luckas

Real Madrid

Leandro

Real Madrid

Cristina

Barcelona

Jackson Elves

Brasil

Brow

Real Madrid

Duilio

Real Madrid

Ernaldo

Barcelona

Claudio

Corinthians

Eduardo

França

Icaro

Barcelona

Leandro

PSG

Claudio

Brasil

Danilo

Portugal

Eduardo

Barcelona

Luckas

Camisa Real Madrid Home 2016/17 [Player]

Fechar

Leandro Cruz

Camisa Real Madrid 2017/18 Home [Torcedor]

Fechar

Cristina Nunes

Camisa Barcelona 2017/18 Home Feminina [Torcedor]

Fechar

Brow

Camisa Real Madrid 2017/18 Home [Torcedor]

Fechar

Duilio

Camisa Real Madrid 2016/17 Home [Torcedor]

Fechar

Ernaldo

Camisa Barcelona 2017/18 Home [Torcedor]

Fechar

Claudio Junior

Camisa Corinthians 2016 Third [Torcedor]

Fechar

Eduardo Mororó

Camisa França 2017 Home [Player]

Fechar

Ícaro Solon

Camisa Barcelona 2016/17 Home [Torcedor]

Fechar

Claudio Junior

Camisa Barsil 2017 Home [Player]

Fechar

Danilo Alves

Camisa Portugal 2017 Away [Player]

Fechar

Leandro Reis

Camisa PSG 2016 Third [Player]

Fechar

Eduardo Vieira

Camisa Barcelona 2016/17 Home [Torcedor]

Fechar

Jackson Elves

Camisa Brasil 2017 Home [Jogador]

Fechar

Emily Thais e Leandro Cruz

Camisa Real Madrid Away 2017/18 [Woman] e Camisa Portugal 2017 Away [Jogador]

Fechar

Rhones Ferreira

Camisa Barcelona 2017/18 Home [Torcedor]

Fechar

Diego Silva e Jaime Dantas

Camisa Manchester City 2017/18 Home [Jogador]

Camisa Flamengo 2017/18 Home [Torcedor]

Fechar

Anderson Diego

Camisa Flamengo [Torcedor]

Fechar

Malan Junior

Camisa Flamengo [Torcedor]

Fechar

Allison

Calça Barcelona [Treino]

Fechar

Rodrigo e Cristina

Camisa Real Madrid [Jogador]

Camisa Barcelona [Woman]

Fechar

Junior Silva

Camisa Real Madrid [Torcedor]

Fechar

Rafael de Sá

Camisa Corinthians [Torcedor]

Fechar

Jackson Elves

Camisa Corinthians [Torcedor]

Fechar

Junior Silva

Camisa Arsenal [Torcedor]

Fechar

Leandro Cruz

Camisa Portugal [Jogador] e Calça Bayern

Fechar

Thiago Cruz

Camisa PSG [Torcedor]

Fechar

Tiago

Camisa PSG [Jogador]

Fechar

Matheus Henrique

Camisa São Paulo [Torcedor]

Fechar

Fabio Amorim

Camisa São Paulo [Torcedor]

Fechar

Marcos Reis

Camisa Real Madrid [Jogador]

Fechar

Ernaldo Rodrigues

Camisa PSG [Jogador]

Fechar


text:
/* true CSS page, we can fix this */

body {
    background-image: url('img/indy_skyline.jpeg');
    background-repeat: no-repeat;
    background-attachment: fixed;
    align-content: center;
}

h1{
	font-size:48px;
	padding: 5px;
	font-family:'Shrikhand', cursive;

	/* positioning */
	position: absolute;
    left: 0;
    width: 100%;
    text-align: center;
}

}

#title_box{
	width: 100vh;
	height: 50vh;
	color: red;
}

#title{
	margin:0;
	border:0;

	height:20vh ;
	width: 30vw;

	padding: 5px;
	background-color: grey;
}

#back_img{
  width: 100vw;
  height: 100vh;
  background-position: center center;
  background-repeat: no-repeat;

}

.panels{
	background-color: grey;
}

#daddy_div{
	background-color: grey;
	opacity: 50%;
	border-radius: 5px;
}

.container{
	font-size: 20px;
}

hr {
	display: block;
	margin-top: 30px;
	margin-bottom: 30px;
	margin-left: 10%;
	margin-right: 20%;
	border-style: double;

	border-right: transparent;
	border-left: transparent;

	border-top-color: black;

	border-width: 3px;
	color: black;
	height: 10px;
  	}


text:
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2018-2020 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

#ifndef LIBCOUCHBASE_couchbase_internalstructs_h__
#define LIBCOUCHBASE_couchbase_internalstructs_h__

#include <libcouchbase/utils.h>
#include "mutation_token.hh"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @private
 */
struct lcb_HTTP_ERROR_CONTEXT_ {
    lcb_STATUS rc;
    uint32_t response_code;
    const char *path;
    size_t path_len;
    const char *body;
    size_t body_len;
    const char *endpoint;
    size_t endpoint_len;
};

struct lcb_CREATEOPTS_ {
    lcb_INSTANCE_TYPE type;
    const char *connstr;
    size_t connstr_len;
    struct lcb_io_opt_st *io;
    const char *username;
    size_t username_len;
    const char *password;
    size_t password_len;
    const lcb_LOGGER *logger;
    const lcb_AUTHENTICATOR *auth;
    /* override bucket in connection string */
    const char *bucket;
    size_t bucket_len;
    lcbtrace_TRACER *tracer;
    const lcbmetrics_METER *meter;
};

/**
 * @name Receiving Responses
 * @details
 *
 * This section describes the APIs used in receiving responses.
 *
 * Each command will have a callback invoked (typically once, for some commands
 * this may be more than once) with a response structure. The response structure
 * will be of a type that extends lcb_RESPBASE. The response structure should
 * not be modified and any of its fields should be considered to point to memory
 * which will be released after the callback exits.
 *
 * The common response header contains the lcb_RESPBASE::cookie field which
 * is the pointer to your application context (passed as the second argument
 * to the spooling function) and allows you to associate a specific command
 * with a specific response.
 *
 * The header will also contain the key (lcb_RESPBASE::key) field which can
 * also help identify the specific command. This is useful if you maintain a
 * single _cookie_ for multiple commands, and have per-item specific data
 * you wish to associate within the _cookie_ itself.
 *
 * Success or failure of the operation is signalled through the lcb_RESPBASE::rc
 * field. Note that even in the case of failure, the lcb_RESPBASE::cookie and
 * lcb_RESPBASE::key fields will _always_ be populated.
 *
 * Most commands also return the CAS of the item (as it exists on the server)
 * and this is placed inside the lcb_RESPBASE::cas field, however it is
 * only valid in the case where lcb_RESPBASE::rc is LCB_SUCCESS.
 *
 * @{
 */

/**
 * Flag for lcb_CMDBASE::cmdflags which indicates that the lcb_CMDBASE::cookie
 * is a special callback object. This flag is used internally within the
 * library.
 *
 * @internal
 */
#define LCB_CMD_F_INTERNAL_CALLBACK (1u << 0u)

/**
 * If this flag is set, then multiple authentication credentials will be passed
 * to the server. By default only the bucket's credentials (i.e. bucket SASL
 * password) are passed.
 */
#define LCB_CMD_F_MULTIAUTH (1u << 1u)

#define LCB_CMD_F_CLONE (1u << 2u)

/**@}*/

/**
 * @committed
 *
 * @brief Set the value buffer for the command. This may be used when the new
 * value is a single contiguous buffer.
 *
 * @param scmd an lcb_CMDSTORE pointer
 * @param valbuf the buffer for the value
 * @param vallen the length of the buffer
 *
 * The buffer needs to remain valid only until the command is passed to the
 * lcb_store3() function.
 */
#define LCB_CMD_SET_VALUE(scmd, valbuf, vallen)                                                                        \
    do {                                                                                \
        (scmd)->value.vtype = LCB_KV_COPY;                                                                             \
        (scmd)->value.u_buf.contig.bytes = valbuf;                                                                     \
        (scmd)->value.u_buf.contig.nbytes = vallen;                                                                    \
    } while (0);

/**
 * @committed
 *
 * @brief Set value from a series of input buffers. This may be used when the
 * input buffer is not contiguous. Using this call eliminates the need for
 * creating a temporary contiguous buffer in which to store the value.
 *
 * @param scmd the command which needs a value
 * @param iovs an array of @ref lcb_IOV structures
 * @param niovs number of items in the array.
 *
 * The buffers (and the IOV array itself)
 * need to remain valid only until the scheduler function is called. Once the
 * scheduling function is called, the buffer contents are copied into the
 * library's internal buffers.
 */
#define LCB_CMD_SET_VALUEIOV(scmd, iovs, niovs)                                                                        \
    do {                                                                                \
        (scmd)->value.vtype = LCB_KV_IOVCOPY;                                                                          \
        (scmd)->value.u_buf.multi.iov = iovs;                                                                          \
        (scmd)->value.u_buf.multi.niov = niovs;                                                                        \
    } while (0);

typedef struct lcb_RESPOBSERVE_ lcb_RESPOBSERVE;
typedef struct lcb_CMDOBSERVE_ lcb_CMDOBSERVE;

typedef struct lcb_RESPENDURE_ lcb_RESPENDURE;
typedef struct lcb_CMDENDURE_ lcb_CMDENDURE;

/**
 * @ingroup lcb-kv-api
 * @defgroup lcb-mctx MULTICMD API
 * @addtogroup lcb-mctx
 * @{
 */
/**
 * Multi Command Context API
 * Some commands (notably, OBSERVE and its higher level equivalent, endue)
 * are handled more efficiently at the cluster side by stuffing multiple
 * items into a single packet.
 *
 * This structure defines three function pointers to invoke. The #addcmd()
 * function will add a new command to the current packet, the #done()
 * function will schedule the packet(s) into the current scheduling context
 * and the #fail() function will destroy the context without progressing
 * further.
 *
 * Some commands will return an lcb_MULTICMD_CTX object to be used for this
 * purpose:
 *
 * @code{.c}
 * lcb_MUTLICMD_CTX *ctx = lcb_observe3_ctxnew(instance);
 *
 * lcb_CMDOBSERVE cmd = { 0 };
 * LCB_CMD_SET_KEY(&cmd, "key1", strlen("key1"));
 * ctx->addcmd(ctx, &cmd);
 * LCB_CMD_SET_KEY(&cmd.key, "key2", strlen("key2"));
 * ctx->addcmd(ctx, &cmd);
 * LCB_CMD_SET_KEY(&cmd.key, "key3", strlen("key3"));
 * ctx->addcmd(ctx, &cmd);
 *
 * ctx->done(ctx);
 * lcb_wait(instance, LCB_WAIT_DEFAULT);
 * @endcode
 */
typedef struct lcb_MULTICMD_CTX_st {
    /**
     * Add a command to the current context
     * @param ctx the context
     * @param cmd the command to add. Note that `cmd` may be a subclass of lcb_CMDBASE
     * @return LCB_SUCCESS, or failure if a command could not be added.
     */
    lcb_STATUS (*add_observe)(struct lcb_MULTICMD_CTX_st *ctx, const lcb_CMDOBSERVE *cmd);
    lcb_STATUS (*add_endure)(struct lcb_MULTICMD_CTX_st *ctx, const lcb_CMDENDURE *cmd);

    /**
     * Indicate that no more commands are added to this context, and that the
     * context should assemble the packets and place them in the current
     * scheduling context
     * @param ctx The multi context
     * @param cookie The cookie for all commands
     * @return LCB_SUCCESS if scheduled successfully, or an error code if there
     * was a problem constructing the packet(s).
     */
    lcb_STATUS (*done)(struct lcb_MULTICMD_CTX_st *ctx, void *cookie);

    /**
     * Indicate that no more commands should be added to this context, and that
     * the context should not add its contents to the packet queues, but rather
     * release its resources. Called if you don't want to actually perform
     * the operations.
     * @param ctx
     */
    void (*fail)(struct lcb_MULTICMD_CTX_st *ctx);

    /**
     * Associate parent tracing span with the group operation
     *
     * @param ctx The multi context
     * @param span Parent span
     */
    void (*setspan)(struct lcb_MULTICMD_CTX_st *ctx, lcbtrace_SPAN *span);
} lcb_MULTICMD_CTX;
/**@}*/

/**
 * @ingroup lcb-kv-api
 * @defgroup lcb-durability Durability
 * @brief Ensure persistence and mutation of documents
 * @addtogroup lcb-durability
 * @{
 */

/**
 * @name Wait for a mutation to be persisted/replicated
 * @{
 */

/**
 * Type of durability polling to use.
 */
typedef enum {
    /**
     * Use the preferred durability. If ::LCB_CNTL_FETCH_MUTATION_TOKENS is
     * enabled and the server version is 4.0 or greater then ::LCB_DURABILITY_MODE_SEQNO
     * is used. Otherwise ::LCB_DURABILITY_MODE_CAS is used.
     */
    LCB_DURABILITY_MODE_DEFAULT = 0,

    /**
     * Explicitly request CAS-based durability. This is done by checking the
     * CAS of the item on each server with the item specified in the input.
     * The durability operation is considered complete when all items' CAS
     * values match. If the CAS value on the master node changes then the
     * durability operation will fail with ::LCB_ERR_DOCUMENT_EXISTS.
     *
     * @note
     * CAS may change either because of a failover or because of another
     * subsequent mutation. These scenarios are possible (though unlikely).
     * The ::LCB_DURABILITY_MODE_SEQNO mode is not subject to these constraints.
     */
    LCB_DURABILITY_MODE_CAS,

    /**
     * Use sequence-number based polling. This is done by checking the current
     * "mutation sequence number" for the given mutation. To use this mode
     * either an explicit @ref lcb_MUTATION_TOKEN needs to be passed, or
     * the ::LCB_CNTL_DURABILITY_MUTATION_TOKENS should be set, allowing
     * the caching of the latest mutation token for each vBucket.
     */
    LCB_DURABILITY_MODE_SEQNO
} lcb_DURMODE;

/** @brief Options for lcb_endure3_ctxnew() */
typedef struct {
    /**
     * Upper limit in microseconds from the scheduling of the command. When
     * this timeout occurs, all remaining non-verified keys will have their
     * callbacks invoked with @ref LCB_ERR_TIMEOUT.
     *
     * If this field is not set, the value of @ref LCB_CNTL_DURABILITY_TIMEOUT
     * will be used.
     */
    lcb_U32 timeout;

    /**
     * The durability check may involve more than a single call to observe - or
     * more than a single packet sent to a server to check the key status. This
     * value determines the time to wait (in microseconds)
     * between multiple probes for the same server.
     * If not set, the @ref LCB_CNTL_DURABILITY_INTERVAL will be used
     * instead.
     */
    lcb_U32 interval;

    /**
     * how many nodes the key should be persisted to (including master).
     * If set to 0 then persistence will not be checked. If set to a large
     * number (i.e. UINT16_MAX) and #cap_max is also set, will be set to the
     * maximum number of nodes to which persistence is possible (which will
     * always contain at least the master node).
     *
     * The maximum valid value for this field is
     * 1 + the total number of configured replicas for the bucket which are part
     * of the cluster. If this number is higher then it will either be
     * automatically capped to the maximum available if (#cap_max is set) or
     * will result in an ::LCB_ERR_DURABILITY_TOO_MANY error.
     */
    lcb_U16 persist_to;

    /**
     * how many nodes the key should be persisted to (excluding master).
     * If set to 0 then replication will not be checked. If set to a large
     * number (i.e. UINT16_MAX) and #cap_max is also set, will be set to the
     * maximum number of nodes to which replication is possible (which may
     * be 0 if the bucket is not configured for replicas).
     *
     * The maximum valid value for this field is the total number of configured
     * replicas which are part of the cluster. If this number is higher then
     * it will either be automatically capped to the maximum available
     * if (#cap_max is set) or will result in an ::LCB_ERR_DURABILITY_TOO_MANY
     * error.
     * */
    lcb_U16 replicate_to;

    /**
     * this flag inverts the sense of the durability check and ensures that
     * the key does *not* exist. This should be used if checking durability
     * after an lcb_remove3() operation.
     */
    lcb_U8 check_delete;

    /**
     * If replication/persistence requirements are excessive, cap to
     * the maximum available
     */
    lcb_U8 cap_max;

    /**
     * Set the polling method to use.
     * The value for this field should be one of the @ref lcb_DURMODE constants.
     */
    lcb_U8 pollopts;
} lcb_DURABILITYOPTSv0;

/**@brief Options for lcb_endure3_ctxnew() (wrapper)
 * @see lcb_DURABILITYOPTSv0 */
typedef struct lcb_durability_opts_st {
    int version;
    union {
        lcb_DURABILITYOPTSv0 v0;
    } v;
} lcb_durability_opts_t;

/**
 * @committed
 *
 * @details
 * Ensure a key is replicated to a set of nodes
 *
 * The lcb_endure3_ctxnew() API is used to wait asynchronously until the item
 * have been persisted and/or replicated to at least the number of nodes
 * specified in the durability options.
 *
 * The command is implemented by sending a series of `OBSERVE` broadcasts
 * (see lcb_observe3_ctxnew()) to all the nodes in the cluster which are either
 * master or replica for a specific key. It polls repeatedly
 * (see lcb_DURABILITYOPTSv0::interval) until all the items have been persisted and/or
 * replicated to the number of nodes specified in the criteria, or the timeout
 * (aee lcb_DURABILITYOPTsv0::timeout) has been reached.
 *
 * The lcb_DURABILITYOPTSv0::persist_to and lcb_DURABILITYOPTS::replicate_to
 * control the number of nodes the item must be persisted/replicated to
 * in order for the durability polling to succeed.
 *
 * @brief Return a new command context for scheduling endure operations
 * @param instance the instance
 * @param options a structure containing the various criteria needed for
 * durability requirements
 * @param[out] err Error code if a new context could not be created
 * @return the new context, or NULL on error. Note that in addition to memory
 * allocation failure, this function might also return NULL because the `options`
 * structure contained bad values. Always check the `err` result.
 *
 * @par Scheduling Errors
 * The following errors may be encountered when scheduling:
 *
 * @cb_err ::LCB_ERR_DURABILITY_TOO_MANY if either lcb_DURABILITYOPTS::persist_to or
 * lcb_DURABILITYOPTS::replicate_to is too big. `err` may indicate this.
 * @cb_err ::LCB_ERR_DURABILITY_NO_MUTATION_TOKENS if no relevant mutation token
 * could be found for a given command (this is returned from the relevant
 * lcb_MULTICMD_CTX::addcmd call).
 * @cb_err ::LCB_DUPLICATE_COMMANDS if using CAS-based durability and the
 * same key was submitted twice to lcb_MULTICMD_CTX::addcmd(). This error is
 * returned from lcb_MULTICMD_CTX::done()
 *
 * @par Callback Errors
 * The following errors may be returned in the callback:
 * @cb_err ::LCB_ERR_TIMEOUT if the criteria could not be verified within the
 * accepted timeframe (see lcb_DURABILITYOPTSv0::timeout)
 * @cb_err ::LCB_ERR_DOCUMENT_EXISTS if using CAS-based durability and the item's
 * CAS has been changed on the master node
 * @cb_err ::LCB_ERR_MUTATION_LOST if using sequence-based durability and the
 * server has detected that data loss has occurred due to a failover.
 *
 * @par Creating request context
 * @code{.c}
 * lcb_durability_opts_t dopts;
 * lcb_STATUS rc;
 * memset(&dopts, 0, sizeof dopts);
 * dopts.v.v0.persist_to = -1;
 * dopts.v.v0.replicate_to = -1;
 * dopts.v.v0.cap_max = 1;
 * mctx = lcb_endure3_ctxnew(instance, &dopts, &rc);
 * // Check mctx != NULL and rc == LCB_SUCCESS
 * @endcode
 *
 * @par Adding keys - CAS
 * This can be used to add keys using CAS-based durability. This shows an
 * example within a store callback.
 * @code{.c}
 * lcb_RESPSTORE *resp = get_store_response();
 * lcb_CMDENDURE cmd = { 0 };
 * LCB_CMD_SET_KEY(&cmd, resp->key, resp->nkey);
 * cmd.cas = resp->cas;
 * rc = mctx->addcmd(mctx, (const lcb_CMDBASE*)&cmd);
 * rc = mctx->done(mctx, cookie);
 * @endcode
 *
 * @par Adding keys - explicit sequence number
 * Shows how to use an explicit sequence number as a basis for polling
 * @code{.c}
 * // during instance creation:
 * lcb_cntl_string(instance, "enable_mutation_tokens", "true");
 * lcb_connect(instance);
 * // ...
 * lcb_RESPSTORE *resp = get_store_response();
 * lcb_CMDENDURE cmd = { 0 };
 * LCB_CMD_SET_KEY(&cmd, resp->key, resp->nkey);
 * cmd.mutation_token = &resp->mutation_token;
 * cmd.cmdflags |= LCB_CMDENDURE_F_MUTATION_TOKEN;
 * rc = mctx->addcmd(mctx, (const lcb_CMDBASE*)&cmd);
 * rc = mctx->done(mctx, cookie);
 * @endcode
 *
 * @par Adding keys - implicit sequence number
 * Shows how to use an implicit mutation token (internally tracked by the
 * library) for durability:
 * @code{.c}
 * // during instance creation
 * lcb_cntl_string(instance, "enable_mutation_tokens", "true");
 * lcb_cntl_string(instance, "dur_mutation_tokens", "true");
 * lcb_connect(instance);
 * // ...
 * lcb_CMDENDURE cmd = { 0 };
 * LCB_CMD_SET_KEY(&cmd, "key", strlen("key"));
 * mctx->addcmd(mctx, (const lcb_CMDBASE*)&cmd);
 * mctx->done(mctx, cookie);
 * @endcode
 *
 * @par Response
 * @code{.c}
 * lcb_install_callback3(instance, LCB_CALLBACK_ENDURE, dur_callback);
 * void dur_callback(lcb_INSTANCE *instance, int cbtype, const lcb_RESPBASE *rb)
 * {
 *     const lcb_RESPENDURE *resp = (const lcb_RESPENDURE*)rb;
 *     printf("Durability polling result for %.*s.. ", (int)resp->nkey, resp->key);
 *     if (resp->ctx.rc != LCB_SUCCESS) {
 *         printf("Failed: %s\n", lcb_strerror_short(resp->ctx.rc);
 *         return;
 *     }
 * }
 * @endcode
 */
LIBCOUCHBASE_API
lcb_MULTICMD_CTX *lcb_endure3_ctxnew(lcb_INSTANCE *instance, const lcb_durability_opts_t *options, lcb_STATUS *err);

#define LCB_DURABILITY_VALIDATE_CAPMAX (1 << 1)

/**
 * @committed
 *
 * Validate durability settings.
 *
 * This function will validate (and optionally modify) the settings. This is
 * helpful to ensure the durability options are valid _before_ issuing a command
 *
 * @param instance the instance
 *
 * @param[in,out] persist_to The desired number of servers to persist to.
 *  If the `CAPMAX` flag is set, on output this will contain the effective
 *  number of servers the item can be persisted to
 *
 * @param[in,out] replicate_to The desired number of servers to replicate to.
 *  If the `CAPMAX` flag is set, on output this will contain the effective
 *  number of servers the item can be replicated to
 *
 * @param options Options to use for validating. The only recognized option
 *  is currently `LCB_DURABILITY_VALIDATE_CAPMAX` which has the same semantics
 *  as lcb_DURABILITYOPTSv0::cap_max.
 *
 * @return LCB_SUCCESS on success
 * @return LCB_ERR_DURABILITY_TOO_MANY if the requirements exceed the number of
 *  servers currently available, and `CAPMAX` was not specifie
 * @return LCB_ERR_INVALID_ARGUMENT if both `persist_to` and `replicate_to` are 0.
 */
LIBCOUCHBASE_API
lcb_STATUS lcb_durability_validate(lcb_INSTANCE *instance, lcb_U16 *persist_to, lcb_U16 *replicate_to, int options);

/**@} (NAME) */

/**
 * @name Retrieve current persistence/replication status
 * @{
 */

/**
 * @brief Create a new multi context for an observe operation
 * @param instance the instance
 * @return a new multi command context, or NULL on allocation failure.
 * @committed
 *
 * Note that the callback for this command will be invoked multiple times,
 * one for each node. To determine when no more callbacks will be invoked,
 * check for the LCB_RESP_F_FINAL flag inside the lcb_RESPOBSERVE::rflags
 * field.
 *
 * @code{.c}
 * void callback(lcb_INSTANCE, lcb_CALLBACK_TYPE, const lcb_RESPOBSERVE *resp)
 * {
 *   if (resp->rflags & LCB_RESP_F_FINAL) {
 *     return;
 *   }
 *
 *   printf("Got status for key %.*s\n", (int)resp->nkey, resp->key);
 *   printf("  Node Type: %s\n", resp->ismaster ? "MASTER" : "REPLICA");
 *   printf("  Status: 0x%x\n", resp->status);
 *   printf("  Current CAS: 0x%"PRIx64"\n", resp->cas);
 * }
 *
 * lcb_MULTICMD_CTX *mctx = lcb_observe3_ctxnew(instance);
 * lcb_CMDOBSERVE cmd = { 0 };
 * LCB_CMD_SET_KEY(&cmd, "key", 3);
 * mctx->addcmd(mctx, (lcb_CMDBASE *)&cmd);
 * mctx->done(mctx, cookie);
 * lcb_install_callback3(instance, LCB_CALLBACK_OBSERVE, (lcb_RESP_cb)callback);
 * @endcode
 *
 * @warning
 * Operations created by observe cannot be undone using lcb_sched_fail().
 */
LIBCOUCHBASE_API
lcb_MULTICMD_CTX *lcb_observe3_ctxnew(lcb_INSTANCE *instance);

typedef struct lcb_RESPOBSEQNO_ lcb_RESPOBSEQNO;
typedef struct lcb_CMDOBSEQNO_ lcb_CMDOBSEQNO;

/**
 * @volatile
 * @brief Get the persistence/replication status for a given mutation token
 * @param instance the handle
 * @param cookie callback cookie
 * @param cmd the command
 */
LIBCOUCHBASE_API
lcb_STATUS lcb_observe_seqno3(lcb_INSTANCE *instance, const void *cookie, const lcb_CMDOBSEQNO *cmd);

/**@} (Name: OBSERVE) */

typedef enum { LCB_DURABILITY_NONE = 0, LCB_DURABILITY_POLL = 1, LCB_DURABILITY_SYNC = 2 } lcb_DURABILITY_MODE;

/**@ingroup lcb-public-api
 * @defgroup lcb-subdoc Sub-Document API
 * @brief Experimental in-document API access
 * @details The sub-document API uses features from the upcoming Couchbase
 * 4.5 release which allows access to parts of the document. These parts are
 * called _sub-documents_ and can be accessed using the sub-document API
 *
 * @addtogroup lcb-subdoc
 * @{
 */

/**@ingroup lcb-public-api
 * @defgroup lcb-misc-cmds Miscellaneous Commands
 * @brief Additional miscellaneous commands which can be executed on the server.
 *
 * @addtogroup lcb-misc-cmds
 * @{
 */

/**@} (Name: Stats) */

/**@} (Group: Misc) */

/**
 * @ingroup lcb-public-api
 * @defgroup lcb-mutation-tokens Mutation Tokens
 *
 * @details Mutation Tokens are returned with mutations if
 * ::LCB_CNTL_FETCH_MUTATION_TOKENS is enabled (off by default). Mutation tokens
 * are largely of internal use, but can be used by N1QL queries and durability
 * requirement polling
 *
 * @addtogroup lcb-mutation-tokens
 * @{
 */

/**
 * @brief
 * Structure representing a synchronization token. This token may be used
 * for durability operations and N1QL queries. The contents of this structure
 * should be considered opaque, and accessed via the various macros
 * @struct lcb_MUTATION_TOKEN
 */

/** Get the vBucket UUID */
#define LCB_MUTATION_TOKEN_ID(p) ((p)->uuid_)
/** Get the sequence number */
#define LCB_MUTATION_TOKEN_SEQ(p) ((p)->seqno_)
/** Get the vBucket number itself */
#define LCB_MUTATION_TOKEN_VB(p) ((p)->vbid_)
/** Whether this mutation token has valid contents */
#define LCB_MUTATION_TOKEN_ISVALID(p) (p && !((p)->uuid_ == 0 && (p)->seqno_ == 0 && (p)->vbid_ == 0))

/**@} (Group: Mutation Tokens) */

#define LCB_CMD_CLONE(TYPE, SRC, DST)                                                                                \
    do {                                                                                \
        TYPE *ret = (TYPE *)calloc(1, sizeof(TYPE));                                                                   \
        memcpy(ret, SRC, sizeof(TYPE));                                                                                \
        if (SRC->key.contig.bytes) {                                                                                \
            ret->key.type = LCB_KV_COPY;                                                                               \
            ret->key.contig.bytes = calloc(SRC->key.contig.nbytes, sizeof(uint8_t));                                   \
            ret->key.contig.nbytes = SRC->key.contig.nbytes;                                                           \
            memcpy((void *)ret->key.contig.bytes, SRC->key.contig.bytes, ret->key.contig.nbytes);                      \
        }                                                                                \
        ret->cmdflags |= LCB_CMD_F_CLONE;                                                                              \
        *DST = ret;                                                                                \
    } while (0)

#define LCB_CMD_DESTROY_CLONE(cmd)                                                                                \
    do {                                                                                \
        if (cmd->cmdflags & LCB_CMD_F_CLONE) {                                                                         \
            if (cmd->key.contig.bytes && cmd->key.type == LCB_KV_COPY) {                                               \
                free((void *)cmd->key.contig.bytes);                                                                   \
            }                                                                                \
        }                                                                                \
        free(cmd);                                                                                \
    } while (0)

#define LCB_CMD_CLONE_WITH_VALUE(TYPE, SRC, DST)                                                                       \
    do {                                                                                \
        TYPE *ret = (TYPE *)calloc(1, sizeof(TYPE));                                                                   \
        memcpy(ret, SRC, sizeof(TYPE));                                                                                \
        if (SRC->key.contig.bytes) {                                                                                \
            ret->key.type = LCB_KV_COPY;                                                                               \
            ret->key.contig.bytes = calloc(SRC->key.contig.nbytes, sizeof(uint8_t));                                   \
            ret->key.contig.nbytes = SRC->key.contig.nbytes;                                                           \
            memcpy((void *)ret->key.contig.bytes, SRC->key.contig.bytes, ret->key.contig.nbytes);                      \
        }                                                                                \
        switch (SRC->value.vtype) {                                                                                \
            case LCB_KV_COPY:                                                                                \
            case LCB_KV_CONTIG:                                                                                \
                ret->value.vtype = LCB_KV_COPY;                                                                        \
                ret->value.u_buf.contig.bytes = calloc(SRC->value.u_buf.contig.nbytes, sizeof(uint8_t));               \
                ret->value.u_buf.contig.nbytes = SRC->value.u_buf.contig.nbytes;                                       \
                memcpy((void *)ret->value.u_buf.contig.bytes, SRC->value.u_buf.contig.bytes,                           \
                       ret->value.u_buf.contig.nbytes);                                                                \
                break;                                                                                \
            case LCB_KV_IOV:                                                                                \
            case LCB_KV_IOVCOPY:                                                                                \
                if (SRC->value.u_buf.multi.iov) {                                                                      \
                    ret->value.vtype = LCB_KV_IOVCOPY;                                                                 \
                    const lcb_FRAGBUF *msrc = &SRC->value.u_buf.multi;                                                 \
                    lcb_FRAGBUF *mdst = &ret->value.u_buf.multi;                                                       \
                    mdst->total_length = 0;                                                                            \
                    mdst->iov = (lcb_IOV *)calloc(msrc->niov, sizeof(lcb_IOV));                                        \
                    for (size_t ii = 0; ii < msrc->niov; ii++) {                                                       \
                        if (msrc->iov[ii].iov_len) {                                                                   \
                            mdst->iov[ii].iov_base = calloc(msrc->iov[ii].iov_len, sizeof(uint8_t));                   \
                            mdst->iov[ii].iov_len = msrc->iov[ii].iov_len;                                             \
                            mdst->total_length += msrc->iov[ii].iov_len;                                               \
                            memcpy(mdst->iov[ii].iov_base, msrc->iov[ii].iov_base, mdst->iov[ii].iov_len);             \
                        }                                                                                \
                    }                                                                                \
                }                                                                                \
                break;                                                                                \
            default:                                                                                \
                free(ret);                                                                                \
                return LCB_ERR_INVALID_ARGUMENT;                                                                       \
                break;                                                                                \
        }                                                                                \
        ret->cmdflags |= LCB_CMD_F_CLONE;                                                                              \
        *DST = ret;                                                                                \
    } while (0)

#define LCB_CMD_DESTROY_CLONE_WITH_VALUE(cmd)                                                                          \
    do {                                                                                \
        if (cmd->cmdflags & LCB_CMD_F_CLONE) {                                                                         \
            if (cmd->key.contig.bytes && cmd->key.type == LCB_KV_COPY) {                                               \
                free((void *)cmd->key.contig.bytes);                                                                   \
            }                                                                                \
            switch (cmd->value.vtype) {                                                                                \
                case LCB_KV_COPY:                                                                                \
                case LCB_KV_CONTIG:                                                                                \
                    free((void *)cmd->value.u_buf.contig.bytes);                                                       \
                    break;                                                                                \
                case LCB_KV_IOV:                                                                                \
                case LCB_KV_IOVCOPY:                                                                                \
                    if (cmd->value.u_buf.multi.iov) {                                                                  \
                        lcb_FRAGBUF *buf = &cmd->value.u_buf.multi;                                                    \
                        for (size_t ii = 0; ii < buf->niov; ii++) {                                                    \
                            if (buf->iov[ii].iov_len) {                                                                \
                                free(buf->iov[ii].iov_base);                                                           \
                            }                                                                                \
                        }                                                                                \
                        free(cmd->value.u_buf.multi.iov);                                                              \
                    }                                                                                \
                    break;                                                                                \
                default:                                                                                \
                    break;                                                                                \
            }                                                                                \
        }                                                                                \
        free(cmd);                                                                                \
    } while (0)

#ifdef __cplusplus
}
#endif

#endif


text:
require 'securerandom'

class Token
  include Mongoid::Document
  before_save :generate_token

  field       :token, type: String
  embedded_in :user

  def generate_token
    self.token = SecureRandom.urlsafe_base64
  end
end


text:
//! [0]
QSqlQueryModel model;
model.setQuery("select * from myTable");
if (model.lastError().isValid())
    qDebug() << model.lastError();
//! [0]