text:
extern "C" {
#define VPX_CODEC_DISABLE_COMPAT 1
#include "third_party/libvpx/source/libvpx/vpx/vp8cx.h"
#include "third_party/libvpx/source/libvpx/vpx/vpx_encoder.h"
}

namespace remoting {

namespace {

// Number of bytes in an RGBx pixel.
const int kBytesPerRgbPixel = 4;

// Defines the dimension of a macro block. This is used to compute the active
// map for the encoder.
const int kMacroBlockSize = 16;

// Magic encoder profile numbers for I420 and I444 input formats.
const int kVp9I420ProfileNumber = 0;
const int kVp9I444ProfileNumber = 1;

// Magic encoder constants for adaptive quantization strategy.
const int kVp9AqModeNone = 0;
const int kVp9AqModeCyclicRefresh = 3;

const int kDefaultTargetBitrateKbps = 1000;

void SetCommonCodecParameters(vpx_codec_enc_cfg_t* config,
                              const webrtc::DesktopSize& size) {
  // Use millisecond granularity time base.
  config->g_timebase.num = 1;
  config->g_timebase.den = base::Time::kMicrosecondsPerSecond;

  config->g_w = size.width();
  config->g_h = size.height();
  config->g_pass = VPX_RC_ONE_PASS;

  // Start emitting packets immediately.
  config->g_lag_in_frames = 0;

  // Since the transport layer is reliable, keyframes should not be necessary.
  // However, due to crbug.com/440223, decoding fails after 30,000 non-key
  // frames, so take the hit of an "unnecessary" key-frame every 10,000 frames.
  config->kf_min_dist = 10000;
  config->kf_max_dist = 10000;

  // Allow multiple cores on a system to be used for encoding for
  // performance while at the same time ensuring we do not saturate.
  config->g_threads = (base::SysInfo::NumberOfProcessors() + 1) / 2;

  // Do not drop any frames at encoder.
  config->rc_dropframe_thresh = 0;
  // We do not want variations in bandwidth.
  config->rc_end_usage = VPX_CBR;
  config->rc_undershoot_pct = 100;
  config->rc_overshoot_pct = 15;
}

void SetVp8CodecParameters(vpx_codec_enc_cfg_t* config,
                           const webrtc::DesktopSize& size) {
  SetCommonCodecParameters(config, size);

  // Value of 2 means using the real time profile. This is basically a
  // redundant option since we explicitly select real time mode when doing
  // encoding.
  config->g_profile = 2;

  // To enable remoting to be highly interactive and allow the target bitrate
  // to be met, we relax the max quantizer. The quality will get topped-off
  // in subsequent frames.
  config->rc_min_quantizer = 20;
  config->rc_max_quantizer = 63;
}

void SetVp9CodecParameters(vpx_codec_enc_cfg_t* config,
                           const webrtc::DesktopSize& size,
                           bool lossless_color,
                           bool lossless_encode) {
  SetCommonCodecParameters(config, size);

  // Configure VP9 for I420 or I444 source frames.
  config->g_profile =
      lossless_color ? kVp9I444ProfileNumber : kVp9I420ProfileNumber;

  if (lossless_encode) {
    // Disable quantization entirely, putting the encoder in "lossless" mode.
    config->rc_min_quantizer = 0;
    config->rc_max_quantizer = 0;
    config->rc_end_usage = VPX_VBR;
  } else {
    // TODO(wez): Set quantization range to 4-40, once the libvpx encoder is
    // updated not to output any bits if nothing needs topping-off.
    config->rc_min_quantizer = 20;
    config->rc_max_quantizer = 30;
    config->rc_end_usage = VPX_CBR;
    // In the absence of a good bandwidth estimator set the target bitrate to a
    // conservative default.
    config->rc_target_bitrate = 500;
  }
}

void SetVp8CodecOptions(vpx_codec_ctx_t* codec) {
  // CPUUSED of 16 will have the smallest CPU load. This turns off sub-pixel
  // motion search.
  vpx_codec_err_t ret = vpx_codec_control(codec, VP8E_SET_CPUUSED, 16);
  DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set CPUUSED";

  // Use the lowest level of noise sensitivity so as to spend less time
  // on motion estimation and inter-prediction mode.
  ret = vpx_codec_control(codec, VP8E_SET_NOISE_SENSITIVITY, 0);
  DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set noise sensitivity";
}

void SetVp9CodecOptions(vpx_codec_ctx_t* codec, bool lossless_encode) {
  // Request the lowest-CPU usage that VP9 supports, which depends on whether
  // we are encoding lossy or lossless.
  // Note that this is configured via the same parameter as for VP8.
  int cpu_used = lossless_encode ? 5 : 6;
  vpx_codec_err_t ret = vpx_codec_control(codec, VP8E_SET_CPUUSED, cpu_used);
  DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set CPUUSED";

  // Use the lowest level of noise sensitivity so as to spend less time
  // on motion estimation and inter-prediction mode.
  ret = vpx_codec_control(codec, VP9E_SET_NOISE_SENSITIVITY, 0);
  DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set noise sensitivity";

  // Configure the codec to tune it for screen media.
  ret = vpx_codec_control(codec, VP9E_SET_TUNE_CONTENT, VP9E_CONTENT_SCREEN);
  DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set screen content mode";

  // Set cyclic refresh (aka "top-off") only for lossy encoding.
  int aq_mode = lossless_encode ? kVp9AqModeNone : kVp9AqModeCyclicRefresh;
  ret = vpx_codec_control(codec, VP9E_SET_AQ_MODE, aq_mode);
  DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to set aq mode";
}

void FreeImageIfMismatched(bool use_i444,
                           const webrtc::DesktopSize& size,
                           std::unique_ptr<vpx_image_t>* out_image,
                           std::unique_ptr<uint8_t[]>* out_image_buffer) {
  if (*out_image) {
    const vpx_img_fmt_t desired_fmt =
        use_i444 ? VPX_IMG_FMT_I444 : VPX_IMG_FMT_I420;
    if (!size.equals(webrtc::DesktopSize((*out_image)->w, (*out_image)->h)) ||
        (*out_image)->fmt != desired_fmt) {
      out_image_buffer->reset();
      out_image->reset();
    }
  }
}

void CreateImage(bool use_i444,
                 const webrtc::DesktopSize& size,
                 std::unique_ptr<vpx_image_t>* out_image,
                 std::unique_ptr<uint8_t[]>* out_image_buffer) {
  DCHECK(!size.is_empty());
  DCHECK(!*out_image_buffer);
  DCHECK(!*out_image);

  std::unique_ptr<vpx_image_t> image(new vpx_image_t());
  memset(image.get(), 0, sizeof(vpx_image_t));

  // libvpx seems to require both to be assigned.
  image->d_w = size.width();
  image->w = size.width();
  image->d_h = size.height();
  image->h = size.height();

  // libvpx should derive chroma shifts from|fmt| but currently has a bug:
  // https://code.google.com/p/webm/issues/detail?id=627
  if (use_i444) {
    image->fmt = VPX_IMG_FMT_I444;
    image->x_chroma_shift = 0;
    image->y_chroma_shift = 0;
  } else {  // I420
    image->fmt = VPX_IMG_FMT_YV12;
    image->x_chroma_shift = 1;
    image->y_chroma_shift = 1;
  }

  // libyuv's fast-path requires 16-byte aligned pointers and strides, so pad
  // the Y, U and V planes' strides to multiples of 16 bytes.
  const int y_stride = ((image->w - 1) & ~15) + 16;
  const int uv_unaligned_stride = y_stride >> image->x_chroma_shift;
  const int uv_stride = ((uv_unaligned_stride - 1) & ~15) + 16;

  // libvpx accesses the source image in macro blocks, and will over-read
  // if the image is not padded out to the next macroblock: crbug.com/119633.
  // Pad the Y, U and V planes' height out to compensate.
  // Assuming macroblocks are 16x16, aligning the planes' strides above also
  // macroblock aligned them.
  static_assert(kMacroBlockSize == 16, "macroblock_size_not_16");
  const int y_rows =
      ((image->h - 1) & ~(kMacroBlockSize - 1)) + kMacroBlockSize;
  const int uv_rows = y_rows >> image->y_chroma_shift;

  // Allocate a YUV buffer large enough for the aligned data & padding.
  const int buffer_size = y_stride * y_rows + 2 * uv_stride * uv_rows;
  std::unique_ptr<uint8_t[]> image_buffer(new uint8_t[buffer_size]);

  // Reset image value to 128 so we just need to fill in the y plane.
  memset(image_buffer.get(), 128, buffer_size);

  // Fill in the information for |image_|.
  unsigned char* uchar_buffer =
      reinterpret_cast<unsigned char*>(image_buffer.get());
  image->planes[0] = uchar_buffer;
  image->planes[1] = image->planes[0] + y_stride * y_rows;
  image->planes[2] = image->planes[1] + uv_stride * uv_rows;
  image->stride[0] = y_stride;
  image->stride[1] = uv_stride;
  image->stride[2] = uv_stride;

  *out_image = std::move(image);
  *out_image_buffer = std::move(image_buffer);
}

}  // namespace

// static
std::unique_ptr<WebrtcVideoEncoderVpx> WebrtcVideoEncoderVpx::CreateForVP8() {
  return base::WrapUnique(new WebrtcVideoEncoderVpx(false));
}

// static
std::unique_ptr<WebrtcVideoEncoderVpx> WebrtcVideoEncoderVpx::CreateForVP9() {
  return base::WrapUnique(new WebrtcVideoEncoderVpx(true));
}

WebrtcVideoEncoderVpx::~WebrtcVideoEncoderVpx() {}

void WebrtcVideoEncoderVpx::SetTickClockForTests(base::TickClock* tick_clock) {
  clock_ = tick_clock;
}

void WebrtcVideoEncoderVpx::SetLosslessEncode(bool want_lossless) {
  if (use_vp9_ && (want_lossless != lossless_encode_)) {
    lossless_encode_ = want_lossless;
    if (codec_)
      Configure(webrtc::DesktopSize(codec_->config.enc->g_w,
                                    codec_->config.enc->g_h));
  }
}

void WebrtcVideoEncoderVpx::SetLosslessColor(bool want_lossless) {
  if (use_vp9_ && (want_lossless != lossless_color_)) {
    lossless_color_ = want_lossless;
    // TODO(wez): Switch to ConfigureCodec() path once libvpx supports it.
    // See https://code.google.com/p/webm/issues/detail?id=913.
    // if (codec_)
    //  Configure(webrtc::DesktopSize(codec_->config.enc->g_w,
    //                                codec_->config.enc->g_h));
    codec_.reset();
  }
}

std::unique_ptr<WebrtcVideoEncoder::EncodedFrame> WebrtcVideoEncoderVpx::Encode(
    const webrtc::DesktopFrame* frame,
    const FrameParams& params) {
  webrtc::DesktopSize previous_frame_size =
      image_ ? webrtc::DesktopSize(image_->w, image_->h)
             : webrtc::DesktopSize();

  webrtc::DesktopSize frame_size = frame ? frame->size() : previous_frame_size;

  // Don't need to send anything until we get the first non-null frame.
  if (frame_size.is_empty()) {
    return nullptr;
  }

  DCHECK_GE(frame_size.width(), 32);
  DCHECK_GE(frame_size.height(), 32);

  // Create or reconfigure the codec to match the size of |frame|.
  if (!codec_ || !frame_size.equals(previous_frame_size)) {
    Configure(frame_size);
  }

  UpdateConfig(params);

  vpx_active_map_t act_map;
  act_map.rows = active_map_size_.height();
  act_map.cols = active_map_size_.width();
  act_map.active_map = active_map_.get();

  webrtc::DesktopRegion updated_region;
  // Convert the updated capture data ready for encode.
  PrepareImage(frame, &updated_region);

  // Update active map based on updated region.
  if (params.clear_active_map)
    ClearActiveMap();

  if (params.key_frame)
    updated_region.SetRect(webrtc::DesktopRect::MakeSize(frame_size));

  SetActiveMapFromRegion(updated_region);

  // Apply active map to the encoder.
  if (vpx_codec_control(codec_.get(), VP8E_SET_ACTIVEMAP, &act_map)) {
    LOG(ERROR) << "Unable to apply active map";
  }

  vpx_codec_err_t ret = vpx_codec_encode(
      codec_.get(), image_.get(), 0, params.duration.InMicroseconds(),
      (params.key_frame) ? VPX_EFLAG_FORCE_KF : 0, VPX_DL_REALTIME);
  DCHECK_EQ(ret, VPX_CODEC_OK)
      << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n"
      << "Details: " << vpx_codec_error(codec_.get()) << "\n"
      << vpx_codec_error_detail(codec_.get());

  if (!lossless_encode_) {
    // VP8 doesn't return active map, so we assume it's the same on the output
    // as on the input.
    if (use_vp9_) {
      ret = vpx_codec_control(codec_.get(), VP9E_GET_ACTIVEMAP, &act_map);
      DCHECK_EQ(ret, VPX_CODEC_OK)
          << "Failed to fetch active map: " << vpx_codec_err_to_string(ret)
          << "\n";
    }

    UpdateRegionFromActiveMap(&updated_region);
  }

  // Read the encoded data.
  vpx_codec_iter_t iter = nullptr;
  bool got_data = false;

  std::unique_ptr<EncodedFrame> encoded_frame(new EncodedFrame());
  encoded_frame->size = frame_size;

  while (!got_data) {
    const vpx_codec_cx_pkt_t* vpx_packet =
        vpx_codec_get_cx_data(codec_.get(), &iter);
    if (!vpx_packet)
      continue;

    switch (vpx_packet->kind) {
      case VPX_CODEC_CX_FRAME_PKT: {
        got_data = true;
        // TODO(sergeyu): Avoid copying the data here..
        encoded_frame->data.assign(
            reinterpret_cast<const char*>(vpx_packet->data.frame.buf),
            vpx_packet->data.frame.sz);
        encoded_frame->key_frame =
            vpx_packet->data.frame.flags & VPX_FRAME_IS_KEY;
        CHECK_EQ(vpx_codec_control(codec_.get(), VP8E_GET_LAST_QUANTIZER_64,
                                   &(encoded_frame->quantizer)),
                 VPX_CODEC_OK);
        break;
      }
      default:
        break;
    }
  }

  return encoded_frame;
}

WebrtcVideoEncoderVpx::WebrtcVideoEncoderVpx(bool use_vp9)
    : use_vp9_(use_vp9),
      clock_(&default_tick_clock_) {
  // Indicates config is still uninitialized.
  config_.g_timebase.den = 0;
}

void WebrtcVideoEncoderVpx::Configure(const webrtc::DesktopSize& size) {
  DCHECK(use_vp9_ || !lossless_color_);
  DCHECK(use_vp9_ || !lossless_encode_);

  // Tear down |image_| if it no longer matches the size and color settings.
  // PrepareImage() will then create a new buffer of the required dimensions if
  // |image_| is not allocated.
  FreeImageIfMismatched(lossless_color_, size, &image_, &image_buffer_);

  // Initialize active map.
  active_map_size_ = webrtc::DesktopSize(
      (size.width() + kMacroBlockSize - 1) / kMacroBlockSize,
      (size.height() + kMacroBlockSize - 1) / kMacroBlockSize);
  active_map_.reset(
      new uint8_t[active_map_size_.width() * active_map_size_.height()]);
  ClearActiveMap();

  // TODO(wez): Remove this hack once VPX can handle frame size reconfiguration.
  // See https://code.google.com/p/webm/issues/detail?id=912.
  if (codec_) {
    // If the frame size has changed then force re-creation of the codec.
    if (codec_->config.enc->g_w != static_cast<unsigned int>(size.width()) ||
        codec_->config.enc->g_h != static_cast<unsigned int>(size.height())) {
      codec_.reset();
    }
  }

  // Fetch a default configuration for the desired codec.
  const vpx_codec_iface_t* interface =
      use_vp9_ ? vpx_codec_vp9_cx() : vpx_codec_vp8_cx();
  vpx_codec_err_t ret = vpx_codec_enc_config_default(interface, &config_, 0);
  DCHECK_EQ(VPX_CODEC_OK, ret) << "Failed to fetch default configuration";

  // Customize the default configuration to our needs.
  if (use_vp9_) {
    SetVp9CodecParameters(&config_, size, lossless_color_, lossless_encode_);
  } else {
    SetVp8CodecParameters(&config_, size);
  }

  config_.rc_target_bitrate = kDefaultTargetBitrateKbps;

  // Initialize or re-configure the codec with the custom configuration.
  if (!codec_) {
    codec_.reset(new vpx_codec_ctx_t);
    ret = vpx_codec_enc_init(codec_.get(), interface, &config_, 0);
    CHECK_EQ(VPX_CODEC_OK, ret) << "Failed to initialize codec";
  } else {
    ret = vpx_codec_enc_config_set(codec_.get(), &config_);
    CHECK_EQ(VPX_CODEC_OK, ret) << "Failed to reconfigure codec";
  }

  // Apply further customizations to the codec now it's initialized.
  if (use_vp9_) {
    SetVp9CodecOptions(codec_.get(), lossless_encode_);
  } else {
    SetVp8CodecOptions(codec_.get());
  }
}

void WebrtcVideoEncoderVpx::UpdateConfig(const FrameParams& params) {
  // Configuration not initialized.
  if (config_.g_timebase.den == 0)
    return;

  bool changed = false;

  if (params.bitrate_kbps >= 0 &&
      config_.rc_target_bitrate !=
          static_cast<unsigned int>(params.bitrate_kbps)) {
    config_.rc_target_bitrate = params.bitrate_kbps;
    changed = true;
  }

  if (params.vpx_min_quantizer >= 0 &&
      config_.rc_min_quantizer !=
          static_cast<unsigned int>(params.vpx_min_quantizer)) {
    config_.rc_min_quantizer = params.vpx_min_quantizer;
    changed = true;
  }

  if (params.vpx_max_quantizer >= 0 &&
      config_.rc_max_quantizer !=
          static_cast<unsigned int>(params.vpx_max_quantizer)) {
    config_.rc_max_quantizer = params.vpx_max_quantizer;
    changed = true;
  }

  if (!changed)
    return;

  // Update encoder context.
  if (vpx_codec_enc_config_set(codec_.get(), &config_))
    NOTREACHED() << "Unable to set encoder config";

}

void WebrtcVideoEncoderVpx::PrepareImage(
    const webrtc::DesktopFrame* frame,
    webrtc::DesktopRegion* updated_region) {
  if (!frame || frame->updated_region().is_empty()) {
    updated_region->Clear();
    return;
  }

  updated_region->Clear();
  if (image_) {
    // Pad each rectangle to avoid the block-artifact filters in libvpx from
    // introducing artifacts; VP9 includes up to 8px either side, and VP8 up to
    // 3px, so unchanged pixels up to that far out may still be affected by the
    // changes in the updated region, and so must be listed in the active map.
    // After padding we align each rectangle to 16x16 active-map macroblocks.
    // This implicitly ensures all rects have even top-left coords, which is
    // is required by ConvertRGBToYUVWithRect().
    // TODO(wez): Do we still need 16x16 align, or is even alignment sufficient?
    int padding = use_vp9_ ? 8 : 3;
    for (webrtc::DesktopRegion::Iterator r(frame->updated_region());
         !r.IsAtEnd(); r.Advance()) {
      const webrtc::DesktopRect& rect = r.rect();
      updated_region->AddRect(AlignRect(webrtc::DesktopRect::MakeLTRB(
          rect.left() - padding, rect.top() - padding, rect.right() + padding,
          rect.bottom() + padding)));
    }
    DCHECK(!updated_region->is_empty());

    // Clip back to the screen dimensions, in case they're not macroblock
    // aligned. The conversion routines don't require even width & height,
    // so this is safe even if the source dimensions are not even.
    updated_region->IntersectWith(
        webrtc::DesktopRect::MakeWH(image_->w, image_->h));
  } else {
    CreateImage(lossless_color_, frame->size(), &image_, &image_buffer_);
    updated_region->AddRect(webrtc::DesktopRect::MakeWH(image_->w, image_->h));
  }

  // Convert the updated region to YUV ready for encoding.
  const uint8_t* rgb_data = frame->data();
  const int rgb_stride = frame->stride();
  const int y_stride = image_->stride[0];
  DCHECK_EQ(image_->stride[1], image_->stride[2]);
  const int uv_stride = image_->stride[1];
  uint8_t* y_data = image_->planes[0];
  uint8_t* u_data = image_->planes[1];
  uint8_t* v_data = image_->planes[2];

  switch (image_->fmt) {
    case VPX_IMG_FMT_I444:
      for (webrtc::DesktopRegion::Iterator r(*updated_region); !r.IsAtEnd();
           r.Advance()) {
        const webrtc::DesktopRect& rect = r.rect();
        int rgb_offset =
            rgb_stride * rect.top() + rect.left() * kBytesPerRgbPixel;
        int yuv_offset = uv_stride * rect.top() + rect.left();
        libyuv::ARGBToI444(rgb_data + rgb_offset, rgb_stride,
                           y_data + yuv_offset, y_stride, u_data + yuv_offset,
                           uv_stride, v_data + yuv_offset, uv_stride,
                           rect.width(), rect.height());
      }
      break;
    case VPX_IMG_FMT_YV12:
      for (webrtc::DesktopRegion::Iterator r(*updated_region); !r.IsAtEnd();
           r.Advance()) {
        const webrtc::DesktopRect& rect = r.rect();
        int rgb_offset =
            rgb_stride * rect.top() + rect.left() * kBytesPerRgbPixel;
        int y_offset = y_stride * rect.top() + rect.left();
        int uv_offset = uv_stride * rect.top() / 2 + rect.left() / 2;
        libyuv::ARGBToI420(rgb_data + rgb_offset, rgb_stride, y_data + y_offset,
                           y_stride, u_data + uv_offset, uv_stride,
                           v_data + uv_offset, uv_stride, rect.width(),
                           rect.height());
      }
      break;
    default:
      NOTREACHED();
      break;
  }
}

void WebrtcVideoEncoderVpx::ClearActiveMap() {
  DCHECK(active_map_);
  // Clear active map first.
  memset(active_map_.get(), 0,
         active_map_size_.width() * active_map_size_.height());
}

void WebrtcVideoEncoderVpx::SetActiveMapFromRegion(
    const webrtc::DesktopRegion& updated_region) {
  // Mark updated areas active.
  for (webrtc::DesktopRegion::Iterator r(updated_region); !r.IsAtEnd();
       r.Advance()) {
    const webrtc::DesktopRect& rect = r.rect();
    int left = rect.left() / kMacroBlockSize;
    int right = (rect.right() - 1) / kMacroBlockSize;
    int top = rect.top() / kMacroBlockSize;
    int bottom = (rect.bottom() - 1) / kMacroBlockSize;
    DCHECK_LT(right, active_map_size_.width());
    DCHECK_LT(bottom, active_map_size_.height());

    uint8_t* map = active_map_.get() + top * active_map_size_.width();
    for (int y = top; y <= bottom; ++y) {
      for (int x = left; x <= right; ++x)
        map[x] = 1;
      map += active_map_size_.width();
    }
  }
}

void WebrtcVideoEncoderVpx::UpdateRegionFromActiveMap(
    webrtc::DesktopRegion* updated_region) {
  const uint8_t* map = active_map_.get();
  for (int y = 0; y < active_map_size_.height(); ++y) {
    for (int x0 = 0; x0 < active_map_size_.width();) {
      int x1 = x0;
      for (; x1 < active_map_size_.width(); ++x1) {
        if (map[y * active_map_size_.width() + x1] == 0)
          break;
      }
      if (x1 > x0) {
        updated_region->AddRect(webrtc::DesktopRect::MakeLTRB(
            kMacroBlockSize * x0, kMacroBlockSize * y, kMacroBlockSize * x1,
            kMacroBlockSize * (y + 1)));
      }
      x0 = x1 + 1;
    }
  }
  updated_region->IntersectWith(
      webrtc::DesktopRect::MakeWH(image_->w, image_->h));
}

}  // namespace remoting


text:
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License.  You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using Apache.Arrow;
using Apache.Arrow.Types;

namespace Apache.Arrow
{
    /// <summary>
    /// A data structure to manage a list of primitive Array arrays logically as one large array
    /// </summary>
    public class ChunkedArray
    {
        private IList<Array> Arrays { get; }
        public IArrowType DataType { get; }
        public long Length { get; }
        public long NullCount { get; }

        public int ArrayCount
        {
            get => Arrays.Count;
        }

        public Array Array(int index) => Arrays[index];

        public ChunkedArray(IList<Array> arrays)
        {
            Arrays = arrays ?? throw new ArgumentNullException(nameof(arrays));
            if (arrays.Count < 1)
            {
                throw new ArgumentException($"Count must be at least 1. Got {arrays.Count} instead");
            }
            DataType = arrays[0].Data.DataType;
            foreach (Array array in arrays)
            {
                Length += array.Length;
                NullCount += array.NullCount;
            }
        }

        public ChunkedArray(Array array) : this(new[] { array }) { }

        public ChunkedArray Slice(long offset, long length)
        {
            if (offset >= Length)
            {
                throw new ArgumentException($"Index {offset} cannot be greater than the Column's Length {Length}");
            }

            int curArrayIndex = 0;
            int numArrays = Arrays.Count;
            while (curArrayIndex < numArrays && offset > Arrays[curArrayIndex].Length)
            {
                offset -= Arrays[curArrayIndex].Length;
                curArrayIndex++;
            }

            IList<Array> newArrays = new List<Array>();
            while (curArrayIndex < numArrays && length > 0)
            {
                newArrays.Add(Arrays[curArrayIndex].Slice((int)offset,
                              length > Arrays[curArrayIndex].Length ? Arrays[curArrayIndex].Length : (int)length));
                length -= Arrays[curArrayIndex].Length - offset;
                offset = 0;
                curArrayIndex++;
            }
            return new ChunkedArray(newArrays);
        }

        public ChunkedArray Slice(long offset)
        {
            return Slice(offset, Length - offset);
        }

        // TODO: Flatten for Structs
    }
}

redpajama_set_name: RedPajamaGithub


text:
package de.crunc.hamcrest.json.matcher;

import com.google.gson.JsonArray;
import com.google.gson.JsonNull;
import com.google.gson.JsonPrimitive;
import de.crunc.hamcrest.json.VertxJsonArrayBuilder;
import de.crunc.hamcrest.json.VertxJsonObjectBuilder;
import org.hamcrest.Description;
import org.hamcrest.StringDescription;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;

import static de.crunc.hamcrest.json.JsonArrayBuilder.array;
import static de.crunc.hamcrest.json.JsonObjectBuilder.object;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

/**
 * Unit test for {@link IsEqualToJsonObject}
 *
 * @author Hauke Jaeger, hauke.jaeger@googlemail.com
 */
@RunWith(Parameterized.class)
public class IsEqualToJsonObjectTest {

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {new IsEqualToJsonObject(), JsonNull.INSTANCE, false},
                {new IsEqualToJsonObject(), new JsonPrimitive(true), false},
                {new IsEqualToJsonObject(), new JsonPrimitive(false), false},
                {new IsEqualToJsonObject(), new JsonPrimitive(42), false},
                {new IsEqualToJsonObject(), new JsonPrimitive(3.1), false},
                {new IsEqualToJsonObject(), new JsonPrimitive("HalliGalli"), false},
                {new IsEqualToJsonObject(), new JsonArray(), false},

                {new IsEqualToJsonObject(object().put("aFloat", 712).build()), object().put("aFloat", 712).build(), true},
                {new IsEqualToJsonObject(object().put("aFloat", 713).build()), object().put("aFloat", 712).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", 712L).build()), object().put("aFloat", 712).build(), true},
                {new IsEqualToJsonObject(object().put("aFloat", 711L).build()), object().put("aFloat", 712).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", 712.0f).build()), object().put("aFloat", 712).build(), true},
                {new IsEqualToJsonObject(object().put("aFloat", 712.1f).build()), object().put("aFloat", 712).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", 712.0).build()), object().put("aFloat", 712).build(), true},
                {new IsEqualToJsonObject(object().put("aFloat", 711.99).build()), object().put("aFloat", 712).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", new BigDecimal("712.00")).build()), object().put("aFloat", 712).build(), true},
                {new IsEqualToJsonObject(object().put("aFloat", new BigDecimal("712.001")).build()), object().put("aFloat", 712).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", new BigInteger("712")).build()), object().put("aFloat", 712).build(), true},
                {new IsEqualToJsonObject(object().put("aFloat", new BigInteger("612")).build()), object().put("aFloat", 712).build(), false},

                {new IsEqualToJsonObject(object().put("aFloat", -9138).build()), object().put("aFloat", -9138.379).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", -9139).build()), object().put("aFloat", -9138.379).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", -9138L).build()), object().put("aFloat", -9138.379).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", -9139L).build()), object().put("aFloat", -9138.379).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", -9138.379f).build()), object().put("aFloat", -9138.379).build(), true},
                {new IsEqualToJsonObject(object().put("aFloat", -9138.378f).build()), object().put("aFloat", -9138.379).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", -9138.379).build()), object().put("aFloat", -9138.379).build(), true},
                {new IsEqualToJsonObject(object().put("aFloat", -9138.389).build()), object().put("aFloat", -9138.379).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", new BigDecimal("-9138.379")).build()), object().put("aFloat", -9138.379).build(), true},
                {new IsEqualToJsonObject(object().put("aFloat", new BigDecimal("-9138.3792")).build()), object().put("aFloat", -9138.379).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", new BigInteger("9138")).build()), object().put("aFloat", -9138.379).build(), false},
                {new IsEqualToJsonObject(object().put("aFloat", new BigInteger("9139")).build()), object().put("aFloat", -9138.379).build(), false},

                {new IsEqualToJsonObject(object().put("booleanTrue", true).build()), object().put("booleanTrue", true).build(), true},
                {new IsEqualToJsonObject(object().put("booleanTrue", false).build()), object().put("booleanTrue", true).build(), false},

                {new IsEqualToJsonObject(object().put("booleanFalse", false).build()), object().put("booleanFalse", false).build(), true},
                {new IsEqualToJsonObject(object().put("booleanFalse", true).build()), object().put("booleanFalse", false).build(), false},

                {new IsEqualToJsonObject(object().put("aString", "A string").build()), object().put("aString", "A string").build(), true},
                {new IsEqualToJsonObject(object().put("aString", "Another string").build()), object().put("aString", "A string").build(), false},

                {new IsEqualToJsonObject(object().put("emptyString", "").build()), object().put("emptyString", "").build(), true},
                {new IsEqualToJsonObject(object().put("emptyString", "Nt empty").build()), object().put("emptyString", "").build(), false},

                {new IsEqualToJsonObject(object().putNull("nullValue").build()), object().putNull("nullValue").build(), true},
                {new IsEqualToJsonObject(object().put("nullValue", "null").build()), object().putNull("nullValue").build(), false},

                {new IsEqualToJsonObject(), object().put("unexpectedTrue", true).build(), false},
                {new IsEqualToJsonObject(), object().put("unexpectedFalse", false).build(), false},
                {new IsEqualToJsonObject(), object().put("unexpectedInteger", 0).build(), false},
                {new IsEqualToJsonObject(), object().put("unexpectedFloat", 0.73).build(), false},
                {new IsEqualToJsonObject(), object().put("unexpectedString", "Oh my gosh!").build(), false},
                {new IsEqualToJsonObject(), object().putNull("unexpectedNull").build(), false},

                {new IsEqualToJsonObject(object().put("unmatchedTrue", true).build()), object().build(), false},
                {new IsEqualToJsonObject(object().put("unmatchedFalse", false).build()), object().build(), false},
                {new IsEqualToJsonObject(object().put("unmatchedInteger", 13).build()), object().build(), false},
                {new IsEqualToJsonObject(object().put("unmatchedFloat", 13.37).build()), object().build(), false},
                {new IsEqualToJsonObject(object().put("unmatchedString", "Where did that come from?").build()), object().build(), false},

                {new IsEqualToJsonObject(object().putNull("unmatchedNull").build()), object().build(), true},

                // -----------------------------------------------------------------------------------------------
                // GSON
                // -----------------------------------------------------------------------------------------------
                {new IsEqualToJsonObject(), object().build(), true},

                {
                        new IsEqualToJsonObject(object()
                                .put("aString", "A day without sunshine is like, you know, night. - Steve Martin")
                                .put("aFloat", 65000)
                                .put("aFloat", 19.17)
                                .put("booleanTrue", true)
                                .put("booleanFalse", false)
                                .putNull("nullValue")
                                .put("anObject", object()
                                        .put("embeddedString", "An embedded string")
                                        .put("embeddedInteger", 319)
                                        .put("embeddedFloat", 99.91)
                                        .put("embeddedBooleanTrue", true)
                                        .put("embeddedBooleanFalse", false)
                                        .putNull("embeddedNullValue"))
                                .put("anArray", array()
                                        .add("An embedded string")
                                        .add(7777)
                                        .add(512.1024)
                                        .add(true)
                                        .add(false)
                                        .addNull())
                                .build()),
                        object()
                                .put("aString", "A day without sunshine is like, you know, night. - Steve Martin")
                                .put("aFloat", 65000)
                                .put("aFloat", 19.17)
                                .put("booleanTrue", true)
                                .put("booleanFalse", false)
                                .putNull("nullValue")
                                .put("anObject", object()
                                        .put("embeddedString", "An embedded string")
                                        .put("embeddedInteger", 319)
                                        .put("embeddedFloat", 99.91)
                                        .put("embeddedBooleanTrue", true)
                                        .put("embeddedBooleanFalse", false)
                                        .putNull("embeddedNullValue"))
                                .put("anArray", array()
                                        .add("An embedded string")
                                        .add(7777)
                                        .add(512.1024)
                                        .add(true)
                                        .add(false)
                                        .addNull())
                                .build(),
                        true
                },

                // -----------------------------------------------------------------------------------------------
                // JSON string
                // -----------------------------------------------------------------------------------------------
                {new IsEqualToJsonObject(), object().encode(), true},

                {
                        new IsEqualToJsonObject(object()
                                .put("aString", "A day without sunshine is like, you know, night. - Steve Martin")
                                .put("aFloat", 65000)
                                .put("aFloat", 19.17)
                                .put("booleanTrue", true)
                                .put("booleanFalse", false)
                                .putNull("nullValue")
                                .put("anObject", object()
                                        .put("embeddedString", "An embedded string")
                                        .put("embeddedInteger", 319)
                                        .put("embeddedFloat", 99.91)
                                        .put("embeddedBooleanTrue", true)
                                        .put("embeddedBooleanFalse", false)
                                        .putNull("embeddedNullValue"))
                                .put("anArray", array()
                                        .add("An embedded string")
                                        .add(7777)
                                        .add(512.1024)
                                        .add(true)
                                        .add(false)
                                        .addNull())
                                .build()),
                        object()
                                .put("aString", "A day without sunshine is like, you know, night. - Steve Martin")
                                .put("aFloat", 65000)
                                .put("aFloat", 19.17)
                                .put("booleanTrue", true)
                                .put("booleanFalse", false)
                                .putNull("nullValue")
                                .put("anObject", object()
                                        .put("embeddedString", "An embedded string")
                                        .put("embeddedInteger", 319)
                                        .put("embeddedFloat", 99.91)
                                        .put("embeddedBooleanTrue", true)
                                        .put("embeddedBooleanFalse", false)
                                        .putNull("embeddedNullValue"))
                                .put("anArray", array()
                                        .add("An embedded string")
                                        .add(7777)
                                        .add(512.1024)
                                        .add(true)
                                        .add(false)
                                        .addNull())
                                .build(),
                        true
                },

                // -----------------------------------------------------------------------------------------------
                // Vertx JSON
                // -----------------------------------------------------------------------------------------------
                {new IsEqualToJsonObject(), VertxJsonObjectBuilder.object().build(), true},

                {
                        new IsEqualToJsonObject(object()
                                .put("aString", "A day without sunshine is like, you know, night. - Steve Martin")
                                .put("aFloat", 65000)
                                .put("aFloat", 19.17)
                                .put("booleanTrue", true)
                                .put("booleanFalse", false)
                                .putNull("nullValue")
                                .put("anObject", object()
                                        .put("embeddedString", "An embedded string")
                                        .put("embeddedInteger", 319)
                                        .put("embeddedFloat", 99.91)
                                        .put("embeddedBooleanTrue", true)
                                        .put("embeddedBooleanFalse", false)
                                        .putNull("embeddedNullValue"))
                                .put("anArray", array()
                                        .add("An embedded string")
                                        .add(7777)
                                        .add(512.1024)
                                        .add(true)
                                        .add(false)
                                        .addNull())
                                .build()),
                        VertxJsonObjectBuilder.object()
                                .put("aString", "A day without sunshine is like, you know, night. - Steve Martin")
                                .put("aFloat", 65000)
                                .put("aFloat", 19.17)
                                .put("booleanTrue", true)
                                .put("booleanFalse", false)
                                .putNull("nullValue")
                                .put("anObject", VertxJsonObjectBuilder.object()
                                        .put("embeddedString", "An embedded string")
                                        .put("embeddedInteger", 319)
                                        .put("embeddedFloat", 99.91)
                                        .put("embeddedBooleanTrue", true)
                                        .put("embeddedBooleanFalse", false)
                                        .putNull("embeddedNullValue"))
                                .put("anArray", VertxJsonArrayBuilder.array()
                                        .add("An embedded string")
                                        .add(7777)
                                        .add(512.1024)
                                        .add(true)
                                        .add(false)
                                        .addNull())
                                .encode(),
                        true
                },

                // -----------------------------------------------------------------------------------------------
                // json.org
                // -----------------------------------------------------------------------------------------------
                {new IsEqualToJsonObject(), new JSONObject(), true},

                {
                        new IsEqualToJsonObject(object()
                                .put("aString", "A day without sunshine is like, you know, night. - Steve Martin")
                                .put("aFloat", 65000)
                                .put("aFloat", 19.17)
                                .put("booleanTrue", true)
                                .put("booleanFalse", false)
                                .putNull("nullValue")
                                .put("anObject", object()
                                        .put("embeddedString", "An embedded string")
                                        .put("embeddedInteger", 319)
                                        .put("embeddedFloat", 99.91)
                                        .put("embeddedBooleanTrue", true)
                                        .put("embeddedBooleanFalse", false)
                                        .putNull("embeddedNullValue"))
                                .put("anArray", array()
                                        .add("An embedded string")
                                        .add(7777)
                                        .add(512.1024)
                                        .add(true)
                                        .add(false)
                                        .addNull())
                                .build()),
                        new JSONObject()
                                .put("aString", "A day without sunshine is like, you know, night. - Steve Martin")
                                .put("aFloat", 65000)
                                .put("aFloat", 19.17)
                                .put("booleanTrue", true)
                                .put("booleanFalse", false)
                                .put("nullValue", (Object) null)
                                .put("anObject", new JSONObject()
                                        .put("embeddedString", "An embedded string")
                                        .put("embeddedInteger", 319)
                                        .put("embeddedFloat", 99.91)
                                        .put("embeddedBooleanTrue", true)
                                        .put("embeddedBooleanFalse", false)
                                        .put("embeddedNullValue", (Object) null))
                                .put("anArray", new JSONArray()
                                        .put("An embedded string")
                                        .put(7777)
                                        .put(512.1024)
                                        .put(true)
                                        .put(false)
                                        .put((Object) null)),
                        true
                },
        });
    }

    @Parameterized.Parameter(0)
    public IsEqualToJsonObject matcher;

    @Parameterized.Parameter(1)
    public Object actual;

    @Parameterized.Parameter(2)
    public boolean result;

    @Test
    public void testMatches() {

        boolean match = matcher.matches(actual);

        Description desc = new StringDescription();
        desc.appendText("expected <");
        if (actual != null) {
            desc.appendText(actual.getClass().getSimpleName());
        } else {
            desc.appendText("null");
        }
        desc.appendText(">:\n");

        matcher.describeTo(desc);
        desc.appendText("\nbut:\n");
        matcher.describeMismatch(actual, desc);

        assertThat(desc.toString(), match, equalTo(result));
    }
}


text:
import plMerc from "./plMerc.json";
import plMill from "./plMill.json";
export { plMerc, plMill };
//# sourceMappingURL=index.js.map


text:
package org.apache.ignite.internal.processors.cache.mvcc;

import org.apache.ignite.cache.CacheMode;

import static org.apache.ignite.cache.CacheMode.REPLICATED;

/** */
public class CacheMvccReplicatedSqlQueriesTest extends CacheMvccSqlQueriesAbstractTest {
    /** {@inheritDoc} */
    protected CacheMode cacheMode() {
        return REPLICATED;
    }
}


text:
FOUNDATION_EXPORT double CycleViewVersionNumber;

//! Project version string for CycleView.
FOUNDATION_EXPORT const unsigned char CycleViewVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <CycleView/PublicHeader.h>


text:
<?php

// phpcs:disable PSR1.Classes.ClassDeclaration.MissingNamespace

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class UserSettings extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->json('settings')->after('remember_token')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('settings');
        });
    }
}


text:
import React from 'react';
import { describe, beforeEach, it } from 'mocha';
import { StaticRouter as Router } from 'react-router-dom';
import { runAxeTest, HTML } from '@folio/stripes-testing';

import { mount } from '../../../tests/helpers';
import PaneBackLink from '../PaneBackLink';

const interactor = HTML.extend('pane back link')
  .selector('[class*=paneBackLink---]');

describe('PaneBackLink', () => {
  const paneBackLink = interactor({ visible: false });

  beforeEach(async () => {
    await mount(
      <Router context={{}}>
        <PaneBackLink to="/" />
      </Router>
    );
  });

  it('contains no axe errors - PaneBackLink', runAxeTest);

  it('displays the back link', () => paneBackLink.exists());
});


text:
package main.java.fr.mrc.ptichat.connection;
import main.java.fr.mrc.ptichat.appmanagement.ChatManager;
import main.java.fr.mrc.ptichat.processing.MessageHandler;
import main.java.fr.mrc.ptichat.utils.LanguagesController;

import java.io.*;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Handles the messages to receive
 */
public class RequestRunnable implements Runnable {

    private BufferedReader in;
    private InetAddress address;
    private int port;
    private ChatManager chatManager;
    private MessageHandler mh = new MessageHandler();
    private Flag stopFlag;
    private LanguagesController languagesController = LanguagesController.getInstance();

    public RequestRunnable(BufferedReader in, InetAddress address, int port, Flag stopFlag, ChatManager chatManager){
        this.in = in;
        this.address = address;
        this.port = port;
        this.stopFlag = stopFlag;
        this.chatManager = chatManager;
    }

    public void run(){
        String message;
        while(!this.stopFlag.getFlag()){
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
            try {
                if (this.in.ready()) {
                    message = this.in.readLine();
                    String intro = "\n>>>>>> " + languagesController.getWord("RECEIVED_AT") + " " + sdf.format(cal.getTime()) + "\n";
                    if (mh.isTerminationMessage(message)) {
                        this.stop();
                    } else if (mh.isFileTransmission(message)){
                        try {
                            int i;
                            String[] messageParts = mh.getContentFromMessage(message);
                            String filePath = mh.messageToFile(messageParts[1], messageParts[2], this.chatManager.getSavedFilesDirectory());
                            message = intro + languagesController.getWord("NEW_FILE_RECEIVED") + filePath + "\n";
                            this.chatManager.receivedFile(((i = filePath.lastIndexOf(File.separator.replace("\\", "\\\\"))) > 0) ? filePath.substring(i+1) : filePath);
                        } catch (IOException e) {
                            message = e.getMessage();
                        }
                    } else {
                        message = intro + message + "\n";
                    }
                    this.chatManager.receivedMessage(message);
                }
            } catch (IOException e){
                e.printStackTrace();
            }
        }
        try {
            this.in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stop() { this.stopFlag.setFlag(true); }

}


text:
package org.omg.CORBA;

/**
* The Helper for <tt>VersionSpec</tt>.  For more information on
* Helper files, see
* "Generated Files: Helper Files".

* org/omg/CORBA/VersionSpecHelper.java
* Generated by the IDL-to-Java compiler (portable), version "3.0"
* from ir.idl
* 03 June 1999 11:33:43 o'clock GMT+00:00
*/

abstract public class VersionSpecHelper
{
  private static String  _id = "IDL:omg.org/CORBA/VersionSpec:1.0";

  public static void insert (Any a, String that)
  {
    org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
    a.type (type ());
    write (out, that);
    a.read_value (out.create_input_stream (), type ());
  }

  public static String extract (Any a)
  {
    return read (a.create_input_stream ());
  }

  private static TypeCode __typeCode = null;
  synchronized public static TypeCode type ()
  {
    if (__typeCode == null)
    {
      __typeCode = ORB.init ().create_string_tc (0);
      __typeCode = ORB.init ().create_alias_tc (VersionSpecHelper.id (), "VersionSpec", __typeCode);
    }
    return __typeCode;
  }

  public static String id ()
  {
    return _id;
  }

  public static String read (org.omg.CORBA.portable.InputStream istream)
  {
    String value = null;
    value = istream.read_string ();
    return value;
  }

  public static void write (org.omg.CORBA.portable.OutputStream ostream, String value)
  {
    ostream.write_string (value);
  }

}


text:
/* $Id$
 */
#ifndef HIPE_PPC_H
#define HIPE_PPC_H

static __inline__ void hipe_flush_icache_word(void *address)
{
    asm volatile("dcbst 0,%0\n"
		 "\tsync\n"
		 "\ticbi 0,%0\n"
		 "\tsync\n"
		 "\tisync"
		 :
		 : "r"(address)
		 : "memory");
}

extern void hipe_flush_icache_range(void *address, unsigned int nbytes);

/* for stack descriptor hash lookup */
#define HIPE_RA_LSR_COUNT	2	/* low 2 bits are always zero */

/* for hipe_bifs_{read,write}_{s,u}32 */
static __inline__ int hipe_word32_address_ok(void *address)
{
    return ((unsigned long)address & 0x3) == 0;
}

/* Native stack growth direction. */
#define HIPE_NSTACK_GROWS_DOWN

#if defined(__powerpc64__)
#define hipe_arch_name	am_ppc64
#define AEXTERN(RET,NAME,PROTO)	extern const int NAME
AEXTERN(void,hipe_ppc_inc_stack,(void));
#else
#define hipe_arch_name	am_powerpc
extern void hipe_ppc_inc_stack(void); /* we don't have the AEXTERN() fallback :-( */
#endif

/* for hipe_bifs_enter_code_2 */
extern void *hipe_alloc_code(Uint nrbytes, Eterm callees, Eterm *trampolines, Process *p);
#define HIPE_ALLOC_CODE(n,c,t,p) hipe_alloc_code((n),(c),(t),(p))

#if !defined(__powerpc64__)
extern const unsigned int fconv_constant[];
#endif

#endif /* HIPE_PPC_H */


text:
CREATE FUNCTION tSQLt.Private_GetConfiguration(
  @Name NVARCHAR(100)
)
RETURNS TABLE
AS
RETURN
  SELECT PC.Name,
         PC.Value
    FROM tSQLt.Private_Configurations AS PC
   WHERE PC.Name = @Name;


text:
<?xml version="1.0" encoding="iso-8859-1"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>FusionCharts Free Documentation</title>
<link rel="stylesheet" href="Style.css" type="text/css" />

Using FusionCharts PHP Class > Charting Data from Array

In this section, we'll show you how to use FusionCharts  PHP class functions to plot charts from data contained in PHP arrays. We'll cover the following examples here:

Creating a single series chart from data contained in an array

Creating a multi-series chart from data contained in arrays

Before you go further with this page, we recommend you to please see the previous section "Basic Examples" as we start off from concepts explained in that page.

The code examples contained in this page are present in Download Package > Code > PHPClass > ArrayExample folder.

    Creating a single series chart from data contained in arrays

    The code to create a single series chart is contained in SingleSeries.php and can be listed as under:

<?php

          //We've included ../Includes/FusionCharts_Gen.php, which contains FusionCharts PHP Class

          //to help us easily embed the charts.

          include("../Includes/FusionCharts_Gen.php");

        ?>

        <HTML>

        <HEAD>

          <TITLE>

    FusionCharts Free - Array Example using Single Series Column 3D Chart

  </TITLE>

<?php

  //You need to include the following JS file, if you intend to embed the chart using JavaScript.

  //Embedding using JavaScripts avoids the "Click to Activate..." issue in Internet Explorer

  //When you make your own charts, make sure that the path to this JS file is correct.

  //Else, you would get JavaScript errors.

?>

  <SCRIPT LANGUAGE="Javascript" SRC="../../FusionCharts/FusionCharts.js"></SCRIPT>

</HEAD>

<BODY>

<CENTER>

        <?php

          //In this example, using FusionCharts PHP Class we plot a single series chart

          //from data contained in an array.

          //The array needs to have two columns - first one for data labels/names

          //and the next one for data values.

          //Let's store the sales data for 6 products in our array. We also store

          //the name of products.

          //Store Name of Products in the first column of the array

          $arrData[0][0] = "Product A";

          $arrData[1][0] = "Product B";

          $arrData[2][0] = "Product C";

          $arrData[3][0] = "Product D";

          $arrData[4][0] = "Product E";

          $arrData[5][0] = "Product F";

  //Store sales data in the second column of the array

          $arrData[0][1] = 567500;

          $arrData[1][1] = 815300;

          $arrData[2][1] = 556800;

          $arrData[3][1] = 734500;

          $arrData[4][1] = 676800;

          $arrData[5][1] = 648500;

   # Create FusionCharts PHP Class object for single series column3d chart

          $FC = new FusionCharts("Column3D","600","300");

   # Set Relative Path of chart swf file.

          $FC->setSwfPath("../../FusionCharts/");

          # Store chart attributes in a variable

          $strParam="caption=Sales by Product;numberPrefix=$;formatNumberScale=0;decimalPrecision=0";

   #  Set chart attributes

          $FC->setChartParams($strParam);

          # Call FusionCharts PHP Class Function to add data from the array

          $FC->addChartDataFromArray($arrData);

          # Render the chart

          $FC->renderChart();

        ?>

        </CENTER>

</BODY>

</HTML>

    In the above example:

We have included FusionCharts_Gen.php and FusionCharts.js.

Stored the category names/labels in the first column of the 2-dimensional array $arrData[]

Then we  stored respective data values in the second column of the 2-dimensional array $arrData[]

Created an instance of the FusionCharts PHP class for Column 3D chart with 600 pixels width, 300 pixels height.

Set relative path of  chart SWF file

Rendered chart using renderChart() function

    Please go through FusionCharts PHP Class API Reference section to know more about the functions used in the above code.

    When you view the chart, you'll see a chart as under:

    Creating a multi-series chart from data contained in arrays

    Let us now create a multi-series chart from data contained in arrays. We create a file MultiSeries.php with the following code:

<?php

          //We've included ../Includes/FusionCharts_Gen.php, which contains FusionCharts PHP Class

          //to help us easily embed the charts.

          include("../Includes/FusionCharts_Gen.php");

        ?>

        <HTML>

        <HEAD>

          <TITLE>

            FusionCharts Free - Array Example using Multi Series Column 3D Chart

          </TITLE>

        <?php

  //You need to include the following JS file, if you intend to embed the chart using JavaScript.

  //Embedding using JavaScripts avoids the "Click to Activate..." issue in Internet Explorer

  //When you make your own charts, make sure that the path to this JS file is correct.

  //Else, you would get JavaScript errors.

?>

  <SCRIPT LANGUAGE="Javascript" SRC="../../FusionCharts/FusionCharts.js"></SCRIPT>

</HEAD>

<BODY>

<CENTER>

        <?php

          //In this example, using FusionCharts PHP Class

          //we plot a mulitseries chart from data contained in arrays

          /* The arrays need to be of the following  structure :

          1. Array to store Category Names :

          A single dimensional array storing the category names

          2. A 2 Dimensional Array to store data values

   ** Each row will store data for 1 dataset

          Column 1 will store : Dataset Series Name.

          Column 2 will store : Dataset attributes

          (as list separated by delimiter.)

          Column 3 and rest will store : values of the dataset

          */

          //Let's store the sales data for 6 products in our array. We also store the name of products.

          //Store Name of Products

          $arrCatNames[0] = "Product A";

          $arrCatNames[1] = "Product B";

          $arrCatNames[2] = "Product C";

          $arrCatNames[3] = "Product D";

          $arrCatNames[4] = "Product E";

          $arrCatNames[5] = "Product F";

          //Store sales data for current year

          $arrData[0][0] = "Current Year";

          $arrData[0][1] = ""; // Dataset Parameters

          $arrData[0][2] = 567500;

          $arrData[0][3] = 815300;

          $arrData[0][4] = 556800;

          $arrData[0][5] = 734500;

          $arrData[0][6] = 676800;

          $arrData[0][7] = 648500;

          //Store sales data for previous year

          $arrData[1][0] = "Previous Year";

          $arrData[1][1] = ""; // Dataset Parameter

          $arrData[1][2] = 547300;

          $arrData[1][3] = 584500;

          $arrData[1][4] = 754000;

          $arrData[1][5] = 456300;

          $arrData[1][6] = 754500;

          $arrData[1][7] = 437600;

   # Create FusionCharts PHP Class object for multiseies column3d chart

          $FC = new FusionCharts("MSColumn3D","600","300");

   # Set Relative Path of chart swf file.

          $FC->setSwfPath("../../FusionCharts/");

          # Store chart attributes in a variable

          $strParam="caption=Sales by Product;numberPrefix=$;formatNumberScale=1;rotateValues=1;decimalPrecision=0";

   # Set chart attributes

          $FC->setChartParams($strParam);

          # Pass the 2 arrays storing data and category names to

  # FusionCharts PHP Class function addChartDataFromArray

  $FC->addChartDataFromArray($arrData, $arrCatNames);

          # Render the Chart

          $FC->renderChart();

?>

        </CENTER>

</BODY>

</HTML>

    Let's analyze what we have done in the code above:

We included FusionCharts_Gen.php class and FusionCharts.js classes

We cteated 2 arrays - one single dimensional aray and one 2-dimensional array. The single dimensional array $arrCatNames stores category names. The 2-dimensional array $arrData stores dataset name, dataset parameters and values in its each row.

	    Note: dataset parameters separated by delimiters should be stored as string. It is optional for multi series charts, but compulsory for combination charts.

We created FusionCharts PHP class object for Multi-series Column 3D chart with 600 pixels width, 300 pixels height

We set relative path of  chart SWF file using setSwfPath() function

We stored delimiter separated chart attributes in $strParam variable and paseed this variable through

	  setChartParams() function to set chart attributes.

Next, we called addChartDataFromArray() function and passed $arrData and $arrCatNames  arrays through it. The arrays should be passed in this order only, i.e., $arrData is to be the first parameter and $arrCatNames the second.

Finally we rendered the chart using renderChart() function

    Please go through FusionCharts PHP Class API Reference section to know more about the functions used in the above code.

    When you view the chart, you'll see a chart as under:

    In Download Package > Code > PHPClass > ArrayExample, we've more example codes to create Stacked and Combination Charts too, which have not been explained here, as they're similar in concept. You can directly see the code if you want to.