text:
/*
  Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image-private.h"
#include "MagickCore/matrix.h"
#include "MagickCore/memory_.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/utility.h"

/*
  Typedef declaration.
*/
struct _MatrixInfo
{
  CacheType
    type;

  size_t
    columns,
    rows,
    stride;

  MagickSizeType
    length;

  MagickBooleanType
    mapped,
    synchronize;

  char
    path[MaxTextExtent];

  int
    file;

  void
    *elements;

  SemaphoreInfo
    *semaphore;

  size_t
    signature;
};

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   A c q u i r e M a t r i x I n f o                                         %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  AcquireMatrixInfo() allocates the ImageInfo structure.
%
%  The format of the AcquireMatrixInfo method is:
%
%      MatrixInfo *AcquireMatrixInfo(const size_t columns,const size_t rows,
%        const size_t stride,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o columns: the matrix columns.
%
%    o rows: the matrix rows.
%
%    o stride: the matrix stride.
%
%    o exception: return any errors or warnings in this structure.
%
*/

#if defined(SIGBUS)
static void MatrixSignalHandler(int status)
{
  ThrowFatalException(CacheFatalError,"UnableToExtendMatrixCache");
}
#endif

static inline MagickOffsetType WriteMatrixElements(
  const MatrixInfo *restrict matrix_info,const MagickOffsetType offset,
  const MagickSizeType length,const unsigned char *restrict buffer)
{
  register MagickOffsetType
    i;

  ssize_t
    count;

#if !defined(MAGICKCORE_HAVE_PWRITE)
  LockSemaphoreInfo(matrix_info->semaphore);
  if (lseek(matrix_info->file,offset,SEEK_SET) < 0)
    {
      UnlockSemaphoreInfo(matrix_info->semaphore);
      return((MagickOffsetType) -1);
    }
#endif
  count=0;
  for (i=0; i < (MagickOffsetType) length; i+=count)
  {
#if !defined(MAGICKCORE_HAVE_PWRITE)
    count=write(matrix_info->file,buffer+i,(size_t) MagickMin(length-i,
      (MagickSizeType) SSIZE_MAX));
#else
    count=pwrite(matrix_info->file,buffer+i,(size_t) MagickMin(length-i,
      (MagickSizeType) SSIZE_MAX),(off_t) (offset+i));
#endif
    if (count <= 0)
      {
        count=0;
        if (errno != EINTR)
          break;
      }
  }
#if !defined(MAGICKCORE_HAVE_PWRITE)
  UnlockSemaphoreInfo(matrix_info->semaphore);
#endif
  return(i);
}

static MagickBooleanType SetMatrixExtent(MatrixInfo *restrict matrix_info,
  MagickSizeType length)
{
  MagickOffsetType
    count,
    extent,
    offset;

  if (length != (MagickSizeType) ((MagickOffsetType) length))
    return(MagickFalse);
  offset=(MagickOffsetType) lseek(matrix_info->file,0,SEEK_END);
  if (offset < 0)
    return(MagickFalse);
  if ((MagickSizeType) offset >= length)
    return(MagickTrue);
  extent=(MagickOffsetType) length-1;
  count=WriteMatrixElements(matrix_info,extent,1,(const unsigned char *) "");
#if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE)
  if (matrix_info->synchronize != MagickFalse)
    (void) posix_fallocate(matrix_info->file,offset+1,extent-offset);
#endif
#if defined(SIGBUS)
  (void) signal(SIGBUS,MatrixSignalHandler);
#endif
  return(count != (MagickOffsetType) 1 ? MagickFalse : MagickTrue);
}

MagickExport MatrixInfo *AcquireMatrixInfo(const size_t columns,
  const size_t rows,const size_t stride,ExceptionInfo *exception)
{
  char
    *synchronize;

  MagickBooleanType
    status;

  MatrixInfo
    *matrix_info;

  matrix_info=(MatrixInfo *) AcquireMagickMemory(sizeof(*matrix_info));
  if (matrix_info == (MatrixInfo *) NULL)
    return((MatrixInfo *) NULL);
  (void) ResetMagickMemory(matrix_info,0,sizeof(*matrix_info));
  matrix_info->signature=MagickSignature;
  matrix_info->columns=columns;
  matrix_info->rows=rows;
  matrix_info->stride=stride;
  matrix_info->semaphore=AcquireSemaphoreInfo();
  synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE");
  if (synchronize != (const char *) NULL)
    {
      matrix_info->synchronize=IsStringTrue(synchronize);
      synchronize=DestroyString(synchronize);
    }
  matrix_info->length=(MagickSizeType) columns*rows*stride;
  if (matrix_info->columns != (size_t) (matrix_info->length/rows/stride))
    {
      (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
        "CacheResourcesExhausted","`%s'","matrix cache");
      return(DestroyMatrixInfo(matrix_info));
    }
  matrix_info->type=MemoryCache;
  status=AcquireMagickResource(AreaResource,matrix_info->length);
  if ((status != MagickFalse) &&
      (matrix_info->length == (MagickSizeType) ((size_t) matrix_info->length)))
    {
      status=AcquireMagickResource(MemoryResource,matrix_info->length);
      if (status != MagickFalse)
        {
          matrix_info->mapped=MagickFalse;
          matrix_info->elements=AcquireMagickMemory((size_t)
            matrix_info->length);
          if (matrix_info->elements == NULL)
            {
              matrix_info->mapped=MagickTrue;
              matrix_info->elements=MapBlob(-1,IOMode,0,(size_t)
                matrix_info->length);
            }
          if (matrix_info->elements == (unsigned short *) NULL)
            RelinquishMagickResource(MemoryResource,matrix_info->length);
        }
    }
  matrix_info->file=(-1);
  if (matrix_info->elements == (unsigned short *) NULL)
    {
      status=AcquireMagickResource(DiskResource,matrix_info->length);
      if (status == MagickFalse)
        {
          (void) ThrowMagickException(exception,GetMagickModule(),CacheError,
            "CacheResourcesExhausted","`%s'","matrix cache");
          return(DestroyMatrixInfo(matrix_info));
        }
      matrix_info->type=DiskCache;
      (void) AcquireMagickResource(MemoryResource,matrix_info->length);
      matrix_info->file=AcquireUniqueFileResource(matrix_info->path);
      if (matrix_info->file == -1)
        return(DestroyMatrixInfo(matrix_info));
      status=AcquireMagickResource(MapResource,matrix_info->length);
      if (status != MagickFalse)
        {
          status=SetMatrixExtent(matrix_info,matrix_info->length);
          if (status != MagickFalse)
            {
              matrix_info->elements=(void *) MapBlob(matrix_info->file,IOMode,0,
                (size_t) matrix_info->length);
              if (matrix_info->elements != NULL)
                matrix_info->type=MapCache;
              else
                RelinquishMagickResource(MapResource,matrix_info->length);
            }
        }
    }
  return(matrix_info);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   A c q u i r e M a g i c k M a t r i x                                     %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  AcquireMagickMatrix() allocates and returns a matrix in the form of an
%  array of pointers to an array of doubles, with all values pre-set to zero.
%
%  This used to generate the two dimensional matrix, and vectors required
%  for the GaussJordanElimination() method below, solving some system of
%  simultanious equations.
%
%  The format of the AcquireMagickMatrix method is:
%
%      double **AcquireMagickMatrix(const size_t number_rows,
%        const size_t size)
%
%  A description of each parameter follows:
%
%    o number_rows: the number pointers for the array of pointers
%      (first dimension).
%
%    o size: the size of the array of doubles each pointer points to
%      (second dimension).
%
*/
MagickExport double **AcquireMagickMatrix(const size_t number_rows,
  const size_t size)
{
  double
    **matrix;

  register ssize_t
    i,
    j;

  matrix=(double **) AcquireQuantumMemory(number_rows,sizeof(*matrix));
  if (matrix == (double **) NULL)
    return((double **) NULL);
  for (i=0; i < (ssize_t) number_rows; i++)
  {
    matrix[i]=(double *) AcquireQuantumMemory(size,sizeof(*matrix[i]));
    if (matrix[i] == (double *) NULL)
    {
      for (j=0; j < i; j++)
        matrix[j]=(double *) RelinquishMagickMemory(matrix[j]);
      matrix=(double **) RelinquishMagickMemory(matrix);
      return((double **) NULL);
    }
    for (j=0; j < (ssize_t) size; j++)
      matrix[i][j]=0.0;
  }
  return(matrix);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   D e s t r o y M a t r i x I n f o                                         %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  DestroyMatrixInfo() dereferences a matrix, deallocating memory associated
%  with the matrix.
%
%  The format of the DestroyImage method is:
%
%      MatrixInfo *DestroyMatrixInfo(MatrixInfo *matrix_info)
%
%  A description of each parameter follows:
%
%    o matrix_info: the matrix.
%
*/
MagickExport MatrixInfo *DestroyMatrixInfo(MatrixInfo *matrix_info)
{
  assert(matrix_info != (MatrixInfo *) NULL);
  assert(matrix_info->signature == MagickSignature);
  LockSemaphoreInfo(matrix_info->semaphore);
  switch (matrix_info->type)
  {
    case MemoryCache:
    {
      if (matrix_info->mapped == MagickFalse)
        matrix_info->elements=RelinquishMagickMemory(matrix_info->elements);
      else
        {
          (void) UnmapBlob(matrix_info->elements,(size_t) matrix_info->length);
          matrix_info->elements=(unsigned short *) NULL;
        }
      RelinquishMagickResource(MemoryResource,matrix_info->length);
      break;
    }
    case MapCache:
    {
      (void) UnmapBlob(matrix_info->elements,(size_t) matrix_info->length);
      matrix_info->elements=NULL;
      RelinquishMagickResource(MapResource,matrix_info->length);
    }
    case DiskCache:
    {
      if (matrix_info->file != -1)
        (void) close(matrix_info->file);
      (void) RelinquishUniqueFileResource(matrix_info->path);
      RelinquishMagickResource(DiskResource,matrix_info->length);
      break;
    }
    default:
      break;
  }
  UnlockSemaphoreInfo(matrix_info->semaphore);
  RelinquishSemaphoreInfo(&matrix_info->semaphore);
  return((MatrixInfo *) RelinquishMagickMemory(matrix_info));
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   G a u s s J o r d a n E l i m i n a t i o n                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GaussJordanElimination() returns a matrix in reduced row echelon form,
%  while simultaneously reducing and thus solving the augumented results
%  matrix.
%
%  See also  http://en.wikipedia.org/wiki/Gauss-Jordan_elimination
%
%  The format of the GaussJordanElimination method is:
%
%      MagickBooleanType GaussJordanElimination(double **matrix,
%        double **vectors,const size_t rank,const size_t number_vectors)
%
%  A description of each parameter follows:
%
%    o matrix: the matrix to be reduced, as an 'array of row pointers'.
%
%    o vectors: the additional matrix argumenting the matrix for row reduction.
%             Producing an 'array of column vectors'.
%
%    o rank:  The size of the matrix (both rows and columns).
%             Also represents the number terms that need to be solved.
%
%    o number_vectors: Number of vectors columns, argumenting the above matrix.
%             Usally 1, but can be more for more complex equation solving.
%
%  Note that the 'matrix' is given as a 'array of row pointers' of rank size.
%  That is values can be assigned as   matrix[row][column]   where 'row' is
%  typically the equation, and 'column' is the term of the equation.
%  That is the matrix is in the form of a 'row first array'.
%
%  However 'vectors' is a 'array of column pointers' which can have any number
%  of columns, with each column array the same 'rank' size as 'matrix'.
%
%  This allows for simpler handling of the results, especially is only one
%  column 'vector' is all that is required to produce the desired solution.
%
%  For example, the 'vectors' can consist of a pointer to a simple array of
%  doubles.  when only one set of simultanious equations is to be solved from
%  the given set of coefficient weighted terms.
%
%     double **matrix = AcquireMagickMatrix(8UL,8UL);
%     double coefficents[8];
%     ...
%     GaussJordanElimination(matrix, &coefficents, 8UL, 1UL);
%
%  However by specifing more 'columns' (as an 'array of vector columns',
%  you can use this function to solve a set of 'separable' equations.
%
%  For example a distortion function where    u = U(x,y)   v = V(x,y)
%  And the functions U() and V() have separate coefficents, but are being
%  generated from a common x,y->u,v  data set.
%
%  Another example is generation of a color gradient from a set of colors at
%  specific coordients, such as a list x,y -> r,g,b,a.
%
%  You can also use the 'vectors' to generate an inverse of the given 'matrix'
%  though as a 'column first array' rather than a 'row first array'. For
%  details see http://en.wikipedia.org/wiki/Gauss-Jordan_elimination
%
*/
MagickExport MagickBooleanType GaussJordanElimination(double **matrix,
  double **vectors,const size_t rank,const size_t number_vectors)
{
#define GaussJordanSwap(x,y) \
{ \
  if ((x) != (y)) \
    { \
      (x)+=(y); \
      (y)=(x)-(y); \
      (x)=(x)-(y); \
    } \
}

  double
    max,
    scale;

  register ssize_t
    i,
    j,
    k;

  ssize_t
    column,
    *columns,
    *pivots,
    row,
    *rows;

  columns=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*columns));
  rows=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*rows));
  pivots=(ssize_t *) AcquireQuantumMemory(rank,sizeof(*pivots));
  if ((rows == (ssize_t *) NULL) || (columns == (ssize_t *) NULL) ||
      (pivots == (ssize_t *) NULL))
    {
      if (pivots != (ssize_t *) NULL)
        pivots=(ssize_t *) RelinquishMagickMemory(pivots);
      if (columns != (ssize_t *) NULL)
        columns=(ssize_t *) RelinquishMagickMemory(columns);
      if (rows != (ssize_t *) NULL)
        rows=(ssize_t *) RelinquishMagickMemory(rows);
      return(MagickFalse);
    }
  (void) ResetMagickMemory(columns,0,rank*sizeof(*columns));
  (void) ResetMagickMemory(rows,0,rank*sizeof(*rows));
  (void) ResetMagickMemory(pivots,0,rank*sizeof(*pivots));
  column=0;
  row=0;
  for (i=0; i < (ssize_t) rank; i++)
  {
    max=0.0;
    for (j=0; j < (ssize_t) rank; j++)
      if (pivots[j] != 1)
        {
          for (k=0; k < (ssize_t) rank; k++)
            if (pivots[k] != 0)
              {
                if (pivots[k] > 1)
                  return(MagickFalse);
              }
            else
              if (fabs(matrix[j][k]) >= max)
                {
                  max=fabs(matrix[j][k]);
                  row=j;
                  column=k;
                }
        }
    pivots[column]++;
    if (row != column)
      {
        for (k=0; k < (ssize_t) rank; k++)
          GaussJordanSwap(matrix[row][k],matrix[column][k]);
        for (k=0; k < (ssize_t) number_vectors; k++)
          GaussJordanSwap(vectors[k][row],vectors[k][column]);
      }
    rows[i]=row;
    columns[i]=column;
    if (matrix[column][column] == 0.0)
      return(MagickFalse);  /* sigularity */
    scale=PerceptibleReciprocal(matrix[column][column]);
    matrix[column][column]=1.0;
    for (j=0; j < (ssize_t) rank; j++)
      matrix[column][j]*=scale;
    for (j=0; j < (ssize_t) number_vectors; j++)
      vectors[j][column]*=scale;
    for (j=0; j < (ssize_t) rank; j++)
      if (j != column)
        {
          scale=matrix[j][column];
          matrix[j][column]=0.0;
          for (k=0; k < (ssize_t) rank; k++)
            matrix[j][k]-=scale*matrix[column][k];
          for (k=0; k < (ssize_t) number_vectors; k++)
            vectors[k][j]-=scale*vectors[k][column];
        }
  }
  for (j=(ssize_t) rank-1; j >= 0; j--)
    if (columns[j] != rows[j])
      for (i=0; i < (ssize_t) rank; i++)
        GaussJordanSwap(matrix[i][rows[j]],matrix[i][columns[j]]);
  pivots=(ssize_t *) RelinquishMagickMemory(pivots);
  rows=(ssize_t *) RelinquishMagickMemory(rows);
  columns=(ssize_t *) RelinquishMagickMemory(columns);
  return(MagickTrue);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   G e t M a t r i x C o l u m n s                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GetMatrixColumns() returns the number of columns in the matrix.
%
%  The format of the GetMatrixColumns method is:
%
%      size_t GetMatrixColumns(const MatrixInfo *matrix_info)
%
%  A description of each parameter follows:
%
%    o matrix_info: the matrix.
%
*/
MagickExport size_t GetMatrixColumns(const MatrixInfo *matrix_info)
{
  assert(matrix_info != (MatrixInfo *) NULL);
  assert(matrix_info->signature == MagickSignature);
  return(matrix_info->columns);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   G e t M a t r i x E l e m e n t                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GetMatrixElement() returns the specifed element in the matrix.
%
%  The format of the GetMatrixElement method is:
%
%      MagickBooleanType GetMatrixElement(const MatrixInfo *matrix_info,
%        const ssize_t x,const ssize_t y,void *value)
%
%  A description of each parameter follows:
%
%    o matrix_info: the matrix columns.
%
%    o x: the matrix x-offset.
%
%    o y: the matrix y-offset.
%
%    o value: return the matrix element in this buffer.
%
*/

static inline ssize_t EdgeX(const ssize_t x,const size_t columns)
{
  if (x < 0L)
    return(0L);
  if (x >= (ssize_t) columns)
    return((ssize_t) (columns-1));
  return(x);
}

static inline ssize_t EdgeY(const ssize_t y,const size_t rows)
{
  if (y < 0L)
    return(0L);
  if (y >= (ssize_t) rows)
    return((ssize_t) (rows-1));
  return(y);
}

static inline MagickOffsetType ReadMatrixElements(
  const MatrixInfo *restrict matrix_info,const MagickOffsetType offset,
  const MagickSizeType length,unsigned char *restrict buffer)
{
  register MagickOffsetType
    i;

  ssize_t
    count;

#if !defined(MAGICKCORE_HAVE_PREAD)
  LockSemaphoreInfo(matrix_info->semaphore);
  if (lseek(matrix_info->file,offset,SEEK_SET) < 0)
    {
      UnlockSemaphoreInfo(matrix_info->semaphore);
      return((MagickOffsetType) -1);
    }
#endif
  count=0;
  for (i=0; i < (MagickOffsetType) length; i+=count)
  {
#if !defined(MAGICKCORE_HAVE_PREAD)
    count=read(matrix_info->file,buffer+i,(size_t) MagickMin(length-i,
      (MagickSizeType) SSIZE_MAX));
#else
    count=pread(matrix_info->file,buffer+i,(size_t) MagickMin(length-i,
      (MagickSizeType) SSIZE_MAX),(off_t) (offset+i));
#endif
    if (count <= 0)
      {
        count=0;
        if (errno != EINTR)
          break;
      }
  }
#if !defined(MAGICKCORE_HAVE_PREAD)
  UnlockSemaphoreInfo(matrix_info->semaphore);
#endif
  return(i);
}

MagickExport MagickBooleanType GetMatrixElement(const MatrixInfo *matrix_info,
  const ssize_t x,const ssize_t y,void *value)
{
  MagickOffsetType
    count,
    i;

  assert(matrix_info != (const MatrixInfo *) NULL);
  assert(matrix_info->signature == MagickSignature);
  i=(MagickOffsetType) EdgeY(y,matrix_info->rows)*matrix_info->columns+
    EdgeX(x,matrix_info->columns);
  if (matrix_info->type != DiskCache)
    {
      (void) memcpy(value,(unsigned char *) matrix_info->elements+i*
        matrix_info->stride,matrix_info->stride);
      return(MagickTrue);
    }
  count=ReadMatrixElements(matrix_info,i*matrix_info->stride,
    matrix_info->stride,(unsigned char *) value);
  if (count != (MagickOffsetType) matrix_info->stride)
    return(MagickFalse);
  return(MagickTrue);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   G e t M a t r i x R o w s                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GetMatrixRows() returns the number of rows in the matrix.
%
%  The format of the GetMatrixRows method is:
%
%      size_t GetMatrixRows(const MatrixInfo *matrix_info)
%
%  A description of each parameter follows:
%
%    o matrix_info: the matrix.
%
*/
MagickExport size_t GetMatrixRows(const MatrixInfo *matrix_info)
{
  assert(matrix_info != (const MatrixInfo *) NULL);
  assert(matrix_info->signature == MagickSignature);
  return(matrix_info->rows);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   L e a s t S q u a r e s A d d T e r m s                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  LeastSquaresAddTerms() adds one set of terms and associate results to the
%  given matrix and vectors for solving using least-squares function fitting.
%
%  The format of the AcquireMagickMatrix method is:
%
%      void LeastSquaresAddTerms(double **matrix,double **vectors,
%        const double *terms,const double *results,const size_t rank,
%        const size_t number_vectors);
%
%  A description of each parameter follows:
%
%    o matrix: the square matrix to add given terms/results to.
%
%    o vectors: the result vectors to add terms/results to.
%
%    o terms: the pre-calculated terms (without the unknown coefficent
%             weights) that forms the equation being added.
%
%    o results: the result(s) that should be generated from the given terms
%               weighted by the yet-to-be-solved coefficents.
%
%    o rank: the rank or size of the dimensions of the square matrix.
%            Also the length of vectors, and number of terms being added.
%
%    o number_vectors: Number of result vectors, and number or results being
%      added.  Also represents the number of separable systems of equations
%      that is being solved.
%
%  Example of use...
%
%     2 dimensional Affine Equations (which are separable)
%         c0*x + c2*y + c4*1 => u
%         c1*x + c3*y + c5*1 => v
%
%     double **matrix = AcquireMagickMatrix(3UL,3UL);
%     double **vectors = AcquireMagickMatrix(2UL,3UL);
%     double terms[3], results[2];
%     ...
%     for each given x,y -> u,v
%        terms[0] = x;
%        terms[1] = y;
%        terms[2] = 1;
%        results[0] = u;
%        results[1] = v;
%        LeastSquaresAddTerms(matrix,vectors,terms,results,3UL,2UL);
%     ...
%     if ( GaussJordanElimination(matrix,vectors,3UL,2UL) ) {
%       c0 = vectors[0][0];
%       c2 = vectors[0][1];
%       c4 = vectors[0][2];
%       c1 = vectors[1][0];
%       c3 = vectors[1][1];
%       c5 = vectors[1][2];
%     }
%     else
%       printf("Matrix unsolvable\n);
%     RelinquishMagickMatrix(matrix,3UL);
%     RelinquishMagickMatrix(vectors,2UL);
%
*/
MagickExport void LeastSquaresAddTerms(double **matrix,double **vectors,
  const double *terms,const double *results,const size_t rank,
  const size_t number_vectors)
{
  register ssize_t
    i,
    j;

  for (j=0; j < (ssize_t) rank; j++)
  {
    for (i=0; i < (ssize_t) rank; i++)
      matrix[i][j]+=terms[i]*terms[j];
    for (i=0; i < (ssize_t) number_vectors; i++)
      vectors[i][j]+=results[i]*terms[j];
  }
  return;
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   M a t r i x T o I m a g e                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  MatrixToImage() returns a matrix as an image.  The matrix elements must be
%  of type double otherwise nonsense is returned.
%
%  The format of the MatrixToImage method is:
%
%      Image *MatrixToImage(const MatrixInfo *matrix_info,
%        ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o matrix_info: the matrix.
%
%    o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *MatrixToImage(const MatrixInfo *matrix_info,
  ExceptionInfo *exception)
{
  CacheView
    *image_view;

  double
    max_value,
    min_value,
    scale_factor,
    value;

  Image
    *image;

  MagickBooleanType
    status;

  ssize_t
    y;

  assert(matrix_info != (const MatrixInfo *) NULL);
  assert(matrix_info->signature == MagickSignature);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  if (matrix_info->stride < sizeof(double))
    return((Image *) NULL);
  /*
    Determine range of matrix.
  */
  (void) GetMatrixElement(matrix_info,0,0,&value);
  min_value=value;
  max_value=value;
  for (y=0; y < (ssize_t) matrix_info->rows; y++)
  {
    register ssize_t
      x;

    for (x=0; x < (ssize_t) matrix_info->columns; x++)
    {
      if (GetMatrixElement(matrix_info,x,y,&value) == MagickFalse)
        continue;
      if (value < min_value)
        min_value=value;
      else
        if (value > max_value)
          max_value=value;
    }
  }
  if ((min_value == 0.0) && (max_value == 0.0))
    scale_factor=0;
  else
    if (min_value == max_value)
      {
        scale_factor=(double) QuantumRange/min_value;
        min_value=0;
      }
    else
      scale_factor=(double) QuantumRange/(max_value-min_value);
  /*
    Convert matrix to image.
  */
  image=AcquireImage((ImageInfo *) NULL,exception);
  image->columns=matrix_info->columns;
  image->rows=matrix_info->rows;
  image->colorspace=GRAYColorspace;
  status=MagickTrue;
  image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static,4) shared(status) \
    magick_threads(image,image,image->rows,1)
#endif
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    double
      value;

    register Quantum
      *q;

    register ssize_t
      x;

    if (status == MagickFalse)
      continue;
    q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
    if (q == (Quantum *) NULL)
      {
        status=MagickFalse;
        continue;
      }
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      if (GetMatrixElement(matrix_info,x,y,&value) == MagickFalse)
        continue;
      value=scale_factor*(value-min_value);
      *q=ClampToQuantum(value);
      q+=GetPixelChannels(image);
    }
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
      status=MagickFalse;
  }
  image_view=DestroyCacheView(image_view);
  if (status == MagickFalse)
    image=DestroyImage(image);
  return(image);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   N u l l M a t r i x                                                       %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  NullMatrix() sets all elements of the matrix to zero.
%
%  The format of the ResetMagickMemory method is:
%
%      MagickBooleanType *NullMatrix(MatrixInfo *matrix_info)
%
%  A description of each parameter follows:
%
%    o matrix_info: the matrix.
%
*/
MagickExport MagickBooleanType NullMatrix(MatrixInfo *matrix_info)
{
  register ssize_t
    x;

  ssize_t
    count,
    y;

  unsigned char
    value;

  assert(matrix_info != (const MatrixInfo *) NULL);
  assert(matrix_info->signature == MagickSignature);
  if (matrix_info->type != DiskCache)
    {
      (void) ResetMagickMemory(matrix_info->elements,0,(size_t)
        matrix_info->length);
      return(MagickTrue);
    }
  value=0;
  (void) lseek(matrix_info->file,0,SEEK_SET);
  for (y=0; y < (ssize_t) matrix_info->rows; y++)
  {
    for (x=0; x < (ssize_t) matrix_info->length; x++)
    {
      count=write(matrix_info->file,&value,sizeof(value));
      if (count != (ssize_t) sizeof(value))
        break;
    }
    if (x < (ssize_t) matrix_info->length)
      break;
  }
  return(y < (ssize_t) matrix_info->rows ? MagickFalse : MagickTrue);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e l i n q u i s h M a g i c k M a t r i x                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  RelinquishMagickMatrix() frees the previously acquired matrix (array of
%  pointers to arrays of doubles).
%
%  The format of the RelinquishMagickMatrix method is:
%
%      double **RelinquishMagickMatrix(double **matrix,
%        const size_t number_rows)
%
%  A description of each parameter follows:
%
%    o matrix: the matrix to relinquish
%
%    o number_rows: the first dimension of the acquired matrix (number of
%      pointers)
%
*/
MagickExport double **RelinquishMagickMatrix(double **matrix,
  const size_t number_rows)
{
  register ssize_t
    i;

  if (matrix == (double **) NULL )
    return(matrix);
  for (i=0; i < (ssize_t) number_rows; i++)
     matrix[i]=(double *) RelinquishMagickMemory(matrix[i]);
  matrix=(double **) RelinquishMagickMemory(matrix);
  return(matrix);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   S e t M a t r i x E l e m e n t                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  SetMatrixElement() sets the specifed element in the matrix.
%
%  The format of the SetMatrixElement method is:
%
%      MagickBooleanType SetMatrixElement(const MatrixInfo *matrix_info,
%        const ssize_t x,const ssize_t y,void *value)
%
%  A description of each parameter follows:
%
%    o matrix_info: the matrix columns.
%
%    o x: the matrix x-offset.
%
%    o y: the matrix y-offset.
%
%    o value: set the matrix element to this value.
%
*/

MagickExport MagickBooleanType SetMatrixElement(const MatrixInfo *matrix_info,
  const ssize_t x,const ssize_t y,const void *value)
{
  MagickOffsetType
    count,
    i;

  assert(matrix_info != (const MatrixInfo *) NULL);
  assert(matrix_info->signature == MagickSignature);
  i=(MagickOffsetType) y*matrix_info->columns+x;
  if ((i < 0) ||
      ((MagickSizeType) (i*matrix_info->stride) >= matrix_info->length))
    return(MagickFalse);
  if (matrix_info->type != DiskCache)
    {
      (void) memcpy((unsigned char *) matrix_info->elements+i*
        matrix_info->stride,value,matrix_info->stride);
      return(MagickTrue);
    }
  count=WriteMatrixElements(matrix_info,i*matrix_info->stride,
    matrix_info->stride,(unsigned char *) value);
  if (count != (MagickOffsetType) matrix_info->stride)
    return(MagickFalse);
  return(MagickTrue);
}


text:
package co.cask.cdap.cli.completer.supplier;

import co.cask.cdap.cli.CLIConfig;
import co.cask.cdap.cli.completer.element.EndpointCompleter;
import co.cask.cdap.cli.completer.element.HttpEndpointPrefixCompleter;
import co.cask.cdap.cli.completer.element.HttpMethodPrefixCompleter;
import co.cask.cdap.client.ServiceClient;
import co.cask.common.cli.supplier.CompleterSupplier;
import com.google.inject.Inject;
import jline.console.completer.Completer;

/**
 *
 */
public class EndpointSupplier implements CompleterSupplier {

  private static final String METHOD_PREFIX = "call service <>";
  private static final String ENDPOINT_PREFIX = "call service <> <>";

  private final ServiceClient serviceClient;
  private final CLIConfig cliConfig;

  @Inject
  private EndpointSupplier(final ServiceClient serviceClient, CLIConfig cliConfig) {
    this.serviceClient = serviceClient;
    this.cliConfig = cliConfig;
  }

  @Override
  public Completer getCompleter(String prefix, Completer completer) {
    if (prefix != null && !prefix.isEmpty()) {
      String prefixMatch = prefix.replaceAll("<.+?>", "<>");
      if (METHOD_PREFIX.equals(prefixMatch)) {
        return new HttpMethodPrefixCompleter(serviceClient, cliConfig, prefix, (EndpointCompleter) completer);
      } else if (ENDPOINT_PREFIX.equals(prefixMatch)) {
        return new HttpEndpointPrefixCompleter(serviceClient, cliConfig, prefix, (EndpointCompleter) completer);
      }
    }
    return null;
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Contains the post embed content template part
 *
 * When a post is embedded in an iframe, this file is used to create the content template part
 * output if the active theme does not include an embed-404.php template.
 *
 * @package WordPress
 * @subpackage Theme_Compat
 * @since 4.5.0
 */
?>

<?php _e( 'Oops! That embed cannot be found.' ); ?>

			<?php
			printf(
				/* translators: %s: A link to the embedded site. */
				__( 'It looks like nothing was found at this location. Maybe try visiting %s directly?' ),
				'' . esc_html( get_bloginfo( 'name' ) ) . ''
			);
			?>

	<?php
	/** This filter is documented in wp-includes/theme-compat/embed-content.php */
	do_action( 'embed_content' );
	?>

		<?php the_embed_site_title(); ?>


text:
const testsContext = require.context('.', true, /^((?!(\.webpack|fixtures\/)).)*\.js$/);
require('classlist.js');
testsContext.keys().forEach(testsContext);


text:
package repo

import (
	"fmt"
	"net/http"
	"strings"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/auth"
	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/util"
	"code.gitea.io/gitea/routers/api/v1/convert"

	api "code.gitea.io/sdk/gitea"
)

var searchOrderByMap = map[string]map[string]models.SearchOrderBy{
	"asc": {
		"alpha":   models.SearchOrderByAlphabetically,
		"created": models.SearchOrderByOldest,
		"updated": models.SearchOrderByLeastUpdated,
		"size":    models.SearchOrderBySize,
		"id":      models.SearchOrderByID,
	},
	"desc": {
		"alpha":   models.SearchOrderByAlphabeticallyReverse,
		"created": models.SearchOrderByNewest,
		"updated": models.SearchOrderByRecentUpdated,
		"size":    models.SearchOrderBySizeReverse,
		"id":      models.SearchOrderByIDReverse,
	},
}

// Search repositories via options
func Search(ctx *context.APIContext) {
	// swagger:operation GET /repos/search repository repoSearch
	// ---
	// summary: Search for repositories
	// produces:
	// - application/json
	// parameters:
	// - name: q
	//   in: query
	//   description: keyword
	//   type: string
	// - name: uid
	//   in: query
	//   description: search only for repos that the user with the given id owns or contributes to
	//   type: integer
	//   format: int64
	// - name: page
	//   in: query
	//   description: page number of results to return (1-based)
	//   type: integer
	// - name: limit
	//   in: query
	//   description: page size of results, maximum page size is 50
	//   type: integer
	// - name: mode
	//   in: query
	//   description: type of repository to search for. Supported values are
	//                "fork", "source", "mirror" and "collaborative"
	//   type: string
	// - name: exclusive
	//   in: query
	//   description: if `uid` is given, search only for repos that the user owns
	//   type: boolean
	// - name: sort
	//   in: query
	//   description: sort repos by attribute. Supported values are
	//                "alpha", "created", "updated", "size", and "id".
	//                Default is "alpha"
	//   type: string
	// - name: order
	//   in: query
	//   description: sort order, either "asc" (ascending) or "desc" (descending).
	//                Default is "asc", ignored if "sort" is not specified.
	//   type: string
	// responses:
	//   "200":
	//     "$ref": "#/responses/SearchResults"
	//   "422":
	//     "$ref": "#/responses/validationError"
	opts := &models.SearchRepoOptions{
		Keyword:     strings.Trim(ctx.Query("q"), " "),
		OwnerID:     ctx.QueryInt64("uid"),
		Page:        ctx.QueryInt("page"),
		PageSize:    convert.ToCorrectPageSize(ctx.QueryInt("limit")),
		TopicOnly:   ctx.QueryBool("topic"),
		Collaborate: util.OptionalBoolNone,
	}

	if ctx.QueryBool("exclusive") {
		opts.Collaborate = util.OptionalBoolFalse
	}

	var mode = ctx.Query("mode")
	switch mode {
	case "source":
		opts.Fork = util.OptionalBoolFalse
		opts.Mirror = util.OptionalBoolFalse
	case "fork":
		opts.Fork = util.OptionalBoolTrue
	case "mirror":
		opts.Mirror = util.OptionalBoolTrue
	case "collaborative":
		opts.Mirror = util.OptionalBoolFalse
		opts.Collaborate = util.OptionalBoolTrue
	case "":
	default:
		ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid search mode: \"%s\"", mode))
		return
	}

	var sortMode = ctx.Query("sort")
	if len(sortMode) > 0 {
		var sortOrder = ctx.Query("order")
		if len(sortOrder) == 0 {
			sortOrder = "asc"
		}
		if searchModeMap, ok := searchOrderByMap[sortOrder]; ok {
			if orderBy, ok := searchModeMap[sortMode]; ok {
				opts.OrderBy = orderBy
			} else {
				ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid sort mode: \"%s\"", sortMode))
				return
			}
		} else {
			ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("Invalid sort order: \"%s\"", sortOrder))
			return
		}
	}

	var err error
	if opts.OwnerID > 0 {
		var repoOwner *models.User
		if ctx.User != nil && ctx.User.ID == opts.OwnerID {
			repoOwner = ctx.User
		} else {
			repoOwner, err = models.GetUserByID(opts.OwnerID)
			if err != nil {
				ctx.JSON(500, api.SearchError{
					OK:    false,
					Error: err.Error(),
				})
				return
			}
		}

		if repoOwner.IsOrganization() {
			opts.Collaborate = util.OptionalBoolFalse
		}

		// Check visibility.
		if ctx.IsSigned {
			if ctx.User.ID == repoOwner.ID {
				opts.Private = true
			} else if repoOwner.IsOrganization() {
				opts.Private, err = repoOwner.IsOwnedBy(ctx.User.ID)
				if err != nil {
					ctx.JSON(500, api.SearchError{
						OK:    false,
						Error: err.Error(),
					})
					return
				}
			}
		}
	}

	repos, count, err := models.SearchRepositoryByName(opts)
	if err != nil {
		ctx.JSON(500, api.SearchError{
			OK:    false,
			Error: err.Error(),
		})
		return
	}

	results := make([]*api.Repository, len(repos))
	for i, repo := range repos {
		if err = repo.GetOwner(); err != nil {
			ctx.JSON(500, api.SearchError{
				OK:    false,
				Error: err.Error(),
			})
			return
		}
		accessMode, err := models.AccessLevel(ctx.User, repo)
		if err != nil {
			ctx.JSON(500, api.SearchError{
				OK:    false,
				Error: err.Error(),
			})
		}
		results[i] = repo.APIFormat(accessMode)
	}

	ctx.SetLinkHeader(int(count), setting.API.MaxResponseItems)
	ctx.Header().Set("X-Total-Count", fmt.Sprintf("%d", count))
	ctx.JSON(200, api.SearchResults{
		OK:   true,
		Data: results,
	})
}

// CreateUserRepo create a repository for a user
func CreateUserRepo(ctx *context.APIContext, owner *models.User, opt api.CreateRepoOption) {
	repo, err := models.CreateRepository(ctx.User, owner, models.CreateRepoOptions{
		Name:        opt.Name,
		Description: opt.Description,
		Gitignores:  opt.Gitignores,
		License:     opt.License,
		Readme:      opt.Readme,
		IsPrivate:   opt.Private,
		AutoInit:    opt.AutoInit,
	})
	if err != nil {
		if models.IsErrRepoAlreadyExist(err) ||
			models.IsErrNameReserved(err) ||
			models.IsErrNamePatternNotAllowed(err) {
			ctx.Error(422, "", err)
		} else {
			if repo != nil {
				if err = models.DeleteRepository(ctx.User, ctx.User.ID, repo.ID); err != nil {
					log.Error(4, "DeleteRepository: %v", err)
				}
			}
			ctx.Error(500, "CreateRepository", err)
		}
		return
	}

	ctx.JSON(201, repo.APIFormat(models.AccessModeOwner))
}

// Create one repository of mine
func Create(ctx *context.APIContext, opt api.CreateRepoOption) {
	// swagger:operation POST /user/repos repository user createCurrentUserRepo
	// ---
	// summary: Create a repository
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: body
	//   in: body
	//   schema:
	//     "$ref": "#/definitions/CreateRepoOption"
	// responses:
	//   "201":
	//     "$ref": "#/responses/Repository"
	if ctx.User.IsOrganization() {
		// Shouldn't reach this condition, but just in case.
		ctx.Error(422, "", "not allowed creating repository for organization")
		return
	}
	CreateUserRepo(ctx, ctx.User, opt)
}

// CreateOrgRepo create one repository of the organization
func CreateOrgRepo(ctx *context.APIContext, opt api.CreateRepoOption) {
	// swagger:operation POST /org/{org}/repos organization createOrgRepo
	// ---
	// summary: Create a repository in an organization
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: org
	//   in: path
	//   description: name of organization
	//   type: string
	//   required: true
	// - name: body
	//   in: body
	//   schema:
	//     "$ref": "#/definitions/CreateRepoOption"
	// responses:
	//   "201":
	//     "$ref": "#/responses/Repository"
	//   "422":
	//     "$ref": "#/responses/validationError"
	//   "403":
	//     "$ref": "#/responses/forbidden"
	org, err := models.GetOrgByName(ctx.Params(":org"))
	if err != nil {
		if models.IsErrOrgNotExist(err) {
			ctx.Error(422, "", err)
		} else {
			ctx.Error(500, "GetOrgByName", err)
		}
		return
	}

	if !ctx.User.IsAdmin {
		isOwner, err := org.IsOwnedBy(ctx.User.ID)
		if err != nil {
			ctx.ServerError("IsOwnedBy", err)
			return
		} else if !isOwner {
			ctx.Error(403, "", "Given user is not owner of organization.")
			return
		}
	}
	CreateUserRepo(ctx, org, opt)
}

// Migrate migrate remote git repository to gitea
func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) {
	// swagger:operation POST /repos/migrate repository repoMigrate
	// ---
	// summary: Migrate a remote git repository
	// consumes:
	// - application/json
	// produces:
	// - application/json
	// parameters:
	// - name: body
	//   in: body
	//   schema:
	//     "$ref": "#/definitions/MigrateRepoForm"
	// responses:
	//   "201":
	//     "$ref": "#/responses/Repository"
	ctxUser := ctx.User
	// Not equal means context user is an organization,
	// or is another user/organization if current user is admin.
	if form.UID != ctxUser.ID {
		org, err := models.GetUserByID(form.UID)
		if err != nil {
			if models.IsErrUserNotExist(err) {
				ctx.Error(422, "", err)
			} else {
				ctx.Error(500, "GetUserByID", err)
			}
			return
		}
		ctxUser = org
	}

	if ctx.HasError() {
		ctx.Error(422, "", ctx.GetErrMsg())
		return
	}

	if !ctx.User.IsAdmin {
		if !ctxUser.IsOrganization() && ctx.User.ID != ctxUser.ID {
			ctx.Error(403, "", "Given user is not an organization.")
			return
		}

		if ctxUser.IsOrganization() {
			// Check ownership of organization.
			isOwner, err := ctxUser.IsOwnedBy(ctx.User.ID)
			if err != nil {
				ctx.Error(500, "IsOwnedBy", err)
				return
			} else if !isOwner {
				ctx.Error(403, "", "Given user is not owner of organization.")
				return
			}
		}
	}

	remoteAddr, err := form.ParseRemoteAddr(ctx.User)
	if err != nil {
		if models.IsErrInvalidCloneAddr(err) {
			addrErr := err.(models.ErrInvalidCloneAddr)
			switch {
			case addrErr.IsURLError:
				ctx.Error(422, "", err)
			case addrErr.IsPermissionDenied:
				ctx.Error(422, "", "You are not allowed to import local repositories.")
			case addrErr.IsInvalidPath:
				ctx.Error(422, "", "Invalid local path, it does not exist or not a directory.")
			default:
				ctx.Error(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error())
			}
		} else {
			ctx.Error(500, "ParseRemoteAddr", err)
		}
		return
	}

	repo, err := models.MigrateRepository(ctx.User, ctxUser, models.MigrateRepoOptions{
		Name:        form.RepoName,
		Description: form.Description,
		IsPrivate:   form.Private || setting.Repository.ForcePrivate,
		IsMirror:    form.Mirror,
		RemoteAddr:  remoteAddr,
	})
	if err != nil {
		err = util.URLSanitizedError(err, remoteAddr)
		if repo != nil {
			if errDelete := models.DeleteRepository(ctx.User, ctxUser.ID, repo.ID); errDelete != nil {
				log.Error(4, "DeleteRepository: %v", errDelete)
			}
		}
		ctx.Error(500, "MigrateRepository", err)
		return
	}

	log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName)
	ctx.JSON(201, repo.APIFormat(models.AccessModeAdmin))
}

// Get one repository
func Get(ctx *context.APIContext) {
	// swagger:operation GET /repos/{owner}/{repo} repository repoGet
	// ---
	// summary: Get a repository
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo
	//   type: string
	//   required: true
	// responses:
	//   "200":
	//     "$ref": "#/responses/Repository"
	ctx.JSON(200, ctx.Repo.Repository.APIFormat(ctx.Repo.AccessMode))
}

// GetByID returns a single Repository
func GetByID(ctx *context.APIContext) {
	// swagger:operation GET /repositories/{id} repository repoGetByID
	// ---
	// summary: Get a repository by id
	// produces:
	// - application/json
	// parameters:
	// - name: id
	//   in: path
	//   description: id of the repo to get
	//   type: integer
	//   format: int64
	//   required: true
	// responses:
	//   "200":
	//     "$ref": "#/responses/Repository"
	repo, err := models.GetRepositoryByID(ctx.ParamsInt64(":id"))
	if err != nil {
		if models.IsErrRepoNotExist(err) {
			ctx.Status(404)
		} else {
			ctx.Error(500, "GetRepositoryByID", err)
		}
		return
	}

	perm, err := models.GetUserRepoPermission(repo, ctx.User)
	if err != nil {
		ctx.Error(500, "AccessLevel", err)
		return
	} else if !perm.HasAccess() {
		ctx.Status(404)
		return
	}
	ctx.JSON(200, repo.APIFormat(perm.AccessMode))
}

// Delete one repository
func Delete(ctx *context.APIContext) {
	// swagger:operation DELETE /repos/{owner}/{repo} repository repoDelete
	// ---
	// summary: Delete a repository
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo to delete
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo to delete
	//   type: string
	//   required: true
	// responses:
	//   "204":
	//     "$ref": "#/responses/empty"
	//   "403":
	//     "$ref": "#/responses/forbidden"
	owner := ctx.Repo.Owner
	repo := ctx.Repo.Repository

	if owner.IsOrganization() {
		isOwner, err := owner.IsOwnedBy(ctx.User.ID)
		if err != nil {
			ctx.Error(500, "IsOwnedBy", err)
			return
		} else if !isOwner {
			ctx.Error(403, "", "Given user is not owner of organization.")
			return
		}
	}

	if err := models.DeleteRepository(ctx.User, owner.ID, repo.ID); err != nil {
		ctx.Error(500, "DeleteRepository", err)
		return
	}

	log.Trace("Repository deleted: %s/%s", owner.Name, repo.Name)
	ctx.Status(204)
}

// MirrorSync adds a mirrored repository to the sync queue
func MirrorSync(ctx *context.APIContext) {
	// swagger:operation POST /repos/{owner}/{repo}/mirror-sync repository repoMirrorSync
	// ---
	// summary: Sync a mirrored repository
	// produces:
	// - application/json
	// parameters:
	// - name: owner
	//   in: path
	//   description: owner of the repo to sync
	//   type: string
	//   required: true
	// - name: repo
	//   in: path
	//   description: name of the repo to sync
	//   type: string
	//   required: true
	// responses:
	//   "200":
	//     "$ref": "#/responses/empty"
	repo := ctx.Repo.Repository

	if !ctx.Repo.CanWrite(models.UnitTypeCode) {
		ctx.Error(403, "MirrorSync", "Must have write access")
	}

	go models.MirrorQueue.Add(repo.ID)
	ctx.Status(200)
}

// TopicSearch search for creating topic
func TopicSearch(ctx *context.Context) {
	// swagger:operation GET /topics/search repository topicSearch
	// ---
	// summary: search topics via keyword
	// produces:
	//   - application/json
	// parameters:
	//   - name: q
	//     in: query
	//     description: keywords to search
	//     required: true
	//     type: string
	// responses:
	//   "200":
	//     "$ref": "#/responses/Repository"
	if ctx.User == nil {
		ctx.JSON(403, map[string]interface{}{
			"message": "Only owners could change the topics.",
		})
		return
	}

	kw := ctx.Query("q")

	topics, err := models.FindTopics(&models.FindTopicOptions{
		Keyword: kw,
		Limit:   10,
	})
	if err != nil {
		log.Error(2, "SearchTopics failed: %v", err)
		ctx.JSON(500, map[string]interface{}{
			"message": "Search topics failed.",
		})
		return
	}

	ctx.JSON(200, map[string]interface{}{
		"topics": topics,
	})
}


text:
'use strict';

var React = require('react')
var radium = require('radium')
var assign = require('lodash/assign')

var componentStyle = {
  padding: 0,
  margin: 0,
  border: 0,
  backgroundColor: 'inherit',
  outline: 'none',
}

var Button = React.createClass({
  displayName: 'Button',

  propTypes: {
    refNode: React.PropTypes.func,
  },

  render: function() {
    var style = [].concat.call( componentStyle, this.props.style )
    var passedProps = assign( {}, this.props, {style: style} )

    // Use refNode pattern to pass back the DOM's node
    if (passedProps.refNode) {
      passedProps.ref = passedProps.refNode
      delete passedProps.refNode
    }

    return React.createElement( 'button', passedProps )
  }
})

module.exports = radium( Button )


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

<TITLE>
All Classes
</TITLE>

<META NAME="date" CONTENT="2010-04-18">

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

All Classes

Add

AllpassFilter

Analyze

Analyze.AnalysisSettings

AudioContext

AudioContextStopTrigger

AudioFile

AudioFile.OperationUnsupportedException

AudioFileIOImplementation

AudioFormat

AudioIO

AudioSegmenter

AudioUtils

BasicDataWriter

BasicTimeDataWriter

Bead

BeadArray

BiquadCustomCoeffCalculator

BiquadFilter

Buffer

BufferFactory

Change

Clicker

Clip

Clock

CombFilter

Compressor

CosineWindow

CrossFade

CrossoverFilter

CurveBuffer

DataBead

DataBeadReceiver

DelayData

DelayEvent

DelayTrigger

Delta

Envelope

Exp01Buffer

FeatureExtractor

FeatureFrame

FeatureManager

FeatureSet

FeatureTrack

FFT

FloatBead

Frequency

Function

Gain

Glide

GnuplotDataWriter

GranularSamplePlayer

HanningWindow

IIRFilter

IIRFilter.IIRFilterAnalysis

IntegerBead

JavaSoundAudioFile

JavaSoundAudioFileIOImplementation

JavaSoundAudioIO

KillTrigger

Log01Buffer

LPRezFilter

Maximum

MeanFilter

MelSpectrum

MFCC

Minimum

MonoPlug

MouseResponder

Mult

MultiWrapper

NBitsConverter

Noise

NoiseBuffer

NonrealtimeIO

OnePoleFilter

OneWindow

OscillatorBank

Panner

PauseTrigger

PeakDetector

Pitch

Plug

PolyLimit

Power

PowerSpectrum

RampBuffer

RandomPWM

RangeLimiter

ReBin

RecordToFile

RecordToSample

RecordToSample.Mode

Reverb

RMS

Sample

Sample.Regime

Sample.TimedRegime

Sample.TimedRegime.Order

Sample.TotalRegime

SampleManager

SampleManager.SampleGroupListener

SamplePlayer

SamplePlayer.EnvelopeType

SamplePlayer.InterpolationType

SamplePlayer.LoopType

SawBuffer

ScalingMixer

SegmentListener

SegmentMaker

ShortFrameSegmenter

SignalReporter

SineBuffer

SoundEvent

SoundEventManager

Spatial

SpectralCentroid

SpectralDifference

SpectralDifference.DifferenceType

SpectralPeaks

SquareBuffer

StartTrigger

Static

TapIn

TapOut

Throughput

TimeStamp

TriangularBuffer

UGen

UGen.OutputInitializationRegime

UGen.OutputPauseRegime

UGenChain

WavePlayer

WaveShaper

ZeroCross

ZMap


text:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
	<meta charset="UTF-8">
	<title>tech | 3camp</title>
	<link rel="stylesheet" href="bower_components/angular-material/angular-material.css">
	<style>
		.top-bar {
			margin-bottom: 50px;
		}
		.menu {
			margin-top: 50px;
		}
		code, pre {
			color: #4285f4;
			padding: 5px;
			border-radius: 3px;
			font-weight: bold;
			font-size: 14px;
			background: #f6f6f6;
			overflow-wrap: break-word;
			font-family: monospace, serif;
		}
	</style>
</head>
<body ng-controller="TechController as ctrl">

	<md-content>
		<ui-view></ui-view>
	</md-content>

	<script src="bower_components/hammerjs/hammer.js"></script>
	<script src="bower_components/angular/angular.js"></script>
	<script src="bower_components/angular-animate/angular-animate.js"></script>
	<script src="bower_components/angular-aria/angular-aria.js"></script>
	<script src="bower_components/angular-material/angular-material.js"></script>
	<script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
	<script src="bower_components/ocLazyLoad/dist/ocLazyLoad.js"></script>
	<script src="bower_components/react/react.js"></script>
	<script src="bower_components/faker/build/build/faker.js"></script>
	<script src="app.js"></script>
</body>
</html>


text:
import { EditorState, SelectionState, Modifier } from 'draft-js';
import linkifyIt from 'linkify-it';
import tlds from 'tlds';
import EntityState from '../EntityState';
import Entities from '../Entities';

// Setup Linkify
const linkify = linkifyIt();
linkify.tlds(tlds);

/**
 * Converts inline links, returns the new editor state
 *
 * @param {EditorState} editorState
 * @return {EditorState}
 */
export function convertLinks(editorState) {
  // Get the current content
  const currentContent = editorState.getCurrentContent();
  // Get the current selection
  const selectionState = editorState.getSelection();

  // Loop through all blocks to find links
  const convertedContent = currentContent.getBlocksAsArray().reduce((contentState, block) => {
    // Get the current block text, so we can see if there are matches for links
    const blockKey = block.getKey();
    const blockText = block.getText();

    // Find and update all existing links that were automatically matched
    block.findEntityRanges((character) => {
      // Find all existing match links
      const entityKey = character.getEntity();
      if (entityKey !== null) {
        const entity = contentState.getEntity(entityKey);
        if (entity.getType() === Entities.Link && entity.getData().created === 'match') {
          return true;
        }
      }
      return false;
    }, (start, end) => {
      // Check if link is invalid or changed
      const entityText = blockText.slice(start, end);
      const matchLink = linkify.match(entityText);
      if (matchLink === null) {
        // Remove previously matched link entity
        const linkSelectionState = new SelectionState({
          anchorKey: blockKey,
          anchorOffset: start,
          focusKey: blockKey,
          focusOffset: end
        });
        contentState = Modifier.applyEntity(contentState, linkSelectionState, null);
      }
    });

    // Find links based on the current block
    const matchLinks = linkify.match(blockText);
    if (matchLinks !== null) {
      // Loop through each matched link
      for (let i = 0; i < matchLinks.length; i += 1) {
        // Create selection from matched link
        const matchSelectionState = new SelectionState({
          anchorKey: blockKey,
          anchorOffset: matchLinks[i].index,
          focusKey: blockKey,
          focusOffset: matchLinks[i].lastIndex
        });
        // Check if there are any existing links
        const entityState = EntityState.create(contentState, matchSelectionState);
        const previousLink = entityState.isEntityType(Entities.Link) ? entityState.getEntity() : null;
        const previousLinkData = previousLink ? previousLink.getData() : null;
        if (!previousLink) {
          // Create link entity
          contentState = contentState.createEntity(Entities.Link, 'MUTABLE', {
            href: matchLinks[i].url,
            created: 'match'
          });
          // Convert text to a link
          const entityKey = contentState.getLastCreatedEntityKey();
          contentState = Modifier.applyEntity(contentState, matchSelectionState, entityKey);
        } else if (previousLink && previousLinkData.created === 'match') {
          // Check if existing entity has changed
          const previousEntityKey = entityState.getEntityKey();
          if (matchLinks[i].url !== previousLinkData.href) {
            // Modify link entity if matched url has changed
            contentState = contentState.mergeEntityData(previousEntityKey, {
              href: matchLinks[i].url
            });
            contentState = Modifier.applyEntity(contentState, matchSelectionState, previousEntityKey);
          }
        }
      }
    }

    return contentState;
  }, currentContent);

  // Apply content changes
  editorState = EditorState.push(editorState, convertedContent, 'create-entity');
  // Reset selection to original state
  editorState = EditorState.acceptSelection(editorState, selectionState);

  return editorState;
}


text:
package dk.itu.mario.scene;

import java.awt.Graphics;
import java.awt.event.MouseEvent;

import dk.itu.mario.engine.sonar.SonarSoundEngine;
import dk.itu.mario.engine.sonar.SoundListener;

public abstract class Scene implements SoundListener
{
    public SonarSoundEngine sound;
    public static boolean[] keys = new boolean[16];

	public static final int COLOR_BLACK = 0;
	public static final int COLOR_RED = 1;
	public static final int COLOR_GREEN = 2;
	public static final int COLOR_BLUE = 3;
	public static final int COLOR_YELLOW = 4;
	public static final int COLOR_PURPLE = 5;
	public static final int COLOR_LIGHTBLUE = 6;
	public static final int COLOR_WHITE = 7;

    public void toggleKey(int key, boolean isPressed)
    {
        keys[key] = isPressed;
    }

    public final void setSound(SonarSoundEngine sound)
    {
        sound.setListener(this);
        this.sound = sound;
    }

    public abstract void mouseClicked(MouseEvent me);

    public abstract void init();

    public abstract void tick();

    public abstract void render(Graphics og, float alpha);
}


text:
namespace SayHello
{
    using System;

    class SayHello
    {
        static void Main()
        {
            Hello();
        }

        static void Hello()
        {
            string name = Console.ReadLine();
            Console.WriteLine("Hello, {0}!", name);
        }
    }
}


text:
package net.sourceforge.servestream.media;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import net.sourceforge.servestream.bean.UriBean;
import net.sourceforge.servestream.provider.Media;
import net.sourceforge.servestream.transport.HTTP;
import net.sourceforge.servestream.transport.HTTPS;
import net.sourceforge.servestream.transport.TransportFactory;
import net.sourceforge.servestream.utils.Utils;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;

public class DownloadPlayer extends FFmpegPlayer {
	private static final String TAG = DownloadPlayer.class.getName();

	private long mTotalSizeInBytes = -1;

	private URL mUrl = null;
	private long mId = -1;
	private long mLength = -1;
	private File mPartialFile = null;
	private File mCompleteFile = null;
	private DownloadTask mDownloadTask = null;
	private PollingAsyncTask mPollingAsyncTask = null;

	public DownloadPlayer() {
		super();
	}

	@Override
	public void setDataSource(Context context, long id) throws IOException,
			IllegalArgumentException, SecurityException, IllegalStateException {
		mId = id;
		String path = getUri(context, id);
		Uri uri = TransportFactory.getUri(path);

		if (uri == null ||
				(!uri.getScheme().equals(HTTP.getProtocolName()) &&
				!uri.getScheme().equals(HTTPS.getProtocolName()))) {
			throw new IllegalArgumentException();
		}

		UriBean uriBean = TransportFactory.getTransport(uri.getScheme()).createUri(uri);

		if (uriBean == null) {
			throw new IllegalArgumentException();
		}

		mUrl = uriBean.getURL();
	}

	@Override
	public void prepareAsync() throws IllegalStateException {
		download();
	}

	@Override
	public void stop() {
		super.stop();
        cancelDownload();
	}

	@Override
	public void seekTo(int msec) throws IllegalStateException {
		if (isCompleteFileAvailable()) {
			super.seekTo(msec);
		}
	}

	@Override
	public int getDuration() {
		if (isCompleteFileAvailable()) {
			return super.getDuration();
		} else {
			return 0;
		}
	}

	@Override
	public void release() {
		super.release();
    	cancelDownload();
    	Utils.deleteAllFiles();
	}

	@Override
	public void reset() {
		super.reset();
    	cancelDownload();
    	Utils.deleteAllFiles();
	}

	private void download() {
		mTotalSizeInBytes = -1;
		mLength = -1;
		mPartialFile = new File(Utils.getDownloadDirectory(), "mediafile" + mId + ".partial.dat");
        mCompleteFile = new File(Utils.getDownloadDirectory(), "mediafile" + mId + ".complete.dat");
        Utils.deleteFile(mPartialFile);
        Utils.deleteFile(mCompleteFile);

        Log.v(TAG, "=============> " + mPartialFile.toString());
		mDownloadTask = new DownloadTask(mUrl, mPartialFile, mCompleteFile);
        mDownloadTask.execute();
        mPollingAsyncTask = new PollingAsyncTask();
        mPollingAsyncTask.execute();
	}

	public void cancelDownload() {
		if (mDownloadTask != null) {
	    	DownloadTask downloadTask = mDownloadTask;
	    	downloadTask.cancel();
	    	mDownloadTask = null;
		}
	}

	public void cancelPollingTask() {
		if (mPollingAsyncTask != null) {
			PollingAsyncTask pollingAsyncTask = mPollingAsyncTask;
			pollingAsyncTask.cancel();
	    	mPollingAsyncTask = null;
		}
	}

	public File getCompleteFile() {
		if (mCompleteFile != null && mCompleteFile.exists()) {
			return mCompleteFile;
		}

		return null;
	}

	public long getCompleteFileDuration() {
        long duration = 0;

    	MediaPlayer mediaPlayer = new MediaPlayer();
        try {
			mediaPlayer.setDataSource(getCompleteFile().toString());
			mediaPlayer.prepare();
			duration = mediaPlayer.getDuration();
			mediaPlayer.release();
		} catch (Exception e) {
		}

		return duration;
	}

	public File getPartialFile() {
		return mPartialFile;
	}

	public synchronized boolean isCompleteFileAvailable() {
		if (mCompleteFile != null && mCompleteFile.exists()) {
			return true;
		}

		return false;
	}

	public synchronized double getPercentDownloaded() {
		if (mCompleteFile != null && mCompleteFile.exists()) {
			return 1.0;
		}

		return (double) mPartialFile.length() / (double) mTotalSizeInBytes;
	}

	public synchronized boolean isDownloadCancelled() {
		return mDownloadTask != null && mDownloadTask.isCancelled();
	}

	public void delete() {
		cancelDownload();
		cancelPollingTask();
		Utils.deleteFile(mPartialFile);
		Utils.deleteFile(mCompleteFile);
	}

	/**
	 * @return the length
	 */
	public long getLength() {
		long length = -1;

		if (isCompleteFileAvailable()) {
			if (mLength == -1) {
				mLength = getCompleteFileDuration();
			}

			length = mLength;
		}

		return length;
	}

	private class DownloadTask implements Runnable {

		private boolean mIsCancelled;

		private URL mUrl = null;
		private File mPartialFile = null;
		private File mCompleteFile = null;

		public DownloadTask(URL url, File partialFile, File completeFile) {
	    	mIsCancelled = false;
	    	mUrl = url;
			mPartialFile = partialFile;
			mCompleteFile = completeFile;
		}

		@Override
		public void run() {
        	HttpURLConnection conn = null;
        	BufferedInputStream in = null;
            FileOutputStream out = null;
            boolean appendToFile = false;

            byte[] buffer = new byte[1024 * 16];
            //long count = 0;

			Log.v(TAG, "starting download task");
            while (!mCompleteFile.exists() && !isCancelled()) {
            	try {
                	conn = determineRange(mUrl, mPartialFile.length());

                	if (conn.getResponseCode() == HttpURLConnection.HTTP_PARTIAL) {
                		appendToFile = true;
                	} else {
                		mTotalSizeInBytes = conn.getContentLength();
                	}

                	in = new BufferedInputStream(conn.getInputStream());
                	out = new FileOutputStream(mPartialFile, appendToFile);

                	int i;
                	while (((i = in.read(buffer)) != -1) && !isCancelled()) {
                		out.write(buffer, 0, i);
                		//count += i;
                	}
                	out.flush();
                	out.close();

                	Utils.copyFile(mPartialFile, mCompleteFile);
        			Log.v(TAG, "download task is complete");

        			if (mOnInfoListener != null) {
        				mOnInfoListener.onInfo(DownloadPlayer.this, AbstractMediaPlayer.MEDIA_INFO_METADATA_UPDATE, 0);
        			}
            	} catch (IOException e) {
            		e.printStackTrace();
            	} finally {
            		Utils.closeInputStream(in);
            		Utils.closeHttpConnection(conn);
            		Utils.closeOutputStream(out);
            	}
            }
        }

        private HttpURLConnection determineRange(URL url, long bytesProcessed) {
        	HttpURLConnection conn = null;

        	try {
        		if (url.getProtocol().equalsIgnoreCase("http")) {
        			conn = (HttpURLConnection) url.openConnection();
        		} else if (url.getProtocol().equalsIgnoreCase("https")) {
        			conn = (HttpsURLConnection) url.openConnection();
        		}

        		if (conn == null) {
        			return null;
        		}

        		conn.setRequestProperty("User-Agent", "ServeStream");
        		conn.setConnectTimeout(6000);
        		conn.setReadTimeout(6000);
        		conn.setRequestProperty("Range", "bytes=" + bytesProcessed + "-");
        		conn.setRequestMethod("GET");
        		conn.connect();
        	} catch (IOException e) {
        		e.printStackTrace();
        	}

        	return conn;
        }

		private synchronized boolean isCancelled() {
			return mIsCancelled;
		}

		public synchronized void cancel() {
			mIsCancelled = true;
		}

		public synchronized void execute() {
			new Thread(this, "").start();
		}
	}

	private class PollingAsyncTask implements Runnable {

		private boolean mIsCancelled;

		//int INITIAL_BUFFER = Math.max(100000, 160 * 1024 / 8 * 5);
		int INITIAL_BUFFER = 81920;

	    public PollingAsyncTask() {
	    	mIsCancelled = false;
	    }

		@Override
		public void run() {
			Log.v(TAG, "polling task started");

			while (!bufferingComplete() && !isCancelled()) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			Log.v(TAG, "setDataSource called");
			try {
				DownloadPlayer.super.setDataSource(getPartialFile().getPath());
				DownloadPlayer.super.prepareAsync();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		private boolean bufferingComplete() {
			return getPartialFile().length() >= INITIAL_BUFFER;
		}

		private synchronized boolean isCancelled() {
			return mIsCancelled;
		}

		public synchronized void cancel() {
			mIsCancelled = true;
		}

		public synchronized void execute() {
			new Thread(this, "").start();
		}
	}

	private String getUri(Context context, long id) {
		String uri = null;

		// Form an array specifying which columns to return.
		String [] projection = new String [] { Media.MediaColumns.URI };

		// Get the base URI for the Media Files table in the Media content provider.
		Uri mediaFile =  Media.MediaColumns.CONTENT_URI;

		// Make the query.
		Cursor cursor = context.getContentResolver().query(mediaFile,
				projection,
				Media.MediaColumns._ID + "= ? ",
				new String [] { String.valueOf(id) },
				null);

		if (cursor.moveToFirst()) {
			int uriColumn = cursor.getColumnIndex(Media.MediaColumns.URI);
			uri = cursor.getString(uriColumn);
		}

		cursor.close();

		return uri;
	}
}


text:
'use strict';

angular.module('ticketbox.admin.block.seats', [
    'ngRoute',
    'ticketbox.components.api',
    'ticketbox.components.canvas'])

    .config(function ($routeProvider) {
        $routeProvider.when('/block/:id/seats', {
            controller: 'BlockSeatsCtrl',
            templateUrl: 'admin.block.seats/admin.block.seats.html'
        });
    })

    .controller('BlockSeatsCtrl', function($scope, $routeParams, $location, $q, Block, Seat, geometry) {
        $scope.block = Block.get({ id: $routeParams.id });
        $scope.seats = Seat.query({ block_id: $routeParams.id });
        _resetState();

        $scope.add = function (block_id, namePattern, startNumber, endNumber, coordinates) {
            var newSeats = [];
            for (var seatNumber = startNumber; seatNumber <= endNumber; seatNumber += 1) {
                var name = '';
                if (namePattern.indexOf('{i}') !== -1) {
                    name = namePattern.replace('{i}', seatNumber);
                } else {
                    name = namePattern;
                }
                var data = {'block_id': block_id, 'name': name};
                if (coordinates.length === 4) {
                    var seatCoordinates = geometry.calculateSeatCoordinates(coordinates, endNumber - startNumber + 1, seatNumber - startNumber);
                    data.x0 = seatCoordinates.x0;
                    data.y0 = seatCoordinates.y0;
                    data.x1 = seatCoordinates.x1;
                    data.y1 = seatCoordinates.y1;
                    data.x2 = seatCoordinates.x2;
                    data.y2 = seatCoordinates.y2;
                    data.x3 = seatCoordinates.x3;
                    data.y3 = seatCoordinates.y3;
                }
                newSeats.push(data);
            }
            Seat.save(newSeats)
                .$promise.then(function(response) {
                    _.each(response, function(s) {
                        $scope.seats.push(s);
                    });
                    _resetState();
                });
        };

        $scope.removeAll = function() {
            var promises = _.map($scope.seats, function(seat) {
                return Seat.delete({ id: seat.id });
            });
            $q.all(promises).then(function() {
                $scope.seats = Seat.query({ block_id: $routeParams.id });
                _resetState();
            });
        };

        function _resetState() {
            $scope.namePattern = '';
            $scope.startSeatNumber = 1;
            $scope.endSeatNumber = 1;
            $scope.coordinates = [];
        }
    })

    .service('coordinates', function() {
        return {
            seatToCoordinates: function(seat) {
                return [
                    { x: seat.x0, y: seat.y0 },
                    { x: seat.x1, y: seat.y1 },
                    { x: seat.x2, y: seat.y2 },
                    { x: seat.x3, y: seat.y3 }
                ];
            }
        };
    })

    .service('geometry', function() {
        return {
            calculateSeatCoordinates: function(coordinates, numberOfSeats, seatIndex) {
                var dx01 = coordinates[1].x - coordinates[0].x;
                var dy01 = coordinates[1].y - coordinates[0].y;
                var dx32 = coordinates[2].x - coordinates[3].x;
                var dy32 = coordinates[2].y - coordinates[3].y;
                var seatCoordinates = {};
                seatCoordinates.x0 = coordinates[0].x + (dx01 / numberOfSeats) * seatIndex;
                seatCoordinates.y0 = coordinates[0].y + (dy01 / numberOfSeats) * seatIndex;
                seatCoordinates.x1 = coordinates[3].x + (dx32 / numberOfSeats) * seatIndex;
                seatCoordinates.y1 = coordinates[3].y + (dy32 / numberOfSeats) * seatIndex;
                seatCoordinates.x2 = coordinates[3].x + (dx32 / numberOfSeats) * (seatIndex + 1);
                seatCoordinates.y2 = coordinates[3].y + (dy32 / numberOfSeats) * (seatIndex + 1);
                seatCoordinates.x3 = coordinates[0].x + (dx01 / numberOfSeats) * (seatIndex + 1);
                seatCoordinates.y3 = coordinates[0].y + (dy01 / numberOfSeats) * (seatIndex + 1);
                return seatCoordinates;
            }
        }
    })

    .directive('ngSeatDefinition', function (canvasImage, coordinates) {
        var coordinateMarkers = [];
        var currentPolygons = [];
        var selectedCoordinates;

        function _refreshSeats(canvas, seats) {
            _.each(currentPolygons, function (p) {
                canvas.removeChild(p, false);
            });
            currentPolygons = [];
            _.each(seats, function (seat) {
                var polygon = canvasImage.drawPolygon(canvas, coordinates.seatToCoordinates(seat), '#333', '2px #000');
                currentPolygons.push(polygon);
            });
            canvas.redraw();
        }

        function _bindClick(canvas) {
            canvas.bind("click tap", function () {
                if (selectedCoordinates.length < 4) {
                    var circle = canvasImage.drawCoordinate(canvas);
                    var point = {x: circle.x, y: circle.y};
                    coordinateMarkers.push({ point: point, marker: circle });
                    selectedCoordinates.push(point);
                }
            });
        }

        function _create(scope, element, attrs) {
            selectedCoordinates = scope.coordinates;
            var canvas = null;
            var canvas = element.children()[0];

            scope.$watch('src', function (newSrc, oldSrc) {
                if (newSrc !== undefined) {
                    canvas = canvasImage.createCanvasObject(newSrc, canvas);
                    _bindClick(canvas);
                }
            }, true);

            scope.$watch('seats', function (newSeats, oldSeats) {
                if (canvas !== null) {
                    _refreshSeats(canvas, newSeats);
                }
            }, true);

            scope.$watch('coordinates', function (newCoordinates, oldCoordinates) {
                selectedCoordinates = newCoordinates;
                var removedCoordinates = _.filter(oldCoordinates, function(c) { return !_.contains(newCoordinates, c); });
                _.each(removedCoordinates, function(c) {
                    var coordinateMarker = _.find(coordinateMarkers, function(m) { return m.point.x === c.x && m.point.y === c.y; });
                    if (coordinateMarker !== undefined) {
                        if (canvas !== null) {
                            canvas.removeChild(coordinateMarker.marker);
                        }
                        coordinateMarkers.splice(coordinateMarker, 1);
                    }
                });
            }, true);
        }

        return {
            restrict: 'E',
            scope: {
                src: '=',
                seats: '=',
                coordinates: '='
            },
            template: '<canvas id="ngClickableImageCanvas"></canvas>',
            link: _create
        }
    });


text:
using System.Collections.Generic;
using Xunit;
using Exercism.Tests;

public class LanguagesTests
{
    [Fact]
    public void NewList()
    {
        Assert.Empty(Languages.NewList());
    }

    [Fact]
    public void ExistingList()
    {
        var expected = new List<string>();
        expected.Add("C#");
        expected.Add("Clojure");
        expected.Add("Elm");
        Assert.Equal(expected, Languages.GetExistingLanguages());
    }

    [Fact]
    public void AddLanguage()
    {
        var expected = new List<string>();
        expected.Add("C#");
        expected.Add("Clojure");
        expected.Add("Elm");
        expected.Add("Bash");
        Assert.Equal(expected,
            Languages.AddLanguage(Languages.GetExistingLanguages(), "Bash"));
    }

    [Fact]
    public void CountLanguages()
    {
        Assert.Equal(3,
            Languages.CountLanguages(Languages.GetExistingLanguages()));
    }

    [Fact]
    public void HasLanguage_yes()
    {
        Assert.True(Languages.HasLanguage(Languages.GetExistingLanguages(), "Elm"));
    }

    [Fact]
    public void HasLanguage_no()
    {
        Assert.False(Languages.HasLanguage(Languages.GetExistingLanguages(), "D"));
    }

    [Fact]
    public void ReverseList()
    {
        var expected = new List<string>();
        expected.Add("Elm");
        expected.Add("Clojure");
        expected.Add("C#");
        Assert.Equal(expected,
            Languages.ReverseList(Languages.GetExistingLanguages()));
    }

    [Fact]
    public void IsExciting_yes()
    {
        Assert.True(Languages.IsExciting(Languages.GetExistingLanguages()));
    }

    [Fact]
    public void IsExciting_too_many()
    {
        var languages = Languages.GetExistingLanguages();
        languages.Insert(0, "VBA");
        Assert.False(Languages.IsExciting(languages));
    }

    [Fact]
    public void IsExciting_empty()
    {
        var languages = Languages.NewList();
        Assert.False(Languages.IsExciting(languages));
    }

    [Fact]
    public void IsExciting_single_star()
    {
        var languages = Languages.GetExistingLanguages();
        languages.RemoveAt(2);
        languages.RemoveAt(1);
        Assert.True(Languages.IsExciting(languages));
    }

    [Fact]
    public void RemoveLanguage_yes()
    {
        var expected = new List<string>();
        expected.Add("C#");
        expected.Add("Elm");
        var languages = Languages.GetExistingLanguages();
        Assert.Equal(expected, Languages.RemoveLanguage(languages, "Clojure"));
    }

    [Fact]
    public void RemoveLanguage_no()
    {
        var expected = new List<string>();
        expected.Add("C#");
        expected.Add("Clojure");
        expected.Add("Elm");
        var languages = Languages.GetExistingLanguages();
        Assert.Equal(expected, Languages.RemoveLanguage(languages, "English"));
    }

    [Fact]
    public void IsUnique_yes()
    {
        var languages = Languages.GetExistingLanguages();
        Assert.True(Languages.IsUnique(languages));
    }

    [Fact]
    public void IsUnique_no()
    {
        var languages = Languages.GetExistingLanguages();
        languages.Add("C#");
        Assert.False(Languages.IsUnique(languages));
    }
}


text:
package at.bioinform

package object io {

  /** A position in a biological seqence. */
  case class Pos(value: Int) extends AnyVal {
    def +(pos: Pos) = Pos(value + pos.value)
  }

  implicit object Pos {
    def pos2Int(pos: Pos): Int = pos.value
  }

  /** An identifier of a biological seqence. */
  case class Id(value: String) extends AnyVal

  implicit object Id {
    def id2String(id: Id): String = id.value
  }

  /** A description of a biological seqence. */
  case class Desc(value: String) extends AnyVal

  implicit object Desc {
    def desc2String(desc: Desc): String = desc.value
  }

  /** A biological seqence. */
  case class Seq(value: String) extends AnyVal {
    def length() = Pos(value.length)

    def substring(start: Int, end: Int) = Seq(value.substring(start, end))
  }

  implicit object Seq {
    def seq2String(seq: Seq): String = seq.value
  }

}


text:
(function (can, GGRC) {
  'use strict';

  var tpl = can.view(GGRC.mustache_path +
    '/components/assessment/inline/inline.mustache');
  var innerTplFolder = GGRC.mustache_path + '/components/assessment/inline';

  function getTemplateByType(type) {
    type = can.Mustache.resolve(type);
    return innerTplFolder + '/' + type + '.mustache';
  }

  GGRC.Components('assessmentInlineEdit', {
    tag: 'assessment-inline-edit',
    template: tpl,
    viewModel: {
      define: {
        readonly: {
          type: 'htmlbool',
          value: false
        },
        isEditable: {
          get: function () {
            return !(this.attr('readonly'));
          }
        }
      },
      titleText: '',
      type: '',
      value: null,
      options: [],
      isSaving: false,
      isEdit: false,
      context: {
        value: null,
        options: null
      },

      _EV_BEFORE_EDIT: 'before-edit',  // before entering the edit mode

      setPerson: function (scope, el, ev) {
        this.attr('context.value', ev.selectedItem.serialize());
      },
      unsetPerson: function (scope, el, ev) {
        ev.preventDefault();
        this.attr('context.value', undefined);
      },

      /**
       * Enter the edit mode if editing is allowed (i.e. the readonly option is
       * not set).
       *
       * If the readonly option is enabled, do not do anything. The same if the
       * beforeEdit handler is not defined, or if the promise it returns is not
       * resolved.
       *
       * @param {can.Map} scope - the scope object itself (this)
       * @param {jQuery.Element} $el - the DOM element that triggered the event
       * @param {jQuery.Event} event - the event object
       */
      enableEdit: function (scope, $el, event) {
        var confirmation;
        var onBeforeEdit = this.$rootEl.attr('can-' + scope._EV_BEFORE_EDIT);

        event.preventDefault();
        event.stopPropagation();

        if (this.attr('readonly')) {
          return;
        }

        if (!onBeforeEdit) {
          this.attr('isEdit', true);
          return;
        }

        confirmation = this.$rootEl.triggerHandler({
          type: this._EV_BEFORE_EDIT
        });

        confirmation.done(function () {
          this.attr('isEdit', true);
        }.bind(this));   // and do nothing if no confirmation by the user
      },
      onCancel: function (scope) {
        var value = scope.attr('value');
        scope.attr('isEdit', false);
        scope.attr('context.value', value);
      },
      onSave: function () {
        var oldValue = this.attr('value');
        var value = this.attr('context.value');

        this.attr('isEdit', false);
        // In case value is String and consists only of spaces - do nothing
        if (typeof value === 'string' && !value.trim()) {
          this.attr('context.value', '');
          value = null;
        }

        if (oldValue === value) {
          return;
        }

        this.attr('value', value);
        this.attr('isSaving', true);
      }
    },
    init: function () {
      var viewModel = this.viewModel;
      var value = viewModel.attr('value');

      viewModel.attr('context.value', value);
    },
    events: {
      inserted: function (el) {
        this.viewModel.attr('$rootEl', $(el));
      },
      '{window} mousedown': function (el, ev) {
        var viewModel = this.viewModel;
        var isInside = GGRC.Utils.events.isInnerClick(this.element, ev.target);

        if (!isInside && viewModel.attr('isEdit')) {
          viewModel.onCancel(viewModel);
        }
      }
    },
    helpers: {
      renderInnerTemplateByType: function (type, options) {
        return can.view.render(getTemplateByType(type), options.context);
      }
    }
  });
})(window.can, window.GGRC);


text:
package kernels.algo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.ListIterator;

import util.Pair;
import util.Utility;

public class AllOrderedCharSubsequencesBF {

	Character[] a1, a2;

	public AllOrderedCharSubsequencesBF(Character[] a1, Character[] a2) {
		this.a1 = a1;
		this.a2 = a2;
	}

	public static Character[][] getAllSubSequences(Character[] a) {
		int resultSize = (int)Math.pow(2, a.length)-1;
		Character[][] result = new Character[resultSize][];
		int i=0;
		for(int l=1; l<=a.length; l++) {
			int[][] nairs = Utility.n_air(a.length, l);
			for(int[] comb : nairs) {
				Character[] result_i = new Character[l];
				for(int j=0; j<l; j++) {
					result_i[j] = a[comb[j]];
				}
				result[i] = result_i;
				i++;
			}
		}
		return result;
	}

	public static boolean equals(Character[] a, Character[] b) {
		if (a.length != b.length) return false;
		for(int i=0; i<a.length; i++) {
			if (!a[i].equals(b[i])) return false;
		}
		return true;
	}

	public ArrayList<ArrayList<Pair<Character>>> getAllSubsequences() {
		ArrayList<ArrayList<Pair<Character>>> result =
			new ArrayList<ArrayList<Pair<Character>>>();
		Character[][] allSubSequencesA1 = getAllSubSequences(a1);
		Character[][] allSubSequencesA2 = getAllSubSequences(a2);
		for(Character[] subA1 : allSubSequencesA1) {
			for(Character[] subA2 : allSubSequencesA2) {
				if (equals(subA1, subA2)) {
					ArrayList<Pair<Character>> pairList = buildPairList(subA1, subA2);
					addClosure(result, pairList);
				}
			}
		}
		return result;
	}

	public static void addClosure(
			ArrayList<ArrayList<Pair<Character>>> closureList,
			ArrayList<Pair<Character>> pairList) {
		ListIterator<ArrayList<Pair<Character>>> iter = closureList.listIterator();
		while(iter.hasNext()) {
			ArrayList<Pair<Character>> list = iter.next();
			if (list.size()==pairList.size()) continue;
			if (pairList.size()>list.size()) {
				if (isSuperSet(pairList, list)) iter.remove();
			}
			else if (isSuperSet(list, pairList)) return;
		}
		closureList.add(pairList);
	}

	public static ArrayList<Pair<Character>> buildPairList(
			Character[] subA1, Character[] subA2) {
		ArrayList<Pair<Character>> result = new ArrayList<Pair<Character>>(subA1.length);
		for(int i=0; i<subA1.length; i++) {
			Pair<Character> pair = new Pair<Character>(subA1[i],subA2[i]);
			result.add(pair);
		}
		return result;
	}

	public static boolean isSuperSet(
			ArrayList<Pair<Character>> bigPairList,
			ArrayList<Pair<Character>> smallPairList) {
		ListIterator<Pair<Character>> smallLI = smallPairList.listIterator();
		ListIterator<Pair<Character>> bigLI = bigPairList.listIterator();
		while(smallLI.hasNext()) {
			Pair<Character> p1 = smallLI.next();
			boolean found = false;
			while(bigLI.hasNext()) {
				Pair<Character> p2 = bigLI.next();
				if (p1.getFirst()==p2.getFirst() &&
						p1.getSecond()==p2.getSecond()) {
					found = true;
					break;
				}
			}
			if (!found) return false;
		}
		return true;
	}

	public static boolean isEqualPairList(
			ArrayList<Pair<Character>> pairList1,
			ArrayList<Pair<Character>> pairList2) {
		if (pairList1.size() != pairList2.size()) return false;
		ListIterator<Pair<Character>> i1 = pairList1.listIterator();
		ListIterator<Pair<Character>> i2 = pairList2.listIterator();
		while(i1.hasNext()) {
			Pair<Character> p1 = i1.next();
			Pair<Character> p2 = i2.next();
			if (p1.getFirst()!=p2.getFirst() ||
					p1.getSecond()!=p2.getSecond()) return false;
		}
		return true;
	}

	public static boolean isEqual(
			ArrayList<ArrayList<Pair<Character>>> allS1,
			ArrayList<ArrayList<Pair<Character>>> allS2) {
		if (allS1.size() != allS2.size()) return false;
		BitSet indexMatched = new BitSet(allS1.size());
		int index1 = 0;
		for(ArrayList<Pair<Character>> pairList1 : allS1) {
			int index2=0;
			boolean found = false;
			for(ArrayList<Pair<Character>> pairList2 : allS2) {
				if (!indexMatched.get(index2)) {
					if (isEqualPairList(pairList1, pairList2)) {
						found = true;
						indexMatched.set(index2);
						break;
					}
				}
				index2++;
			}
			if (!found) {
				return false;
			}
			index1++;
		}
		return true;
	}

	public static int indexOf(Character c, Character[] a) {
		for(int i=0; i<a.length; i++) {
			if (c==a[i]) return i;
		}
		return -1;
	}

	public static String toString(ArrayList<Pair<Character>> pairList,
			Character[] a1, Character[] a2) {
		String result = "(";
		for(ListIterator<Pair<Character>> iter2 = pairList.listIterator();
				iter2.hasNext();) {
			Pair<Character> p = iter2.next();
			Character c1 = p.getFirst();
			Character c2 = p.getSecond();
			int i1 = indexOf(c1, a1);
			int i2 = indexOf(c2, a2);
			result += "(" + c1 + i1 + "," + c2 + i2 + ")";
			if (iter2.hasNext()) result += ", ";
		}
		result += ")";
		return result;
	}

	public static void main1(String[] args) {
		Character[] a1 = new Character[]{new Character('A'),new Character('B'),new Character('C'),new Character('C'),new Character('A'),new Character('F'),new Character('G'),new Character('A'),new Character('A'),new Character('I'),new Character('L')};
		Character[] a2 = new Character[]{new Character('A'),new Character('B'),new Character('C'),new Character('D'),new Character('F'),new Character('A'),new Character('C'),new Character('F'),new Character('G'),new Character('H')};
		//Character[] a1 = new Character[]{new Character('A'),new Character('B'),new Character('C')};
		//Character[] a2 = new Character[]{new Character('A'),new Character('B'),new Character('B')};
		AllOrderedCharSubsequencesBF S = new AllOrderedCharSubsequencesBF(a1,a2);
		ArrayList<ArrayList<Pair<Character>>> allS = S.getAllSubsequences();
		for(ArrayList<Pair<Character>> pairList : allS) {
			System.out.println(pairList);
		}
		System.out.println(allS.size());
	}

	public static Character[] makeNewRandomCharArray(Character[] alphabet, int size) {
		int lastAlphaChar = alphabet.length-1;
		Character[] result = new Character[size];
		for(int i=0; i<size; i++) {
			result[i] = new Character(
					alphabet[Utility.randomInteger(lastAlphaChar)]);
		}
		return result;
	}

	public static Character[] makeNewCharArray(Character[] array) {
		Character[] result = new Character[array.length];
		for(int i=0; i<array.length; i++) {
			result[i] = new Character(array[i]);
		}
		return result;
	}

	public static void main4(String[] args) {

		Character[] alphabet = new Character[]{'A','B','C','D','E'};
		int maxLength = 8;

		while(true) {
			int a1Size = Utility.randomInteger(maxLength);
			Character[] a1 = makeNewRandomCharArray(alphabet, a1Size);

			int a2Size = Utility.randomInteger(maxLength);
			Character[] a2 = makeNewRandomCharArray(alphabet, a2Size);

			AllOrderedCharSubsequencesBF S1 = new AllOrderedCharSubsequencesBF(a1,a2);
			ArrayList<ArrayList<Pair<Character>>> allS1 = S1.getAllSubsequences();

			AllOrderedCharSubsequences S2 = new AllOrderedCharSubsequences(a1,a2);
			ArrayList<ArrayList<Pair<Character>>> allS2 = S2.getAllSubsequences();

			System.out.println(Arrays.toString(a1));
			System.out.println(Arrays.toString(a2));

			boolean isEqual = isEqual(allS1, allS2);
			if (isEqual) System.out.println("CORRECT\n");
			else {
				System.out.println("NON CORRECT:\n");
				for(ArrayList<Pair<Character>> pairList : allS1) {
					System.out.println(toString(pairList, a1, a2));
				}
				System.out.println("------------");
				for(ArrayList<Pair<Character>> pairList : allS2) {
					System.out.println(toString(pairList, a1, a2));
				}
				break;
			}
		}
	}

	public static void main(String[] args) {

		Character[] a1 = makeNewCharArray(new Character[]{'B','C','B','D'});
		Character[] a2 = makeNewCharArray(new Character[]{'B','B','C'});

		AllOrderedCharSubsequencesBF S1 = new AllOrderedCharSubsequencesBF(a1,a2);
		ArrayList<ArrayList<Pair<Character>>> allS1 = S1.getAllSubsequences();

		AllOrderedCharSubsequences S2 = new AllOrderedCharSubsequences(a1,a2);
		ArrayList<ArrayList<Pair<Character>>> allS2 = S2.getAllSubsequences();

		System.out.println(Arrays.toString(a1));
		System.out.println(Arrays.toString(a2));

		boolean isEqual = isEqual(allS1, allS2);
		if (isEqual) System.out.println("CORRECT\n");
		else System.out.println("NON CORRECT:\n");
		for(ArrayList<Pair<Character>> pairList : allS1) {
			System.out.println(toString(pairList, a1, a2));
		}
	}
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=constant.MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT.html">

Redirecting to constant.MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT.html...


text:
<?xml version="1.0"?>

<!--L
   Copyright Ekagra Software Technologies Ltd.
   Copyright SAIC, SAIC-Frederick

   Distributed under the OSI-approved BSD 3-Clause License.
   See http://ncip.github.com/common-security-module/LICENSE.txt for details.
L-->

<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping default-lazy="false">
<!--
    Created by the Middlegen Hibernate plugin 2.1

    http://boss.bekk.no/boss/middlegen/
    http://www.hibernate.org/
-->

<class
    name="gov.nih.nci.security.authorization.domainobjects.Group"
    table="CSM_GROUP"
>

    <id
        name="groupId"
        type="java.lang.Long"
        column="GROUP_ID"
        unsaved-value="0"
    >
        <generator class="native">
		 <param name="sequence">CSM_GROUP_GROUP_ID_SEQ</param>
	 </generator>
    </id>

    <property
        name="groupName"
        type="java.lang.String"
        column="GROUP_NAME"
        length="255"
    />
    <property
        name="groupDesc"
        type="java.lang.String"
        column="GROUP_DESC"
        length="200"
    />
    <property
        name="updateDate"
        type="java.sql.Date"
        column="UPDATE_DATE"
        length="10"
    />

    <!-- Associations -->

    <many-to-one
        name="application"
        class="gov.nih.nci.security.authorization.domainobjects.Application"
        not-null="true"
    >
        <column name="APPLICATION_ID" />
    </many-to-one>

    <set name="users" lazy="true" table="CSM_USER_GROUP">
           <key column="group_id"/>
           <many-to-many column="user_id" class="gov.nih.nci.security.authorization.domainobjects.User"/>
     </set>

</class>
</hibernate-mapping>