text:
#include <string.h>
#include "rtpulpfeccommon.h"

#define MIN_RTP_HEADER_LEN 12

typedef struct
{
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
  unsigned int csrc_count:4;    /* CSRC count */
  unsigned int extension:1;     /* header extension flag */
  unsigned int padding:1;       /* padding flag */
  unsigned int version:2;       /* protocol version */
  unsigned int payload_type:7;  /* payload type */
  unsigned int marker:1;        /* marker bit */
#elif G_BYTE_ORDER == G_BIG_ENDIAN
  unsigned int version:2;       /* protocol version */
  unsigned int padding:1;       /* padding flag */
  unsigned int extension:1;     /* header extension flag */
  unsigned int csrc_count:4;    /* CSRC count */
  unsigned int marker:1;        /* marker bit */
  unsigned int payload_type:7;  /* payload type */
#else
#error "G_BYTE_ORDER should be big or little endian."
#endif
  unsigned int seq:16;          /* sequence number */
  unsigned int timestamp:32;    /* timestamp */
  unsigned int ssrc:32;         /* synchronization source */
  guint8 csrclist[4];           /* optional CSRC list, 32 bits each */
} RtpHeader;

static gsize
fec_level_hdr_get_size (gboolean l_bit)
{
  return sizeof (RtpUlpFecLevelHeader) - (l_bit ? 0 : 4);
}

static guint64
fec_level_hdr_get_mask (RtpUlpFecLevelHeader const *fec_lvl_hdr, gboolean l_bit)
{
  return ((guint64) g_ntohs (fec_lvl_hdr->mask) << 32) |
      (l_bit ? g_ntohl (fec_lvl_hdr->mask_continued) : 0);
}

static void
fec_level_hdr_set_mask (RtpUlpFecLevelHeader * fec_lvl_hdr, gboolean l_bit,
    guint64 mask)
{
  fec_lvl_hdr->mask = g_htons (mask >> 32);
  if (l_bit)
    fec_lvl_hdr->mask_continued = g_htonl (mask);
}

static guint16
fec_level_hdr_get_protection_len (RtpUlpFecLevelHeader * fec_lvl_hdr)
{
  return g_ntohs (fec_lvl_hdr->protection_len);
}

static void
fec_level_hdr_set_protection_len (RtpUlpFecLevelHeader * fec_lvl_hdr,
    guint16 len)
{
  fec_lvl_hdr->protection_len = g_htons (len);
}

static RtpUlpFecLevelHeader *
fec_hdr_get_level_hdr (RtpUlpFecHeader const *fec_hdr)
{
  return (RtpUlpFecLevelHeader *) (fec_hdr + 1);
}

static guint64
fec_hdr_get_mask (RtpUlpFecHeader const *fec_hdr)
{
  return fec_level_hdr_get_mask (fec_hdr_get_level_hdr (fec_hdr), fec_hdr->L);
}

static guint16
fec_hdr_get_seq_base (RtpUlpFecHeader const *fec_hdr, gboolean is_ulpfec,
    guint16 fec_seq)
{
  guint16 seq = g_ntohs (fec_hdr->seq);
  if (is_ulpfec)
    return seq;
  return fec_seq - seq;
}

static guint16
fec_hdr_get_packets_len_recovery (RtpUlpFecHeader const *fec_hdr)
{
  return g_htons (fec_hdr->len);
}

static guint32
fec_hdr_get_timestamp_recovery (RtpUlpFecHeader const *fec_hdr)
{
  return g_ntohl (fec_hdr->timestamp);
}

static void
_xor_mem (guint8 * restrict dst, const guint8 * restrict src, gsize length)
{
  guint i;

  for (i = 0; i < (length / sizeof (guint64)); ++i) {
    *((guint64 *) dst) ^= *((const guint64 *) src);
    dst += sizeof (guint64);
    src += sizeof (guint64);
  }
  for (i = 0; i < (length % sizeof (guint64)); ++i)
    dst[i] ^= src[i];
}

guint16
rtp_ulpfec_hdr_get_protection_len (RtpUlpFecHeader const *fec_hdr)
{
  return fec_level_hdr_get_protection_len (fec_hdr_get_level_hdr (fec_hdr));
}

RtpUlpFecHeader *
rtp_ulpfec_buffer_get_fechdr (GstRTPBuffer * rtp)
{
  return (RtpUlpFecHeader *) gst_rtp_buffer_get_payload (rtp);
}

guint64
rtp_ulpfec_buffer_get_mask (GstRTPBuffer * rtp)
{
  return fec_hdr_get_mask (rtp_ulpfec_buffer_get_fechdr (rtp));
}

guint16
rtp_ulpfec_buffer_get_seq_base (GstRTPBuffer * rtp)
{
  return g_ntohs (rtp_ulpfec_buffer_get_fechdr (rtp)->seq);
}

guint
rtp_ulpfec_get_headers_len (gboolean fec_mask_long)
{
  return sizeof (RtpUlpFecHeader) + fec_level_hdr_get_size (fec_mask_long);
}

#define ONE_64BIT G_GUINT64_CONSTANT(1)

guint64
rtp_ulpfec_packet_mask_from_seqnum (guint16 seq,
    guint16 fec_seq_base, gboolean fec_mask_long)
{
  gint seq_delta = gst_rtp_buffer_compare_seqnum (fec_seq_base, seq);
  if (seq_delta >= 0
      && seq_delta <= RTP_ULPFEC_SEQ_BASE_OFFSET_MAX (fec_mask_long)) {
    return ONE_64BIT << (RTP_ULPFEC_SEQ_BASE_OFFSET_MAX (TRUE) - seq_delta);
  }
  return 0;
}

gboolean
rtp_ulpfec_mask_is_long (guint64 mask)
{
  return (mask & 0xffffffff) ? TRUE : FALSE;
}

gboolean
rtp_ulpfec_buffer_is_valid (GstRTPBuffer * rtp)
{
  guint payload_len = gst_rtp_buffer_get_payload_len (rtp);
  RtpUlpFecHeader *fec_hdr;
  guint fec_hdrs_len;
  guint fec_packet_len;

  if (payload_len < sizeof (RtpUlpFecHeader))
    goto toosmall;

  fec_hdr = rtp_ulpfec_buffer_get_fechdr (rtp);
  if (fec_hdr->E)
    goto invalidcontent;

  fec_hdrs_len = rtp_ulpfec_get_headers_len (fec_hdr->L);
  if (payload_len < fec_hdrs_len)
    goto toosmall;

  fec_packet_len = fec_hdrs_len + rtp_ulpfec_hdr_get_protection_len (fec_hdr);
  if (fec_packet_len != payload_len)
    goto lengthmismatch;

  return TRUE;
toosmall:
  GST_WARNING ("FEC packet too small");
  return FALSE;

lengthmismatch:
  GST_WARNING ("invalid FEC packet (declared length %u, real length %u)",
      fec_packet_len, payload_len);
  return FALSE;

invalidcontent:
  GST_WARNING ("FEC Header contains invalid fields: %u", fec_hdr->E);
  return FALSE;
}

void
rtp_buffer_to_ulpfec_bitstring (GstRTPBuffer * rtp, GArray * dst_arr,
    gboolean fec_buffer, gboolean fec_mask_long)
{
  if (G_UNLIKELY (fec_buffer)) {
    guint payload_len = gst_rtp_buffer_get_payload_len (rtp);
    g_array_set_size (dst_arr, MAX (payload_len, dst_arr->len));
    memcpy (dst_arr->data, gst_rtp_buffer_get_payload (rtp), payload_len);
  } else {
    const guint8 *src = rtp->data[0];
    guint len = gst_rtp_buffer_get_packet_len (rtp) - MIN_RTP_HEADER_LEN;
    guint dst_offset = rtp_ulpfec_get_headers_len (fec_mask_long);
    guint src_offset = MIN_RTP_HEADER_LEN;
    guint8 *dst;

    g_array_set_size (dst_arr, MAX (dst_offset + len, dst_arr->len));
    dst = (guint8 *) dst_arr->data;

    *((guint64 *) dst) ^= *((const guint64 *) src);
    ((RtpUlpFecHeader *) dst)->len ^= g_htons (len);
    _xor_mem (dst + dst_offset, src + src_offset, len);
  }
}

GstBuffer *
rtp_ulpfec_bitstring_to_media_rtp_buffer (GArray * arr,
    gboolean fec_mask_long, guint32 ssrc, guint16 seq)
{
  guint fec_hdrs_len = rtp_ulpfec_get_headers_len (fec_mask_long);
  guint payload_len =
      fec_hdr_get_packets_len_recovery ((RtpUlpFecHeader *) arr->data);
  GstMapInfo ret_info = GST_MAP_INFO_INIT;
  GstMemory *ret_mem;
  GstBuffer *ret;

  if (payload_len > arr->len - fec_hdrs_len)
    return NULL;                // Not enough data

  ret_mem = gst_allocator_alloc (NULL, MIN_RTP_HEADER_LEN + payload_len, NULL);
  gst_memory_map (ret_mem, &ret_info, GST_MAP_READWRITE);

  /* Filling 12 bytes of RTP header */
  *((guint64 *) ret_info.data) = *((guint64 *) arr->data);
  ((RtpHeader *) ret_info.data)->version = 2;
  ((RtpHeader *) ret_info.data)->seq = g_htons (seq);
  ((RtpHeader *) ret_info.data)->ssrc = g_htonl (ssrc);
  /* Filling payload */
  memcpy (ret_info.data + MIN_RTP_HEADER_LEN,
      arr->data + fec_hdrs_len, payload_len);

  gst_memory_unmap (ret_mem, &ret_info);
  ret = gst_buffer_new ();
  gst_buffer_append_memory (ret, ret_mem);
  return ret;
}

GstBuffer *
rtp_ulpfec_bitstring_to_fec_rtp_buffer (GArray * arr,
    guint16 seq_base, gboolean fec_mask_long, guint64 fec_mask,
    gboolean marker, guint8 pt, guint16 seq, guint32 timestamp, guint32 ssrc)
{
  GstRTPBuffer rtp = GST_RTP_BUFFER_INIT;
  GstBuffer *ret;

  /* Filling FEC headers */
  {
    RtpUlpFecHeader *hdr = (RtpUlpFecHeader *) arr->data;
    RtpUlpFecLevelHeader *lvlhdr;
    hdr->E = 0;
    hdr->L = fec_mask_long;
    hdr->seq = g_htons (seq_base);

    lvlhdr = fec_hdr_get_level_hdr (hdr);
    fec_level_hdr_set_protection_len (lvlhdr,
        arr->len - rtp_ulpfec_get_headers_len (fec_mask_long));
    fec_level_hdr_set_mask (lvlhdr, fec_mask_long, fec_mask);
  }

  /* Filling RTP header, copying payload */
  ret = gst_rtp_buffer_new_allocate (arr->len, 0, 0);
  if (!gst_rtp_buffer_map (ret, GST_MAP_READWRITE, &rtp))
    g_assert_not_reached ();

  gst_rtp_buffer_set_marker (&rtp, marker);
  gst_rtp_buffer_set_payload_type (&rtp, pt);
  gst_rtp_buffer_set_seq (&rtp, seq);
  gst_rtp_buffer_set_timestamp (&rtp, timestamp);
  gst_rtp_buffer_set_ssrc (&rtp, ssrc);

  memcpy (gst_rtp_buffer_get_payload (&rtp), arr->data, arr->len);

  gst_rtp_buffer_unmap (&rtp);

  return ret;
}

/**
 * rtp_ulpfec_map_info_map:
 * @buffer: (transfer: full) #GstBuffer
 * @info: #RtpUlpFecMapInfo
 *
 * Maps the contents of @buffer into @info. If @buffer made of many #GstMemory
 * objects, merges them together to create a new buffer made of single
 * continious #GstMemory.
 *
 * Returns: %TRUE if @buffer could be mapped
 **/
gboolean
rtp_ulpfec_map_info_map (GstBuffer * buffer, RtpUlpFecMapInfo * info)
{
  /* We need to make sure we are working with continious memory chunk.
   * If not merge all memories together */
  if (gst_buffer_n_memory (buffer) > 1) {
    GstBuffer *new_buffer = gst_buffer_new ();
    GstMemory *mem = gst_buffer_get_all_memory (buffer);
    gst_buffer_append_memory (new_buffer, mem);

    /* We supposed to own the old buffer, but we don't use it here, so unref */
    gst_buffer_unref (buffer);
    buffer = new_buffer;
  }

  if (!gst_rtp_buffer_map (buffer,
          GST_MAP_READ | GST_RTP_BUFFER_MAP_FLAG_SKIP_PADDING, &info->rtp)) {
    /* info->rtp.buffer = NULL is an indication for rtp_ulpfec_map_info_unmap()
     * that mapping has failed */
    g_assert (NULL == info->rtp.buffer);
    gst_buffer_unref (buffer);
    return FALSE;
  }
  return TRUE;
}

/**
 * rtp_ulpfec_map_info_unmap:
 * @info: #RtpUlpFecMapInfo
 *
 * Unmap @info previously mapped with rtp_ulpfec_map_info_map() and unrefs the
 * buffer. For convinience can even be called even if rtp_ulpfec_map_info_map
 * returned FALSE
 **/
void
rtp_ulpfec_map_info_unmap (RtpUlpFecMapInfo * info)
{
  GstBuffer *buffer = info->rtp.buffer;

  if (buffer) {
    gst_rtp_buffer_unmap (&info->rtp);
    gst_buffer_unref (buffer);
  }
}

#ifndef GST_DISABLE_GST_DEBUG
void
rtp_ulpfec_log_rtppacket (GstDebugCategory * cat, GstDebugLevel level,
    gpointer object, const gchar * name, GstRTPBuffer * rtp)
{
  guint seq;
  guint ssrc;
  guint timestamp;
  guint pt;

  if (level > gst_debug_category_get_threshold (cat))
    return;

  seq = gst_rtp_buffer_get_seq (rtp);
  ssrc = gst_rtp_buffer_get_ssrc (rtp);
  timestamp = gst_rtp_buffer_get_timestamp (rtp);
  pt = gst_rtp_buffer_get_payload_type (rtp);

  GST_CAT_LEVEL_LOG (cat, level, object,
      "%-22s: [%c%c%c%c] ssrc=0x%08x pt=%u tstamp=%u seq=%u size=%u(%u,%u)",
      name,
      gst_rtp_buffer_get_marker (rtp) ? 'M' : ' ',
      gst_rtp_buffer_get_extension (rtp) ? 'X' : ' ',
      gst_rtp_buffer_get_padding (rtp) ? 'P' : ' ',
      gst_rtp_buffer_get_csrc_count (rtp) > 0 ? 'C' : ' ',
      ssrc, pt, timestamp, seq,
      gst_rtp_buffer_get_packet_len (rtp),
      gst_rtp_buffer_get_packet_len (rtp) - MIN_RTP_HEADER_LEN,
      gst_rtp_buffer_get_payload_len (rtp));
}
#endif /* GST_DISABLE_GST_DEBUG */

#ifndef GST_DISABLE_GST_DEBUG
void
rtp_ulpfec_log_fec_packet (GstDebugCategory * cat, GstDebugLevel level,
    gpointer object, GstRTPBuffer * fecrtp)
{
  RtpUlpFecHeader *fec_hdr;
  RtpUlpFecLevelHeader *fec_level_hdr;

  if (level > gst_debug_category_get_threshold (cat))
    return;

  fec_hdr = gst_rtp_buffer_get_payload (fecrtp);
  GST_CAT_LEVEL_LOG (cat, level, object,
      "%-22s: [%c%c%c%c%c%c] pt=%u tstamp=%u seq=%u recovery_len=%u",
      "fec header",
      fec_hdr->E ? 'E' : ' ',
      fec_hdr->L ? 'L' : ' ',
      fec_hdr->P ? 'P' : ' ',
      fec_hdr->X ? 'X' : ' ',
      fec_hdr->CC ? 'C' : ' ',
      fec_hdr->M ? 'M' : ' ',
      fec_hdr->pt,
      fec_hdr_get_timestamp_recovery (fec_hdr),
      fec_hdr_get_seq_base (fec_hdr, TRUE,
          gst_rtp_buffer_get_seq (fecrtp)),
      fec_hdr_get_packets_len_recovery (fec_hdr));

  fec_level_hdr = fec_hdr_get_level_hdr (fec_hdr);
  GST_CAT_LEVEL_LOG (cat, level, object,
      "%-22s: protection_len=%u mask=0x%012" G_GINT64_MODIFIER "x",
      "fec level header",
      g_ntohs (fec_level_hdr->protection_len),
      fec_level_hdr_get_mask (fec_level_hdr, fec_hdr->L));
}
#endif /* GST_DISABLE_GST_DEBUG */


text:
def can_test_mecab_spec?
  # In Travis Ci dictionares_controller#build failed because of there is no MeCab installed.
  # So, before test, check whether we can do MeCab specific tests.
  return false if SS.config.kana.disable
  unless ::File.exists?(SS.config.kana.mecab_indexer)
    puts("[MeCab Spec] not found: #{SS.config.kana.mecab_indexer}")
    return false
  end
  unless ::File.exists?(SS.config.kana.mecab_dicdir)
    puts("[MeCab Spec] not found: #{SS.config.kana.mecab_dicdir}")
    return false
  end
  true
end

RSpec.configuration.before(:suite) do
  prefix = "kana"
  timestamp = Time.zone.now.strftime("%Y%m%d")
  tmp = ::File.join(Dir.tmpdir, "#{prefix}-#{timestamp}")
  ::Dir.mkdir(tmp) unless ::Dir.exists?(tmp)

  SS.config.kana
  SS::Config.replace_value_at(:kana, :root, tmp)
end

RSpec.configuration.after(:suite) do
  ::FileUtils.rm_rf SS.config.kana.root if ::Dir.exists?(SS.config.kana.root)
end

redpajama_set_name: RedPajamaGithub


text:
<?php

class HighRollerToolTip {

        public $backgroundColor = null;

        public function __construct() {

        }

}


text:
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 *  Main authors:
 *     Christian Schulte <schulte@gecode.org>
 *     Vincent Barichard <Vincent.Barichard@univ-angers.fr>
 *
 *  Copyright:
 *     Christian Schulte, 2002
 *     Vincent Barichard, 2012
 *
 *  Last modified:
 *     $Date: 2012-03-28 23:47:11 +0900 (水, 28 3 2012) $ by $Author: vbarichard $
 *     $Revision: 12648 $
 *
 *  This file is part of Gecode, the generic constraint
 *  development environment:
 *     http://www.gecode.org
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include <gecode/float/rel.hh>

#include <algorithm>

namespace Gecode {

  void
  rel(Home home, FloatVar x0, FloatRelType frt, FloatVal n) {
    using namespace Float;
    Limits::check(n,"Float::rel");
    if (home.failed()) return;
    FloatView x(x0);
    switch (frt) {
    case FRT_EQ: GECODE_ME_FAIL(x.eq(home,n)); break;
    case FRT_LQ: GECODE_ME_FAIL(x.lq(home,n)); break;
    case FRT_GQ: GECODE_ME_FAIL(x.gq(home,n)); break;
    default: throw UnknownRelation("Float::rel");
    }
  }

  void
  rel(Home home, FloatVar x0, FloatRelType frt, FloatVar x1) {
    using namespace Float;
    if (home.failed()) return;
    switch (frt) {
    case FRT_EQ:
      GECODE_ES_FAIL((Rel::Eq<FloatView,FloatView>::post(home,x0,x1)));
      break;
    case FRT_GQ:
      std::swap(x0,x1); // Fall through
    case FRT_LQ:
      GECODE_ES_FAIL((Rel::Lq<FloatView>::post(home,x0,x1))); break;
    default:
      throw UnknownRelation("Float::rel");
    }
  }

#define GECODE_WRITE_REIFIED_UNA_PROP(name,view0,mode,a,c,bvar) \
        if (b) GECODE_ES_FAIL((name<view0,Int::BoolView,mode>:: \
                               post(home,a,c,bvar))); \
        else   GECODE_ES_FAIL((name<view0,Int::NegBoolView,mode>:: \
                               post(home,a,c,Int::NegBoolView(bvar))));

  void
  rel(Home home, FloatVar x0, FloatRelType frt, FloatVar x1, Reify r, bool b) {
    using namespace Float;
    if (home.failed()) return;
    switch (frt) {
    case FRT_EQ:
      switch (r.mode()) {
      case RM_EQV:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReEq,FloatView,RM_EQV,x0,x1,r.var());
        break;
      case RM_IMP:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReEq,FloatView,RM_IMP,x0,x1,r.var());
        break;
      case RM_PMI:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReEq,FloatView,RM_PMI,x0,x1,r.var());
        break;
      default: throw Int::UnknownReifyMode("Float::rel");
      }
      break;
    case FRT_GQ:
      std::swap(x0,x1); // Fall through
    case FRT_LQ:
      switch (r.mode()) {
      case RM_EQV:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReLq,FloatView,RM_EQV,x0,x1,r.var());
        break;
      case RM_IMP:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReLq,FloatView,RM_EQV,x0,x1,r.var());
        break;
      case RM_PMI:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReLq,FloatView,RM_EQV,x0,x1,r.var());
        break;
      default: throw Int::UnknownReifyMode("Float::rel");
      }
      break;
    default:
      throw Int::UnknownRelation("Float::rel");
    }
  }

  void
  rel(Home home, FloatVar x, FloatRelType frt, FloatVal n, Reify r, bool b) {
    using namespace Float;
    Limits::check(n,"Float::rel");
    if (home.failed()) return;
    switch (frt) {
    case FRT_EQ:
      switch (r.mode()) {
      case RM_EQV:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReEqFloat,FloatView,RM_EQV,x,n,r.var());
        break;
      case RM_IMP:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReEqFloat,FloatView,RM_IMP,x,n,r.var());
        break;
      case RM_PMI:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReEqFloat,FloatView,RM_PMI,x,n,r.var());
        break;
      default: throw Int::UnknownReifyMode("Float::rel");
      }
    case FRT_LQ:
      switch (r.mode()) {
      case RM_EQV:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReLqFloat,FloatView,RM_EQV,x,n,r.var());
        break;
      case RM_IMP:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReLqFloat,FloatView,RM_IMP,x,n,r.var());
        break;
      case RM_PMI:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReLqFloat,FloatView,RM_PMI,x,n,r.var());
        break;
      default: throw Int::UnknownReifyMode("Float::rel");
      }
      break;
    case FRT_GQ:
      switch (r.mode()) {
      case RM_EQV:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReGqFloat,FloatView,RM_EQV,x,n,r.var());
        break;
      case RM_IMP:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReGqFloat,FloatView,RM_IMP,x,n,r.var());
        break;
      case RM_PMI:
        GECODE_WRITE_REIFIED_UNA_PROP(Rel::ReGqFloat,FloatView,RM_PMI,x,n,r.var());
        break;
      default: throw Int::UnknownReifyMode("Float::rel");
      }
      break;
    default:
      throw Int::UnknownRelation("Float::rel");
    }
  }

#undef GECODE_WRITE_REIFIED_UNA_PROP

  void
  rel(Home home, const FloatVarArgs& x, FloatRelType frt, FloatVal c) {
    using namespace Float;
    Limits::check(c,"Float::rel");
    if (home.failed()) return;
    switch (frt) {
    case FRT_EQ:
      for (int i=x.size(); i--; ) {
        FloatView xi(x[i]); GECODE_ME_FAIL(xi.eq(home,c));
      }
      break;
    case FRT_LQ:
      for (int i=x.size(); i--; ) {
        FloatView xi(x[i]); GECODE_ME_FAIL(xi.lq(home,c));
      }
      break;
    case FRT_GQ:
      for (int i=x.size(); i--; ) {
        FloatView xi(x[i]); GECODE_ME_FAIL(xi.gq(home,c));
      }
      break;
    default:
      throw UnknownRelation("Float::rel");
    }
  }

}

// STATISTICS: float-post


text:
package org.ow2.contrail.federation.federationapi.resources.impl;

import org.apache.log4j.Logger;
import org.ow2.contrail.federation.federationapi.resources.IOvfResource;
import org.ow2.contrail.federation.federationapi.utils.JSONObject;
import org.ow2.contrail.federation.federationdb.jpa.entities.Ovf;
import org.ow2.contrail.federation.federationdb.jpa.entities.Provider;
import org.ow2.contrail.federation.federationdb.utils.PersistenceUtils;

import javax.persistence.EntityManager;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;

public class OvfResource implements IOvfResource {

    protected static Logger logger =
            Logger.getLogger(OvfResource.class);

    private Ovf ovf;
    private Provider provider;

    public OvfResource(Ovf ovf) {
        this.ovf = ovf;
    }

    public OvfResource(Provider provider, Ovf ovf) {
        this.ovf = ovf;
        this.provider = provider;
    }

    /**
     * Returns the JSON representation of the selected OVF.
     *
     * @return
     */
    @GET
    @Produces("application/json")
    public Response getOvf() throws Exception {
        logger.debug("Entering getOvf");
        JSONObject ovf = new JSONObject();
        ovf.put("providerId", String.format("/providers/%d", this.ovf.getProviderId().getProviderId()));
        ovf.put("ovfId", this.ovf.getOvfId());
        ovf.put("name", this.ovf.getName());
        ovf.put("attributes", this.ovf.getAttributes());
        logger.debug("Exiting getOvf");
        return Response.ok(ovf.toString()).build();
    }

    /**
     * Updates the selected OVF.
     *
     * @return
     */
    @PUT
    @Consumes("application/json")
    public Response updateOvf(String requestBody) throws Exception {
        logger.debug("Modifying ovf");
        JSONObject json = new JSONObject(requestBody);
        String name = (String) json.get("name");
        ovf.setName(name);
        ovf.setAttributes(json.toString());
        EntityManager em = PersistenceUtils.getInstance().getEntityManager();
        try {
            em.getTransaction().begin();
            ovf = em.merge(ovf);
            em.getTransaction().commit();
            return Response.status(Response.Status.NO_CONTENT).build();
        }
        finally {
            logger.debug("Exiting modifying ovf");
            PersistenceUtils.getInstance().closeEntityManager(em);
        }
    }

    /**
     * Deletes selected OVF.
     *
     * @return
     */
    @DELETE
    public Response removeOvf() throws Exception {
        EntityManager em = PersistenceUtils.getInstance().getEntityManager();
        try {
            em.getTransaction().begin();
            ovf = em.merge(ovf);
            em.remove(ovf);
            provider.getOvfList().remove(ovf);
            provider = em.merge(provider);
            em.getTransaction().commit();

            return Response.status(Response.Status.NO_CONTENT).build();
        }
        finally {
            PersistenceUtils.getInstance().closeEntityManager(em);
        }
    }
}


text:
package org.globus.ftp;

/**
 * Utility class for parsing and converting host-port information from EPSV
 * and EPRT ftp commands.
 */
public class HostPort6 extends HostPort {

    public static final String IPv4 = "1";
    public static final String IPv6 = "2";

    private String host;
    private int port;
    private String version;

    public HostPort6(String version, String host, int port) {
        this.version = version;
        this.host = host;
        this.port = port;
    }

    /**
     * Parses host-port from passive mode reply message.
     * Note that the argument is not the whole message, but
     * only the content of the brackets:
     * <d><net-prt><d><net-addr><d><tcp-port><d>
     *
     * @param passiveReplyMessage reply message for the EPSV command
     */
    public HostPort6(String passiveReplyMessage) {
        Parser tokens = new Parser(passiveReplyMessage);
        String token = null;

        token = tokens.nextToken().trim();
        if (token.length() == 0) {
            // do nothing assume the same as control channel
        } else if (token.equals(IPv4)) {
            this.version = IPv4;
        } else if (token.equals(IPv6)) {
            this.version = IPv6;
        } else {
            throw new IllegalArgumentException("Invalid network protocol: " +
                                               token);
        }

        token = tokens.nextToken().trim();
        if (token.length() == 0) {
            // do nothing assume the same as control channel
        } else {
            this.host = token;
        }

        token = tokens.nextToken().trim();
        if (token.length() == 0) {
            throw new IllegalArgumentException("Port number is required");
        }
        this.port = Integer.parseInt(token);
    }

    private static class Parser {

        String line;
        int offset = 0;

        public Parser(String line) {
            this.line = line;
        }

        public String nextToken() {
            int start = line.indexOf('|', this.offset);
            if (start == -1) {
                throw new IllegalArgumentException("Formatting error");
            }
            int end = line.indexOf('|', start+1);
            if (end == -1) {
                throw new IllegalArgumentException("Formatting error");
            }
            this.offset = end;
            return line.substring(start+1, end);
        }
    }

    /**
     * Returns the port number
     *
     * @return port number
     */
    public int getPort() {
	return this.port;
    }

    /**
     * Sets the host address
     *
     * @param host the host address
     */
    public void setHost(String host) {
	this.host = host;
    }

    /**
     * Returns the host address
     *
     * @return host address
     */
    public String getHost() {
	return this.host;
    }

    /**
     * Returns the address version
     *
     * @return address version
     */
    public String getVersion() {
	return this.version;
    }

    /**
     * Sets the address version
     *
     * @param version the address version
     */
    public void setVersion(String version) {
	this.version = version;
    }

    /**
     * Returns the host-port information in the
     * format used by EPRT command.
     * <d><net-prt><d><net-addr><d><tcp-port><d>
     *
     * @return host-port information in EPRT command
     *         representation.
     */
    public String toFtpCmdArgument() {
	StringBuffer msg = new StringBuffer();
        msg.append("|");
        if (this.version != null) {
            msg.append(this.version);
        }
        msg.append("|");
        if (this.host != null) {
            msg.append(this.host);
        }
        msg.append("|");
        msg.append(String.valueOf(this.port));
        msg.append("|");
	return msg.toString();
    }

    public static String getIPAddressVersion(String address) {
        return (address.indexOf(':') == -1) ? IPv4 : IPv6;
    }

}


text:
<?php

namespace Bootstrap\Components\AppzioUiKit\Headers;

trait uiKitFauxTopBarTransparent {

    /**
     * This is a component for creating a top bar which can include logo, custom buttons etc.
     * @param array $parameters
     * title, btn_title, btn_onclick, route_back, mode, logo, right_menu
     * @return mixed
     */
    public function uiKitFauxTopBarTransparent($parameters = array()){
        /** @var BootstrapComponent $this */

        $title = isset($parameters['title']) ? $parameters['title'] : false;
        $btn_title = isset($parameters['btn_title']) ? $parameters['btn_title'] : '';
        $action = isset($parameters['btn_onclick']) ? $parameters['btn_onclick'] : $this->getOnclickSubmit('photo');
        $color = isset($parameters['icon_color']) ? $parameters['icon_color'] : 'white';

        if($this->notch){
            $height = '80';
            $padding = '0 0 10 0';
        } else {
            if($this->transparent_statusbar AND $this->phone_statusbar){
                $height = '60';
                $padding = '0 0 10 0';
            } else {
                $height = '40';
                $padding = '0 0 6 0';
            }
        }

        if(isset($parameters['route_back'])){
            $close = $this->getOnclickRoute($parameters['route_back']);
            $top[] = $this->getComponentImage('div-back-icon.png',array('onclick' => $close,'style' => 'fauxheader_close'));
        }elseif(isset($parameters['mode']) AND $parameters['mode'] == 'gohome'){
            $close = $this->getOnclickGoHome();
            $top[] = $this->getComponentImage('div-back-icon.png',array('onclick' => $close,'style' => 'fauxheader_close'));
        }elseif(isset($parameters['mode']) AND $parameters['mode'] == 'close'){
            $close = $this->getOnclickClosePopup();
            $top[] = $this->getComponentImage('close-icon-div.png',array('onclick' => $close,'style' => 'fauxheader_close'));
        }elseif(isset($parameters['mode']) AND $parameters['mode'] == 'close-go-home'){
            $close = $this->getOnclickGoHome();
            $top[] = $this->getComponentImage('close-icon-div.png',array('onclick' => $close,'style' => 'fauxheader_close'));
        }elseif(isset($parameters['mode']) AND $parameters['mode'] == 'sidemenu'){
            $menuAction = $this->getOnclickOpenSidemenu();
            $top[] = $this->getComponentImage(
                'white_hamburger_icon.png',
                array('onclick' => $menuAction),
                array(
                    "height" => "24",
                    "width" => "24",
                    "margin" => "0 0 0 13",
                    'shadow-color' => '#545050',
                    'shadow-radius' => 2,
                    'shadow-offset' => '0 0',
                )
            );
        } else {
            $close = $this->getOnclickTab(1);
            $top[] = $this->getComponentImage('div-close-icon.png',array('onclick' => $close,'style' => 'fauxheader_close'));
        }

        if(isset($parameters['notification_count']) AND $parameters['notification_count']) {
            $center_width = $this->screen_width - 137;
            $top[] = $this->getComponentVerticalSpacer(30);
        } else {
            $center_width = $this->screen_width - 77;
        }

        if(isset($parameters['logo']) AND $parameters['logo']){
            $top[] = $this->getComponentImage($parameters['logo'],[],['height' => '30','margin' => '4 0 5 0','width' => $center_width,'text-align' => 'center']);
        } elseif($title) {
            if($color == 'white'){
                $top[] = $this->getComponentText($title,array(),[
                    'text-align' => 'center','width' => $center_width,
                    'margin' => '8 0 5 0','font-size' => '15','color' => '#ffffff']);
            } else {
                $top[] = $this->getComponentText($title,array(),[
                    'text-align' => 'center','width' => $center_width,
                    'margin' => '8 0 5 0','font-size' => '15','color' => '#000000']);
            }
        } elseif($title) {
            $top[] = $this->getComponentText($title,[],['color' => '#fffffff']);
        } else {
            $top[] = $this->getComponentVerticalSpacer($center_width);
        }

        if(isset($parameters['right_menu']) AND $parameters['right_menu'] AND isset($parameters['right_menu']['icon'])) {
            $top[] = $this->getComponentImage($parameters['right_menu']['icon'],[
                'onclick' => $this->getOnclickOpenAction(false,$parameters['right_menu']['config'])
            ],[
                    'height' => '25',
                    'padding' => '1 0 0 0',
                    'shadow-color' => '#545050',
                    'shadow-radius' => 2,
                    'shadow-offset' => '0 0',
                ]
            );
        }

        if($btn_title){
            if($btn_title == 'X'){
                $top[] = $this->getComponentImage('div-close-icon.png',array('onclick' => $action,'style' => 'fauxheader_close'));
            } else {
                $top[] = $this->getComponentText($btn_title,array('onclick' => $action,'style' => 'fauxheader_add'));
            }
        } else {
            $top[] = $this->getComponentText('',array('style' => 'fauxheader_add'));
        }

        $layout = new \stdClass();
        $layout->top = 15;
        $layout->left = 0;
        $layout->right = 0;
        $layout->center = 0;

        return $this->getComponentRow($top,array(),array(
            'height' => $height,
            //'border' => 1,
            //'border-color' => '#ffffff',
            'width' => 'auto',
            'text-align' => 'center',
            'vertical-align' => 'middle',
            'layout' => $layout,
            'padding' => $padding));

    }

}


text:
#ifndef _PUZZLE_STD_H_
#define _PUZZLE_STD_H_

#ifndef _SIZE_T
#define _SIZE_T
typedef unsigned int size_t;
#endif

void exit(int errcode);

void putch(char c);
void puts(char *s);
int printf(const char *fmt, ...);
const char* strchr(const char *s, int c);
int atoi(const char *s);

char getch();
void gets(char *str);

int exec(char *s, int wait);

void waitpid(int pid);

void *malloc(size_t size);
void free(void *addr);

void kill(int pid);
void ps();

#endif


text:
from google.cloud import domains_v1beta1

async def sample_delete_registration():
    # Create a client
    client = domains_v1beta1.DomainsAsyncClient()

    # Initialize request argument(s)
    request = domains_v1beta1.DeleteRegistrationRequest(
        name="name_value",
    )

    # Make the request
    operation = client.delete_registration(request=request)

    print("Waiting for operation to complete...")

    response = await operation.result()

    # Handle the response
    print(response)

# [END domains_v1beta1_generated_Domains_DeleteRegistration_async]


text:
/*
 ObjObserver by Spencer Hedger (https://github.com/SpencerHedger/object-observer).

 Call ObjObserver.observable() passing in an underlying data object to observe.
 A Proxy to the object is created and returned which reflects the underlying object and
 is responsible for notifying observers when changes are made and synchronising these
 changes to the underlying data object.

 Add observers to the object through an 'observe' property on the returned Proxy. To
 observe changes to a specific property of the object, use 'observe.propertyName' where
 propertyName is a property of the observed object.

 An observers can be notified either before, after or on cancel of a change made through
 the proxy. They take the form of either:
 	A function, with three parameters (which is called before update):
		value			The value that is about to be assigned

		data			The data object containing the property

		propertyName	The name of the property in the target object

      Using these parameters, you can establish what the value currently is
      (e.g. data[propertyName]) and what it is about to become (e.g. value).

 	... or ...

 	An object with any of the following functions defined:
 		onBind		Called once when the observer is bound to the proxy
 					Expects a function with parameters of value, data and propertyName

		before		Called each time before a value is updated
					Expects a function with parameters of value, data and propertyName
					Return false from this function to prevent an update to the object

		after		Called each time after a value is updated
					Function with parameters of value, data and propertyName

		cancel		Called each time when the update of a value is attempted but cancelled by
					one of the "before" observers.
					Function with parameters of value, data and propertyName

 You can use this information to drive interface updates or validate changes. For example
 if you create an element where the innerHTML is updated by an observer function, when
 you change the value of the observed property through the proxy the element will
 automatically update to reflect the changes.

 To perform validation, you can prevent a change from reaching the underlying
 data object by returning 'false' from any of the "before" observer functions.

 Note that if validation is performed, any observers which update view state should
 probably use "after" observer functions so they do not become out of step with the
 underlying data.

 An "options" object can be specified as a second parameter to the observable() function:
 	nameOfObserveProperty		Default name is 'observe' for assigning observers on
 								the Proxy. If this clashes with any property in your data,
 								you can specifying an alternative here.

 You can add more than one observer to any given object or property.
*/
var ObjObserver = function() {
	function observable(d, options) {
		var _options = options || { };
		_options.nameOfObserveProperty = _options.nameOfObserveProperty || 'observe';

		var _l = {
			_fireOnAllChanges: []
		};

		var _listeners = new Proxy(_l,
			{
				get: function(obj, prop) {
					if(!_l[prop]) _l[prop] = new Array();
					return _l[prop];
				},
				set: function(obj, prop, value) {
					if(!_l[prop]) _l[prop] = new Array();

					if(typeof(value) === 'function') _l[prop].push( { before: value } );
					else {
						_l[prop].push(value);
						if(value.onBind) value.onBind(d[prop], d, prop);
					}
				}
			});

		var _o = {
		};

		return new Proxy(d,
		{
			get: function(obj, prop) {
				if(prop === _options.nameOfObserveProperty) {
					return _listeners;
				}
				else {
					// Does this object need to be converted into a proxy?
					if(typeof obj[prop] === 'object' && obj[obsProp] == undefined) {
						if(_o[prop] == undefined) _o[prop] = observable(obj[prop], obsProp);
						return _o[prop];
					}
					else return obj[prop]; // Simply value
				}
			},
			set: function(obj, prop, value) {
				if(prop === _options.nameOfObserveProperty) {
					if(value == null) _l.length = 0; // Clear all listeners with a null value
					else if(typeof(value) === 'function') _l._fireOnAllChanges.push(value);

					return true; // success
				}
				else {
					var ok = true; // Can be set to false by "before" listeners

					// Loop over specific property listeners (any listener returning false prevents value change)
					if(_l[prop]) {
						for(var i = 0; i < _l[prop].length; i++) {
							if(_l[prop][i].before) {
								if(_l[prop][i].before(value, obj, prop) === false) ok = false;
							}
						}
					};

					// Loop over broader object-wide listeners (any listener returning false prevents value change)
					for(var i = 0; i < _l._fireOnAllChanges.length; i++) {
						if(_l._fireOnAllChanges[i].before) {
							if(_l._fireOnAllChanges[i].before(value, obj, prop) === false) ok = false;
						}
					};

					// Do the assignment
					if(ok) {
						if(typeof value === 'object' || Array.isArray(value)) obj[prop] = observable(value, obsProp);
						else obj[prop] = value;

						// Loop over specific property listeners
						if(_l[prop]) { for(var i = 0; i < _l[prop].length; i++) if(_l[prop][i].after) _l[prop][i].after(value, obj, prop); };
						for(var i = 0; i < _l._fireOnAllChanges.length; i++) if(_l._fireOnAllChanges[i].after) _l._fireOnAllChanges[i].after(value, obj, prop);

						return true; // success
					}
					else {
						if(_l[prop]) { for(var i = 0; i < _l[prop].length; i++) if(_l[prop][i].cancel) _l[prop][i].cancel(value, obj, prop); };
						for(var i = 0; i < _l._fireOnAllChanges.length; i++) if(_l._fireOnAllChanges[i].cancel) _l._fireOnAllChanges[i].cancel(value, obj, prop);

						return false;
					}
				}
			}
		});
	}

	return {
		observable: observable
	};
}();


text:
import test from "ava";
import * as React from "react";
import { shallow } from "enzyme";

import Rainbow from "../src/components/Rainbow";
import RainbowColor from "../src/components/RainbowColor";

test("rainbow must contain 7 colors", t => {
    const wrapper = shallow(<Rainbow />);
    t.is(wrapper.find(RainbowColor).length, 7);
});


text:
package mc.clownfish.api;

public class CommonFunctions
{

	public static <M> boolean eitherIs (M what, Object... objects)
	{
		for (Object e : objects)
		{
			if (e == what)
				return true;
		}
		return false;
	}

	public static <M> boolean neitherIs (M what, Object... objects)
	{
		for (Object e : objects)
		{
			if (e != what)
				return false;
		}
		return true;
	}

}


text:
from django.core.serializers.json import DjangoJSONEncoder
from django.utils.functional import Promise

# Python3 compatibility
try:
    from django.utils.encoding import force_unicode as force_text
except ImportError:
    from django.utils.encoding import force_text

from django.utils import timezone
import datetime
import json

class LazyEncoder(DjangoJSONEncoder):
    """
    JSON encoder class for encode correctly traduction strings.
    Is for ajax response encode.
    """

    def default(self, obj):
        if isinstance(obj, Promise):
            return force_text(obj)
        elif isinstance(obj, datetime.datetime):
            obj = timezone.localtime(obj)
        return super(LazyEncoder, self).default(obj)

def datetime_to_ecma262(value):
    """
    Convert a convencional datetime object
    to ecma-262 javascript/json format.
    """
    r = value.isoformat()
    if value.microsecond:
        r = r[:23] + r[26:]
    if r.endswith('+00:00'):
        r = r[:-6] + 'Z'
    return r

def ecma262_to_datetime(value):
    """
    Convert ecma-262 javascript format to
    correct python datetime format.

    This always return a timezone aware datetimes
    with utc as timezone.
    """

    spec = "%Y-%m-%dT%H:%M:%S.%f"
    is_utc = False

    if value.endswith("Z"):
        is_utc = True
        value = value[:-1]

    dt = strptime(value, spec)
    if is_utc:
        return timezone.make_aware(dt, timezone.utc)

    dt = timezone.make_aware(dt, timezone.get_current_timezone())
    dt = timezone.astimezone(timezone.utc)
    dt = timezone.utc.normalize(dt)
    return dt

def to_json(data):
    return json.dumps(data, cls=LazyEncoder)


text:
<!DOCTYPE html>

  <title>Site A Bar</title>

Site A Bar

  Service worker returns a response object if it's offline, so the page
  supports the offline environment.


text:
namespace Akumuli {
namespace QP {

TopN::TopN(size_t N, std::shared_ptr<Node> next)
    : next_(next)
    , N_(N)
{
}

TopN::TopN(const boost::property_tree::ptree& ptree, const ReshapeRequest &, std::shared_ptr<Node> next)
    : next_(next)
{
    N_ = ptree.get<size_t>("N");
}

void TopN::complete() {
    std::vector<const Context*> ctx;
    for (const auto& p: table_) {
        ctx.push_back(&p.second);
    }
    std::sort(ctx.begin(), ctx.end(), [](const Context* lhs, const Context* rhs) {
        return lhs->sum > rhs->sum;
    });
    for (size_t i = 0; i < N_; i++) {
        if (i >= ctx.size()) {
            break;
        }
        aku_Sample sample;
        sample.paramid = ctx[i]->id;
        sample.timestamp = ctx[i]->last_ts;
        sample.payload.size    = sizeof(aku_Sample);
        sample.payload.float64 = ctx[i]->sum;
        sample.payload.type = AKU_PAYLOAD_FLOAT;
        MutableSample mut(&sample);
        if (!next_->put(mut)) {
            break;
        }
    }
    next_->complete();
}

bool TopN::put(MutableSample& sample) {
    static const double nanosinsec = 1000000000.0;
    // Require scalar
    if ((sample.payload_.sample.payload.type & AKU_PAYLOAD_FLOAT) != AKU_PAYLOAD_FLOAT) {
        // Query doesn't work with tuples
        set_error(AKU_EHIGH_CARDINALITY);
        return false;
    }
    aku_Timestamp ts = sample.get_timestamp();
    auto key = sample.get_paramid();
    auto it = table_.find(key);
    if (it == table_.end()) {
        bool inserted;
        std::tie(it, inserted) = table_.insert(std::make_pair(key, Context{}));
        assert(inserted);
        it->second.id = key;
    } else {
        Context& ctx    = it->second;
        double* pval    = sample[0];
        if (pval) {
            auto delta  = (ts - ctx.last_ts) / nanosinsec;
            auto value  = delta * ctx.last_xs;
            ctx.sum    += value;
            ctx.last_ts = ts;
            ctx.last_xs = *pval;
        }
    }
    return true;
}

void TopN::set_error(aku_Status status) {
    next_->set_error(status);
}

int TopN::get_requirements() const {
    return TERMINAL;
}

static QueryParserToken<TopN>  cusum_token("top");

}
}


text:
@extends('layouts.admin_template')

@section('content')

        {{ $page_title or "Issuance Entries" }}
        {{ $page_description or null }}

 Home

Issuance Entries

Options

                        Number of Records:

                        Item Category:

                            <select id="item_category_cd" class="form-control" style="width: 100%;" tabindex="-1" aria-hidden="true">
                                <option selected="selected" value="RM">Raw Materials</option>
                                <option value="PM">Packaging Materials</option>
                                <option value="OS">Office Supplies</option>
                                <option value="MS">Motorpool Supplies</option>
                            </select>

                        Transaction Type:

                            <select id="trx_type" class="form-control" style="width: 100%;" tabindex="-1" aria-hidden="true">
                                <option selected="selected" value="IS">Issuance Stock</option>
                                <option value="IT">Stock Transfer</option>
                                <option value="IA">Stock Adjustment</option>
                                <option value="IQ">Stock Quarantine</option>
                            </select>

                        Status:

                            <select id="status" class="form-control" style="width: 100%;" tabindex="-1" aria-hidden="true">
                                <option  value="Approved">Approved</option>
                                <option selected="selected" value="Draft">Draft</option>
                                <option value="Disapprove">Disapproved</option>
                            </select>

@endsection


text:
/*
 ONOS GUI -- Topo View -- Topo Toolbar Service - Unit Tests
 */
describe('factory: view/topo/topoToolbar.js', function() {
    var $log, fs, ttbs, prefs, ps,
        d3Elem;

    beforeEach(module('ovTopo', 'onosUtil', 'onosLayer', 'ngRoute', 'onosNav',
        'onosWidget', 'onosMast'));

    beforeEach(inject(function (_$log_, FnService,
                                TopoToolbarService, PanelService, PrefsService) {
        $log = _$log_;
        fs = FnService;
        ttbs = TopoToolbarService;
        prefs = PrefsService;
        ps = PanelService;
        d3Elem = d3.select('body').append('div').attr('id', 'floatpanels');
        ps.init();
    }));

    xit('should define TopoToolbarService', function () {
        expect(ttbs).toBeDefined();
    });

    xit('should define api functions', function () {
        expect(fs.areFunctions(ttbs, [
            'init', 'createToolbar', 'destroyToolbar',
            'keyListener', 'toggleToolbar'
        ])).toBeTruthy();
    });

    // NOTE: topoToolbar relies too much on topo's closure variables
    // to adequately test it

});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.OData;
using Microsoft.OData.Edm;
using Microsoft.OData.Edm.Library;

namespace WebStack.QA.Test.OData.AlternateKeys
{
    public static class AlternateKeysDataSource
    {
        public static EdmEntityObjectCollection Customers { get; private set; }

        public static EdmEntityObjectCollection Orders { get; private set; }

        public static EdmEntityObjectCollection People { get; private set; }

        public static EdmEntityObjectCollection Companies { get; private set; }

        static AlternateKeysDataSource()
        {
            IEdmModel model = AlternateKeysEdmModel.GetEdmModel();

            BuildCustomers(model);

            BuildOrderss(model);

            BuildPeople(model);

            BuildCompanies(model);
        }

        private static void BuildCustomers(IEdmModel model)
        {
            IEdmEntityType customerType = model.SchemaElements.OfType<IEdmEntityType>().First(e => e.Name == "Customer");

            IEdmEntityObject[] untypedCustomers = new IEdmEntityObject[6];
            for (int i = 1; i <= 5; i++)
            {
                dynamic untypedCustomer = new EdmEntityObject(customerType);
                untypedCustomer.ID = i;
                untypedCustomer.Name = string.Format("Name {0}", i);
                untypedCustomer.SSN = "SSN-" + i + "-" + (100 + i);
                untypedCustomers[i-1] = untypedCustomer;
            }

            // create a special customer for "PATCH"
            dynamic customer = new EdmEntityObject(customerType);
            customer.ID = 6;
            customer.Name = "Name 6";
            customer.SSN = "SSN-6-T-006";
            untypedCustomers[5] = customer;

            IEdmCollectionTypeReference entityCollectionType =
                new EdmCollectionTypeReference(
                    new EdmCollectionType(
                        new EdmEntityTypeReference(customerType, isNullable: false)));

            Customers = new EdmEntityObjectCollection(entityCollectionType, untypedCustomers.ToList());
        }

        private static void BuildOrderss(IEdmModel model)
        {
            IEdmEntityType orderType = model.SchemaElements.OfType<IEdmEntityType>().First(e => e.Name == "Order");

            Guid[] tokes =
            {
                new Guid("196B3584-EF3D-41FD-90B4-76D59F9B929C"),
                new Guid("6CED5600-28BA-40EE-A2DF-E80AFADBE6C7"),
                new Guid("75036B94-C836-4946-8CC8-054CF54060EC"),
                new Guid("B3FF5460-6E77-4678-B959-DCC1C4937FA7"),
                new Guid("ED773C85-4E3C-4FC4-A3E9-9F1DA0A626DA")
            };

            IEdmEntityObject[] untypedOrders = new IEdmEntityObject[5];
            for (int i = 0; i < 5; i++)
            {
                dynamic untypedOrder = new EdmEntityObject(orderType);
                untypedOrder.OrderId = i;
                untypedOrder.Name = string.Format("Order-{0}", i);
                untypedOrder.Token = tokes[i];
                untypedOrder.Amount = 10 + i;
                untypedOrders[i] = untypedOrder;
            }

            IEdmCollectionTypeReference entityCollectionType =
                new EdmCollectionTypeReference(
                    new EdmCollectionType(
                        new EdmEntityTypeReference(orderType, isNullable: false)));

            Orders = new EdmEntityObjectCollection(entityCollectionType, untypedOrders.ToList());
        }

        private static void BuildPeople(IEdmModel model)
        {
            IEdmEntityType personType = model.SchemaElements.OfType<IEdmEntityType>().First(e => e.Name == "Person");

            IEdmEntityObject[] untypedPeople = new IEdmEntityObject[5];
            for (int i = 0; i < 5; i++)
            {
                dynamic untypedPerson = new EdmEntityObject(personType);
                untypedPerson.ID = i;
                untypedPerson.Country = new[] { "England", "China", "United States", "Russia", "Japan" }[i];
                untypedPerson.Passport = new[] { "1001", "2010", "9999", "3199992", "00001"}[i];
                untypedPeople[i] = untypedPerson;
            }

            IEdmCollectionTypeReference entityCollectionType =
                new EdmCollectionTypeReference(
                    new EdmCollectionType(
                        new EdmEntityTypeReference(personType, isNullable: false)));

            People = new EdmEntityObjectCollection(entityCollectionType, untypedPeople.ToList());
        }

        private static void BuildCompanies(IEdmModel model)
        {
            IEdmEntityType companyType = model.SchemaElements.OfType<IEdmEntityType>().First(e => e.Name == "Company");

            IList<IEdmComplexObject> addresses = BuildAddrsses(model);

            IEdmEntityObject[] untypedCompanies = new IEdmEntityObject[5];
            for (int i = 0; i < 5; i++)
            {
                dynamic untypedCompany = new EdmEntityObject(companyType);
                untypedCompany.ID = i;
                untypedCompany.Location = addresses[i];
                untypedCompanies[i] = untypedCompany;
            }

            IEdmCollectionTypeReference entityCollectionType =
                new EdmCollectionTypeReference(
                    new EdmCollectionType(
                        new EdmEntityTypeReference(companyType, isNullable: false)));

            Companies = new EdmEntityObjectCollection(entityCollectionType, untypedCompanies.ToList());
        }

        private static IList<IEdmComplexObject> BuildAddrsses(IEdmModel model)
        {
            IEdmComplexType addressType = model.SchemaElements.OfType<IEdmComplexType>().First(e => e.Name == "Address");

            return Enumerable.Range(1, 5).Select(e =>
            {
                dynamic address = new EdmComplexObject(addressType);
                address.Street = new[] {"Fuxing Rd", "Zixing Rd", "Xiaoxiang Rd", "Kehua Rd", "Taoyuan Rd"}[e - 1];
                address.City = new[] {"Beijing", "Shanghai", "Guangzhou", "Chengdu", "Wuhan"}[e - 1];
                return address as IEdmComplexObject;
            }).ToList();
        }
    }
}


text:
package com.sfl.pms.persistence.repositories.payment.customer.method;

import com.sfl.pms.services.customer.model.Customer;
import com.sfl.pms.services.payment.customer.method.model.CustomerPaymentMethod;
import com.sfl.pms.services.payment.customer.method.model.authorization.CustomerPaymentMethodAuthorizationRequest;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

/**
 * User: Ruben Dilanyan
 * Company: SFL LLC
 * Date: 1/2/15
 * Time: 4:30 PM
 */
public interface AbstractCustomerPaymentMethodRepository<T extends CustomerPaymentMethod> extends JpaRepository<T, Long> {

    /**
     * Find customer payment method by authorization request
     *
     * @param authorizationRequest
     * @return customerPaymentMethod
     */
    T findByAuthorizationRequest(final CustomerPaymentMethodAuthorizationRequest authorizationRequest);

    /**
     * Find customer payment method by uuId
     *
     * @param uuId
     * @return customerPaymentMethod
     */
    T findByUuId(final String uuId);

    /**
     * Find customer payment methods by customer
     *
     * @param customer
     * @return customerPaymentMethods
     */
    List<T> findByCustomer(final Customer customer);
}


text:
package com.example.mapjournal.model;

import com.example.mapjournal.model.MapJournalDbContract.MediaEntry;
import com.example.mapjournal.model.MapJournalDbContract.PointEntry;
import com.example.mapjournal.model.MapJournalDbContract.TripEntry;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MapJournalDbHelper extends SQLiteOpenHelper {

  private static MapJournalDbHelper instance;

  private static final int DATABASE_VERSION = 1;
  private static final String DATABASE_NAME = "MapJournal.db";

  private static final String ENABLE_FOREIGN_KEYS = "PRAGMA foreign_keys = ON;";

  private static final String CREATE_TABLE_TRIP =
      "CREATE TABLE " + TripEntry.TABLE_NAME + "(" +
      TripEntry._ID + " INTEGER PRIMARY KEY" + "," +
      TripEntry._COUNT + "INTEGER" + "," +
      TripEntry.COLUMN_NAME_NAME + " TEXT" + "," +
      TripEntry.COLUMN_NAME_DESC + " TEXT" +
      ")";

  private static final String CREATE_TABLE_POINT =
      "CREATE TABLE " + PointEntry.TABLE_NAME + "(" +
      PointEntry._ID + " INTEGER PRIMARY KEY" + "," +
      PointEntry._COUNT + "INTEGER" + "," +
      PointEntry.COLUMN_NAME_TRIP + " INTEGER" + "," +
      PointEntry.COLUMN_NAME_TITLE + " TEXT" + "," +
      PointEntry.COLUMN_NAME_LATITUDE + " REAL" + "," +
      PointEntry.COLUMN_NAME_LONGITUDE + " REAL" + "," +
      PointEntry.COLUMN_NAME_ALTITUDE + " REAL" + "," +
      PointEntry.COLUMN_NAME_TIME + " INTEGER" + "," +
      PointEntry.COLUMN_NAME_ADDRESS + " TEXT" + "," +
      PointEntry.COLUMN_NAME_JOURNAL + " TEXT" + "," +
      "FOREIGN KEY (" + PointEntry.COLUMN_NAME_TRIP + ") REFERENCES " +
        TripEntry.TABLE_NAME + "(" + TripEntry._ID + ")" +
      ")";

  private static final String CREATE_TABLE_MEDIA =
      "CREATE TABLE " + MediaEntry.TABLE_NAME + "(" +
      MediaEntry._ID + " INTEGER PRIMARY KEY" + "," +
      MediaEntry._COUNT + "INTEGER" + "," +
      MediaEntry.COLUMN_NAME_POINT_ID + " INTEGER" + "," +
      MediaEntry.COLUMN_NAME_CAPTION + " TEXT" + "," +
      MediaEntry.COLUMN_NAME_PATH + " TEXT" + "," +
      "FOREIGN KEY (" + MediaEntry.COLUMN_NAME_POINT_ID + ") REFERENCES " +
        PointEntry.TABLE_NAME + "(" + PointEntry._ID + ")" +
      ")";

  /**
   * Factory method for getting a MapJournalDbHelper. Enforces the singleton
   * property to prevent issues with concurrency in the db.
   * @param context
   * @return The instance of MapJournalDbHelper
   */
  public static MapJournalDbHelper getInstance(Context context) {
    if (instance == null) {
      instance = new MapJournalDbHelper(context.getApplicationContext());
    }
    return instance;
  }

  private MapJournalDbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL(ENABLE_FOREIGN_KEYS);
    db.execSQL(CREATE_TABLE_TRIP);
    db.execSQL(CREATE_TABLE_POINT);
    db.execSQL(CREATE_TABLE_MEDIA);
  }

  @Override
  public void onOpen(SQLiteDatabase db) {
    super.onOpen(db);
    db.execSQL(ENABLE_FOREIGN_KEYS);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
    // TODO(ericzeng): implement when there are new database versions

  }

}


text:
/* jshint expr: true, camelcase: false */
/* global unexpected_identifier */
unexpected_identifier;


text:
Question: When to stop testing your code?

Answer: [Dalal and Mallows (1988)](https://htmlpreview.github.io/?https://github.com/hoehleatsu/When2Stop/blob/master/when2stop.html)


text:
"""Analytics services module."""

class AggregationService:

    def __init__(self, user_repository, photo_repository):
        self.user_repository = user_repository
        self.photo_repository = photo_repository


text:
pager
=====

Add to your **Gemfile**

```ruby
gem 'pager', path: '~/rails/pager/'
```
and install the bundle

```console
bundle install
```

Install the migrations

```console
rake pager_engine:install:migrations
```

Run the migrations

```console
rake db:migrate
```

Add to **app/assets/javascripts/application.js**

```js
//= require codemirror
//= require codemirror/modes/xml
//= require codemirror/modes/javascript
//= require codemirror/modes/css
//= require codemirror/modes/htmlmixed
```

Add to **/app/assets/stylesheets/application.css**

```css
 *= require codemirror
*= require codemirror/themes/night
```

Add to **/config/routes.rub**

```ruby
root to: "pages#show", id: 'home'
```

At a minimum you will need to create a Page called "home" and a view called "show" for the homepage of your site.

### To use layouts

Create a Page called "layouts" and create Views within this page.

Then on your Pages, set the Layout of the page to the name of one of your layout views.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using GmailWebClient.Models;
using GmailWebClient.Services;
using GmailWebClient.Services.Abstract;
using GmailWebClient.Services.Models;
using WebMatrix.WebData;
using Attachment = AE.Net.Mail.Attachment;
using MailMessage = AE.Net.Mail.MailMessage;

namespace GmailWebClient.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private readonly IMailService _mailService = new MailService();

        private UserProfile _user;
        private UserProfile UserProfile
        {
            get
            {
                if (_user == null)
                {
                    using (var dataContext = new UsersContext())
                    {
                        _user = dataContext.UserProfiles.FirstOrDefault(x => x.UserName == User.Identity.Name);

                        if (_user == null)
                        {
                            throw new HttpException((int)HttpStatusCode.Unauthorized, "Unauthorized");
                        }
                    }
                }

                return _user;
            }
        }

        public ActionResult Index()
        {
            ViewBag.UserAddress = UserProfile.GmailAccount;

            return View();
        }

        public JsonNetResult GetMessageList(Mailbox mailBox, int skip, int take)
        {
            var messages = _mailService.GetMessages(UserProfile, mailBox, skip, take);

            return new JsonNetResult(messages);
        }
        public JsonNetResult GetMessage(Mailbox mailBox, int uid)
        {
            var message = _mailService.GetMessage(UserProfile, mailBox, uid);

            return new JsonNetResult(message);
        }

        public ActionResult GetAttachment(Mailbox mailbox, int uid, int attachmentId)
        {
            var message = _mailService.GetMessage(UserProfile, mailbox, uid, false);

            if (attachmentId < 0 || attachmentId >= message.Attachments.Count)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var attachment = message.Attachments.ElementAt(attachmentId);

            return File(attachment.GetData(), attachment.ContentType, attachment.Filename);
        }

        public HttpStatusCodeResult DeleteMessage(Mailbox mailbox, int uid)
        {
            _mailService.DeleteMessage(UserProfile, mailbox, uid.ToString());

            return new HttpStatusCodeResult(HttpStatusCode.OK);
        }

        public HttpStatusCodeResult SendMessage(MailMessageModel message)
        {
            if (!ModelState.IsValid)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var mailMessage = new MailMessage
                                  {
                                      Body = message.Body,
                                      Subject = message.Subject
                                  };

            foreach (var to in message.To.Split(';'))
            {
                var address = to.Trim();

                if (!string.IsNullOrWhiteSpace(address))
                {
                    mailMessage.To.Add(new MailAddress(address));
                }
            }

            if (!string.IsNullOrWhiteSpace(message.Cc))
            {
                foreach (var cc in message.Cc.Split(';'))
                {
                    var address = cc.Trim();

                    if (!string.IsNullOrWhiteSpace(address))
                    {
                        mailMessage.Cc.Add(new MailAddress(address));
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(message.Bcc))
            {
                foreach (var bcc in message.Bcc.Split(';'))
                {
                    var address = bcc.Trim();

                    if (!string.IsNullOrWhiteSpace(address))
                    {
                        mailMessage.Bcc.Add(new MailAddress(address));
                    }
                }
            }

            if (message.Attachments != null && message.Attachments.Any())
            {
                foreach (var attachment in message.Attachments)
                {
                    mailMessage.Attachments.Add(new Attachment(ReadFully(attachment.InputStream), attachment.ContentType,
                                                               attachment.FileName, true));
                }
            }

            var currentUserId = UserProfile.UserId;
            var addresses = mailMessage.To.Union(mailMessage.Cc).Union(mailMessage.Bcc);
            var context = new UsersContext();

            var addressesToAdd =
                addresses.Where(
                    x => !context.Contacts.Any(y => y.Address == x.Address && y.UserId == currentUserId)).ToList();

            if (addressesToAdd.Any())
            {
                foreach (var address in addressesToAdd)
                {
                    context.Contacts.Add(new Contact { Address = address.Address, UserId = currentUserId });
                }
            }

            context.SaveChanges();

            _mailService.SendMessage(UserProfile, mailMessage);

            return new HttpStatusCodeResult(HttpStatusCode.OK);
        }

        public JsonNetResult GetAddressList(string term)
        {
            var userId = UserProfile.UserId;
            var context = new UsersContext();
            var contacts = context.Contacts.Where(x => x.UserId == userId
                && x.Address.ToLower().Contains(term.ToLower())).Take(10).Select(x => x.Address);

            return new JsonNetResult(contacts);
        }

        private static byte[] ReadFully(Stream input)
        {
            var buffer = new byte[16 * 1024];
            using (var ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }
    }
}


text:
package org.jfree.data.xy;

import java.io.Serializable;
import java.util.List;

import org.jfree.data.general.DatasetChangeEvent;
import org.jfree.util.ObjectUtilities;

/**
 * A collection of {@link XIntervalSeries} objects.
 *
 * @since 1.0.3
 *
 * @see XIntervalSeries
 */
public class XIntervalSeriesCollection extends AbstractIntervalXYDataset
                                implements IntervalXYDataset, Serializable {

    /** Storage for the data series. */
    private List data;

    /**
     * Creates a new instance of XIntervalSeriesCollection.
     */
    public XIntervalSeriesCollection() {
        this.data = new java.util.ArrayList();
    }

    /**
     * Adds a series to the collection and sends a {@link DatasetChangeEvent}
     * to all registered listeners.
     *
     * @param series  the series (null not permitted).
     */
    public void addSeries(XIntervalSeries series) {
        if (series == null) {
            throw new IllegalArgumentException("Null 'series' argument.");
        }
        this.data.add(series);
        series.addChangeListener(this);
        fireDatasetChanged();
    }

    /**
     * Returns the number of series in the collection.
     *
     * @return The series count.
     */
    public int getSeriesCount() {
        return this.data.size();
    }

    /**
     * Returns a series from the collection.
     *
     * @param series  the series index (zero-based).
     *
     * @return The series.
     *
     * @throws IllegalArgumentException if series is not in the
     *     range 0 to getSeriesCount() - 1.
     */
    public XIntervalSeries getSeries(int series) {
        if ((series < 0) || (series >= getSeriesCount())) {
            throw new IllegalArgumentException("Series index out of bounds");
        }
        return (XIntervalSeries) this.data.get(series);
    }

    /**
     * Returns the key for a series.
     *
     * @param series  the series index (in the range 0 to
     *     getSeriesCount() - 1).
     *
     * @return The key for a series.
     *
     * @throws IllegalArgumentException if series is not in the
     *     specified range.
     */
    public Comparable getSeriesKey(int series) {
        // defer argument checking
        return getSeries(series).getKey();
    }

    /**
     * Returns the number of items in the specified series.
     *
     * @param series  the series (zero-based index).
     *
     * @return The item count.
     *
     * @throws IllegalArgumentException if series is not in the
     *     range 0 to getSeriesCount() - 1.
     */
    public int getItemCount(int series) {
        // defer argument checking
        return getSeries(series).getItemCount();
    }

    /**
     * Returns the x-value for an item within a series.
     *
     * @param series  the series index.
     * @param item  the item index.
     *
     * @return The x-value.
     */
    public Number getX(int series, int item) {
        XIntervalSeries s = (XIntervalSeries) this.data.get(series);
        XIntervalDataItem di = (XIntervalDataItem) s.getDataItem(item);
        return di.getX();
    }

    /**
     * Returns the y-value for an item within a series.
     *
     * @param series  the series index.
     * @param item  the item index.
     *
     * @return The y-value.
     */
    public Number getY(int series, int item) {
        XIntervalSeries s = (XIntervalSeries) this.data.get(series);
        XIntervalDataItem di = (XIntervalDataItem) s.getDataItem(item);
        return new Double(di.getYValue());
    }

    /**
     * Returns the start x-value for an item within a series.
     *
     * @param series  the series index.
     * @param item  the item index.
     *
     * @return The x-value.
     */
    public Number getStartX(int series, int item) {
        XIntervalSeries s = (XIntervalSeries) this.data.get(series);
        XIntervalDataItem di = (XIntervalDataItem) s.getDataItem(item);
        return new Double(di.getXLowValue());
    }

    /**
     * Returns the end x-value for an item within a series.
     *
     * @param series  the series index.
     * @param item  the item index.
     *
     * @return The x-value.
     */
    public Number getEndX(int series, int item) {
        XIntervalSeries s = (XIntervalSeries) this.data.get(series);
        XIntervalDataItem di = (XIntervalDataItem) s.getDataItem(item);
        return new Double(di.getXHighValue());
    }

    /**
     * Returns the start y-value for an item within a series.  This method
     * maps directly to {@link #getY(int, int)}.
     *
     * @param series  the series index.
     * @param item  the item index.
     *
     * @return The start y-value.
     */
    public Number getStartY(int series, int item) {
        return getY(series, item);
    }

    /**
     * Returns the end y-value for an item within a series.  This method
     * maps directly to {@link #getY(int, int)}.
     *
     * @param series  the series index.
     * @param item  the item index.
     *
     * @return The end y-value.
     */
    public Number getEndY(int series, int item) {
        return getY(series, item);
    }

    /**
     * Tests this instance for equality with an arbitrary object.
     *
     * @param obj  the object (null permitted).
     *
     * @return A boolean.
     */
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof XIntervalSeriesCollection)) {
            return false;
        }
        XIntervalSeriesCollection that = (XIntervalSeriesCollection) obj;
        return ObjectUtilities.equal(this.data, that.data);
    }

    /**
     * Returns a clone of this instance.
     *
     * @return A clone.
     *
     * @throws CloneNotSupportedException if there is a problem.
     */
    public Object clone() throws CloneNotSupportedException {
        XIntervalSeriesCollection clone
                = (XIntervalSeriesCollection) super.clone();
        clone.data = (List) ObjectUtilities.deepClone(this.data);
        return clone;
    }

}


text:
package com.stratio.streaming.api

import java.util.List

import com.stratio.streaming.api.messaging.MessageBuilder.builder
import com.stratio.streaming.api.messaging.{ColumnNameType, ColumnNameValue, MessageBuilderWithColumns}
import com.stratio.streaming.api.zookeeper.ZookeeperConsumer
import com.stratio.streaming.commons.constants.InternalTopic
import com.stratio.streaming.commons.constants.STREAMING.{ZK_EPHEMERAL_NODE_STATUS_PATH, ZK_EPHEMERAL_NODE_STATUS_CONNECTED, ZK_EPHEMERAL_NODE_STATUS_INITIALIZED}
import com.stratio.streaming.commons.constants.STREAM_OPERATIONS.ACTION.{INDEX, LISTEN, SAVETO_CASSANDRA, SAVETO_MONGO, SAVETO_SOLR, STOP_INDEX, STOP_LISTEN, STOP_SAVETO_CASSANDRA, STOP_SAVETO_MONGO, STOP_SAVETO_SOLR}
import com.stratio.streaming.commons.constants.STREAM_OPERATIONS.DEFINITION
import com.stratio.streaming.commons.constants.STREAM_OPERATIONS.DEFINITION.{ADD_QUERY, ALTER, DROP, REMOVE_QUERY}
import com.stratio.streaming.commons.constants.STREAM_OPERATIONS.MANIPULATION.LIST
import com.stratio.streaming.commons.exceptions.{StratioEngineConnectionException, StratioEngineOperationException, StratioEngineStatusException}
import com.stratio.streaming.commons.kafka.service.{KafkaTopicService, TopicService}
import com.stratio.streaming.commons.messages.ColumnNameTypeValue
import com.stratio.streaming.commons.streams.StratioStream
import com.stratio.streaming.dto.StratioQueryStream
import com.stratio.streaming.kafka.{KafkaConsumer, KafkaProducer}
import com.stratio.streaming.messaging.{InsertMessageBuilder, QueryMessageBuilder, StreamMessageBuilder}
import org.apache.curator.framework.api.CuratorEventType.WATCHED
import org.apache.curator.framework.api.{CuratorEvent, CuratorListener}
import org.apache.curator.framework.{CuratorFramework, CuratorFrameworkFactory}
import org.apache.curator.retry.RetryOneTime
import org.slf4j.LoggerFactory

import scala.collection.JavaConversions.{asScalaBuffer, bufferAsJavaList}

class StratioStreamingAPI
  extends IStratioStreamingAPI {

  import com.stratio.streaming.api.StratioStreamingAPI._

  def createStream(streamName: String, columns: List[ColumnNameType]) = {
    checkStreamingStatus()
    val operation = DEFINITION.CREATE.toLowerCase
    val creationStreamMessage = MessageBuilderWithColumns(sessionId, operation).build(streamName, columns)
    syncOperation.performSyncOperation(creationStreamMessage)
  }

  def alterStream(streamName: String, columns: List[ColumnNameType]) = {
    checkStreamingStatus()
    val operation = ALTER.toLowerCase
    val alterStreamMessage = MessageBuilderWithColumns(sessionId, operation).build(streamName, columns)
    syncOperation.performSyncOperation(alterStreamMessage)
  }

  def insertData(streamName: String, data: List[ColumnNameValue]) = {
    checkStreamingStatus()
    val insertStreamMessage = InsertMessageBuilder(sessionId).build(streamName, data)
    asyncOperation.performAsyncOperation(insertStreamMessage)
  }

  def addQuery(streamName: String, query: String): String = {
    checkStreamingStatus()
    val operation = ADD_QUERY.toLowerCase
    val addQueryStreamMessage = QueryMessageBuilder(sessionId).build(streamName, query, operation)
    syncOperation.performSyncOperation(addQueryStreamMessage)
    getQueryId(streamName, query)
  }

  def getQueryId(streamName: String, query: String): String = {
    val queries = queriesFromStream(streamName)
    val addedQuery = queries.find(theQuery => theQuery.query.equals(query))
    addedQuery match {
      case Some(q) => q.queryId
      case _ => ""
    }
  }

  def removeQuery(streamName: String, queryId: String) = {
    checkStreamingStatus()
    val operation = REMOVE_QUERY.toLowerCase
    val removeQueryMessage = QueryMessageBuilder(sessionId).build(streamName, queryId, operation)
    syncOperation.performSyncOperation(removeQueryMessage)
  }

  def dropStream(streamName: String) = {
    checkStreamingStatus()
    val operation = DROP.toLowerCase
    val dropStreamMessage = StreamMessageBuilder(sessionId).build(streamName, operation)
    syncOperation.performSyncOperation(dropStreamMessage)
  }

  def listenStream(streamName: String) = {
    checkStreamingStatus()
    val operation = LISTEN.toLowerCase
    val listenStreamMessage = StreamMessageBuilder(sessionId).build(streamName, operation)
    syncOperation.performSyncOperation(listenStreamMessage)
    val kafkaConsumer = new KafkaConsumer(streamName, zookeeperCluster, readFromStartOfStream = false)
    streamingListeners.put(streamName, kafkaConsumer)
    kafkaConsumer.stream
  }

  def stopListenStream(streamName: String) = {
    checkStreamingStatus()
    val operation = STOP_LISTEN.toLowerCase
    val stopListenStreamMessage = StreamMessageBuilder(sessionId).build(streamName, operation)
    shutdownKafkaConsumerAndRemoveStreamingListener(streamName)
    syncOperation.performSyncOperation(stopListenStreamMessage)
  }

  private def shutdownKafkaConsumerAndRemoveStreamingListener(streamName: String) {
    val kafkaConsumer = streamingListeners.get(streamName)
    kafkaConsumer match {
      case Some(consumer) => consumer.close()
      case _ => //
    }
    streamingListeners.remove(streamName)
  }

  def queriesFromStream(stream: String): List[StratioQueryStream] = {
    val stratioStreams = listStreams().toList
    val stratioStream = stratioStreams.find(element => element.getStreamName.equals(stream))
    stratioStream match {
      case None => throw new StratioEngineOperationException("StratioEngine error: STREAM DOES NOT EXIST")
      case Some(element) => element.getQueries.map(query => new StratioQueryStream(query.getQuery, query.getQueryId))
    }
  }

  def columnsFromStream(stream: String): List[ColumnNameTypeValue] = {
    val stratioStreams = listStreams().toList
    val stratioStream = stratioStreams.find(element => element.getStreamName.equals(stream))
    stratioStream match {
      case None => throw new StratioEngineOperationException("StratioEngine error: STREAM DOES NOT EXIST")
      case Some(element) => element.getColumns
    }
  }

  def listStreams(): List[StratioStream] = {
    checkStreamingStatus()
    val operation = LIST.toLowerCase
    val listStreamMessage = builder.withOperation(operation)
      .withSessionId(sessionId)
      .build()
    statusOperation.getListStreams(listStreamMessage)
  }

  def saveToCassandra(streamName: String) = {
    checkStreamingStatus()
    val operation = SAVETO_CASSANDRA.toLowerCase
    val saveToCassandraMessage = StreamMessageBuilder(sessionId).build(streamName, operation)
    syncOperation.performSyncOperation(saveToCassandraMessage)
  }

  def stopSaveToCassandra(streamName: String) = {
    checkStreamingStatus()
    val operation = STOP_SAVETO_CASSANDRA.toLowerCase
    val stopSaveToCassandraMessage = StreamMessageBuilder(sessionId).build(streamName, operation)
    syncOperation.performSyncOperation(stopSaveToCassandraMessage)
  }

  def saveToMongo(streamName: String) = {
    checkStreamingStatus()
    val operation = SAVETO_MONGO.toLowerCase
    val saveToCassandraMessage = StreamMessageBuilder(sessionId).build(streamName, operation)
    syncOperation.performSyncOperation(saveToCassandraMessage)
  }

  def stopSaveToMongo(streamName: String) = {
    checkStreamingStatus()
    val operation = STOP_SAVETO_MONGO.toLowerCase
    val stopSaveToCassandraMessage = StreamMessageBuilder(sessionId).build(streamName, operation)
    syncOperation.performSyncOperation(stopSaveToCassandraMessage)
  }

  def saveToSolr(streamName: String) = {
    checkStreamingStatus()
    val operation = SAVETO_SOLR.toLowerCase
    val saveToSolrMEssage = StreamMessageBuilder(sessionId).build(streamName, operation)
    syncOperation.performSyncOperation(saveToSolrMEssage)
  }

  def stopSaveToSolr(streamName: String) = {
    checkStreamingStatus()
    val operation = STOP_SAVETO_SOLR.toLowerCase
    val stopSaveToSolrMessage = StreamMessageBuilder(sessionId).build(streamName, operation)
    syncOperation.performSyncOperation(stopSaveToSolrMessage)
  }

  def indexStream(streamName: String) = {
    checkStreamingStatus()
    val operation = INDEX.toLowerCase
    val indexStreamMessage = StreamMessageBuilder(sessionId).build(streamName, operation)
    syncOperation.performSyncOperation(indexStreamMessage)
  }

  def stopIndexStream(streamName: String) = {
    checkStreamingStatus()
    val operation = STOP_INDEX.toLowerCase
    val indexStreamMessage = StreamMessageBuilder(sessionId).build(streamName, operation)
    syncOperation.performSyncOperation(indexStreamMessage)
  }

  def initialize() = {
    try {
      val brokerServer = config.getString("kafka.server")
      val brokerPort = config.getInt("kafka.port")
      kafkaCluster = s"$brokerServer:$brokerPort"

      val theZookeeperServer = config.getString("zookeeper.server")
      val zookeeperPort = config.getInt("zookeeper.port")
      zookeeperServer = s"$theZookeeperServer:$zookeeperPort"

      log.info("Establishing connection with the engine...")
      checkEphemeralNode()
      startEphemeralNodeWatch()
      log.info("Initializing kafka topic...")
      initializeTopic()
      this
    } catch {
      case ex => throw new StratioEngineConnectionException("Unable to connect to stratio streaming. " + ex.getMessage)
    }
  }

  def initializeWithServerConfig(kafkaServer: String,
                                 kafkaPort: Int,
                                 theZookeeperServer: String,
                                 theZookeeperPort: Int) = {
    try {
      kafkaCluster = s"$kafkaServer:$kafkaPort"
      zookeeperServer = s"$theZookeeperServer:$theZookeeperPort"

      log.info("Establishing connection with the engine...")
      checkEphemeralNode()
      startEphemeralNodeWatch()
      log.info("Initializing kafka topic...")
      initializeTopic()
      this
    } catch {
      case ex => throw new StratioEngineConnectionException("Unable to connect to stratio streaming. " + ex.getMessage)
    }
  }

  override def withServerConfig(kafkaQuorum: String, zookeeperQuorum: String): IStratioStreamingAPI = {
    kafkaCluster = kafkaQuorum
    zookeeperServer = zookeeperQuorum
    this
  }

  override def withServerConfig(kafkaHost: String,
                                kafkaPort: Int,
                                zookeeperHost: String,
                                zookeeperPort: Int): IStratioStreamingAPI = {

    kafkaCluster = s"$kafkaHost:$kafkaPort"
    zookeeperServer = s"$zookeeperHost:$zookeeperPort"
    this
  }

  override def init(): IStratioStreamingAPI = {
    try {
      log.info("Establishing connection with the engine...")
      checkEphemeralNode()
      startEphemeralNodeWatch()
      log.info("Initializing kafka topic...")
      initializeTopic()
      this
    } catch {
      case ex => throw new StratioEngineConnectionException("Unable to connect to stratio streaming. " + ex.getMessage)
    }
  }

  override def isInit(): Boolean = streamingUp && streamingRunning

  override def isConnected(): Boolean = {
    return streamingUp && streamingRunning
  }

  def defineAcknowledgeTimeOut(timeOutInMs: Int) = {
    ackTimeOut = timeOutInMs
    this
  }

  override def close: Unit = {
    kafkaProducer.close()
    kafkaDataProducer.close()
    topicService.close()
    zookeeperClient.close()
  }

  val streamingTopicName = InternalTopic.TOPIC_REQUEST.getTopicName();
  val streamingDataTopicName = InternalTopic.TOPIC_DATA.getTopicName();
  val sessionId = "" + System.currentTimeMillis()

  //TODO refactor ASAP
  lazy val consumerBrokerServer = kafkaCluster.split(",")(0).split(":")(0)
  lazy val consumerBrokerPort = kafkaCluster.split(",")(0).split(":")(1).toInt

  var kafkaCluster = ""
  lazy val kafkaBroker = s"$kafkaCluster"
  var zookeeperServer = ""
  lazy val zookeeperCluster = s"$zookeeperServer"
  var streamingUp = false
  var streamingRunning = false
  val streamingListeners = scala.collection.mutable.Map[String, KafkaConsumer]()
  lazy val kafkaProducer = new KafkaProducer(InternalTopic.TOPIC_REQUEST.getTopicName(), kafkaBroker)
  lazy val kafkaDataProducer = new KafkaProducer(InternalTopic.TOPIC_DATA.getTopicName(), kafkaBroker)
  val retryPolicy = new RetryOneTime(500)
  lazy val zookeeperClient = CuratorFrameworkFactory.newClient(zookeeperCluster, retryPolicy)
  var topicService: TopicService = _
  var ackTimeOut = 8000
  lazy val zookeeperConsumer = {
    zookeeperClient.start()
    ZookeeperConsumer(zookeeperClient)
  }
  lazy val syncOperation = new StreamingAPISyncOperation(kafkaProducer, zookeeperConsumer, ackTimeOut)
  lazy val asyncOperation = new StreamingAPIAsyncOperation(kafkaDataProducer)
  lazy val statusOperation = new StreamingAPIListOperation(kafkaProducer, zookeeperConsumer, ackTimeOut)

  private def checkEphemeralNode() {
    val ephemeralNodePath = ZK_EPHEMERAL_NODE_STATUS_PATH
    if (!zookeeperConsumer.zNodeExists(ephemeralNodePath)) {
      log.warn("Ephemeral node does not exist")
      throw new StratioEngineStatusException("Can't connect. Check if Stratio streaming is down or connection to " +
        "Zookeeper")
    } else {
      val streamingStatus = zookeeperConsumer.getZNodeData(ZK_EPHEMERAL_NODE_STATUS_PATH).get
      streamingStatus match {
        case ZK_EPHEMERAL_NODE_STATUS_CONNECTED =>
          streamingUp = true
          streamingRunning = false
        case ZK_EPHEMERAL_NODE_STATUS_INITIALIZED =>
          streamingUp = true
          streamingRunning = true
      }
    }
  }

  private def startEphemeralNodeWatch() {
    zookeeperClient.checkExists().watched().forPath(ZK_EPHEMERAL_NODE_STATUS_PATH)
    addListener()
  }

  private def initializeTopic() {
    topicService = new KafkaTopicService(zookeeperCluster, consumerBrokerServer, consumerBrokerPort, 10000, 10000)
    topicService.createTopicIfNotExist(streamingTopicName, 1, 1)
    topicService.createTopicIfNotExist(streamingDataTopicName, 1, 1);
  }

  private def checkStreamingStatus() {
    if (!streamingUp) throw new StratioEngineStatusException("Stratio streaming is down")
    if (!streamingRunning) throw new StratioEngineStatusException("Stratio streaming not yet initialized")
  }

  private def addListener() = {
    zookeeperClient.getCuratorListenable().addListener(new CuratorListener() {
      def eventReceived(client: CuratorFramework, event: CuratorEvent) = {
        event.getType() match {
          case WATCHED => {
            zookeeperClient.checkExists().watched().forPath(ZK_EPHEMERAL_NODE_STATUS_PATH)
            zookeeperConsumer.getZNodeData(ZK_EPHEMERAL_NODE_STATUS_PATH) match {
              case Some(ZK_EPHEMERAL_NODE_STATUS_CONNECTED) => streamingUp = true
              case Some(ZK_EPHEMERAL_NODE_STATUS_INITIALIZED) => streamingUp = false
              case _ => {
                streamingUp = false
                streamingRunning = false
              }
            }
          }
          case x => {
            log.debug("Unused curatorEvent {}", x)
          }
        }
      }
    })
  }
}

object StratioStreamingAPI
  extends StratioStreamingAPIConfig {
  lazy val log = LoggerFactory.getLogger(getClass)
}


text:
IMPLEMENT_CO_DATABLOCK_V1(afxAreaDamageData);

ConsoleDocClass( afxAreaDamageData,
   "@brief A datablock that specifies an Area Damage effect.\n\n"

   "An Area Damage effect is useful for assigning area damage with unusual timing that must be synchronized with other "
   "effects. Negative damage amounts can be used for healing effects."
   "\n\n"

   "The primary difference between afxAreaDamageData and afxDamageData, which is also capable of inflicting area damage, "
   "is that afxAreaDamageData effects calculate the area damage in C++ code rather than calling out to the script function "
   "radiusDamage(). In cases where area damage needs to be inflicted repeatedly or in areas crowded with many targets, "
   "afxAreaDamageData is likely to get better performance."
   "\n\n"

   "@ingroup afxEffects\n"
   "@ingroup AFX\n"
   "@ingroup Datablocks\n"
);

afxAreaDamageData::afxAreaDamageData()
{
  flavor = ST_NULLSTRING;
  amount = 0;
  radius = 0;
  impulse = 0;
  notify_damage_src = false;
  exclude_cons_obj = false;
}

afxAreaDamageData::afxAreaDamageData(const afxAreaDamageData& other, bool temp_clone) : GameBaseData(other, temp_clone)
{
  flavor = other.flavor;
  amount = other.amount;
  radius = other.radius;
  impulse = other.impulse;
  notify_damage_src = other.notify_damage_src;
  exclude_cons_obj = other.exclude_cons_obj;
}

#define myOffset(field) Offset(field, afxAreaDamageData)

void afxAreaDamageData::initPersistFields()
{
  addField("flavor",                    TypeString,     myOffset(flavor),
    "An arbitrary string which is passed as an argument to a spell's onDamage() script "
    "method. It is used to classify a type of damage such as 'melee', 'magical', or "
    "'fire'.");
  addField("damage",                    TypeF32,        myOffset(amount),
    "An amount of area damage to inflict on a target. Objects within half the radius "
    "receive full damage which then diminishes out to the full distance of the specified "
    "radius.");
  addField("radius",                    TypeF32,        myOffset(radius),
    "Radius centered at the effect position in which damage will be applied.");
  addField("impulse",                   TypeF32,        myOffset(impulse),
    "Specifies an amount of force to apply to damaged objects. Objects within half the "
    "radius receive full impulse which then diminishes out to the full distance of the "
    "specified radius.");
  addField("notifyDamageSource",        TypeBool,       myOffset(notify_damage_src),
    "When true, the onInflictedAreaDamage() method of the damaged object will be called "
    "to notify it of the damage. This is useful for starting some effects or action that "
    "responds to the damage.");
  addField("excludeConstraintObject",   TypeBool,       myOffset(exclude_cons_obj),
    "When true, the object specified as the effect's primary position constraint will not "
    "receive any damage.");

  Parent::initPersistFields();
}

bool afxAreaDamageData::onAdd()
{
  if (Parent::onAdd() == false)
    return false;

  return true;
}

void afxAreaDamageData::packData(BitStream* stream)
{
	Parent::packData(stream);
}

void afxAreaDamageData::unpackData(BitStream* stream)
{
  Parent::unpackData(stream);
}

//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//