text:
/*
  Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/property.h"
#include "MagickCore/animate.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/client.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/compress.h"
#include "MagickCore/constitute.h"
#include "MagickCore/display.h"
#include "MagickCore/draw.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/feature.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/list.h"
#include "MagickCore/image-private.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/resource_.h"
#include "MagickCore/segment.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/signature-private.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/timer.h"
#include "MagickCore/utility.h"
#include "MagickCore/version.h"

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   G e t I m a g e F e a t u r e s                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GetImageFeatures() returns features for each channel in the image in
%  each of four directions (horizontal, vertical, left and right diagonals)
%  for the specified distance.  The features include the angular second
%  moment, contrast, correlation, sum of squares: variance, inverse difference
%  moment, sum average, sum varience, sum entropy, entropy, difference variance,%  difference entropy, information measures of correlation 1, information
%  measures of correlation 2, and maximum correlation coefficient.  You can
%  access the red channel contrast, for example, like this:
%
%      channel_features=GetImageFeatures(image,1,exception);
%      contrast=channel_features[RedPixelChannel].contrast[0];
%
%  Use MagickRelinquishMemory() to free the features buffer.
%
%  The format of the GetImageFeatures method is:
%
%      ChannelFeatures *GetImageFeatures(const Image *image,
%        const size_t distance,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image: the image.
%
%    o distance: the distance.
%
%    o exception: return any errors or warnings in this structure.
%
*/

static inline ssize_t MagickAbsoluteValue(const ssize_t x)
{
  if (x < 0)
    return(-x);
  return(x);
}

MagickExport ChannelFeatures *GetImageFeatures(const Image *image,
  const size_t distance,ExceptionInfo *exception)
{
  typedef struct _ChannelStatistics
  {
    PixelInfo
      direction[4];  /* horizontal, vertical, left and right diagonals */
  } ChannelStatistics;

  CacheView
    *image_view;

  ChannelFeatures
    *channel_features;

  ChannelStatistics
    **cooccurrence,
    correlation,
    *density_x,
    *density_xy,
    *density_y,
    entropy_x,
    entropy_xy,
    entropy_xy1,
    entropy_xy2,
    entropy_y,
    mean,
    **Q,
    *sum,
    sum_squares,
    variance;

  PixelPacket
    gray,
    *grays;

  MagickBooleanType
    status;

  register ssize_t
    i;

  size_t
    length;

  ssize_t
    y;

  unsigned int
    number_grays;

  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  if ((image->columns < (distance+1)) || (image->rows < (distance+1)))
    return((ChannelFeatures *) NULL);
  length=CompositeChannels+1UL;
  channel_features=(ChannelFeatures *) AcquireQuantumMemory(length,
    sizeof(*channel_features));
  if (channel_features == (ChannelFeatures *) NULL)
    ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
  (void) ResetMagickMemory(channel_features,0,length*
    sizeof(*channel_features));
  /*
    Form grays.
  */
  grays=(PixelPacket *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*grays));
  if (grays == (PixelPacket *) NULL)
    {
      channel_features=(ChannelFeatures *) RelinquishMagickMemory(
        channel_features);
      (void) ThrowMagickException(exception,GetMagickModule(),
        ResourceLimitError,"MemoryAllocationFailed","'%s'",image->filename);
      return(channel_features);
    }
  for (i=0; i <= (ssize_t) MaxMap; i++)
  {
    grays[i].red=(~0U);
    grays[i].green=(~0U);
    grays[i].blue=(~0U);
    grays[i].alpha=(~0U);
    grays[i].black=(~0U);
  }
  status=MagickTrue;
  image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static,4) shared(status) \
    dynamic_number_threads(image,image->columns,image->rows,1)
#endif
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    register const Quantum
      *restrict p;

    register ssize_t
      x;

    if (status == MagickFalse)
      continue;
    p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
    if (p == (const Quantum *) NULL)
      {
        status=MagickFalse;
        continue;
      }
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      grays[ScaleQuantumToMap(GetPixelRed(image,p))].red=
        ScaleQuantumToMap(GetPixelRed(image,p));
      grays[ScaleQuantumToMap(GetPixelGreen(image,p))].green=
        ScaleQuantumToMap(GetPixelGreen(image,p));
      grays[ScaleQuantumToMap(GetPixelBlue(image,p))].blue=
        ScaleQuantumToMap(GetPixelBlue(image,p));
      if (image->colorspace == CMYKColorspace)
        grays[ScaleQuantumToMap(GetPixelBlack(image,p))].black=
          ScaleQuantumToMap(GetPixelBlack(image,p));
      if (image->alpha_trait == BlendPixelTrait)
        grays[ScaleQuantumToMap(GetPixelAlpha(image,p))].alpha=
          ScaleQuantumToMap(GetPixelAlpha(image,p));
      p+=GetPixelChannels(image);
    }
  }
  image_view=DestroyCacheView(image_view);
  if (status == MagickFalse)
    {
      grays=(PixelPacket *) RelinquishMagickMemory(grays);
      channel_features=(ChannelFeatures *) RelinquishMagickMemory(
        channel_features);
      return(channel_features);
    }
  (void) ResetMagickMemory(&gray,0,sizeof(gray));
  for (i=0; i <= (ssize_t) MaxMap; i++)
  {
    if (grays[i].red != ~0U)
      grays[gray.red++].red=grays[i].red;
    if (grays[i].green != ~0U)
      grays[gray.green++].green=grays[i].green;
    if (grays[i].blue != ~0U)
      grays[gray.blue++].blue=grays[i].blue;
    if (image->colorspace == CMYKColorspace)
      if (grays[i].black != ~0U)
        grays[gray.black++].black=grays[i].black;
    if (image->alpha_trait == BlendPixelTrait)
      if (grays[i].alpha != ~0U)
        grays[gray.alpha++].alpha=grays[i].alpha;
  }
  /*
    Allocate spatial dependence matrix.
  */
  number_grays=gray.red;
  if (gray.green > number_grays)
    number_grays=gray.green;
  if (gray.blue > number_grays)
    number_grays=gray.blue;
  if (image->colorspace == CMYKColorspace)
    if (gray.black > number_grays)
      number_grays=gray.black;
  if (image->alpha_trait == BlendPixelTrait)
    if (gray.alpha > number_grays)
      number_grays=gray.alpha;
  cooccurrence=(ChannelStatistics **) AcquireQuantumMemory(number_grays,
    sizeof(*cooccurrence));
  density_x=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1),
    sizeof(*density_x));
  density_xy=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1),
    sizeof(*density_xy));
  density_y=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1),
    sizeof(*density_y));
  Q=(ChannelStatistics **) AcquireQuantumMemory(number_grays,sizeof(*Q));
  sum=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(*sum));
  if ((cooccurrence == (ChannelStatistics **) NULL) ||
      (density_x == (ChannelStatistics *) NULL) ||
      (density_xy == (ChannelStatistics *) NULL) ||
      (density_y == (ChannelStatistics *) NULL) ||
      (Q == (ChannelStatistics **) NULL) ||
      (sum == (ChannelStatistics *) NULL))
    {
      if (Q != (ChannelStatistics **) NULL)
        {
          for (i=0; i < (ssize_t) number_grays; i++)
            Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]);
          Q=(ChannelStatistics **) RelinquishMagickMemory(Q);
        }
      if (sum != (ChannelStatistics *) NULL)
        sum=(ChannelStatistics *) RelinquishMagickMemory(sum);
      if (density_y != (ChannelStatistics *) NULL)
        density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y);
      if (density_xy != (ChannelStatistics *) NULL)
        density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy);
      if (density_x != (ChannelStatistics *) NULL)
        density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x);
      if (cooccurrence != (ChannelStatistics **) NULL)
        {
          for (i=0; i < (ssize_t) number_grays; i++)
            cooccurrence[i]=(ChannelStatistics *)
              RelinquishMagickMemory(cooccurrence[i]);
          cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(
            cooccurrence);
        }
      grays=(PixelPacket *) RelinquishMagickMemory(grays);
      channel_features=(ChannelFeatures *) RelinquishMagickMemory(
        channel_features);
      (void) ThrowMagickException(exception,GetMagickModule(),
        ResourceLimitError,"MemoryAllocationFailed","'%s'",image->filename);
      return(channel_features);
    }
  (void) ResetMagickMemory(&correlation,0,sizeof(correlation));
  (void) ResetMagickMemory(density_x,0,2*(number_grays+1)*sizeof(*density_x));
  (void) ResetMagickMemory(density_xy,0,2*(number_grays+1)*sizeof(*density_xy));
  (void) ResetMagickMemory(density_y,0,2*(number_grays+1)*sizeof(*density_y));
  (void) ResetMagickMemory(&mean,0,sizeof(mean));
  (void) ResetMagickMemory(sum,0,number_grays*sizeof(*sum));
  (void) ResetMagickMemory(&sum_squares,0,sizeof(sum_squares));
  (void) ResetMagickMemory(density_xy,0,2*number_grays*sizeof(*density_xy));
  (void) ResetMagickMemory(&entropy_x,0,sizeof(entropy_x));
  (void) ResetMagickMemory(&entropy_xy,0,sizeof(entropy_xy));
  (void) ResetMagickMemory(&entropy_xy1,0,sizeof(entropy_xy1));
  (void) ResetMagickMemory(&entropy_xy2,0,sizeof(entropy_xy2));
  (void) ResetMagickMemory(&entropy_y,0,sizeof(entropy_y));
  (void) ResetMagickMemory(&variance,0,sizeof(variance));
  for (i=0; i < (ssize_t) number_grays; i++)
  {
    cooccurrence[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,
      sizeof(**cooccurrence));
    Q[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(**Q));
    if ((cooccurrence[i] == (ChannelStatistics *) NULL) ||
        (Q[i] == (ChannelStatistics *) NULL))
      break;
    (void) ResetMagickMemory(cooccurrence[i],0,number_grays*
      sizeof(**cooccurrence));
    (void) ResetMagickMemory(Q[i],0,number_grays*sizeof(**Q));
  }
  if (i < (ssize_t) number_grays)
    {
      for (i--; i >= 0; i--)
      {
        if (Q[i] != (ChannelStatistics *) NULL)
          Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]);
        if (cooccurrence[i] != (ChannelStatistics *) NULL)
          cooccurrence[i]=(ChannelStatistics *)
            RelinquishMagickMemory(cooccurrence[i]);
      }
      Q=(ChannelStatistics **) RelinquishMagickMemory(Q);
      cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence);
      sum=(ChannelStatistics *) RelinquishMagickMemory(sum);
      density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y);
      density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy);
      density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x);
      grays=(PixelPacket *) RelinquishMagickMemory(grays);
      channel_features=(ChannelFeatures *) RelinquishMagickMemory(
        channel_features);
      (void) ThrowMagickException(exception,GetMagickModule(),
        ResourceLimitError,"MemoryAllocationFailed","'%s'",image->filename);
      return(channel_features);
    }
  /*
    Initialize spatial dependence matrix.
  */
  status=MagickTrue;
  image_view=AcquireVirtualCacheView(image,exception);
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    register const Quantum
      *restrict p;

    register ssize_t
      x;

    ssize_t
      i,
      offset,
      u,
      v;

    if (status == MagickFalse)
      continue;
    p=GetCacheViewVirtualPixels(image_view,-(ssize_t) distance,y,image->columns+
      2*distance,distance+2,exception);
    if (p == (const Quantum *) NULL)
      {
        status=MagickFalse;
        continue;
      }
    p+=distance*GetPixelChannels(image);;
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      for (i=0; i < 4; i++)
      {
        switch (i)
        {
          case 0:
          default:
          {
            /*
              Horizontal adjacency.
            */
            offset=(ssize_t) distance;
            break;
          }
          case 1:
          {
            /*
              Vertical adjacency.
            */
            offset=(ssize_t) (image->columns+2*distance);
            break;
          }
          case 2:
          {
            /*
              Right diagonal adjacency.
            */
            offset=(ssize_t) ((image->columns+2*distance)-distance);
            break;
          }
          case 3:
          {
            /*
              Left diagonal adjacency.
            */
            offset=(ssize_t) ((image->columns+2*distance)+distance);
            break;
          }
        }
        u=0;
        v=0;
        while (grays[u].red != ScaleQuantumToMap(GetPixelRed(image,p)))
          u++;
        while (grays[v].red != ScaleQuantumToMap(GetPixelRed(image,p+offset*GetPixelChannels(image))))
          v++;
        cooccurrence[u][v].direction[i].red++;
        cooccurrence[v][u].direction[i].red++;
        u=0;
        v=0;
        while (grays[u].green != ScaleQuantumToMap(GetPixelGreen(image,p)))
          u++;
        while (grays[v].green != ScaleQuantumToMap(GetPixelGreen(image,p+offset*GetPixelChannels(image))))
          v++;
        cooccurrence[u][v].direction[i].green++;
        cooccurrence[v][u].direction[i].green++;
        u=0;
        v=0;
        while (grays[u].blue != ScaleQuantumToMap(GetPixelBlue(image,p)))
          u++;
        while (grays[v].blue != ScaleQuantumToMap(GetPixelBlue(image,p+offset*GetPixelChannels(image))))
          v++;
        cooccurrence[u][v].direction[i].blue++;
        cooccurrence[v][u].direction[i].blue++;
        if (image->colorspace == CMYKColorspace)
          {
            u=0;
            v=0;
            while (grays[u].black != ScaleQuantumToMap(GetPixelBlack(image,p)))
              u++;
            while (grays[v].black != ScaleQuantumToMap(GetPixelBlack(image,p+offset*GetPixelChannels(image))))
              v++;
            cooccurrence[u][v].direction[i].black++;
            cooccurrence[v][u].direction[i].black++;
          }
        if (image->alpha_trait == BlendPixelTrait)
          {
            u=0;
            v=0;
            while (grays[u].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p)))
              u++;
            while (grays[v].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p+offset*GetPixelChannels(image))))
              v++;
            cooccurrence[u][v].direction[i].alpha++;
            cooccurrence[v][u].direction[i].alpha++;
          }
      }
      p+=GetPixelChannels(image);
    }
  }
  grays=(PixelPacket *) RelinquishMagickMemory(grays);
  image_view=DestroyCacheView(image_view);
  if (status == MagickFalse)
    {
      for (i=0; i < (ssize_t) number_grays; i++)
        cooccurrence[i]=(ChannelStatistics *)
          RelinquishMagickMemory(cooccurrence[i]);
      cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence);
      channel_features=(ChannelFeatures *) RelinquishMagickMemory(
        channel_features);
      (void) ThrowMagickException(exception,GetMagickModule(),
        ResourceLimitError,"MemoryAllocationFailed","'%s'",image->filename);
      return(channel_features);
    }
  /*
    Normalize spatial dependence matrix.
  */
  for (i=0; i < 4; i++)
  {
    double
      normalize;

    register ssize_t
      y;

    switch (i)
    {
      case 0:
      default:
      {
        /*
          Horizontal adjacency.
        */
        normalize=2.0*image->rows*(image->columns-distance);
        break;
      }
      case 1:
      {
        /*
          Vertical adjacency.
        */
        normalize=2.0*(image->rows-distance)*image->columns;
        break;
      }
      case 2:
      {
        /*
          Right diagonal adjacency.
        */
        normalize=2.0*(image->rows-distance)*(image->columns-distance);
        break;
      }
      case 3:
      {
        /*
          Left diagonal adjacency.
        */
        normalize=2.0*(image->rows-distance)*(image->columns-distance);
        break;
      }
    }
    normalize=PerceptibleReciprocal(normalize);
    for (y=0; y < (ssize_t) number_grays; y++)
    {
      register ssize_t
        x;

      for (x=0; x < (ssize_t) number_grays; x++)
      {
        cooccurrence[x][y].direction[i].red*=normalize;
        cooccurrence[x][y].direction[i].green*=normalize;
        cooccurrence[x][y].direction[i].blue*=normalize;
        if (image->colorspace == CMYKColorspace)
          cooccurrence[x][y].direction[i].black*=normalize;
        if (image->alpha_trait == BlendPixelTrait)
          cooccurrence[x][y].direction[i].alpha*=normalize;
      }
    }
  }
  /*
    Compute texture features.
  */
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static,4) shared(status) \
    dynamic_number_threads(image,number_grays,number_grays,1)
#endif
  for (i=0; i < 4; i++)
  {
    register ssize_t
      y;

    for (y=0; y < (ssize_t) number_grays; y++)
    {
      register ssize_t
        x;

      for (x=0; x < (ssize_t) number_grays; x++)
      {
        /*
          Angular second moment:  measure of homogeneity of the image.
        */
        channel_features[RedPixelChannel].angular_second_moment[i]+=
          cooccurrence[x][y].direction[i].red*
          cooccurrence[x][y].direction[i].red;
        channel_features[GreenPixelChannel].angular_second_moment[i]+=
          cooccurrence[x][y].direction[i].green*
          cooccurrence[x][y].direction[i].green;
        channel_features[BluePixelChannel].angular_second_moment[i]+=
          cooccurrence[x][y].direction[i].blue*
          cooccurrence[x][y].direction[i].blue;
        if (image->colorspace == CMYKColorspace)
          channel_features[BlackPixelChannel].angular_second_moment[i]+=
            cooccurrence[x][y].direction[i].black*
            cooccurrence[x][y].direction[i].black;
        if (image->alpha_trait == BlendPixelTrait)
          channel_features[AlphaPixelChannel].angular_second_moment[i]+=
            cooccurrence[x][y].direction[i].alpha*
            cooccurrence[x][y].direction[i].alpha;
        /*
          Correlation: measure of linear-dependencies in the image.
        */
        sum[y].direction[i].red+=cooccurrence[x][y].direction[i].red;
        sum[y].direction[i].green+=cooccurrence[x][y].direction[i].green;
        sum[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue;
        if (image->colorspace == CMYKColorspace)
          sum[y].direction[i].black+=cooccurrence[x][y].direction[i].black;
        if (image->alpha_trait == BlendPixelTrait)
          sum[y].direction[i].alpha+=cooccurrence[x][y].direction[i].alpha;
        correlation.direction[i].red+=x*y*cooccurrence[x][y].direction[i].red;
        correlation.direction[i].green+=x*y*
          cooccurrence[x][y].direction[i].green;
        correlation.direction[i].blue+=x*y*
          cooccurrence[x][y].direction[i].blue;
        if (image->colorspace == CMYKColorspace)
          correlation.direction[i].black+=x*y*
            cooccurrence[x][y].direction[i].black;
        if (image->alpha_trait == BlendPixelTrait)
          correlation.direction[i].alpha+=x*y*
            cooccurrence[x][y].direction[i].alpha;
        /*
          Inverse Difference Moment.
        */
        channel_features[RedPixelChannel].inverse_difference_moment[i]+=
          cooccurrence[x][y].direction[i].red/((y-x)*(y-x)+1);
        channel_features[GreenPixelChannel].inverse_difference_moment[i]+=
          cooccurrence[x][y].direction[i].green/((y-x)*(y-x)+1);
        channel_features[BluePixelChannel].inverse_difference_moment[i]+=
          cooccurrence[x][y].direction[i].blue/((y-x)*(y-x)+1);
        if (image->colorspace == CMYKColorspace)
          channel_features[BlackPixelChannel].inverse_difference_moment[i]+=
            cooccurrence[x][y].direction[i].black/((y-x)*(y-x)+1);
        if (image->alpha_trait == BlendPixelTrait)
          channel_features[AlphaPixelChannel].inverse_difference_moment[i]+=
            cooccurrence[x][y].direction[i].alpha/((y-x)*(y-x)+1);
        /*
          Sum average.
        */
        density_xy[y+x+2].direction[i].red+=
          cooccurrence[x][y].direction[i].red;
        density_xy[y+x+2].direction[i].green+=
          cooccurrence[x][y].direction[i].green;
        density_xy[y+x+2].direction[i].blue+=
          cooccurrence[x][y].direction[i].blue;
        if (image->colorspace == CMYKColorspace)
          density_xy[y+x+2].direction[i].black+=
            cooccurrence[x][y].direction[i].black;
        if (image->alpha_trait == BlendPixelTrait)
          density_xy[y+x+2].direction[i].alpha+=
            cooccurrence[x][y].direction[i].alpha;
        /*
          Entropy.
        */
        channel_features[RedPixelChannel].entropy[i]-=
          cooccurrence[x][y].direction[i].red*
          log10(cooccurrence[x][y].direction[i].red+MagickEpsilon);
        channel_features[GreenPixelChannel].entropy[i]-=
          cooccurrence[x][y].direction[i].green*
          log10(cooccurrence[x][y].direction[i].green+MagickEpsilon);
        channel_features[BluePixelChannel].entropy[i]-=
          cooccurrence[x][y].direction[i].blue*
          log10(cooccurrence[x][y].direction[i].blue+MagickEpsilon);
        if (image->colorspace == CMYKColorspace)
          channel_features[BlackPixelChannel].entropy[i]-=
            cooccurrence[x][y].direction[i].black*
            log10(cooccurrence[x][y].direction[i].black+MagickEpsilon);
        if (image->alpha_trait == BlendPixelTrait)
          channel_features[AlphaPixelChannel].entropy[i]-=
            cooccurrence[x][y].direction[i].alpha*
            log10(cooccurrence[x][y].direction[i].alpha+MagickEpsilon);
        /*
          Information Measures of Correlation.
        */
        density_x[x].direction[i].red+=cooccurrence[x][y].direction[i].red;
        density_x[x].direction[i].green+=cooccurrence[x][y].direction[i].green;
        density_x[x].direction[i].blue+=cooccurrence[x][y].direction[i].blue;
        if (image->alpha_trait == BlendPixelTrait)
          density_x[x].direction[i].alpha+=
            cooccurrence[x][y].direction[i].alpha;
        if (image->colorspace == CMYKColorspace)
          density_x[x].direction[i].black+=
            cooccurrence[x][y].direction[i].black;
        density_y[y].direction[i].red+=cooccurrence[x][y].direction[i].red;
        density_y[y].direction[i].green+=cooccurrence[x][y].direction[i].green;
        density_y[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue;
        if (image->colorspace == CMYKColorspace)
          density_y[y].direction[i].black+=
            cooccurrence[x][y].direction[i].black;
        if (image->alpha_trait == BlendPixelTrait)
          density_y[y].direction[i].alpha+=
            cooccurrence[x][y].direction[i].alpha;
      }
      mean.direction[i].red+=y*sum[y].direction[i].red;
      sum_squares.direction[i].red+=y*y*sum[y].direction[i].red;
      mean.direction[i].green+=y*sum[y].direction[i].green;
      sum_squares.direction[i].green+=y*y*sum[y].direction[i].green;
      mean.direction[i].blue+=y*sum[y].direction[i].blue;
      sum_squares.direction[i].blue+=y*y*sum[y].direction[i].blue;
      if (image->colorspace == CMYKColorspace)
        {
          mean.direction[i].black+=y*sum[y].direction[i].black;
          sum_squares.direction[i].black+=y*y*sum[y].direction[i].black;
        }
      if (image->alpha_trait == BlendPixelTrait)
        {
          mean.direction[i].alpha+=y*sum[y].direction[i].alpha;
          sum_squares.direction[i].alpha+=y*y*sum[y].direction[i].alpha;
        }
    }
    /*
      Correlation: measure of linear-dependencies in the image.
    */
    channel_features[RedPixelChannel].correlation[i]=
      (correlation.direction[i].red-mean.direction[i].red*
      mean.direction[i].red)/(sqrt(sum_squares.direction[i].red-
      (mean.direction[i].red*mean.direction[i].red))*sqrt(
      sum_squares.direction[i].red-(mean.direction[i].red*
      mean.direction[i].red)));
    channel_features[GreenPixelChannel].correlation[i]=
      (correlation.direction[i].green-mean.direction[i].green*
      mean.direction[i].green)/(sqrt(sum_squares.direction[i].green-
      (mean.direction[i].green*mean.direction[i].green))*sqrt(
      sum_squares.direction[i].green-(mean.direction[i].green*
      mean.direction[i].green)));
    channel_features[BluePixelChannel].correlation[i]=
      (correlation.direction[i].blue-mean.direction[i].blue*
      mean.direction[i].blue)/(sqrt(sum_squares.direction[i].blue-
      (mean.direction[i].blue*mean.direction[i].blue))*sqrt(
      sum_squares.direction[i].blue-(mean.direction[i].blue*
      mean.direction[i].blue)));
    if (image->colorspace == CMYKColorspace)
      channel_features[BlackPixelChannel].correlation[i]=
        (correlation.direction[i].black-mean.direction[i].black*
        mean.direction[i].black)/(sqrt(sum_squares.direction[i].black-
        (mean.direction[i].black*mean.direction[i].black))*sqrt(
        sum_squares.direction[i].black-(mean.direction[i].black*
        mean.direction[i].black)));
    if (image->alpha_trait == BlendPixelTrait)
      channel_features[AlphaPixelChannel].correlation[i]=
        (correlation.direction[i].alpha-mean.direction[i].alpha*
        mean.direction[i].alpha)/(sqrt(sum_squares.direction[i].alpha-
        (mean.direction[i].alpha*mean.direction[i].alpha))*sqrt(
        sum_squares.direction[i].alpha-(mean.direction[i].alpha*
        mean.direction[i].alpha)));
  }
  /*
    Compute more texture features.
  */
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static,4) shared(status) \
    dynamic_number_threads(image,number_grays,number_grays,1)
#endif
  for (i=0; i < 4; i++)
  {
    register ssize_t
      x;

    for (x=2; x < (ssize_t) (2*number_grays); x++)
    {
      /*
        Sum average.
      */
      channel_features[RedPixelChannel].sum_average[i]+=
        x*density_xy[x].direction[i].red;
      channel_features[GreenPixelChannel].sum_average[i]+=
        x*density_xy[x].direction[i].green;
      channel_features[BluePixelChannel].sum_average[i]+=
        x*density_xy[x].direction[i].blue;
      if (image->colorspace == CMYKColorspace)
        channel_features[BlackPixelChannel].sum_average[i]+=
          x*density_xy[x].direction[i].black;
      if (image->alpha_trait == BlendPixelTrait)
        channel_features[AlphaPixelChannel].sum_average[i]+=
          x*density_xy[x].direction[i].alpha;
      /*
        Sum entropy.
      */
      channel_features[RedPixelChannel].sum_entropy[i]-=
        density_xy[x].direction[i].red*
        log10(density_xy[x].direction[i].red+MagickEpsilon);
      channel_features[GreenPixelChannel].sum_entropy[i]-=
        density_xy[x].direction[i].green*
        log10(density_xy[x].direction[i].green+MagickEpsilon);
      channel_features[BluePixelChannel].sum_entropy[i]-=
        density_xy[x].direction[i].blue*
        log10(density_xy[x].direction[i].blue+MagickEpsilon);
      if (image->colorspace == CMYKColorspace)
        channel_features[BlackPixelChannel].sum_entropy[i]-=
          density_xy[x].direction[i].black*
          log10(density_xy[x].direction[i].black+MagickEpsilon);
      if (image->alpha_trait == BlendPixelTrait)
        channel_features[AlphaPixelChannel].sum_entropy[i]-=
          density_xy[x].direction[i].alpha*
          log10(density_xy[x].direction[i].alpha+MagickEpsilon);
      /*
        Sum variance.
      */
      channel_features[RedPixelChannel].sum_variance[i]+=
        (x-channel_features[RedPixelChannel].sum_entropy[i])*
        (x-channel_features[RedPixelChannel].sum_entropy[i])*
        density_xy[x].direction[i].red;
      channel_features[GreenPixelChannel].sum_variance[i]+=
        (x-channel_features[GreenPixelChannel].sum_entropy[i])*
        (x-channel_features[GreenPixelChannel].sum_entropy[i])*
        density_xy[x].direction[i].green;
      channel_features[BluePixelChannel].sum_variance[i]+=
        (x-channel_features[BluePixelChannel].sum_entropy[i])*
        (x-channel_features[BluePixelChannel].sum_entropy[i])*
        density_xy[x].direction[i].blue;
      if (image->colorspace == CMYKColorspace)
        channel_features[BlackPixelChannel].sum_variance[i]+=
          (x-channel_features[BlackPixelChannel].sum_entropy[i])*
          (x-channel_features[BlackPixelChannel].sum_entropy[i])*
          density_xy[x].direction[i].black;
      if (image->alpha_trait == BlendPixelTrait)
        channel_features[AlphaPixelChannel].sum_variance[i]+=
          (x-channel_features[AlphaPixelChannel].sum_entropy[i])*
          (x-channel_features[AlphaPixelChannel].sum_entropy[i])*
          density_xy[x].direction[i].alpha;
    }
  }
  /*
    Compute more texture features.
  */
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static,4) shared(status) \
    dynamic_number_threads(image,number_grays,number_grays,1)
#endif
  for (i=0; i < 4; i++)
  {
    register ssize_t
      y;

    for (y=0; y < (ssize_t) number_grays; y++)
    {
      register ssize_t
        x;

      for (x=0; x < (ssize_t) number_grays; x++)
      {
        /*
          Sum of Squares: Variance
        */
        variance.direction[i].red+=(y-mean.direction[i].red+1)*
          (y-mean.direction[i].red+1)*cooccurrence[x][y].direction[i].red;
        variance.direction[i].green+=(y-mean.direction[i].green+1)*
          (y-mean.direction[i].green+1)*cooccurrence[x][y].direction[i].green;
        variance.direction[i].blue+=(y-mean.direction[i].blue+1)*
          (y-mean.direction[i].blue+1)*cooccurrence[x][y].direction[i].blue;
        if (image->colorspace == CMYKColorspace)
          variance.direction[i].black+=(y-mean.direction[i].black+1)*
            (y-mean.direction[i].black+1)*cooccurrence[x][y].direction[i].black;
        if (image->alpha_trait == BlendPixelTrait)
          variance.direction[i].alpha+=(y-mean.direction[i].alpha+1)*
            (y-mean.direction[i].alpha+1)*
            cooccurrence[x][y].direction[i].alpha;
        /*
          Sum average / Difference Variance.
        */
        density_xy[MagickAbsoluteValue(y-x)].direction[i].red+=
          cooccurrence[x][y].direction[i].red;
        density_xy[MagickAbsoluteValue(y-x)].direction[i].green+=
          cooccurrence[x][y].direction[i].green;
        density_xy[MagickAbsoluteValue(y-x)].direction[i].blue+=
          cooccurrence[x][y].direction[i].blue;
        if (image->colorspace == CMYKColorspace)
          density_xy[MagickAbsoluteValue(y-x)].direction[i].black+=
            cooccurrence[x][y].direction[i].black;
        if (image->alpha_trait == BlendPixelTrait)
          density_xy[MagickAbsoluteValue(y-x)].direction[i].alpha+=
            cooccurrence[x][y].direction[i].alpha;
        /*
          Information Measures of Correlation.
        */
        entropy_xy.direction[i].red-=cooccurrence[x][y].direction[i].red*
          log10(cooccurrence[x][y].direction[i].red+MagickEpsilon);
        entropy_xy.direction[i].green-=cooccurrence[x][y].direction[i].green*
          log10(cooccurrence[x][y].direction[i].green+MagickEpsilon);
        entropy_xy.direction[i].blue-=cooccurrence[x][y].direction[i].blue*
          log10(cooccurrence[x][y].direction[i].blue+MagickEpsilon);
        if (image->colorspace == CMYKColorspace)
          entropy_xy.direction[i].black-=cooccurrence[x][y].direction[i].black*
            log10(cooccurrence[x][y].direction[i].black+MagickEpsilon);
        if (image->alpha_trait == BlendPixelTrait)
          entropy_xy.direction[i].alpha-=
            cooccurrence[x][y].direction[i].alpha*log10(
            cooccurrence[x][y].direction[i].alpha+MagickEpsilon);
        entropy_xy1.direction[i].red-=(cooccurrence[x][y].direction[i].red*
          log10(density_x[x].direction[i].red*density_y[y].direction[i].red+
          MagickEpsilon));
        entropy_xy1.direction[i].green-=(cooccurrence[x][y].direction[i].green*
          log10(density_x[x].direction[i].green*density_y[y].direction[i].green+
          MagickEpsilon));
        entropy_xy1.direction[i].blue-=(cooccurrence[x][y].direction[i].blue*
          log10(density_x[x].direction[i].blue*density_y[y].direction[i].blue+
          MagickEpsilon));
        if (image->colorspace == CMYKColorspace)
          entropy_xy1.direction[i].black-=(
            cooccurrence[x][y].direction[i].black*log10(
            density_x[x].direction[i].black*density_y[y].direction[i].black+
            MagickEpsilon));
        if (image->alpha_trait == BlendPixelTrait)
          entropy_xy1.direction[i].alpha-=(
            cooccurrence[x][y].direction[i].alpha*log10(
            density_x[x].direction[i].alpha*density_y[y].direction[i].alpha+
            MagickEpsilon));
        entropy_xy2.direction[i].red-=(density_x[x].direction[i].red*
          density_y[y].direction[i].red*log10(density_x[x].direction[i].red*
          density_y[y].direction[i].red+MagickEpsilon));
        entropy_xy2.direction[i].green-=(density_x[x].direction[i].green*
          density_y[y].direction[i].green*log10(density_x[x].direction[i].green*
          density_y[y].direction[i].green+MagickEpsilon));
        entropy_xy2.direction[i].blue-=(density_x[x].direction[i].blue*
          density_y[y].direction[i].blue*log10(density_x[x].direction[i].blue*
          density_y[y].direction[i].blue+MagickEpsilon));
        if (image->colorspace == CMYKColorspace)
          entropy_xy2.direction[i].black-=(density_x[x].direction[i].black*
            density_y[y].direction[i].black*log10(
            density_x[x].direction[i].black*density_y[y].direction[i].black+
            MagickEpsilon));
        if (image->alpha_trait == BlendPixelTrait)
          entropy_xy2.direction[i].alpha-=(density_x[x].direction[i].alpha*
            density_y[y].direction[i].alpha*log10(
            density_x[x].direction[i].alpha*density_y[y].direction[i].alpha+
            MagickEpsilon));
      }
    }
    channel_features[RedPixelChannel].variance_sum_of_squares[i]=
      variance.direction[i].red;
    channel_features[GreenPixelChannel].variance_sum_of_squares[i]=
      variance.direction[i].green;
    channel_features[BluePixelChannel].variance_sum_of_squares[i]=
      variance.direction[i].blue;
    if (image->colorspace == CMYKColorspace)
      channel_features[BlackPixelChannel].variance_sum_of_squares[i]=
        variance.direction[i].black;
    if (image->alpha_trait == BlendPixelTrait)
      channel_features[AlphaPixelChannel].variance_sum_of_squares[i]=
        variance.direction[i].alpha;
  }
  /*
    Compute more texture features.
  */
  (void) ResetMagickMemory(&variance,0,sizeof(variance));
  (void) ResetMagickMemory(&sum_squares,0,sizeof(sum_squares));
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static,4) shared(status) \
    dynamic_number_threads(image,number_grays,number_grays,1)
#endif
  for (i=0; i < 4; i++)
  {
    register ssize_t
      x;

    for (x=0; x < (ssize_t) number_grays; x++)
    {
      /*
        Difference variance.
      */
      variance.direction[i].red+=density_xy[x].direction[i].red;
      variance.direction[i].green+=density_xy[x].direction[i].green;
      variance.direction[i].blue+=density_xy[x].direction[i].blue;
      if (image->colorspace == CMYKColorspace)
        variance.direction[i].black+=density_xy[x].direction[i].black;
      if (image->alpha_trait == BlendPixelTrait)
        variance.direction[i].alpha+=density_xy[x].direction[i].alpha;
      sum_squares.direction[i].red+=density_xy[x].direction[i].red*
        density_xy[x].direction[i].red;
      sum_squares.direction[i].green+=density_xy[x].direction[i].green*
        density_xy[x].direction[i].green;
      sum_squares.direction[i].blue+=density_xy[x].direction[i].blue*
        density_xy[x].direction[i].blue;
      if (image->colorspace == CMYKColorspace)
        sum_squares.direction[i].black+=density_xy[x].direction[i].black*
          density_xy[x].direction[i].black;
      if (image->alpha_trait == BlendPixelTrait)
        sum_squares.direction[i].alpha+=density_xy[x].direction[i].alpha*
          density_xy[x].direction[i].alpha;
      /*
        Difference entropy.
      */
      channel_features[RedPixelChannel].difference_entropy[i]-=
        density_xy[x].direction[i].red*
        log10(density_xy[x].direction[i].red+MagickEpsilon);
      channel_features[GreenPixelChannel].difference_entropy[i]-=
        density_xy[x].direction[i].green*
        log10(density_xy[x].direction[i].green+MagickEpsilon);
      channel_features[BluePixelChannel].difference_entropy[i]-=
        density_xy[x].direction[i].blue*
        log10(density_xy[x].direction[i].blue+MagickEpsilon);
      if (image->colorspace == CMYKColorspace)
        channel_features[BlackPixelChannel].difference_entropy[i]-=
          density_xy[x].direction[i].black*
          log10(density_xy[x].direction[i].black+MagickEpsilon);
      if (image->alpha_trait == BlendPixelTrait)
        channel_features[AlphaPixelChannel].difference_entropy[i]-=
          density_xy[x].direction[i].alpha*
          log10(density_xy[x].direction[i].alpha+MagickEpsilon);
      /*
        Information Measures of Correlation.
      */
      entropy_x.direction[i].red-=(density_x[x].direction[i].red*
        log10(density_x[x].direction[i].red+MagickEpsilon));
      entropy_x.direction[i].green-=(density_x[x].direction[i].green*
        log10(density_x[x].direction[i].green+MagickEpsilon));
      entropy_x.direction[i].blue-=(density_x[x].direction[i].blue*
        log10(density_x[x].direction[i].blue+MagickEpsilon));
      if (image->colorspace == CMYKColorspace)
        entropy_x.direction[i].black-=(density_x[x].direction[i].black*
          log10(density_x[x].direction[i].black+MagickEpsilon));
      if (image->alpha_trait == BlendPixelTrait)
        entropy_x.direction[i].alpha-=(density_x[x].direction[i].alpha*
          log10(density_x[x].direction[i].alpha+MagickEpsilon));
      entropy_y.direction[i].red-=(density_y[x].direction[i].red*
        log10(density_y[x].direction[i].red+MagickEpsilon));
      entropy_y.direction[i].green-=(density_y[x].direction[i].green*
        log10(density_y[x].direction[i].green+MagickEpsilon));
      entropy_y.direction[i].blue-=(density_y[x].direction[i].blue*
        log10(density_y[x].direction[i].blue+MagickEpsilon));
      if (image->colorspace == CMYKColorspace)
        entropy_y.direction[i].black-=(density_y[x].direction[i].black*
          log10(density_y[x].direction[i].black+MagickEpsilon));
      if (image->alpha_trait == BlendPixelTrait)
        entropy_y.direction[i].alpha-=(density_y[x].direction[i].alpha*
          log10(density_y[x].direction[i].alpha+MagickEpsilon));
    }
    /*
      Difference variance.
    */
    channel_features[RedPixelChannel].difference_variance[i]=
      (((double) number_grays*number_grays*sum_squares.direction[i].red)-
      (variance.direction[i].red*variance.direction[i].red))/
      ((double) number_grays*number_grays*number_grays*number_grays);
    channel_features[GreenPixelChannel].difference_variance[i]=
      (((double) number_grays*number_grays*sum_squares.direction[i].green)-
      (variance.direction[i].green*variance.direction[i].green))/
      ((double) number_grays*number_grays*number_grays*number_grays);
    channel_features[BluePixelChannel].difference_variance[i]=
      (((double) number_grays*number_grays*sum_squares.direction[i].blue)-
      (variance.direction[i].blue*variance.direction[i].blue))/
      ((double) number_grays*number_grays*number_grays*number_grays);
    if (image->colorspace == CMYKColorspace)
      channel_features[BlackPixelChannel].difference_variance[i]=
        (((double) number_grays*number_grays*sum_squares.direction[i].black)-
        (variance.direction[i].black*variance.direction[i].black))/
        ((double) number_grays*number_grays*number_grays*number_grays);
    if (image->alpha_trait == BlendPixelTrait)
      channel_features[AlphaPixelChannel].difference_variance[i]=
        (((double) number_grays*number_grays*sum_squares.direction[i].alpha)-
        (variance.direction[i].alpha*variance.direction[i].alpha))/
        ((double) number_grays*number_grays*number_grays*number_grays);
    /*
      Information Measures of Correlation.
    */
    channel_features[RedPixelChannel].measure_of_correlation_1[i]=
      (entropy_xy.direction[i].red-entropy_xy1.direction[i].red)/
      (entropy_x.direction[i].red > entropy_y.direction[i].red ?
       entropy_x.direction[i].red : entropy_y.direction[i].red);
    channel_features[GreenPixelChannel].measure_of_correlation_1[i]=
      (entropy_xy.direction[i].green-entropy_xy1.direction[i].green)/
      (entropy_x.direction[i].green > entropy_y.direction[i].green ?
       entropy_x.direction[i].green : entropy_y.direction[i].green);
    channel_features[BluePixelChannel].measure_of_correlation_1[i]=
      (entropy_xy.direction[i].blue-entropy_xy1.direction[i].blue)/
      (entropy_x.direction[i].blue > entropy_y.direction[i].blue ?
       entropy_x.direction[i].blue : entropy_y.direction[i].blue);
    if (image->colorspace == CMYKColorspace)
      channel_features[BlackPixelChannel].measure_of_correlation_1[i]=
        (entropy_xy.direction[i].black-entropy_xy1.direction[i].black)/
        (entropy_x.direction[i].black > entropy_y.direction[i].black ?
         entropy_x.direction[i].black : entropy_y.direction[i].black);
    if (image->alpha_trait == BlendPixelTrait)
      channel_features[AlphaPixelChannel].measure_of_correlation_1[i]=
        (entropy_xy.direction[i].alpha-entropy_xy1.direction[i].alpha)/
        (entropy_x.direction[i].alpha > entropy_y.direction[i].alpha ?
         entropy_x.direction[i].alpha : entropy_y.direction[i].alpha);
    channel_features[RedPixelChannel].measure_of_correlation_2[i]=
      (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].red-
      entropy_xy.direction[i].red)))));
    channel_features[GreenPixelChannel].measure_of_correlation_2[i]=
      (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].green-
      entropy_xy.direction[i].green)))));
    channel_features[BluePixelChannel].measure_of_correlation_2[i]=
      (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].blue-
      entropy_xy.direction[i].blue)))));
    if (image->colorspace == CMYKColorspace)
      channel_features[BlackPixelChannel].measure_of_correlation_2[i]=
        (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].black-
        entropy_xy.direction[i].black)))));
    if (image->alpha_trait == BlendPixelTrait)
      channel_features[AlphaPixelChannel].measure_of_correlation_2[i]=
        (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].alpha-
        entropy_xy.direction[i].alpha)))));
  }
  /*
    Compute more texture features.
  */
#if defined(MAGICKCORE_OPENMP_SUPPORT)
  #pragma omp parallel for schedule(static,4) shared(status) \
    dynamic_number_threads(image,number_grays,number_grays,1)
#endif
  for (i=0; i < 4; i++)
  {
    ssize_t
      z;

    for (z=0; z < (ssize_t) number_grays; z++)
    {
      register ssize_t
        y;

      ChannelStatistics
        pixel;

      (void) ResetMagickMemory(&pixel,0,sizeof(pixel));
      for (y=0; y < (ssize_t) number_grays; y++)
      {
        register ssize_t
          x;

        for (x=0; x < (ssize_t) number_grays; x++)
        {
          /*
            Contrast:  amount of local variations present in an image.
          */
          if (((y-x) == z) || ((x-y) == z))
            {
              pixel.direction[i].red+=cooccurrence[x][y].direction[i].red;
              pixel.direction[i].green+=cooccurrence[x][y].direction[i].green;
              pixel.direction[i].blue+=cooccurrence[x][y].direction[i].blue;
              if (image->colorspace == CMYKColorspace)
                pixel.direction[i].black+=cooccurrence[x][y].direction[i].black;
              if (image->alpha_trait == BlendPixelTrait)
                pixel.direction[i].alpha+=
                  cooccurrence[x][y].direction[i].alpha;
            }
          /*
            Maximum Correlation Coefficient.
          */
          Q[z][y].direction[i].red+=cooccurrence[z][x].direction[i].red*
            cooccurrence[y][x].direction[i].red/density_x[z].direction[i].red/
            density_y[x].direction[i].red;
          Q[z][y].direction[i].green+=cooccurrence[z][x].direction[i].green*
            cooccurrence[y][x].direction[i].green/
            density_x[z].direction[i].green/density_y[x].direction[i].red;
          Q[z][y].direction[i].blue+=cooccurrence[z][x].direction[i].blue*
            cooccurrence[y][x].direction[i].blue/density_x[z].direction[i].blue/
            density_y[x].direction[i].blue;
          if (image->colorspace == CMYKColorspace)
            Q[z][y].direction[i].black+=cooccurrence[z][x].direction[i].black*
              cooccurrence[y][x].direction[i].black/
              density_x[z].direction[i].black/density_y[x].direction[i].black;
          if (image->alpha_trait == BlendPixelTrait)
            Q[z][y].direction[i].alpha+=
              cooccurrence[z][x].direction[i].alpha*
              cooccurrence[y][x].direction[i].alpha/
              density_x[z].direction[i].alpha/
              density_y[x].direction[i].alpha;
        }
      }
      channel_features[RedPixelChannel].contrast[i]+=z*z*
        pixel.direction[i].red;
      channel_features[GreenPixelChannel].contrast[i]+=z*z*
        pixel.direction[i].green;
      channel_features[BluePixelChannel].contrast[i]+=z*z*
        pixel.direction[i].blue;
      if (image->colorspace == CMYKColorspace)
        channel_features[BlackPixelChannel].contrast[i]+=z*z*
          pixel.direction[i].black;
      if (image->alpha_trait == BlendPixelTrait)
        channel_features[AlphaPixelChannel].contrast[i]+=z*z*
          pixel.direction[i].alpha;
    }
    /*
      Maximum Correlation Coefficient.
      Future: return second largest eigenvalue of Q.
    */
    channel_features[RedPixelChannel].maximum_correlation_coefficient[i]=
      sqrt((double) -1.0);
    channel_features[GreenPixelChannel].maximum_correlation_coefficient[i]=
      sqrt((double) -1.0);
    channel_features[BluePixelChannel].maximum_correlation_coefficient[i]=
      sqrt((double) -1.0);
    if (image->colorspace == CMYKColorspace)
      channel_features[BlackPixelChannel].maximum_correlation_coefficient[i]=
        sqrt((double) -1.0);
    if (image->alpha_trait == BlendPixelTrait)
      channel_features[AlphaPixelChannel].maximum_correlation_coefficient[i]=
        sqrt((double) -1.0);
  }
  /*
    Relinquish resources.
  */
  sum=(ChannelStatistics *) RelinquishMagickMemory(sum);
  for (i=0; i < (ssize_t) number_grays; i++)
    Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]);
  Q=(ChannelStatistics **) RelinquishMagickMemory(Q);
  density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y);
  density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy);
  density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x);
  for (i=0; i < (ssize_t) number_grays; i++)
    cooccurrence[i]=(ChannelStatistics *)
      RelinquishMagickMemory(cooccurrence[i]);
  cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence);
  return(channel_features);
}


text:
    #ifdef STD_REGIONS_EXPORTS
        #define STD_REGIONS_EXPORT _declspec(dllexport)
    #else
        #define STD_REGIONS_EXPORT _declspec(dllimport)
    #endif
#else
    #define STD_REGIONS_EXPORT
#endif

#define LOKI_CLASS_LEVEL_THREADING

#endif //NEKTAR_STD_REGIONS_DECLSPEC_H

redpajama_set_name: RedPajamaGithub


text:
import 'tabris';

let promise1 = new Promise<any>((resolve, reject) => {
  if (1 === 1) {
    resolve('result');
  } else {
    reject('reason');
  }
});

promise1.then((result) => {
  return 'nextResult';
}).then((result) => {
  return 'nextResult';
}).catch((reason) => {
  // handle error
});

let promise2 = new Promise<any>((resolve, reject) => {
  if (1 === 1) {
    resolve('result');
  } else {
    reject('reason');
  }
});

let allPromise: Promise<any> = Promise.race([promise1, promise2]).then((results) => {
  let result1 = results[0];
  let result2 = results[1];
});

let racePromise: Promise<any> = Promise.race([promise1, promise2]).then((result) => {
  result.doSomething();
});

let rejectedPromise: Promise<any> = Promise.reject<any>('reason');
let resolvedPromise: Promise<any> = Promise.resolve<any>('value');


text:
(function () {

    'use strict';

    var Module = angular.module('rmDatepicker', []);

    Module.constant('rmDatepickerConfig', {
        mondayStart: false,
        textToday: "Today",
        closeOnToday: false,

        initState: "month",
        maxState: "decade",
        minState: "month",
        toggleState: true,

        decadeSize: 12,
        monthSize: 42, /* "auto" || fixed nr. (35 or 42) */

        min: null,
        max: null,
        format: "dd/MM/yyyy"
    });

    Module.directive("rmDatepicker", ['rmDatepickerConfig', '$compile', '$filter', '$document', '$timeout',
        function (rmDatepickerConfig, $compile, $filter, $document, $timeout) {

            var link = function (scope, element, attrs, ngModel) {
                var conf = angular.copy(rmDatepickerConfig);

                if (scope.rmConfig) {
                    for (var prop in conf)
                        if (conf.hasOwnProperty(prop))
                            if (scope.rmConfig[prop] != undefined) conf[prop] = scope.rmConfig[prop];
                }
                if (conf.min) conf.min.setHours(0, 0, 0, 0);
                if (conf.max) conf.max.setHours(23, 59, 59, 999);

                var isInput = element[0].tagName.toUpperCase() == "INPUT";
                var isReached = {
                    min: false,
                    max: false
                };
                var daysInMonth = function (year, month) {
                    return new Date(year, month + 1, 0).getDate();
                };
                var adjustDate = function (date) {
                    var date = parseInt(date, 10);
                    if (!isNaN(date)) {
                        var max = daysInMonth(scope.model.getFullYear(), scope.model.getMonth());
                        if (date < 1) date = 1;
                        if (date > max) date = max;
                        scope.model.setDate(date);
                    }
                };
                var gen = {
                    decade: function (oDate) {
                        var Y = oDate.getFullYear(),
                            m = oDate.getMonth(),
                            d = oDate.getDate(),
                            max,
                            i = 0,
                            n = conf.decadeSize || 12; // count of years in decade
                        var aDecade = new Array(n);

                        Y = Math.floor(Y / n) * n; // begin year of current decade

                        for (; i < n; Y++, i++) {
                            max = daysInMonth(Y, m);
                            if (d > max) d = max;
                            aDecade[i] = new Date(Y, m, d, 3, 0, 1, 0);
                        }
                        return aDecade;
                    },
                    year: function (oDate) {
                        var Y = oDate.getFullYear(),
                            m = 0,
                            d = oDate.getDate(),
                            max;
                        var aYear = [];
                        for (; m < 12; m++) {
                            max = daysInMonth(Y, m);
                            if (d > max) d = max;
                            aYear.push(new Date(Y, m, d, 3, 0, 1, 0));
                        }
                        return aYear;
                    },
                    month: function (oDate) {
                        var Y = oDate.getFullYear(),
                            m = oDate.getMonth(),
                            startDate = new Date(Y, m, 1, 3, 0, 1, 0),
                            n;
                        var startPos = startDate.getDay() || 7;
                        if (scope.mondayStart) startPos = startPos - 1 || 7;

                        if (conf.monthSize == "auto")
                            n = ( startPos + daysInMonth(Y, m) < 35 ) ? 35 : 42;
                        else
                            n = conf.monthSize;

                        startDate.setDate(-startPos + 1);
                        return gen.dates(startDate, n);
                    },
                    dates: function (startDate, n) {
                        var aDates = new Array(n),
                            current = new Date(startDate),
                            i = 0;
                        while (i < n) {
                            aDates[i++] = new Date(current);
                            current.setDate(current.getDate() + 1);
                        }
                        return aDates;
                    }
                };
                var refresh = function (state) {
                    state = state || scope.state;

                    if(scope.model){
                        scope.model = new Date(scope.model);
                        scope.initialDate = scope.model;
                    }

                    scope.aDates = gen[state](scope.initialDate);

                    if (conf.min) {
                        //if(scope.aDates[0] < conf.min) scope.aDates[0].setDate( conf.min.getDate() );
                        isReached.min = scope.aDates[0] < conf.min;
                    }
                    if (conf.max) {
                        var oDate = scope.aDates[scope.aDates.length - 1];
                        //if(oDate > conf.max) oDate.setDate( conf.max.getDate() );
                        isReached.max = oDate > conf.max;
                    }
                };
                var init = function () {
                    scope.initialDate = new Date(scope.initialDate || scope.model || new Date());
                    refresh();
                };

                var isBefore = function (oDate1, oDate2) {
                    if (scope.state == "decade")
                        return oDate1.getFullYear() < oDate2.getFullYear();

                    if (scope.state == "year") {
                        if (oDate1.getFullYear() == oDate2.getFullYear())
                            return oDate1.getMonth() < oDate2.getMonth();
                        else
                            return oDate1.getFullYear() < oDate2.getFullYear();
                    }

                    return oDate1 < oDate2;
                };
                scope.isOff = function (oDate) {
                    if (!conf.min && !conf.max)
                        return false;
                    if (conf.min && isBefore(oDate, conf.min))
                        return true;
                    if (conf.max && isBefore(conf.max, oDate))
                        return true;
                };
                scope.isActive = {
                    year: function (oDate) {
                        if(scope.model){
                            return oDate.getFullYear() == scope.model.getFullYear();
                        }
                        return oDate.getFullYear() == scope.initialDate.getFullYear();
                    },
                    month: function (oDate) {
                        if(scope.model){
                            return oDate.getMonth() == scope.model.getMonth();
                        }
                        return oDate.getMonth() == scope.initialDate.getMonth();
                    },
                    date: function (oDate) {
                        if(scope.model){
                            return oDate.getDate() == scope.model.getDate();
                        }
                        return oDate.getDate() == scope.initialDate.getDate();
                    }
                };
                scope.isToday = function (oDate) {
                    return scope.isActive.date(oDate)
                        && scope.isActive.month(oDate)
                        && scope.isActive.year(oDate);
                };

                scope.go = function (oDate) {
                    if (scope.isOff(oDate)) return;

                    if( isInput && scope.state == conf.minState && scope.isActive.month(oDate) ) {
                        togglePicker(false);
                    }

                    var m = scope.initialDate.getMonth();

                    scope.model = new Date(oDate);
                    scope.initialDate = scope.model;
                    //
                    // $timeout(function () {
                    //     ngModel.$setViewValue(scope.model);
                    // });
                    if (conf.toggleState) scope.toggleState(1);

                    if (m != scope.initialDate.getMonth()){
                        refresh();
                    }
                };
                scope.now = function () {
                    scope.model = new Date();
                    scope.initialDate = scope.model;
                    refresh();
                    if(scope.closeOnToday) { togglePicker(false) }
                };
                scope.next = function (delta) {
                    scope.model = scope.model || scope.initialDate;

                    delta = delta || 1;

                    if (delta > 0) {
                        if (isReached.max) return;
                    }
                    else {
                        if (isReached.min) return;
                    }

                    var Y = scope.model.getFullYear(),
                        m = scope.model.getMonth(),
                        d = scope.model.getDate();

                    switch (scope.state) {
                        case "decade":
                            delta = delta * scope.aDates.length;
                        case "year":
                            scope.model.setFullYear(Y + delta, m, 15);
                            adjustDate(d);
                            break;
                        case "month":
                            scope.model.setMonth(m + delta, 15);
                            adjustDate(d);
                            break;
                        case "week" :
                            scope.model.setDate(d + (delta * 7));
                            break;
                    }
                    refresh();
                };
                scope.prev = function (delta) {
                    return scope.next(-delta || -1);
                };
                scope.toggleState = function (direction) {
                    direction = direction || 1;

                    if (scope.state == conf.maxState && direction == -1 ||
                        scope.state == conf.minState && direction == 1) {
                        return;
                    }
                    scope.state = scope.aStates[scope.aStates.indexOf(scope.state) + direction];
                    refresh();
                };

                scope.mondayStart = conf.mondayStart;
                scope.textToday = conf.textToday;
                scope.closeOnToday = conf.closeOnToday;

                scope.aStates = ["decade", "year", "month"];
                scope.state = conf.initState;

                init(); // generate initial state

                var offset = function (objElement, container) {
                    var x = 0, y = 0;

                    do {
                        x += objElement.offsetLeft;
                        y += objElement.offsetTop;
                        objElement = objElement.offsetParent
                    } while (objElement != container);

                    return {top: y, left: x};
                };
                var togglePicker = function (toggle) {
                    overlay.css("display", toggle ? "block" : "none");
                    calendar.css("display", toggle ? "block" : "none");
                };

                var adjustPos = function (pos, el, container) {
                    var datePickerClientHeight = el.clientHeight < 100?342:el.clientHeight;
                    var overspill = (pos.top + datePickerClientHeight) - container.clientHeight;
                    if(overspill > 0){
                        pos.top -= (overspill + 5);
                    }

                    return pos;
                };

                if (isInput) {
                    ngModel.$parsers.push(function (sDate) {
                        if (typeof(sDate) === 'string' ) {
                            return moment.utc(sDate, "DD/MM/YYYY").startOf('day').toDate();
                        }
                        return new Date(sDate);
                    });
                    ngModel.$formatters.push(function (oDate) {
                        return $filter('date')(oDate, conf.format);
                    });

                    var overlay = angular.element('

');
                    overlay.on('click', function () {
                        togglePicker(false);
                    });

                    var overlayContainer = element.closest(".scroll-container");
                    overlayContainer.append(overlay);

                    overlay.after($compile(TEMPLATE)(scope));

                    var calendar = overlay.next();
                    calendar.css({display: "none"});
                    calendar.addClass('it-is-input');

                    element.on('click', function () {
                        var el = element[0];
                        if(el.readOnly){
                            return;
                        }

                        if (window.innerWidth < 481) el.blur();
                        var pos = offset(el, overlayContainer.get(0));

                        pos.top += el.offsetHeight + 1;

                        calendar.css({top: pos.top + "px", left: pos.left + "px", display: "block"});
                        togglePicker(true);

                        adjustPos(pos, calendar.get(0), overlayContainer.get(0));
                        calendar.css({top: pos.top + "px", left: pos.left + "px"});

                        $timeout(function () {
                            refresh();
                        }, 0);
                    });

                    $document.on('keydown', function (e) {
                        if ([9, 13, 27].indexOf(e.keyCode) >= 0) togglePicker(false);
                    });
                }
                else {
                    element.append($compile(TEMPLATE)(scope));
                }
            };

            var TEMPLATE =
                '
' +
                '
' +
                '' +
                '' +
                '{{aDates[0].getFullYear()}} - {{aDates[aDates.length-1].getFullYear()}}' +
                '{{initialDate.getFullYear()}}' +
                '{{initialDate | date: \'MMMM yyyy\'}}' +
                '{{initialDate | date: \'d MMMM yyyy\' }}' +
                '' +
                '' +
                '' +
                '{{textToday}}' +
                '
' +
                '

' +
                '
' +

                '' +

                '' +

                '';

            return {
                require: 'ngModel',
                scope: {
                    model: '=ngModel',
                    initialDate: '=?rmInitialDate',
                    rmConfig: "=rmConfig"
                },
                link: link
            }
        }]);
}());


text:
<?php

namespace interactivesolutions\honeycombecommerceorders\app\services;

use Illuminate\Http\Request;
use interactivesolutions\honeycombecommercegoods\app\helpers\PriceHelper;
use interactivesolutions\honeycombecommerceorders\app\models\ecommerce\carts\HCECCartItems;

class HCCart
{
    /**
     * Cart content
     *
     * @var void
     */
    public $items;

    /**
     * Cart id
     *
     * @var
     */
    public $cartId;

    /**
     * Get cart content
     *
     * @param Request $request
     * @param null $userId - cart content by user id
     * @param null $cartId - cart content by given cart id
     * @return array|bool|false|int|string
     */
    public function getContent(Request $request, $userId = null, $cartId = null)
    {
        $this->items = $this->getItemsContent($request, $userId, $cartId);

        return $this->getCartContent();
    }

    /**
     * Get formatted cart content
     *
     * @return array
     */
    protected function getCartContent()
    {
        return [
            'cart_id'                   => $this->cartId,
            'count'                     => $this->count(),
            'price'                     => $this->price(),
            'price_before_tax'          => $this->priceBeforeTax(),
            'price_tax_amount'          => $this->priceTaxAmount(),
            'unit_price'                => $this->unitPrice(),
            'unit_price_before_tax'     => $this->unitPriceBeforeTax(),
            'unit_price_tax_amount'     => $this->unitPriceTaxAmount(),
            'items'                     => $this->getItems(),
        ];
    }

    /**
     * Get cart items content
     *
     * @param Request $request
     * @param $userId
     * @param $cartId
     * @return \Illuminate\Support\Collection
     */
    protected function getItemsContent(Request $request, $userId, $cartId)
    {
        if( $userId && is_null($cartId) ) {
            $cartId = app(HCCartService::class)->getUserCartId($userId);
        } else if( is_null($cartId) ) {
            $cartId = app(HCCartService::class)->getCartId($request, false);
        }

        $this->cartId = $cartId;

        $cartItems = HCECCartItems::byCartId($cartId)->get();

        return $this->getGoods($cartItems);
    }

    /**
     * Get the number of items in the cart.
     *
     * @return int|float
     */
    public function count()
    {
        $items = $this->getItems();

        return $items->sum('selected_amount');
    }

    /**
     * Items getter
     *
     * @return void
     */
    public function getItems()
    {
        return $this->items;
    }

    /**
     * Get the total price of the items in the cart.
     */
    public function price()
    {
        $items = $this->getItems();

        $total = $items->reduce(function ($total, $cartItem) {
            return $total + (array_get($cartItem, 'prices.total_price'));
        }, 0);

        return PriceHelper::round($total);
    }

    /**
     * Get the total price of the items in the cart.
     */
    public function priceBeforeTax()
    {
        $items = $this->getItems();

        $total = $items->reduce(function ($total, $cartItem) {
            return $total + (array_get($cartItem, 'prices.total_price_before_tax'));
        }, 0);

        return PriceHelper::round($total);
    }

    /**
     * Get the total price of the items in the cart.
     */
    public function priceTaxAmount()
    {
        $items = $this->getItems();

        $total = $items->reduce(function ($total, $cartItem) {
            return $total + (array_get($cartItem, 'prices.total_price_tax_amount'));
        }, 0);

        return PriceHelper::round($total);
    }

    /**
     * Get the total price of the items in the cart.
     */
    public function unitPrice()
    {
        $items = $this->getItems();

        $total = $items->reduce(function ($total, $cartItem) {
            return $total + (array_get($cartItem, 'prices.total_unit_price'));
        }, 0);

        return PriceHelper::round($total);
    }

    /**
     * Get the total price of the items in the cart.
     */
    public function unitPriceBeforeTax()
    {
        $items = $this->getItems();

        $total = $items->reduce(function ($total, $cartItem) {
            return $total + (array_get($cartItem, 'prices.total_unit_price_before_tax'));
        }, 0);

        return PriceHelper::round($total);
    }

    /**
     * Get the total price of the items in the cart.
     */
    public function unitPriceTaxAmount()
    {
        $items = $this->getItems();

        $total = $items->reduce(function ($total, $cartItem) {
            return $total + (array_get($cartItem, 'prices.total_unit_price_tax_amount'));
        }, 0);

        return PriceHelper::round($total);
    }

    /**
     * Get goods by cart item
     *
     * @param $cartItems
     * @return array
     */
    protected function getGoods($cartItems)
    {
        $goods = collect([]);

        $cartItems->load([
            'goods' => function ($query) {
                $query->with([
                    'images' => function ($query) {
                        $query->orderBy('position');
                    },
                    'translations',
                    'stock_summary',
                    'tax.translations',
                ]);
            }]);

        foreach ( $cartItems as $cartItem ) {
            $item = [];

            $item['selected_amount'] = $cartItem->amount;
            $item['cart_item_id'] = $cartItem->id;
            $item['goods_id'] = $cartItem->goods_id;
            $item['prices'] = [
                'price'                           => PriceHelper::round($cartItem->goods->price),
                'price_before_tax'                => PriceHelper::round($cartItem->goods->price_before_tax),
                'price_tax_amount'                => PriceHelper::round($cartItem->goods->price_tax_amount),

                'unit_price'                      => PriceHelper::round($cartItem->goods->price),
                'unit_price_before_tax'           => PriceHelper::round($cartItem->goods->price_before_tax),
                'unit_price_tax_amount'           => PriceHelper::round($cartItem->goods->price_tax_amount),

                'total_unit_price'                => PriceHelper::round($cartItem->amount * $cartItem->goods->price),
                'total_unit_price_before_tax'     => PriceHelper::round($cartItem->amount * $cartItem->goods->price_before_tax),
                'total_unit_price_tax_amount'     => PriceHelper::round($cartItem->amount * $cartItem->goods->price_tax_amount),

                'total_price'                     => PriceHelper::round($cartItem->amount * $cartItem->goods->price),
                'total_price_before_tax'          => PriceHelper::round($cartItem->amount * $cartItem->goods->price_before_tax),
                'total_price_tax_amount'          => PriceHelper::round($cartItem->amount * $cartItem->goods->price_tax_amount),
            ];

            $goods[] = $item;
        }

        return $goods;
    }
}


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

<title>org.apache.poi.hpbf.model (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.apache.poi.hpbf.model

Classes

EscherDelayStm

EscherPart

EscherStm

HPBFPart

MainContents

QuillContents


text:
package main

import (
	"bytes"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"

	"github.com/TingYunAPM/go"
)

// ResponseRecorder is an implementation of http.ResponseWriter that
// records its mutations for later inspection in tests.
type ResponseRecorder struct {
	Code      int           // the HTTP response code from WriteHeader
	HeaderMap http.Header   // the HTTP response headers
	Body      *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to
	Flushed   bool

	result      *http.Response // cache of Result's return value
	snapHeader  http.Header    // snapshot of HeaderMap at first Write
	wroteHeader bool
}

// NewRecorder returns an initialized ResponseRecorder.
func NewRecorder() *ResponseRecorder {
	return &ResponseRecorder{
		HeaderMap: make(http.Header),
		Body:      new(bytes.Buffer),
		Code:      200,
	}
}

// DefaultRemoteAddr is the default remote address to return in RemoteAddr if
// an explicit DefaultRemoteAddr isn't set on ResponseRecorder.
const DefaultRemoteAddr = "1.2.3.4"

// Header returns the response headers.
func (rw *ResponseRecorder) Header() http.Header {
	m := rw.HeaderMap
	if m == nil {
		m = make(http.Header)
		rw.HeaderMap = m
	}
	return m
}

// writeHeader writes a header if it was not written yet and
// detects Content-Type if needed.
//
// bytes or str are the beginning of the response body.
// We pass both to avoid unnecessarily generate garbage
// in rw.WriteString which was created for performance reasons.
// Non-nil bytes win.
func (rw *ResponseRecorder) writeHeader(b []byte, str string) {
	if rw.wroteHeader {
		return
	}
	if len(str) > 512 {
		str = str[:512]
	}

	m := rw.Header()

	_, hasType := m["Content-Type"]
	hasTE := m.Get("Transfer-Encoding") != ""
	if !hasType && !hasTE {
		if b == nil {
			b = []byte(str)
		}
		m.Set("Content-Type", http.DetectContentType(b))
	}

	rw.WriteHeader(200)
}

// Write always succeeds and writes to rw.Body, if not nil.
func (rw *ResponseRecorder) Write(buf []byte) (int, error) {
	rw.writeHeader(buf, "")
	if rw.Body != nil {
		rw.Body.Write(buf)
	}
	return len(buf), nil
}

// WriteString always succeeds and writes to rw.Body, if not nil.
func (rw *ResponseRecorder) WriteString(str string) (int, error) {
	rw.writeHeader(nil, str)
	if rw.Body != nil {
		rw.Body.WriteString(str)
	}
	return len(str), nil
}

// WriteHeader sets rw.Code. After it is called, changing rw.Header
// will not affect rw.HeaderMap.
func (rw *ResponseRecorder) WriteHeader(code int) {
	if rw.wroteHeader {
		return
	}
	rw.Code = code
	rw.wroteHeader = true
	if rw.HeaderMap == nil {
		rw.HeaderMap = make(http.Header)
	}
	rw.snapHeader = cloneHeader(rw.HeaderMap)
}

func cloneHeader(h http.Header) http.Header {
	h2 := make(http.Header, len(h))
	for k, vv := range h {
		vv2 := make([]string, len(vv))
		copy(vv2, vv)
		h2[k] = vv2
	}
	return h2
}

// Flush sets rw.Flushed to true.
func (rw *ResponseRecorder) Flush() {
	if !rw.wroteHeader {
		rw.WriteHeader(200)
	}
	rw.Flushed = true
}

func (rw *ResponseRecorder) ReadFrom(r io.Reader) (int64, error) {
	return rw.Body.ReadFrom(r)
}

// Result returns the response generated by the handler.
//
// The returned Response will have at least its StatusCode,
// Header, Body, and optionally Trailer populated.
// More fields may be populated in the future, so callers should
// not DeepEqual the result in tests.
//
// The Response.Header is a snapshot of the headers at the time of the
// first write call, or at the time of this call, if the handler never
// did a write.
//
// Result must only be called after the handler has finished running.
func (rw *ResponseRecorder) Result() *http.Response {
	if rw.result != nil {
		return rw.result
	}
	if rw.snapHeader == nil {
		rw.snapHeader = cloneHeader(rw.HeaderMap)
	}
	res := &http.Response{
		Proto:      "HTTP/1.1",
		ProtoMajor: 1,
		ProtoMinor: 1,
		StatusCode: rw.Code,
		Header:     rw.snapHeader,
	}
	rw.result = res
	if res.StatusCode == 0 {
		res.StatusCode = 200
	}
	res.Status = http.StatusText(res.StatusCode)
	if rw.Body != nil {
		res.Body = ioutil.NopCloser(bytes.NewReader(rw.Body.Bytes()))
	}

	if trailers, ok := rw.snapHeader["Trailer"]; ok {
		res.Trailer = make(http.Header, len(trailers))
		for _, k := range trailers {
			// TODO: use http2.ValidTrailerHeader, but we can't
			// get at it easily because it's bundled into net/http
			// unexported. This is good enough for now:
			switch k {
			case "Transfer-Encoding", "Content-Length", "Trailer":
				// Ignore since forbidden by RFC 2616 14.40.
				continue
			}
			k = http.CanonicalHeaderKey(k)
			vv, ok := rw.HeaderMap[k]
			if !ok {
				continue
			}
			vv2 := make([]string, len(vv))
			copy(vv2, vv)
			res.Trailer[k] = vv2
		}
	}
	return res
}

func TestServerHandlerFunc(t *testing.T) {
	//
	tingyun.AppInit("app.json")
	defer tingyun.AppStop()
	//
	route := "/login"
	url := "/login/user?id=123"

	_, handleFunc := tingyun.WrapHandleFunc(route, webHandler)
	request, _ := http.NewRequest("GET", url, nil)
	response := NewRecorder()

	handleFunc(response, request)

	h := response.Header().Get("X-Action")
	if !strings.Contains(h, "WebAction/Handler/") {
		t.Errorf("action name fail: ", h)
	} else {
		t.Log(h)
	}

	h = response.Header().Get("X-URL")
	if h != url {
		t.Error("URL 失败")
	} else {
		t.Log(h)
	}

	h = response.Header().Get("X-Interface")
	t.Log(h)
	if strings.Index(h, "Flusher") == -1 {
		t.Error(h)
	}
	if strings.Index(h, "ReaderFrom") == -1 {
		t.Error(h)
	}
}

func TestServerHandler(t *testing.T) {
	//
	tingyun.AppInit("app.json")
	defer tingyun.AppStop()
	//
	route := "/login"
	url := "/login/user?id=123"

	_, handler := tingyun.WrapHandle(route, http.HandlerFunc(webHandler))

	request, _ := http.NewRequest("GET", url, nil)
	response := NewRecorder()

	handler.ServeHTTP(response, request)

	h := response.Header().Get("X-Action")
	if !strings.Contains(h, "WebAction/Handler/") {
		t.Errorf("action name fail: ", h)
	} else {
		t.Log(h)
	}

	h = response.Header().Get("X-URL")
	if h != url {
		t.Error("URL 失败")
	} else {
		t.Log(h)
	}

	h = response.Header().Get("X-Interface")
	t.Log(h)
	if strings.Index(h, "Flusher") == -1 {
		t.Error(h)
	}
	if strings.Index(h, "ReaderFrom") == -1 {
		t.Error(h)
	}
}

func TestServerDisable(t *testing.T) {
	//
	tingyun.AppInit("miss.json")
	defer tingyun.AppStop()
	//
	_, handleFunc := tingyun.WrapHandleFunc("/", webHandler)

	request, _ := http.NewRequest("GET", "/test", nil)
	response := NewRecorder()

	handleFunc(response, request)

	h := response.Header().Get("X-Action")
	if h != "" {
		t.Error("agent 禁用失败")
	}

	h = response.Header().Get("X-URL")
	if h != "" {
		t.Error("agent 禁用失败")
	}

	h = response.Header().Get("X-Interface")
	t.Log(h)
	if strings.Index(h, "Flusher") == -1 {
		t.Error(h)
	}
	if strings.Index(h, "ReaderFrom") == -1 {
		t.Error(h)
	}
}

func TestServerOrig(t *testing.T) {

	handleFunc := webHandler
	request, _ := http.NewRequest("GET", "/test", nil)
	response := NewRecorder()
	handleFunc(response, request)
	//
	h := response.Header().Get("X-Action")
	if h != "" {
		t.Error("agent 禁用失败")
	}

	h = response.Header().Get("X-URL")
	if h != "" {
		t.Error("agent 禁用失败")
	}

	h = response.Header().Get("X-Interface")
	t.Log(h)
	if strings.Index(h, "Flusher") == -1 {
		t.Error(h)
	}
	if strings.Index(h, "ReaderFrom") == -1 {
		t.Error(h)
	}
}

func webHandler(w http.ResponseWriter, r *http.Request) {

	action := tingyun.GetAction(w)
	if action != nil {
		w.Header().Set("X-Action", action.GetName())
		w.Header().Set("X-URL", action.GetUrl())
	}
	comp := action.CreateComponent("test.webHandler")
	defer comp.Finish()

	w.Write([]byte("hello"))

	i := "Interface:"
	if _, ok := w.(http.CloseNotifier); ok {
		i += " CloseNotifier"
	}
	if _, ok := w.(http.Flusher); ok {
		i += " Flusher"
	}
	if _, ok := w.(http.Hijacker); ok {
		i += " Hijacker"
	}
	if _, ok := w.(io.ReaderFrom); ok {
		i += " ReaderFrom"
	}
	w.Header().Set("X-Interface", i)

}


text:
\hypertarget{structscene}{\section{scene Struct Reference}
\label{structscene}\index{scene@{scene}}
}

{\ttfamily \#include $<$scene.\-h$>$}

\subsection*{Public Attributes}
\begin{DoxyCompactItemize}
\item
\hypertarget{structscene_ae16ccb28bb52bb2c3eef4f8e4beeb9cb}{struct \hyperlink{structlist}{list} {\bfseries entities}}\label{structscene_ae16ccb28bb52bb2c3eef4f8e4beeb9cb}

\item
\hypertarget{structscene_a48297a6a0f770b58336d3e57d7f0f674}{struct \hyperlink{structlist}{list} {\bfseries sprites}}\label{structscene_a48297a6a0f770b58336d3e57d7f0f674}

\end{DoxyCompactItemize}

\subsection{Detailed Description}
A scene contains a collection of entities and sprites

The documentation for this struct was generated from the following file\-:\begin{DoxyCompactItemize}
\item
/home/ian/\-Development/\-Open\-Hydorah/openhydorah/include/\hyperlink{scene_8h}{scene.\-h}\end{DoxyCompactItemize}


text:
<?php

use stringEncode\Encode;

class ContentTest extends PHPUnit_Framework_TestCase {

	public function testTo()
	{
		$encode = new Encode;
		$encode->to('ISO-8859-1');
		$this->assertEquals('ISO-8859-1', $encode->charset()['to']);
	}

	public function testFrom()
	{
		$encode = new Encode;
		$encode->from('ISO-8859-1');
		$this->assertEquals('ISO-8859-1', $encode->charset()['from']);
	}

	public function testDetect()
	{
		$encode = new Encode;
		$encode->detect('Calendrier de l\'avent façon Necta!');
		$this->assertEquals('UTF-8', $encode->charset()['from']);
	}

}


text:
@interface DeliveryListRequest : BaseRequest

- (void)setParametersWithUserId:(NSString *)userId;

@end


text:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V11.Enums {

  /// Holder for reflection information generated from google/ads/googleads/v11/enums/ad_network_type.proto
  public static partial class AdNetworkTypeReflection {

    #region Descriptor
    /// File descriptor for google/ads/googleads/v11/enums/ad_network_type.proto
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static AdNetworkTypeReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "CjRnb29nbGUvYWRzL2dvb2dsZWFkcy92MTEvZW51bXMvYWRfbmV0d29ya190",
            "eXBlLnByb3RvEh5nb29nbGUuYWRzLmdvb2dsZWFkcy52MTEuZW51bXMiowEK",
            "EUFkTmV0d29ya1R5cGVFbnVtIo0BCg1BZE5ldHdvcmtUeXBlEg8KC1VOU1BF",
            "Q0lGSUVEEAASCwoHVU5LTk9XThABEgoKBlNFQVJDSBACEhMKD1NFQVJDSF9Q",
            "QVJUTkVSUxADEgsKB0NPTlRFTlQQBBISCg5ZT1VUVUJFX1NFQVJDSBAFEhEK",
            "DVlPVVRVQkVfV0FUQ0gQBhIJCgVNSVhFRBAHQuwBCiJjb20uZ29vZ2xlLmFk",
            "cy5nb29nbGVhZHMudjExLmVudW1zQhJBZE5ldHdvcmtUeXBlUHJvdG9QAVpD",
            "Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hZHMvZ29v",
            "Z2xlYWRzL3YxMS9lbnVtcztlbnVtc6ICA0dBQaoCHkdvb2dsZS5BZHMuR29v",
            "Z2xlQWRzLlYxMS5FbnVtc8oCHkdvb2dsZVxBZHNcR29vZ2xlQWRzXFYxMVxF",
            "bnVtc+oCIkdvb2dsZTo6QWRzOjpHb29nbGVBZHM6OlYxMTo6RW51bXNiBnBy",
            "b3RvMw=="));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { },
          new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
            new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V11.Enums.AdNetworkTypeEnum), global::Google.Ads.GoogleAds.V11.Enums.AdNetworkTypeEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V11.Enums.AdNetworkTypeEnum.Types.AdNetworkType) }, null, null)
          }));
    }
    #endregion

  }
  #region Messages
  ///
  /// Container for enumeration of Google Ads network types.
  ///
  public sealed partial class AdNetworkTypeEnum : pb::IMessage<AdNetworkTypeEnum>
  #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      , pb::IBufferMessage
  #endif
  {
    private static readonly pb::MessageParser<AdNetworkTypeEnum> _parser = new pb::MessageParser<AdNetworkTypeEnum>(() => new AdNetworkTypeEnum());
    private pb::UnknownFieldSet _unknownFields;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pb::MessageParser<AdNetworkTypeEnum> Parser { get { return _parser; } }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pbr::MessageDescriptor Descriptor {
      get { return global::Google.Ads.GoogleAds.V11.Enums.AdNetworkTypeReflection.Descriptor.MessageTypes[0]; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public AdNetworkTypeEnum() {
      OnConstruction();
    }

    partial void OnConstruction();

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public AdNetworkTypeEnum(AdNetworkTypeEnum other) : this() {
      _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public AdNetworkTypeEnum Clone() {
      return new AdNetworkTypeEnum(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override bool Equals(object other) {
      return Equals(other as AdNetworkTypeEnum);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool Equals(AdNetworkTypeEnum other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      return Equals(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override int GetHashCode() {
      int hash = 1;
      if (_unknownFields != null) {
        hash ^= _unknownFields.GetHashCode();
      }
      return hash;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override string ToString() {
      return pb::JsonFormatter.ToDiagnosticString(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void WriteTo(pb::CodedOutputStream output) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      output.WriteRawMessage(this);
    #else
      if (_unknownFields != null) {
        _unknownFields.WriteTo(output);
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
      if (_unknownFields != null) {
        _unknownFields.WriteTo(ref output);
      }
    }
    #endif

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public int CalculateSize() {
      int size = 0;
      if (_unknownFields != null) {
        size += _unknownFields.CalculateSize();
      }
      return size;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(AdNetworkTypeEnum other) {
      if (other == null) {
        return;
      }
      _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(pb::CodedInputStream input) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      input.ReadRawMessage(this);
    #else
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
            break;
        }
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
            break;
        }
      }
    }
    #endif

    #region Nested types
    /// Container for nested types declared in the AdNetworkTypeEnum message type.
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static partial class Types {
      ///
      /// Enumerates Google Ads network types.
      ///
      public enum AdNetworkType {
        ///
        /// Not specified.
        ///
        [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
        ///
        /// The value is unknown in this version.
        ///
        [pbr::OriginalName("UNKNOWN")] Unknown = 1,
        ///
        /// Google search.
        ///
        [pbr::OriginalName("SEARCH")] Search = 2,
        ///
        /// Search partners.
        ///
        [pbr::OriginalName("SEARCH_PARTNERS")] SearchPartners = 3,
        ///
        /// Display Network.
        ///
        [pbr::OriginalName("CONTENT")] Content = 4,
        ///
        /// YouTube Search.
        ///
        [pbr::OriginalName("YOUTUBE_SEARCH")] YoutubeSearch = 5,
        ///
        /// YouTube Videos
        ///
        [pbr::OriginalName("YOUTUBE_WATCH")] YoutubeWatch = 6,
        ///
        /// Cross-network.
        ///
        [pbr::OriginalName("MIXED")] Mixed = 7,
      }

    }
    #endregion

  }

  #endregion

}

#endregion Designer generated code


text:
<?php
namespace Migration\Components\Templating;

use Migration\Io\Io as Base;

/*
 * class Io
 *
 */
class Io extends Base
{

    protected $dir = 'template';

    /*
     * __construct()
     * @param string $base_folder the path to a project
     */

    public function __construct($base_folder)
    {
        parent::__construct($base_folder);
    }

}
/* End of File */


text:
    Module for checking if your NodeJS program runs on a Raspberry PI

##Installation

    $ npm install rpi-model

##Usage

```js
var rpi_model = require('rpi-model');
rpi_model(function(status,model,revision){
    // status - true if the hardware is a Raspberry Pi, false otherwise
    // model - model of the Raspberry Pi
    // revision - hardware revision code of the board
})
```


text:
package edu.howest.breakout.client.render;

import edu.howest.breakout.game.entity.Entity;

import java.awt.*;
import java.awt.geom.Rectangle2D;

/**
 * Created by thomas on 05/11/2014.
 */
public class RenderBlock implements Render {

    private Rectangle2D block;

    public RenderBlock() {
        this.block = new Rectangle2D.Double();
    }

    @Override
    public void render(Graphics2D g, Entity entity) {
        block.setFrame(entity.getX(), entity.getY(), entity.getWidth(), entity.getHeight());
        g.setColor(entity.getColor());
        g.fill(block);

        g.setColor(Color.black);
        g.draw(block);

    }
}


text:
package tests.services;

import com.markbudai.openfleet.model.Location;
import com.markbudai.openfleet.services.LocationService;
import com.markbudai.openfleet.services.implementations.LocationServiceImpl;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import tests.listprovider.LocationListProvider;
import tests.supplier.LocationSupplier;

import java.util.List;

/**
 * Created by Mark on 2017. 05. 26..
 */
public class LocationServiceTest {
    private static LocationService locationService;

    @BeforeClass
    public static void init() {
        LocationListProvider provider = new LocationListProvider();
        provider.preload(LocationSupplier.getSampleLocationList());
        locationService = new LocationServiceImpl(provider);
    }

    @Test
    public void testAddIncreaseSize(){
        int size = locationService.getAllLocations().size();
        locationService.addLocation(LocationSupplier.getSampleLocation());
        Assert.assertEquals(size+1,locationService.getAllLocations().size());
    }

    @Test
    public void testUpdateLocation(){
        Location location = LocationSupplier.getUniqueLocation();
        locationService.addLocation(location);
        location = LocationSupplier.getUniqueLocation();
        location.setCity("SampleNewSample");
        Location stored = locationService.getLocationById(99);
        Assert.assertNotNull(stored);
        Assert.assertNotEquals(location, stored);
        locationService.updateLocation(location);
        Assert.assertEquals("SampleNewSample",locationService.getLocationById(99).getCity());
    }

    @Test
    public void testDeleteLocation(){
        Location location = LocationSupplier.getUniqueLocation();
        location.setId(999);
        locationService.addLocation(location);
        locationService.deleteLocation(999);
        Assert.assertNull(locationService.getLocationById(999));
    }
}


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview
 * 'OobeDialogHostBehavior' is a behavior for oobe-dialog containers to
 * match oobe-dialog bahavior.
 */

/** @polymerBehavior */
var OobeDialogHostBehavior = {
  properties: {
    /**
     * True when dialog is displayed in full-screen mode.
     */
    fullScreenDialog: {
      type: Boolean,
      value: false,
      reflectToAttribute: true,
    },
  },

  /**
   * Triggers onBeforeShow for elements matched by |selector|.
   * and sets |fullScreenDialog| attribute on them.
   * @param {string=} selector CSS selector (optional).
   */
  propagateFullScreenMode(selector) {
    if (!selector)
      selector = 'oobe-dialog';

    var screens = Polymer.dom(this.root).querySelectorAll(selector);
    for (var i = 0; i < screens.length; ++i) {
      if (this.fullScreenDialog)
        screens[i].fullScreenDialog = true;

      screens[i].onBeforeShow();
    }
  },

  /**
   * Pass down fullScreenDialog attribute.
   */
  onBeforeShow() {
    if (document.documentElement.hasAttribute('full-screen-dialog'))
      this.fullScreenDialog = true;

    this.propagateFullScreenMode();
  },

  /**
   * Triggers updateLocalizedContent() for elements matched by |selector|.
   * @param {string} selector CSS selector (optional).
   */
  propagateUpdateLocalizedContent(selector) {
    var screens = Polymer.dom(this.root).querySelectorAll(selector);
    for (var i = 0; i < screens.length; ++i) {
      /** @type {{updateLocalizedContent: function()}}}*/ (screens[i])
          .updateLocalizedContent();
    }
  },
};

/**
 * TODO(alemate): Replace with an interface. b/24294625
 * @typedef {{
 *   onBeforeShow: function()
 * }}
 */
OobeDialogHostBehavior.Proto;