text:
import six

from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest.common import waiters
from tempest import config
from tempest import test

CONF = config.CONF

class ImagesMetadataTestJSON(base.BaseV2ComputeTest):

    @classmethod
    def skip_checks(cls):
        super(ImagesMetadataTestJSON, cls).skip_checks()
        if not CONF.service_available.glance:
            skip_msg = ("%s skipped as glance is not available" % cls.__name__)
            raise cls.skipException(skip_msg)

    @classmethod
    def setup_clients(cls):
        super(ImagesMetadataTestJSON, cls).setup_clients()
        cls.glance_client = cls.os.image_client
        cls.client = cls.images_client

    @classmethod
    def resource_setup(cls):
        super(ImagesMetadataTestJSON, cls).resource_setup()
        cls.image_id = None

        name = data_utils.rand_name('image')
        body = cls.glance_client.create_image(name=name,
                                              container_format='bare',
                                              disk_format='raw',
                                              is_public=False)['image']
        cls.image_id = body['id']
        cls.images.append(cls.image_id)
        image_file = six.StringIO(('*' * 1024))
        cls.glance_client.update_image(cls.image_id, data=image_file)
        waiters.wait_for_image_status(cls.client, cls.image_id, 'ACTIVE')

    def setUp(self):
        super(ImagesMetadataTestJSON, self).setUp()
        meta = {'os_version': 'value1', 'os_distro': 'value2'}
        self.client.set_image_metadata(self.image_id, meta)

    @test.idempotent_id('37ec6edd-cf30-4c53-bd45-ae74db6b0531')
    def test_list_image_metadata(self):
        # All metadata key/value pairs for an image should be returned
        resp_metadata = self.client.list_image_metadata(self.image_id)
        expected = {'os_version': 'value1', 'os_distro': 'value2'}
        self.assertEqual(expected, resp_metadata)

    @test.idempotent_id('ece7befc-d3ce-42a4-b4be-c3067a418c29')
    def test_set_image_metadata(self):
        # The metadata for the image should match the new values
        req_metadata = {'os_version': 'value2', 'architecture': 'value3'}
        self.client.set_image_metadata(self.image_id,
                                       req_metadata)

        resp_metadata = self.client.list_image_metadata(self.image_id)
        self.assertEqual(req_metadata, resp_metadata)

    @test.idempotent_id('7b491c11-a9d5-40fe-a696-7f7e03d3fea2')
    def test_update_image_metadata(self):
        # The metadata for the image should match the updated values
        req_metadata = {'os_version': 'alt1', 'architecture': 'value3'}
        self.client.update_image_metadata(self.image_id,
                                          req_metadata)

        resp_metadata = self.client.list_image_metadata(self.image_id)
        expected = {'os_version': 'alt1',
                    'os_distro': 'value2',
                    'architecture': 'value3'}
        self.assertEqual(expected, resp_metadata)

    @test.idempotent_id('4f5db52f-6685-4c75-b848-f4bb363f9aa6')
    def test_get_image_metadata_item(self):
        # The value for a specific metadata key should be returned
        meta = self.client.show_image_metadata_item(self.image_id,
                                                    'os_distro')
        self.assertEqual('value2', meta['os_distro'])

    @test.idempotent_id('f2de776a-4778-4d90-a5da-aae63aee64ae')
    def test_set_image_metadata_item(self):
        # The value provided for the given meta item should be set for
        # the image
        meta = {'os_version': 'alt'}
        self.client.set_image_metadata_item(self.image_id,
                                            'os_version', meta)
        resp_metadata = self.client.list_image_metadata(self.image_id)
        expected = {'os_version': 'alt', 'os_distro': 'value2'}
        self.assertEqual(expected, resp_metadata)

    @test.idempotent_id('a013796c-ba37-4bb5-8602-d944511def14')
    def test_delete_image_metadata_item(self):
        # The metadata value/key pair should be deleted from the image
        self.client.delete_image_metadata_item(self.image_id,
                                               'os_version')
        resp_metadata = self.client.list_image_metadata(self.image_id)
        expected = {'os_distro': 'value2'}
        self.assertEqual(expected, resp_metadata)


text:
namespace flutter {

// clang-format off
constexpr float invert_color_matrix[20] = {
  -1.0,    0,    0, 1.0, 0,
     0, -1.0,    0, 1.0, 0,
     0,    0, -1.0, 1.0, 0,
   1.0,  1.0,  1.0, 1.0, 0
};
// clang-format on

void SkPaintDispatchHelper::setAntiAlias(bool aa) {
  paint_.setAntiAlias(aa);
}
void SkPaintDispatchHelper::setDither(bool dither) {
  paint_.setDither(dither);
}
void SkPaintDispatchHelper::setInvertColors(bool invert) {
  invert_colors_ = invert;
  paint_.setColorFilter(makeColorFilter());
}
void SkPaintDispatchHelper::setStrokeCap(SkPaint::Cap cap) {
  paint_.setStrokeCap(cap);
}
void SkPaintDispatchHelper::setStrokeJoin(SkPaint::Join join) {
  paint_.setStrokeJoin(join);
}
void SkPaintDispatchHelper::setStyle(SkPaint::Style style) {
  paint_.setStyle(style);
}
void SkPaintDispatchHelper::setStrokeWidth(SkScalar width) {
  paint_.setStrokeWidth(width);
}
void SkPaintDispatchHelper::setStrokeMiter(SkScalar limit) {
  paint_.setStrokeMiter(limit);
}
void SkPaintDispatchHelper::setColor(SkColor color) {
  paint_.setColor(color);
}
void SkPaintDispatchHelper::setBlendMode(SkBlendMode mode) {
  paint_.setBlendMode(mode);
}
void SkPaintDispatchHelper::setBlender(sk_sp<SkBlender> blender) {
  paint_.setBlender(blender);
}
void SkPaintDispatchHelper::setShader(sk_sp<SkShader> shader) {
  paint_.setShader(shader);
}
void SkPaintDispatchHelper::setImageFilter(sk_sp<SkImageFilter> filter) {
  paint_.setImageFilter(filter);
}
void SkPaintDispatchHelper::setColorFilter(sk_sp<SkColorFilter> filter) {
  color_filter_ = filter;
  paint_.setColorFilter(makeColorFilter());
}
void SkPaintDispatchHelper::setPathEffect(sk_sp<SkPathEffect> effect) {
  paint_.setPathEffect(effect);
}
void SkPaintDispatchHelper::setMaskFilter(sk_sp<SkMaskFilter> filter) {
  paint_.setMaskFilter(filter);
}
void SkPaintDispatchHelper::setMaskBlurFilter(SkBlurStyle style,
                                              SkScalar sigma) {
  paint_.setMaskFilter(SkMaskFilter::MakeBlur(style, sigma));
}

sk_sp<SkColorFilter> SkPaintDispatchHelper::makeColorFilter() {
  if (!invert_colors_) {
    return color_filter_;
  }
  sk_sp<SkColorFilter> invert_filter =
      SkColorFilters::Matrix(invert_color_matrix);
  if (color_filter_) {
    invert_filter = invert_filter->makeComposed(color_filter_);
  }
  return invert_filter;
}

void SkMatrixDispatchHelper::translate(SkScalar tx, SkScalar ty) {
  matrix_.preTranslate(tx, ty);
  matrix33_ = matrix_.asM33();
}
void SkMatrixDispatchHelper::scale(SkScalar sx, SkScalar sy) {
  matrix_.preScale(sx, sy);
  matrix33_ = matrix_.asM33();
}
void SkMatrixDispatchHelper::rotate(SkScalar degrees) {
  matrix33_.setRotate(degrees);
  matrix_.preConcat(matrix33_);
  matrix33_ = matrix_.asM33();
}
void SkMatrixDispatchHelper::skew(SkScalar sx, SkScalar sy) {
  matrix33_.setSkew(sx, sy);
  matrix_.preConcat(matrix33_);
  matrix33_ = matrix_.asM33();
}

// clang-format off

// 2x3 2D affine subset of a 4x4 transform in row major order
void SkMatrixDispatchHelper::transform2DAffine(
    SkScalar mxx, SkScalar mxy, SkScalar mxt,
    SkScalar myx, SkScalar myy, SkScalar myt) {
  matrix_.preConcat({
      mxx, mxy,  0 , mxt,
      myx, myy,  0 , myt,
       0 ,  0 ,  1 ,  0 ,
       0 ,  0 ,  0 ,  1 ,
  });
  matrix33_ = matrix_.asM33();
}
// full 4x4 transform in row major order
void SkMatrixDispatchHelper::transformFullPerspective(
    SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt,
    SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt,
    SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt,
    SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) {
  matrix_.preConcat({
      mxx, mxy, mxz, mxt,
      myx, myy, myz, myt,
      mzx, mzy, mzz, mzt,
      mwx, mwy, mwz, mwt,
  });
  matrix33_ = matrix_.asM33();
}

// clang-format on

void SkMatrixDispatchHelper::save() {
  saved_.push_back(matrix_);
}
void SkMatrixDispatchHelper::restore() {
  matrix_ = saved_.back();
  matrix33_ = matrix_.asM33();
  saved_.pop_back();
}
void SkMatrixDispatchHelper::reset() {
  matrix_.setIdentity();
  matrix33_ = matrix_.asM33();
}

void ClipBoundsDispatchHelper::clipRect(const SkRect& rect,
                                        SkClipOp clip_op,
                                        bool is_aa) {
  if (clip_op == SkClipOp::kIntersect) {
    intersect(rect, is_aa);
  }
}
void ClipBoundsDispatchHelper::clipRRect(const SkRRect& rrect,
                                         SkClipOp clip_op,
                                         bool is_aa) {
  if (clip_op == SkClipOp::kIntersect) {
    intersect(rrect.getBounds(), is_aa);
  }
}
void ClipBoundsDispatchHelper::clipPath(const SkPath& path,
                                        SkClipOp clip_op,
                                        bool is_aa) {
  if (clip_op == SkClipOp::kIntersect) {
    intersect(path.getBounds(), is_aa);
  }
}
void ClipBoundsDispatchHelper::intersect(const SkRect& rect, bool is_aa) {
  SkRect devClipBounds = matrix().mapRect(rect);
  if (is_aa) {
    devClipBounds.roundOut(&devClipBounds);
  }
  if (has_clip_) {
    if (!bounds_.intersect(devClipBounds)) {
      bounds_.setEmpty();
    }
  } else {
    has_clip_ = true;
    if (devClipBounds.isEmpty()) {
      bounds_.setEmpty();
    } else {
      bounds_ = devClipBounds;
    }
  }
}
void ClipBoundsDispatchHelper::save() {
  if (!has_clip_) {
    saved_.push_back(SkRect::MakeLTRB(0, 0, -1, -1));
  } else if (bounds_.isEmpty()) {
    saved_.push_back(SkRect::MakeEmpty());
  } else {
    saved_.push_back(bounds_);
  }
}
void ClipBoundsDispatchHelper::restore() {
  bounds_ = saved_.back();
  saved_.pop_back();
  has_clip_ = (bounds_.fLeft <= bounds_.fRight &&  //
               bounds_.fTop <= bounds_.fBottom);
  if (!has_clip_) {
    bounds_.setEmpty();
  }
}
void ClipBoundsDispatchHelper::reset(const SkRect* cull_rect) {
  if ((has_clip_ = cull_rect != nullptr) && !cull_rect->isEmpty()) {
    bounds_ = *cull_rect;
  } else {
    bounds_.setEmpty();
  }
}

DisplayListBoundsCalculator::DisplayListBoundsCalculator(
    const SkRect* cull_rect)
    : ClipBoundsDispatchHelper(cull_rect) {
  layer_infos_.emplace_back(std::make_unique<RootLayerData>());
  accumulator_ = layer_infos_.back()->layer_accumulator();
}
void DisplayListBoundsCalculator::setStrokeCap(SkPaint::Cap cap) {
  cap_is_square_ = (cap == SkPaint::kSquare_Cap);
}
void DisplayListBoundsCalculator::setStrokeJoin(SkPaint::Join join) {
  join_is_miter_ = (join == SkPaint::kMiter_Join);
}
void DisplayListBoundsCalculator::setStyle(SkPaint::Style style) {
  style_ = style;
}
void DisplayListBoundsCalculator::setStrokeWidth(SkScalar width) {
  half_stroke_width_ = std::max(width * 0.5f, kMinStrokeWidth);
}
void DisplayListBoundsCalculator::setStrokeMiter(SkScalar limit) {
  miter_limit_ = std::max(limit, 1.0f);
}
void DisplayListBoundsCalculator::setBlendMode(SkBlendMode mode) {
  blend_mode_ = mode;
}
void DisplayListBoundsCalculator::setBlender(sk_sp<SkBlender> blender) {
  SkPaint paint;
  paint.setBlender(std::move(blender));
  blend_mode_ = paint.asBlendMode();
}
void DisplayListBoundsCalculator::setImageFilter(sk_sp<SkImageFilter> filter) {
  image_filter_ = std::move(filter);
}
void DisplayListBoundsCalculator::setColorFilter(sk_sp<SkColorFilter> filter) {
  color_filter_ = std::move(filter);
}
void DisplayListBoundsCalculator::setPathEffect(sk_sp<SkPathEffect> effect) {
  path_effect_ = std::move(effect);
}
void DisplayListBoundsCalculator::setMaskFilter(sk_sp<SkMaskFilter> filter) {
  mask_filter_ = std::move(filter);
  mask_sigma_pad_ = 0.0f;
}
void DisplayListBoundsCalculator::setMaskBlurFilter(SkBlurStyle style,
                                                    SkScalar sigma) {
  mask_sigma_pad_ = std::max(3.0f * sigma, 0.0f);
  mask_filter_ = nullptr;
}
void DisplayListBoundsCalculator::save() {
  SkMatrixDispatchHelper::save();
  ClipBoundsDispatchHelper::save();
  layer_infos_.emplace_back(std::make_unique<SaveData>(accumulator_));
  accumulator_ = layer_infos_.back()->layer_accumulator();
}
void DisplayListBoundsCalculator::saveLayer(const SkRect* bounds,
                                            bool with_paint) {
  SkMatrixDispatchHelper::save();
  ClipBoundsDispatchHelper::save();
  if (with_paint) {
    layer_infos_.emplace_back(std::make_unique<SaveLayerData>(
        accumulator_, image_filter_, paint_nops_on_transparency()));
  } else {
    layer_infos_.emplace_back(
        std::make_unique<SaveLayerData>(accumulator_, nullptr, true));
  }
  accumulator_ = layer_infos_.back()->layer_accumulator();
  // Accumulate the layer in its own coordinate system and then
  // filter and transform its bounds on restore.
  SkMatrixDispatchHelper::reset();
  if (bounds) {
    clipRect(*bounds, SkClipOp::kIntersect, false);
  }
}
void DisplayListBoundsCalculator::restore() {
  if (layer_infos_.size() > 1) {
    SkMatrixDispatchHelper::restore();
    ClipBoundsDispatchHelper::restore();
    accumulator_ = layer_infos_.back()->restore_accumulator();
    SkRect layer_bounds = layer_infos_.back()->layer_bounds();
    // Must read unbounded state after layer_bounds
    bool layer_unbounded = layer_infos_.back()->is_unbounded();
    layer_infos_.pop_back();

    // We accumulate the bounds even if the layer was unbounded because
    // the unbounded state may be contained at a higher level, so we at
    // least accumulate our best estimate about what we have.
    if (!layer_bounds.isEmpty()) {
      // kUnfiltered because the layer already applied all bounds
      // modifications based on the attributes that were in place
      // when it was instantiated. Modifying it further base on the
      // current attributes would mix attribute states.
      AccumulateRect(layer_bounds, kSaveLayerFlags);
    }
    if (layer_unbounded) {
      AccumulateUnbounded();
    }
  }
}

void DisplayListBoundsCalculator::drawPaint() {
  AccumulateUnbounded();
}
void DisplayListBoundsCalculator::drawColor(SkColor color, SkBlendMode mode) {
  AccumulateUnbounded();
}
void DisplayListBoundsCalculator::drawLine(const SkPoint& p0,
                                           const SkPoint& p1) {
  SkRect bounds = SkRect::MakeLTRB(p0.fX, p0.fY, p1.fX, p1.fY).makeSorted();
  DisplayListAttributeFlags flags =
      (bounds.width() > 0.0f && bounds.height() > 0.0f) ? kDrawLineFlags
                                                        : kDrawHVLineFlags;
  AccumulateRect(bounds, flags);
}
void DisplayListBoundsCalculator::drawRect(const SkRect& rect) {
  AccumulateRect(rect, kDrawRectFlags);
}
void DisplayListBoundsCalculator::drawOval(const SkRect& bounds) {
  AccumulateRect(bounds, kDrawOvalFlags);
}
void DisplayListBoundsCalculator::drawCircle(const SkPoint& center,
                                             SkScalar radius) {
  AccumulateRect(SkRect::MakeLTRB(center.fX - radius, center.fY - radius,
                                  center.fX + radius, center.fY + radius),
                 kDrawCircleFlags);
}
void DisplayListBoundsCalculator::drawRRect(const SkRRect& rrect) {
  AccumulateRect(rrect.getBounds(), kDrawRRectFlags);
}
void DisplayListBoundsCalculator::drawDRRect(const SkRRect& outer,
                                             const SkRRect& inner) {
  AccumulateRect(outer.getBounds(), kDrawDRRectFlags);
}
void DisplayListBoundsCalculator::drawPath(const SkPath& path) {
  if (path.isInverseFillType()) {
    AccumulateUnbounded();
  } else {
    AccumulateRect(path.getBounds(), kDrawPathFlags);
  }
}
void DisplayListBoundsCalculator::drawArc(const SkRect& bounds,
                                          SkScalar start,
                                          SkScalar sweep,
                                          bool useCenter) {
  // This could be tighter if we compute where the start and end
  // angles are and then also consider the quadrants swept and
  // the center if specified.
  AccumulateRect(bounds,
                 useCenter  //
                     ? kDrawArcWithCenterFlags
                     : kDrawArcNoCenterFlags);
}
void DisplayListBoundsCalculator::drawPoints(SkCanvas::PointMode mode,
                                             uint32_t count,
                                             const SkPoint pts[]) {
  if (count > 0) {
    BoundsAccumulator ptBounds;
    for (size_t i = 0; i < count; i++) {
      ptBounds.accumulate(pts[i]);
    }
    SkRect point_bounds = ptBounds.bounds();
    switch (mode) {
      case SkCanvas::kPoints_PointMode:
        AccumulateRect(point_bounds, kDrawPointsAsPointsFlags);
        break;
      case SkCanvas::kLines_PointMode:
        AccumulateRect(point_bounds, kDrawPointsAsLinesFlags);
        break;
      case SkCanvas::kPolygon_PointMode:
        AccumulateRect(point_bounds, kDrawPointsAsPolygonFlags);
        break;
    }
  }
}
void DisplayListBoundsCalculator::drawVertices(const sk_sp<SkVertices> vertices,
                                               SkBlendMode mode) {
  AccumulateRect(vertices->bounds(), kDrawVerticesFlags);
}
void DisplayListBoundsCalculator::drawImage(const sk_sp<SkImage> image,
                                            const SkPoint point,
                                            const SkSamplingOptions& sampling,
                                            bool render_with_attributes) {
  SkRect bounds = SkRect::MakeXYWH(point.fX, point.fY,  //
                                   image->width(), image->height());
  DisplayListAttributeFlags flags = render_with_attributes  //
                                        ? kDrawImageWithPaintFlags
                                        : kDrawImageFlags;
  AccumulateRect(bounds, flags);
}
void DisplayListBoundsCalculator::drawImageRect(
    const sk_sp<SkImage> image,
    const SkRect& src,
    const SkRect& dst,
    const SkSamplingOptions& sampling,
    bool render_with_attributes,
    SkCanvas::SrcRectConstraint constraint) {
  DisplayListAttributeFlags flags = render_with_attributes
                                        ? kDrawImageRectWithPaintFlags
                                        : kDrawImageRectFlags;
  AccumulateRect(dst, flags);
}
void DisplayListBoundsCalculator::drawImageNine(const sk_sp<SkImage> image,
                                                const SkIRect& center,
                                                const SkRect& dst,
                                                SkFilterMode filter,
                                                bool render_with_attributes) {
  DisplayListAttributeFlags flags = render_with_attributes
                                        ? kDrawImageNineWithPaintFlags
                                        : kDrawImageNineFlags;
  AccumulateRect(dst, flags);
}
void DisplayListBoundsCalculator::drawImageLattice(
    const sk_sp<SkImage> image,
    const SkCanvas::Lattice& lattice,
    const SkRect& dst,
    SkFilterMode filter,
    bool render_with_attributes) {
  DisplayListAttributeFlags flags = render_with_attributes
                                        ? kDrawImageLatticeWithPaintFlags
                                        : kDrawImageLatticeFlags;
  AccumulateRect(dst, flags);
}
void DisplayListBoundsCalculator::drawAtlas(const sk_sp<SkImage> atlas,
                                            const SkRSXform xform[],
                                            const SkRect tex[],
                                            const SkColor colors[],
                                            int count,
                                            SkBlendMode mode,
                                            const SkSamplingOptions& sampling,
                                            const SkRect* cullRect,
                                            bool render_with_attributes) {
  SkPoint quad[4];
  BoundsAccumulator atlasBounds;
  for (int i = 0; i < count; i++) {
    const SkRect& src = tex[i];
    xform[i].toQuad(src.width(), src.height(), quad);
    for (int j = 0; j < 4; j++) {
      atlasBounds.accumulate(quad[j]);
    }
  }
  if (atlasBounds.is_not_empty()) {
    DisplayListAttributeFlags flags = render_with_attributes  //
                                          ? kDrawAtlasWithPaintFlags
                                          : kDrawAtlasFlags;
    AccumulateRect(atlasBounds.bounds(), flags);
  }
}
void DisplayListBoundsCalculator::drawPicture(const sk_sp<SkPicture> picture,
                                              const SkMatrix* pic_matrix,
                                              bool render_with_attributes) {
  // TODO(flar) cull rect really cannot be trusted in general, but it will
  // work for SkPictures generated from our own PictureRecorder or any
  // picture captured with an SkRTreeFactory or accurate bounds estimate.
  SkRect bounds = picture->cullRect();
  if (pic_matrix) {
    pic_matrix->mapRect(&bounds);
  }
  DisplayListAttributeFlags flags = render_with_attributes  //
                                        ? kDrawPictureWithPaintFlags
                                        : kDrawPictureFlags;
  AccumulateRect(bounds, flags);
}
void DisplayListBoundsCalculator::drawDisplayList(
    const sk_sp<DisplayList> display_list) {
  AccumulateRect(display_list->bounds(), kDrawDisplayListFlags);
}
void DisplayListBoundsCalculator::drawTextBlob(const sk_sp<SkTextBlob> blob,
                                               SkScalar x,
                                               SkScalar y) {
  AccumulateRect(blob->bounds().makeOffset(x, y), kDrawTextBlobFlags);
}
void DisplayListBoundsCalculator::drawShadow(const SkPath& path,
                                             const SkColor color,
                                             const SkScalar elevation,
                                             bool transparent_occluder,
                                             SkScalar dpr) {
  SkRect shadow_bounds =
      PhysicalShapeLayer::ComputeShadowBounds(path, elevation, dpr, matrix());
  AccumulateRect(shadow_bounds, kDrawShadowFlags);
}

bool DisplayListBoundsCalculator::ComputeFilteredBounds(SkRect& bounds,
                                                        SkImageFilter* filter) {
  if (filter) {
    if (!filter->canComputeFastBounds()) {
      return false;
    }
    bounds = filter->computeFastBounds(bounds);
  }
  return true;
}

bool DisplayListBoundsCalculator::AdjustBoundsForPaint(
    SkRect& bounds,
    DisplayListAttributeFlags flags) {
  if (flags.ignores_paint()) {
    return true;
  }

  if (flags.is_geometric()) {
    // Path effect occurs before stroking...
    DisplayListSpecialGeometryFlags special_flags =
        flags.WithPathEffect(path_effect_);
    if (path_effect_) {
      SkPaint p;
      p.setPathEffect(path_effect_);
      if (!p.canComputeFastBounds()) {
        return false;
      }
      bounds = p.computeFastBounds(bounds, &bounds);
    }

    if (flags.is_stroked(style_)) {
      // Determine the max multiplier to the stroke width first.
      SkScalar pad = 1.0f;
      if (join_is_miter_ && special_flags.may_have_acute_joins()) {
        pad = std::max(pad, miter_limit_);
      }
      if (cap_is_square_ && special_flags.may_have_diagonal_caps()) {
        pad = std::max(pad, SK_ScalarSqrt2);
      }
      pad *= half_stroke_width_;
      bounds.outset(pad, pad);
    }
  }

  if (flags.applies_mask_filter()) {
    if (mask_filter_) {
      SkPaint p;
      p.setMaskFilter(mask_filter_);
      if (!p.canComputeFastBounds()) {
        return false;
      }
      bounds = p.computeFastBounds(bounds, &bounds);
    }
    if (mask_sigma_pad_ > 0.0f) {
      bounds.outset(mask_sigma_pad_, mask_sigma_pad_);
    }
  }

  if (flags.applies_image_filter()) {
    return ComputeFilteredBounds(bounds, image_filter_.get());
  }

  return true;
}

void DisplayListBoundsCalculator::AccumulateUnbounded() {
  if (has_clip()) {
    accumulator_->accumulate(clip_bounds());
  } else {
    layer_infos_.back()->set_unbounded();
  }
}
void DisplayListBoundsCalculator::AccumulateRect(
    SkRect& rect,
    DisplayListAttributeFlags flags) {
  if (AdjustBoundsForPaint(rect, flags)) {
    matrix().mapRect(&rect);
    if (!has_clip() || rect.intersect(clip_bounds())) {
      accumulator_->accumulate(rect);
    }
  } else {
    AccumulateUnbounded();
  }
}

bool DisplayListBoundsCalculator::paint_nops_on_transparency() {
  // SkImageFilter::canComputeFastBounds tests for transparency behavior
  // This test assumes that the blend mode checked down below will
  // NOP on transparent black.
  if (image_filter_ && !image_filter_->canComputeFastBounds()) {
    return false;
  }

  // We filter the transparent black that is used for the background of a
  // saveLayer and make sure it returns transparent black. If it does, then
  // the color filter will leave all area surrounding the contents of the
  // save layer untouched out to the edge of the output surface.
  // This test assumes that the blend mode checked down below will
  // NOP on transparent black.
  if (color_filter_ &&
      color_filter_->filterColor(SK_ColorTRANSPARENT) != SK_ColorTRANSPARENT) {
    return false;
  }

  if (!blend_mode_) {
    return false;  // can we query other blenders for this?
  }
  // Unusual blendmodes require us to process a saved layer
  // even with operations outisde the clip.
  // For example, DstIn is used by masking layers.
  // https://code.google.com/p/skia/issues/detail?id=1291
  // https://crbug.com/401593
  switch (blend_mode_.value()) {
    // For each of the following transfer modes, if the source
    // alpha is zero (our transparent black), the resulting
    // blended pixel is not necessarily equal to the original
    // destination pixel.
    // Mathematically, any time in the following equations where
    // the result is not d assuming source is 0
    case SkBlendMode::kClear:     // r = 0
    case SkBlendMode::kSrc:       // r = s
    case SkBlendMode::kSrcIn:     // r = s * da
    case SkBlendMode::kDstIn:     // r = d * sa
    case SkBlendMode::kSrcOut:    // r = s * (1-da)
    case SkBlendMode::kDstATop:   // r = d*sa + s*(1-da)
    case SkBlendMode::kModulate:  // r = s*d
      return false;
      break;

    // And in these equations, the result must be d if the
    // source is 0
    case SkBlendMode::kDst:         // r = d
    case SkBlendMode::kSrcOver:     // r = s + (1-sa)*d
    case SkBlendMode::kDstOver:     // r = d + (1-da)*s
    case SkBlendMode::kDstOut:      // r = d * (1-sa)
    case SkBlendMode::kSrcATop:     // r = s*da + d*(1-sa)
    case SkBlendMode::kXor:         // r = s*(1-da) + d*(1-sa)
    case SkBlendMode::kPlus:        // r = min(s + d, 1)
    case SkBlendMode::kScreen:      // r = s + d - s*d
    case SkBlendMode::kOverlay:     // multiply or screen, depending on dest
    case SkBlendMode::kDarken:      // rc = s + d - max(s*da, d*sa),
                                    // ra = kSrcOver
    case SkBlendMode::kLighten:     // rc = s + d - min(s*da, d*sa),
                                    // ra = kSrcOver
    case SkBlendMode::kColorDodge:  // brighten destination to reflect source
    case SkBlendMode::kColorBurn:   // darken destination to reflect source
    case SkBlendMode::kHardLight:   // multiply or screen, depending on source
    case SkBlendMode::kSoftLight:   // lighten or darken, depending on source
    case SkBlendMode::kDifference:  // rc = s + d - 2*(min(s*da, d*sa)),
                                    // ra = kSrcOver
    case SkBlendMode::kExclusion:   // rc = s + d - two(s*d), ra = kSrcOver
    case SkBlendMode::kMultiply:    // r = s*(1-da) + d*(1-sa) + s*d
    case SkBlendMode::kHue:         // ra = kSrcOver
    case SkBlendMode::kSaturation:  // ra = kSrcOver
    case SkBlendMode::kColor:       // ra = kSrcOver
    case SkBlendMode::kLuminosity:  // ra = kSrcOver
      return true;
      break;
  }
}

}  // namespace flutter

redpajama_set_name: RedPajamaGithub


text:
Please see http://www.dumaisnet.ca/index.php?article=c3db6d72f1dd661d22f36ea2f76da041 for usage examples

This project requires my "json" library.
You must clone the json library in the parent folder of the rest library


text:
package com.amazonaws.services.sagemaker.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.sagemaker.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * BlueGreenUpdatePolicy JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BlueGreenUpdatePolicyJsonUnmarshaller implements Unmarshaller<BlueGreenUpdatePolicy, JsonUnmarshallerContext> {

    public BlueGreenUpdatePolicy unmarshall(JsonUnmarshallerContext context) throws Exception {
        BlueGreenUpdatePolicy blueGreenUpdatePolicy = new BlueGreenUpdatePolicy();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("TrafficRoutingConfiguration", targetDepth)) {
                    context.nextToken();
                    blueGreenUpdatePolicy.setTrafficRoutingConfiguration(TrafficRoutingConfigJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("TerminationWaitInSeconds", targetDepth)) {
                    context.nextToken();
                    blueGreenUpdatePolicy.setTerminationWaitInSeconds(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("MaximumExecutionTimeoutInSeconds", targetDepth)) {
                    context.nextToken();
                    blueGreenUpdatePolicy.setMaximumExecutionTimeoutInSeconds(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return blueGreenUpdatePolicy;
    }

    private static BlueGreenUpdatePolicyJsonUnmarshaller instance;

    public static BlueGreenUpdatePolicyJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new BlueGreenUpdatePolicyJsonUnmarshaller();
        return instance;
    }
}


text:
package io.craigmiller160.locus.otherview;

import io.craigmiller160.locus.annotations.LView;

/**
 * A second view in a separate package. Used
 * primarily for testing the validation
 * logic, since it has a method that
 * should register as a duplicate with
 * ViewOne.
 *
 * Created by craigmiller on 3/19/16.
 */
@LView
public class ViewTwo {

    private String firstField;

    public String getFirstField() {
        return firstField;
    }

    public void setFirstField(String firstField) {
        this.firstField = firstField;
    }
}


text:
package org.axonframework.test.saga;

import org.axonframework.deadline.DeadlineManager;
import org.axonframework.deadline.annotation.DeadlineHandler;
import org.axonframework.eventhandling.Timestamp;
import org.axonframework.modelling.saga.EndSaga;
import org.axonframework.modelling.saga.SagaEventHandler;
import org.axonframework.modelling.saga.StartSaga;
import org.axonframework.test.AxonAssertionError;
import org.junit.jupiter.api.*;

import java.time.Duration;
import java.time.Instant;

import static org.axonframework.deadline.GenericDeadlineMessage.asDeadlineMessage;
import static org.axonframework.test.matchers.Matchers.*;
import static org.junit.jupiter.api.Assertions.*;

/**
 * Test class intended to validate all methods in regards to scheduling and validating deadlines.
 *
 * @author Milan Savic
 * @author Steven van Beelen
 */
class FixtureTest_Deadlines {

    private static final String AGGREGATE_ID = "id";
    private static final TriggerSagaStartEvent START_SAGA_EVENT = new TriggerSagaStartEvent(AGGREGATE_ID);
    private static final int TRIGGER_DURATION_MINUTES = 10;
    private static final String DEADLINE_NAME = "deadlineName";
    private static final String DEADLINE_PAYLOAD = "deadlineDetails";
    private static final String NONE_OCCURRING_DEADLINE_PAYLOAD = "none-occurring-deadline";

    private SagaTestFixture<MySaga> fixture;

    @BeforeEach
    void setUp() {
        fixture = new SagaTestFixture<>(MySaga.class);
    }

    @Test
    void expectScheduledDeadline() {
        fixture.givenNoPriorActivity()
               .whenAggregate(AGGREGATE_ID)
               .publishes(START_SAGA_EVENT)
               .expectActiveSagas(1)
               .expectScheduledDeadline(Duration.ofMinutes(TRIGGER_DURATION_MINUTES), DEADLINE_PAYLOAD)
               .expectNoScheduledEvents();
    }

    @Test
    void expectScheduledDeadlineOfType() {
        fixture.givenNoPriorActivity()
               .whenAggregate(AGGREGATE_ID)
               .publishes(START_SAGA_EVENT)
               .expectActiveSagas(1)
               .expectScheduledDeadlineOfType(Duration.ofMinutes(TRIGGER_DURATION_MINUTES), String.class)
               .expectNoScheduledEvents();
    }

    @Test
    void expectScheduledDeadlineWithName() {
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenAggregate(AGGREGATE_ID)
               .publishes(new PayloadlessDeadlineShouldBeSetEvent(AGGREGATE_ID))
               .expectScheduledDeadlineWithName(Duration.ofMinutes(TRIGGER_DURATION_MINUTES), "payloadless-deadline");
    }

    @Test
    void expectNoScheduledDeadline() {
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenPublishingA(new ResetTriggerEvent(AGGREGATE_ID))
               .expectActiveSagas(1)
               .expectNoScheduledDeadline(Duration.ofMinutes(TRIGGER_DURATION_MINUTES), DEADLINE_PAYLOAD)
               .expectNoScheduledEvents();
    }

    @Test
    void expectNoScheduledDeadlineOfType() {
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenPublishingA(new ResetTriggerEvent(AGGREGATE_ID))
               .expectActiveSagas(1)
               .expectNoScheduledDeadlineOfType(Duration.ofMinutes(TRIGGER_DURATION_MINUTES), String.class)
               .expectNoScheduledEvents();
    }

    @Test
    void expectNoScheduledDeadlineWithName() {
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenPublishingA(new ResetTriggerEvent(AGGREGATE_ID))
               .expectActiveSagas(1)
               .expectNoScheduledDeadlineWithName(Duration.ofMinutes(TRIGGER_DURATION_MINUTES), DEADLINE_NAME)
               .expectNoScheduledEvents();
    }

    @Test
    void deadlineMetMatching() {
        //noinspection deprecation
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1))
               .expectActiveSagas(1)
               .expectDeadlinesMetMatching(payloadsMatching(exactSequenceOf(equalTo(DEADLINE_PAYLOAD))))
               .expectNoScheduledEvents();
    }

    @Test
    void triggeredDeadlinesMatching() {
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1))
               .expectActiveSagas(1)
               .expectTriggeredDeadlinesMatching(payloadsMatching(exactSequenceOf(equalTo(DEADLINE_PAYLOAD))))
               .expectNoScheduledEvents();
    }

    @Test
    void deadlineMet() {
        //noinspection deprecation
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1))
               .expectActiveSagas(1)
               .expectDeadlinesMet(DEADLINE_PAYLOAD)
               .expectNoScheduledEvents();
    }

    @Test
    void triggeredDeadlines() {
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1))
               .expectActiveSagas(1)
               .expectTriggeredDeadlines(DEADLINE_PAYLOAD)
               .expectNoScheduledEvents();
    }

    @Test
    void triggeredDeadlinesFailsForIncorrectDeadlines() {
        FixtureExecutionResult given = fixture.givenAggregate(AGGREGATE_ID)
                                              .published(START_SAGA_EVENT)
                                              .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1));

        AxonAssertionError result = assertThrows(
                AxonAssertionError.class,
                () -> given.expectTriggeredDeadlines(NONE_OCCURRING_DEADLINE_PAYLOAD)
        );

        assertTrue(
                result.getMessage().contains("Expected deadlines were not triggered at the given deadline manager.")
        );
    }

    @Test
    void triggeredDeadlinesFailsForIncorrectNumberOfDeadlines() {
        FixtureExecutionResult given = fixture.givenAggregate(AGGREGATE_ID)
                                              .published(START_SAGA_EVENT)
                                              .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1));

        AxonAssertionError result = assertThrows(
                AxonAssertionError.class,
                () -> given.expectTriggeredDeadlines(DEADLINE_PAYLOAD, NONE_OCCURRING_DEADLINE_PAYLOAD)
        );

        assertTrue(result.getMessage().contains("Got wrong number of triggered deadlines."));
    }

    @Test
    void triggeredDeadlinesWithName() {
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1))
               .expectActiveSagas(1)
               .expectTriggeredDeadlinesWithName(DEADLINE_NAME)
               .expectNoScheduledEvents();
    }

    @Test
    void triggeredDeadlinesWithNameFailsForIncorrectDeadlines() {
        FixtureExecutionResult given = fixture.givenAggregate(AGGREGATE_ID)
                                              .published(START_SAGA_EVENT)
                                              .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1));
        AxonAssertionError result = assertThrows(
                AxonAssertionError.class,
                () -> given.expectTriggeredDeadlinesWithName(NONE_OCCURRING_DEADLINE_PAYLOAD)
        );

        assertTrue(
                result.getMessage().contains("Expected deadlines were not triggered at the given deadline manager.")
        );
    }

    @Test
    void triggeredDeadlinesWithNameFailsForIncorrectNumberOfDeadlines() {
        FixtureExecutionResult given = fixture.givenAggregate(AGGREGATE_ID)
                                              .published(START_SAGA_EVENT)
                                              .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1));

        AxonAssertionError result = assertThrows(
                AxonAssertionError.class,
                () -> given.expectTriggeredDeadlinesWithName(DEADLINE_NAME, NONE_OCCURRING_DEADLINE_PAYLOAD)
        );

        assertTrue(result.getMessage().contains("Got wrong number of triggered deadlines."));
    }

    @Test
    void triggeredDeadlinesOfType() {
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1))
               .expectActiveSagas(1)
               .expectTriggeredDeadlinesOfType(String.class)
               .expectNoScheduledEvents();
    }

    @Test
    void triggeredDeadlinesOfTypeFailsForIncorrectDeadlines() {
        FixtureExecutionResult given = fixture.givenAggregate(AGGREGATE_ID)
                                              .published(START_SAGA_EVENT)
                                              .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1));

        AxonAssertionError result = assertThrows(
                AxonAssertionError.class,
                () -> given.expectTriggeredDeadlinesOfType(Integer.class)
        );

        assertTrue(
                result.getMessage().contains("Expected deadlines were not triggered at the given deadline manager.")
        );
    }

    @Test
    void triggeredDeadlinesOfTypeFailsForIncorrectNumberOfDeadlines() {
        FixtureExecutionResult given = fixture.givenAggregate(AGGREGATE_ID)
                                              .published(START_SAGA_EVENT)
                                              .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1));

        AxonAssertionError result = assertThrows(
                AxonAssertionError.class,
                () -> given.expectTriggeredDeadlinesOfType(String.class, String.class)
        );

        assertTrue(result.getMessage().contains("Got wrong number of triggered deadlines."));
    }

    @Test
    void deadlineCancelled() {
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenPublishingA(new ResetTriggerEvent(AGGREGATE_ID))
               .expectActiveSagas(1)
               .expectNoScheduledDeadlines()
               .expectNoScheduledEvents();
    }

    @Test
    void deadlineWhichCancelsAll() {
        fixture.givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenPublishingA(new ResetAllTriggeredEvent(AGGREGATE_ID))
               .expectActiveSagas(1)
               .expectNoScheduledDeadlines()
               .expectNoScheduledEvents();
    }

    @Test
    void deadlineDispatchInterceptor() {
        fixture.registerDeadlineDispatchInterceptor(
                messages -> (i, m) -> asDeadlineMessage(m.getDeadlineName(), "fakeDeadlineDetails", m.getTimestamp())
        )
               .givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1))
               .expectActiveSagas(1)
               .expectTriggeredDeadlines("fakeDeadlineDetails")
               .expectNoScheduledEvents();
    }

    @Test
    void deadlineHandlerInterceptor() {
        fixture.registerDeadlineHandlerInterceptor((uow, chain) -> {
            uow.transformMessage(deadlineMessage -> asDeadlineMessage(
                    deadlineMessage.getDeadlineName(), "fakeDeadlineDetails", deadlineMessage.getTimestamp())
            );
            return chain.proceed();
        })
               .givenAggregate(AGGREGATE_ID)
               .published(START_SAGA_EVENT)
               .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1))
               .expectActiveSagas(1)
               .expectTriggeredDeadlines("fakeDeadlineDetails")
               .expectNoScheduledEvents();
    }

    @Test
    void deadlineHandlerEndsSagaLifecycle() {
        fixture.givenAggregate(AGGREGATE_ID)
               .published(new TriggerSagaStartEvent(AGGREGATE_ID, "sagaEndingDeadline"))
               .whenTimeElapses(Duration.ofMinutes(TRIGGER_DURATION_MINUTES + 1))
               .expectActiveSagas(0);
    }

    private static class ResetAllTriggeredEvent {

        private final String identifier;

        private ResetAllTriggeredEvent(String identifier) {
            this.identifier = identifier;
        }

        public String getIdentifier() {
            return identifier;
        }
    }

    private static class PayloadlessDeadlineShouldBeSetEvent {

        private final String identifier;

        private PayloadlessDeadlineShouldBeSetEvent(String identifier) {
            this.identifier = identifier;
        }

        public String getIdentifier() {
            return identifier;
        }
    }

    @SuppressWarnings("unused")
    public static class MySaga {

        private String deadlineId;
        private String deadlineName;

        @StartSaga
        @SagaEventHandler(associationProperty = "identifier")
        public void on(TriggerSagaStartEvent event, @Timestamp Instant timestamp, DeadlineManager deadlineManager) {
            deadlineName = event.getDeadlineName();
            deadlineId = deadlineManager.schedule(
                    Duration.ofMinutes(TRIGGER_DURATION_MINUTES), deadlineName, DEADLINE_PAYLOAD
            );
        }

        @SagaEventHandler(associationProperty = "identifier")
        public void on(ResetTriggerEvent event, DeadlineManager deadlineManager) {
            deadlineManager.cancelSchedule(deadlineName, deadlineId);
        }

        @SagaEventHandler(associationProperty = "identifier")
        public void on(ResetAllTriggeredEvent event, DeadlineManager deadlineManager) {
            deadlineManager.cancelAll(deadlineName);
        }

        @SagaEventHandler(associationProperty = "identifier")
        public void on(PayloadlessDeadlineShouldBeSetEvent event, DeadlineManager deadlineManager) {
            deadlineManager.schedule(Duration.ofMinutes(TRIGGER_DURATION_MINUTES), "payloadless-deadline");
        }

        @DeadlineHandler
        public void handleDeadline(String deadlineInfo) {
            // Nothing to be done for test purposes, having this deadline handler invoked is sufficient
        }

        @DeadlineHandler(deadlineName = "payloadless-deadline")
        public void handle() {
            // Nothing to be done for test purposes, having this deadline handler invoked is sufficient
        }

        @EndSaga
        @DeadlineHandler(deadlineName = "sagaEndingDeadline")
        public void sagaEndingDeadline() {
        }
    }
}


text:
header.shrink {
    background-image: url("../images/bkd_header_index.jpg");
}

a.gameLinks:link {
    color: #fff2f2;
    text-decoration: underline;
}

a.gameLinks:visited {
    color: #fff2f2;
}

a.gameLinks:hover {
    color: white;
    text-shadow: 0px 0px 5px #1bd6d8;
    text-decoration: none;
}

a.gameLinks:active {
    text-decoration: underline;
}

a.visualLinks:link {
    color: #fff2f2;
    text-decoration: underline;
}

a.visualLinks:visited {
    color: #fff2f2;
}

a.visualLinks:hover {
    color: white;
    text-shadow: 0px 0px 5px #e014bc;
    text-decoration: none;
}

a.visualLinks:active {
    text-decoration: underline;
}

/*a.blogLinks:link {
    color: #fff2f2;
    text-decoration: underline;
}

a.blogLinks:visited {
    color: #fff2f2;
}

a.blogLinks:hover {
    color: white;
    text-shadow: 0px 0px 5px white;
    text-decoration: none;
}*/

a.gameLinks:active {
    text-decoration: underline;
}

body{
    background: black url("../images/bkd_index_main.jpg") no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

section{
    position: relative;
    float: right;
    height: auto;
    width: 370px;
    margin: 30px;
}

.cyanBorder{
    overflow: hidden;
    max-height: 500px;
    max-width: 960px;
    height: auto;
    width: 960px;
    margin-bottom: 10px;
    padding-left: 0px;
    border-radius: 3px;
    background-image: url('../images/bkd_game_sections.png');
    -webkit-transition: all 0.8s ease-in-out;
    -moz-transition: all 0.8s ease-in-out;
    -ms-transition: all 0.8s ease-in-out;
    -o-transition: all 0.8s ease-in-out;
    transition: all 0.8s ease-in-out;
    font-family: "Trebuchet MS", Helvetica, sans-serif;
    font-size: 16px;
    color: #fff2f2;
}

.magentaBorder{
    margin-bottom: 10px;
    height: auto;
    width: 960px;
    max-height: 700px;
    max-width: 960px;
    border-radius: 3px;
    overflow: hidden;
    -webkit-transition: all 0.8s ease-in-out;
    -moz-transition: all 0.8s ease-in-out;
    -ms-transition: all 0.8s ease-in-out;
    -o-transition: all 0.8s ease-in-out;
    transition: all 0.8s ease-in-out;
    font-family: "Trebuchet MS", Helvetica, sans-serif;
    font-size: 16px;
    color: #fff2f2;
    background-image: url("../images/bkd_visual_sections.png");
}

.video{
    position: relative;
    float: right;
    margin: 30px 0px 30px 30px;
}

.thumbnail{
    position: relative;
    float: right;
    background-position: 0px -330px;
    border-radius: 3px;
    height: 280px;
    width: 500px;
    margin: 30px 0px 30px 30px;
    -webkit-transition: background-position 0.5s ease-in-out;
    -moz-transition: background-position 0.5s ease-in-out;
    -ms-transition: background-position 0.5s ease-in-out;
    -o-transition: background-position 0.5s ease-in-out;
    transition: background-position 0.5s ease-in-out;
}

/*#gdImage{
    position: relative;
    width: 630px;
    height: 70px;
    margin: 0px auto 0px auto;
    padding: 0px;
    background-image: url(../images/bkd_index_games.png);
    background-size: 630px, 70px;
    border-radius: 3px;
    background-repeat: no-repeat;
    -webkit-transition: all 0.3s ease-in-out;
    -moz-transition: all 0.3s ease-in-out;
    -ms-transition: all 0.3s ease-in-out;
    -o-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
}

#gdImage:hover{
    background-image: url(../images/bkd_index_games_text.png);
    height: 185.5px;
    background-size: 630px, 185.5px;
    background-repeat: no-repeat;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -ms-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

#vmImage{
    position: relative;
    width: 630px;
    height: 70px;
    margin: 15px auto 0px auto;
    background-image: url(../images/bkd_index_visuals.png);
    background-size: 630px, 70px;
    border-radius: 3px;
    background-repeat: no-repeat;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -ms-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

#vmImage:hover{
    background-image: url(../images/bkd_index_visuals_text.png);
    height: 185.5px;
    background-size: 630px, 185.5px;
    background-repeat: no-repeat;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -ms-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

#blogImage {
    position: relative;
    width: 630px;
    height: 70px;
    margin: 15px auto 0px auto;
    background-image: url(../images/bkd_index_blog.png);
    background-size: 630px, 70px;
    border-radius: 3px;
    background-repeat: no-repeat;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -ms-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

#blogImage:hover{
    background-image: url(../images/bkd_index_blog_text.png);
    height: 185.5px;
    background-size: 630px, 185.5px;
    background-repeat: no-repeat;
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -ms-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

.overlay{
    position: absolute;
    width: 250px;
    height: 250px;
    padding: 30px;
    background: rgba(0, 0, 0, 0.9);
    opacity: 0;
    border-radius: 3px;
    cursor: default;
    font-family: "Trebuchet MS", Helvetica, sans-serif;
    font-size: 15.7px;
    color: #fff2f2;
    text-align: left;
    -webkit-transition: all 0.4s ease-in-out;
    -moz-transition: all 0.4s ease-in-out;
    -ms-transition: all 0.4s ease-in-out;
    -o-transition: all 0.4s ease-in-out;
    transition: all 0.4s ease-in-out;
}

.overlay.show{
    opacity: 1;
}

.overlay a:link{
    text-decoration: none;
}

.overlay p{
    text-shadow: none;
}

#projects{
    position: relative;
    width: 560px;
    height: auto;
    margin: 15px auto 0px auto;
    padding: 30px;
    border-radius: 5px;
    font-family: "Trebuchet MS", Helvetica, sans-serif;
    font-size: 15.7px;
    color: #fff2f2;
    background: rgba(0, 0, 0, 0.6);
}
*/


text:
var ko = require('knockout'),
    payment = require('jquery.payment'),
    $ = null,
    stripe = null;

if (typeof(window) == 'undefined') {
    $ = require('jquery');
}
else {
    $ = window.$;
}

// TODO stripe doesn't support loading locally very well, do they?
if (typeof(window) != 'undefined' && typeof(window.Stripe) != 'undefined') {
    stripe = window.Stripe || {};
}

function PaymentView (config) {
    var self = this,
        config = config || {};

    // Config
    stripe.publishableKey = self.stripe_key = config.key;
    self.form = config.form;

    // Credit card parameters
    self.cc_number = ko.observable(null);
    self.cc_expiry = ko.observable(null);
    self.cc_cvv = ko.observable(null);
    self.cc_error_number = ko.observable(null);
    self.cc_error_expiry = ko.observable(null);
    self.cc_error_cvv = ko.observable(null);

    // Credit card validation
    self.initialize_form();

    // Outputs
    self.error = ko.observable(null);

    // Process form inputs and send API request to Stripe. Using jquery.payment
    // for some validation, display field errors and some generic errors.
    self.process_form = function () {
        var expiry = $.payment.cardExpiryVal(self.cc_expiry()),
            card = {
                number: self.cc_number(),
                exp_month: expiry.month,
                exp_year: expiry.year,
                cvc: self.cc_cvv()
            };

        self.error(null);
        self.cc_error_number(null);
        self.cc_error_expiry(null);
        self.cc_error_cvv(null);

        if (!$.payment.validateCardNumber(card.number)) {
            self.cc_error_number('Invalid card number');
            console.log(card);
            return false;
        }
        if (!$.payment.validateCardExpiry(card.exp_month, card.exp_year)) {
            self.cc_error_expiry('Invalid expiration date');
            return false;
        }
        if (!$.payment.validateCardCVC(card.cvc)) {
            self.cc_error_cvv('Invalid security code');
            return false;
        }

        stripe.createToken(card, function(status, response) {
            if (status === 200) {
                // Update form fields that are actually sent to
                var cc_last_digits = self.form.find('#id_last_4_digits'),
                    token = self.form.find('#id_stripe_id,#id_stripe_token');
                cc_last_digits.val(response.card.last4);
                token.val(response.id);
                self.form.submit();
            }
            else {
                self.error(response.error.message);
            }
        });
    };
}

PaymentView.prototype.initialize_form = function () {
    var cc_number = $('input#cc-number'),
        cc_cvv = $('input#cc-cvv'),
        cc_expiry = $('input#cc-expiry');

    cc_number.payment('formatCardNumber');
    cc_expiry.payment('formatCardExpiry');
    cc_cvv.payment('formatCardCVC');
};

PaymentView.init = function (config, obj) {
    var view = new GoldView(config),
        obj = obj || $('#payment-form')[0];
    ko.applyBindings(view, obj);
    return view;
}

module.exports.PaymentView = PaymentView;

if (typeof(window) != 'undefined') {
    window.payment = module.exports;
}


text:
{% extends "careers/jobpost_list.html" %}
{% load mezzanine_tags keyword_tags i18n %}

{% block meta_title %}{{ jobpost.meta_title }}{% endblock %}

{% block meta_keywords %}{% metablock %}
{% keywords_for jobpost as tags %}
{% for tag in tags %}{% if not forloop.first %}, {% endif %}{{ tag }}{% endfor %}
{% endmetablock %}{% endblock %}

{% block meta_description %}{% metablock %}
{{ jobpost.description }}
{% endmetablock %}{% endblock %}

{% block title %}
{% editable jobpost.title %}{{ jobpost.title }}{% endeditable %}
{% endblock %}

{% block breadcrumb_menu %}
{{ block.super }}

{{ jobpost.title }}

{% endblock %}

{% block main %}

    {% trans "Posted" %} {{ jobpost.publish_date|timesince }} {% trans "ago" %}.

{% editable jobpost.content %}
{{ jobpost.content|richtext_filter|safe }}
{% endeditable %}

{% keywords_for jobpost as tags %}
{% if tags %}
{% spaceless %}

{% trans "Tags" %}:

    {% for tag in tags %}

{{ tag }}

    {% endfor %}

{% endspaceless %}
{% endif %}

{% set_short_url_for jobpost %}
{% trans "Share on Twitter" %}
{% trans "Share on Facebook" %}

{% endblock %}


text:
package models

import java.util.UUID
import play.api.Play
import play.api.db.slick.DatabaseConfigProvider
import scala.concurrent.Future
import slick.driver.JdbcProfile
import slick.driver.H2Driver.api._
//import slick.driver.MySQLDriver.api._
import scala.concurrent.ExecutionContext.Implicits.global
import slick.lifted.ProvenShape.proveShapeOf
import models.daos._

case class DBUserRole (
  userID: String,
  role: String
)

case class UserRole (
  userID: String,
  role: String
)

class DBUserRoles(tag: Tag) extends Table[DBUserRole](tag, "userrole") {
  def userID = column[String]("userID", O.PrimaryKey)
  def role = column[String]("role")
  override def * = (userID, role) <> (DBUserRole.tupled, DBUserRole.unapply)
}

object Userroles {

  val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current)

  val slickUsersRole = TableQuery[DBUserRoles]

  def add(role: DBUserRole): Future[String] = {
    dbConfig.db.run(slickUsersRole += role).map(res => "successfully").recover {
      case ex: Exception => ex.getCause.getMessage
    }
  }

  def delete(userID: String): Future[Int] = {
    dbConfig.db.run(slickUsersRole.filter(_.userID === userID).delete)
  }

  def get(userID: String): Future[Option[DBUserRole]] = {
    dbConfig.db.run(slickUsersRole.filter(_.userID === userID).result.headOption)
  }

  def listAll: Future[Seq[DBUserRole]] = {
    dbConfig.db.run(slickUsersRole.result)
  }

  def update(id : String): Future[String] = {
    val db = DBUserRole(
      userID = id,
      role = "นักศึกษาโปรเจค"
    )
    dbConfig.db.run(slickUsersRole.filter(_.userID === id).update(db)).map(res => "successfully").recover {
      case ex: Exception => ex.getCause.getMessage
    }
  }

  def updateRole(id : String): Future[String] = {
    val db = DBUserRole(
      userID = id,
      role = "นักศึกษา"
    )
    dbConfig.db.run(slickUsersRole.filter(_.userID === id).update(db)).map(res => "successfully").recover {
      case ex: Exception => ex.getCause.getMessage
    }
  }
}


text:
layout: page
title: About
permalink: /about/
published: true
---

# Stormtrooper

Welcome to my blog!

### Contact me


text:
.mcrb_inBox { width:60em; }
.mcrb_charButton { font-family:monospace; }


text:
package org.smartdeveloperhub.curator.protocol;

import java.util.UUID;

import org.joda.time.DateTime;

public interface Message {

	UUID messageId();

	DateTime submittedOn();

	Agent submittedBy();

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Free.Dolphin.Common
{
    public enum RedisColumnType
    {
        RedisKey,
        RedisScore,
        RedisColumn
    }
}


text:
package models

// Site represents a group for tracking data
type Site struct {
	ID         int64  `db:"id" json:"id"`
	TrackingID string `db:"tracking_id" json:"trackingId"`
	Name       string `db:"name" json:"name"`
}


text:
package org.apache.camel.component.kubernetes.customresources;

import java.util.Map;

import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext;
import io.fabric8.kubernetes.client.dsl.internal.RawCustomResourceOperationsImpl;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.component.kubernetes.AbstractKubernetesEndpoint;
import org.apache.camel.component.kubernetes.KubernetesConstants;
import org.apache.camel.component.kubernetes.KubernetesOperations;
import org.apache.camel.support.DefaultProducer;
import org.apache.camel.support.MessageHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KubernetesCustomResourcesProducer extends DefaultProducer {

    private static final Logger LOG = LoggerFactory.getLogger(KubernetesCustomResourcesProducer.class);

    public KubernetesCustomResourcesProducer(AbstractKubernetesEndpoint endpoint) {
        super(endpoint);
    }

    @Override
    public AbstractKubernetesEndpoint getEndpoint() {
        return (AbstractKubernetesEndpoint) super.getEndpoint();
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        String operation;
        String namespace;

        if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getOperation())) {
            operation = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_OPERATION, String.class);
        } else {
            operation = getEndpoint().getKubernetesConfiguration().getOperation();
        }
        if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getNamespace())) {
            namespace = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, String.class);
        } else {
            namespace = getEndpoint().getKubernetesConfiguration().getNamespace();
        }
        if (ObjectHelper.isEmpty(namespace)) {
            throw new IllegalArgumentException("Custom Resource producer requires a namespace argument");
        }

        switch (operation) {

            case KubernetesOperations.LIST_CUSTOMRESOURCES:
                doList(exchange, operation, namespace);
                break;

            case KubernetesOperations.LIST_CUSTOMRESOURCES_BY_LABELS_OPERATION:
                doListByLabels(exchange, operation, namespace);
                break;

            case KubernetesOperations.GET_CUSTOMRESOURCE:
                doGet(exchange, operation, namespace);
                break;

            case KubernetesOperations.DELETE_CUSTOMRESOURCE:
                doDelete(exchange, operation, namespace);
                break;

            case KubernetesOperations.CREATE_CUSTOMRESOURCE:
                doCreate(exchange, operation, namespace);
                break;

            default:
                throw new IllegalArgumentException("Unsupported operation " + operation);
        }
    }

    protected void doList(Exchange exchange, String operation, String namespaceName) throws Exception {
        JsonObject customResourcesListJSON = new JsonObject(
                getEndpoint().getKubernetesClient().customResource(getCRDContext(exchange.getIn())).list(namespaceName));
        if (LOG.isDebugEnabled()) {
            LOG.debug(customResourcesListJSON.toString());
        }

        JsonArray customResourcesListItems;
        if (customResourcesListJSON.getCollection("items") != null) {
            customResourcesListItems = new JsonArray(customResourcesListJSON.getCollection("items"));
        } else {
            customResourcesListItems = new JsonArray();
        }

        MessageHelper.copyHeaders(exchange.getIn(), exchange.getOut(), true);
        exchange.getOut().setBody(customResourcesListItems);
    }

    protected void doListByLabels(Exchange exchange, String operation, String namespaceName) throws Exception {
        Map<String, String> labels = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CRD_LABELS, Map.class);
        JsonObject customResourcesListJSON = new JsonObject(
                getEndpoint().getKubernetesClient().customResource(getCRDContext(exchange.getIn())).list(namespaceName,
                        labels));
        if (LOG.isDebugEnabled()) {
            LOG.debug(customResourcesListJSON.toString());
        }
        JsonArray customResourcesListItems = new JsonArray(customResourcesListJSON.getCollection("items"));

        MessageHelper.copyHeaders(exchange.getIn(), exchange.getOut(), true);
        exchange.getOut().setBody(customResourcesListItems);
    }

    protected void doGet(Exchange exchange, String operation, String namespaceName) throws Exception {
        String customResourceName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CRD_INSTANCE_NAME, String.class);
        if (ObjectHelper.isEmpty(customResourceName)) {
            throw new IllegalArgumentException("Get a specific Deployment require specify a Deployment name");
        }
        JsonObject customResourceJSON = new JsonObject();
        try {
            customResourceJSON = new JsonObject(
                    getEndpoint().getKubernetesClient().customResource(getCRDContext(exchange.getIn())).get(namespaceName,
                            customResourceName));
        } catch (KubernetesClientException e) {
            if (e.getCode() == 404) {
                LOG.info("Custom resource instance not found", e);
            } else {
                throw e;
            }
        }

        MessageHelper.copyHeaders(exchange.getIn(), exchange.getOut(), true);
        exchange.getOut().setBody(customResourceJSON);
    }

    protected void doDelete(Exchange exchange, String operation, String namespaceName) throws Exception {
        String customResourceName = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CRD_INSTANCE_NAME, String.class);
        if (ObjectHelper.isEmpty(customResourceName)) {
            LOG.error("Delete a specific deployment require specify a deployment name");
            throw new IllegalArgumentException("Delete a specific deployment require specify a deployment name");
        }

        try {
            RawCustomResourceOperationsImpl raw
                    = getEndpoint().getKubernetesClient().customResource(getCRDContext(exchange.getIn()));
            boolean deleted = raw.delete(namespaceName, customResourceName);
            exchange.getMessage().setHeader(KubernetesConstants.KUBERNETES_DELETE_RESULT, deleted);
        } catch (KubernetesClientException e) {
            if (e.getCode() == 404) {
                LOG.info("Custom resource instance not found", e);
            } else {
                throw e;
            }
        }
    }

    protected void doCreate(Exchange exchange, String operation, String namespaceName) throws Exception {
        String customResourceInstance = exchange.getIn().getHeader(KubernetesConstants.KUBERNETES_CRD_INSTANCE, String.class);
        JsonObject gitHubSourceJSON = new JsonObject();
        try {
            gitHubSourceJSON = new JsonObject(
                    getEndpoint().getKubernetesClient().customResource(getCRDContext(exchange.getIn())).create(namespaceName,
                            customResourceInstance));
        } catch (KubernetesClientException e) {
            if (e.getCode() == 409) {
                LOG.info("Custom resource instance already exists", e);
            } else {
                throw e;
            }
        }
        MessageHelper.copyHeaders(exchange.getIn(), exchange.getOut(), true);
        exchange.getOut().setBody(gitHubSourceJSON);
    }

    private CustomResourceDefinitionContext getCRDContext(Message message) {
        String name;
        String group;
        String scope;
        String version;
        String plural;

        if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getCrdName())) {
            name = message.getHeader(KubernetesConstants.KUBERNETES_CRD_NAME, String.class);
        } else {
            name = getEndpoint().getKubernetesConfiguration().getCrdName();
        }
        if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getCrdGroup())) {
            group = message.getHeader(KubernetesConstants.KUBERNETES_CRD_GROUP, String.class);
        } else {
            group = getEndpoint().getKubernetesConfiguration().getCrdGroup();
        }
        if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getCrdScope())) {
            scope = message.getHeader(KubernetesConstants.KUBERNETES_CRD_SCOPE, String.class);
        } else {
            scope = getEndpoint().getKubernetesConfiguration().getCrdScope();
        }
        if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getCrdVersion())) {
            version = message.getHeader(KubernetesConstants.KUBERNETES_CRD_VERSION, String.class);
        } else {
            version = getEndpoint().getKubernetesConfiguration().getCrdVersion();
        }
        if (ObjectHelper.isEmpty(getEndpoint().getKubernetesConfiguration().getCrdPlural())) {
            plural = message.getHeader(KubernetesConstants.KUBERNETES_CRD_PLURAL, String.class);
        } else {
            plural = getEndpoint().getKubernetesConfiguration().getCrdPlural();
        }
        if (ObjectHelper.isEmpty(name) || ObjectHelper.isEmpty(group) || ObjectHelper.isEmpty(scope)
                || ObjectHelper.isEmpty(version) || ObjectHelper.isEmpty(plural)) {
            LOG.error("one of more of the custom resource definition argument(s) are missing.");
            throw new IllegalArgumentException("one of more of the custom resource definition argument(s) are missing.");
        }

        CustomResourceDefinitionContext cRDContext = new CustomResourceDefinitionContext.Builder()
                .withName(message.getHeader(KubernetesConstants.KUBERNETES_CRD_NAME, String.class))       // example: "githubsources.sources.knative.dev"
                .withGroup(message.getHeader(KubernetesConstants.KUBERNETES_CRD_GROUP, String.class))     // example: "sources.knative.dev"
                .withScope(message.getHeader(KubernetesConstants.KUBERNETES_CRD_SCOPE, String.class))     // example: "Namespaced"
                .withVersion(message.getHeader(KubernetesConstants.KUBERNETES_CRD_VERSION, String.class)) // example: "v1alpha1"
                .withPlural(message.getHeader(KubernetesConstants.KUBERNETES_CRD_PLURAL, String.class))   // example: "githubsources"
                .build();
        return cRDContext;
    }
}


text:
package active.since93.recyclerview.audio;

import android.media.MediaPlayer;
import android.os.Handler;

import java.io.IOException;

/**
 * Created by myzupp on 26-02-2017.
 *
 * @author Darshan Parikh (parikhdarshan36@gmail.com)
 */

public class MediaPlayerUtils {

    private static MediaPlayer mediaPlayer;
    private static MediaPlayerUtils.Listener listener;
    private static Handler mHandler;

    /**
     * Get database instance
     * @return database handler instance
     */
    public static void getInstance() {
        if(mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }

        if(mHandler == null) {
            mHandler = new Handler();
        }
    }

    /**
     * Release mediaPlayer
     */
    public static void releaseMediaPlayer() {
        if(mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    public static void pauseMediaPlayer() {
        mediaPlayer.pause();
    }

    public static void playMediaPlayer() {
        mediaPlayer.start();
        mHandler.postDelayed(mRunnable, 100);
    }

    public static void applySeekBarValue(int selectedValue) {
        mediaPlayer.seekTo(selectedValue);
        mHandler.postDelayed(mRunnable, 100);
    }

    /**
     * Start mediaPlayer
     * @param audioUrl sd card media file
     * @throws IOException exception
     */
    public static void startAndPlayMediaPlayer(String audioUrl, final MediaPlayerUtils.Listener listener) throws IOException {
        MediaPlayerUtils.listener = listener;
        getInstance();
        if(isPlaying()) {
            pauseMediaPlayer();
        }
        releaseMediaPlayer();
        getInstance();
        mediaPlayer.setDataSource(audioUrl);
        mediaPlayer.prepare();
        mediaPlayer.setOnCompletionListener(onCompletionListener);

        mHandler.postDelayed(mRunnable, 100);
        playMediaPlayer();
    }

    public static boolean isPlaying() {
        return mediaPlayer != null && mediaPlayer.isPlaying();
    }

    public static int getTotalDuration() {
        return mediaPlayer.getDuration();
    }

    private static MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            MediaPlayerUtils.releaseMediaPlayer();
            listener.onAudioComplete();
        }
    };

    private static Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                if (isPlaying()) {
                    mHandler.postDelayed(mRunnable, 100);
                    listener.onAudioUpdate(mediaPlayer.getCurrentPosition());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    interface Listener {
        void onAudioComplete();
        void onAudioUpdate(int currentPosition);
    }

}


text:
@interface Y9ServiceProxyRequest : NSObject

@property (strong,nonatomic) NSString *token;
@property (strong,nonatomic) NSString  *action;
@property (strong,nonatomic) NSMutableDictionary  *header;
@property (strong,nonatomic) NSMutableDictionary *data;

-(instancetype)initWithAction:(NSString *)action;

@end


text:
#include "avmshell.h"
#include "genericzlib.h"

namespace avmshell
{
	//
	// ByteArray
	//

	ByteArray::ByteArray()
	{
		m_subscriberRoot = NULL;
		m_capacity = 0;
		m_length   = 0;
		m_array    = NULL;
	}

	ByteArray::ByteArray(const ByteArray &lhs)
	{
		m_subscriberRoot = NULL;
		m_array    = new U8[lhs.m_length];
		if (!m_array)
		{
			ThrowMemoryError();
			return;
		}

		m_capacity = lhs.m_length;
		m_length   = lhs.m_length;

		VMPI_memcpy(m_array, lhs.m_array, m_length);
	}

	ByteArray::~ByteArray()
	{
		m_subscriberRoot = NULL;
		if (m_array)
		{
			delete [] m_array;
			m_array = NULL;
		}
		m_capacity = 0;
		m_length = 0;
	}

	void ByteArray::ThrowMemoryError()
	{
		// todo throw out of memory exception
		// m_toplevel->memoryError->throwError(kOutOfMemoryError);
	}

	bool ByteArray::Grow(uint32 minimumCapacity)
	{
		if (minimumCapacity > m_capacity)
		{
			uint32 newCapacity = m_capacity << 1;
			if (newCapacity < minimumCapacity)
			{
				newCapacity = minimumCapacity;
			}
			if (newCapacity < kGrowthIncr)
			{
				newCapacity = kGrowthIncr;
			}
			U8 *newArray = new U8[newCapacity];
			if (!newArray)
			{
				return false;
			}
			if (m_array)
			{
				VMPI_memcpy(newArray, m_array, m_length);
				delete [] m_array;
			}
			VMPI_memset(newArray+m_length, 0, newCapacity-m_capacity);
			m_array = newArray;
			m_capacity = newCapacity;
			NotifySubscribers();
		}
		return true;
	}

	U8 ByteArray::operator[] (uint32 index) const
	{
		if (m_length <= index)
		{
			return 0;
		}
		return m_array[index];
	}

	U8& ByteArray::operator[] (uint32 index)
	{
		if (m_length <= index)
		{
			Grow(index+1);
			m_length = index+1;
			NotifySubscribers();
		}
		return m_array[index];
	}

	void ByteArray::Push(U8 value)
	{
		if (m_length >= m_capacity)
		{
			Grow(m_length + 1);
		}
		m_array[m_length++] = value;
		NotifySubscribers();
	}

	void ByteArray::Push(const U8 *data, uint32 count)
	{
		Grow(m_length + count);
		VMPI_memcpy(m_array + m_length, data, count);
		m_length += count;
		NotifySubscribers();
	}

	void ByteArray::SetLength(uint32 newLength)
	{
 		if(m_subscriberRoot && m_length < Domain::GLOBAL_MEMORY_MIN_SIZE)
 			ThrowMemoryError();
		if (newLength > m_capacity)
		{
			if (!Grow(newLength))
			{
				ThrowMemoryError();
				return;
			}
		}
		m_length = newLength;
		NotifySubscribers();
	}

 	void ByteArray::NotifySubscribers()
 	{
 		SubscriberLink *curLink = m_subscriberRoot;
 		SubscriberLink **prevNext = &m_subscriberRoot;

 		while(curLink != NULL) // notify subscribers
 		{
 			AvmAssert(m_length >= Domain::GLOBAL_MEMORY_MIN_SIZE);

 			Domain *dom = (Domain *)curLink->weakDomain->get();

 			if(dom)
 			{
 				(dom->*(curLink->notify))(m_array, m_length);
 				prevNext = &curLink->next;
 			}
 			else
 				// Domain went away? remove link
 				MMgc::GC::WriteBarrier(prevNext, curLink->next);
 			curLink = curLink->next;
 		}
 	}

 	bool ByteArray::GlobalMemorySubscribe(const Domain *subscriber, GlobalMemoryNotifyFunc notify)
 	{
 		if(m_length >= Domain::GLOBAL_MEMORY_MIN_SIZE)
 		{
 			GlobalMemoryUnsubscribe(subscriber);
			SubscriberLink *newLink = new (MMgc::GC::GetGC(subscriber)) SubscriberLink;
 			newLink->weakDomain = subscriber->GetWeakRef();
 			newLink->notify = notify;
 			MMgc::GC::WriteBarrier(&newLink->next, m_subscriberRoot);
 			MMgc::GC::WriteBarrier(&m_subscriberRoot, newLink);
 			// notify the new "subscriber" of the current state of the world
 			(subscriber->*notify)(m_array, m_length);
 			return true;
 		}
 		return false;
 	}

 	bool ByteArray::GlobalMemoryUnsubscribe(const Domain *subscriber)
 	{
 		SubscriberLink **prevNext = &m_subscriberRoot;
 		SubscriberLink *curLink = m_subscriberRoot;

 		while(curLink)
 		{
 			if(curLink->weakDomain->get() == (MMgc::GCObject *)subscriber)
 			{
 				MMgc::GC::WriteBarrier(prevNext, curLink->next);
 				return true;
 			}
 			prevNext = &curLink->next;
 			curLink = curLink->next;
 		}
 		return false;
	}

	//
	// ByteArrayFile
	//

	ByteArrayFile::ByteArrayFile(Toplevel *toplevel)
		: DataInput(toplevel),
		  DataOutput(toplevel)
	{
		m_filePointer = 0;
	}

	uint32 ByteArrayFile::Available()
	{
		if (m_filePointer <= m_length) {
			return m_length - m_filePointer;
		} else {
			return 0;
		}
	}

	void ByteArrayFile::SetLength(uint32 newLength)
	{
		ByteArray::SetLength(newLength);
		if (m_filePointer > newLength) {
			m_filePointer = newLength;
		}
	}

	void ByteArrayFile::Read(void *buffer, uint32 count)
	{
		CheckEOF(count);

		if (count > 0)
		{
			VMPI_memcpy(buffer, m_array+m_filePointer, count);
			m_filePointer += count;
		}
	}

	void ByteArrayFile::Write(const void *buffer, uint32 count)
	{
		if (m_filePointer+count >= m_length) {
			Grow(m_filePointer+count);
			m_length = m_filePointer+count;
		}
		VMPI_memcpy(m_array+m_filePointer, buffer, count);
		m_filePointer += count;
	}

	//
	// ByteArrayObject
	//

	ByteArrayObject::ByteArrayObject(VTable *ivtable,
									 ScriptObject *delegate)
		: ScriptObject(ivtable, delegate),
		  m_byteArray(toplevel())
	{
		c.set(&m_byteArray, sizeof(ByteArrayFile));
	}

	Atom ByteArrayObject::getUintProperty(uint32 i) const
	{
		if (i < (uint32)m_byteArray.GetLength()) {
			return core()->intToAtom(m_byteArray[i]);
		} else {
			return undefinedAtom;
		}
	}

	void ByteArrayObject::setUintProperty(uint32 i, Atom value)
	{
		m_byteArray[i] = (U8)(AvmCore::integer(value));
	}

	Atom ByteArrayObject::getAtomProperty(Atom name) const
	{
		uint32 index;
		if (AvmCore::getIndexFromAtom(name, &index)) {
			if (index < (uint32) m_byteArray.GetLength()) {
				return core()->intToAtom(m_byteArray[index]);
			} else {
				return undefinedAtom;
			}
		}

		return ScriptObject::getAtomProperty(name);
	}

	void ByteArrayObject::setAtomProperty(Atom name, Atom value)
	{
		uint32 index;
		if (AvmCore::getIndexFromAtom(name, &index)) {
			int intValue = AvmCore::integer(value);
			m_byteArray[index] = (U8)(intValue);
		} else {
			ScriptObject::setAtomProperty(name, value);
		}
	}

	bool ByteArrayObject::hasAtomProperty(Atom name) const
	{
		return ScriptObject::hasAtomProperty(name) || getAtomProperty(name) != undefinedAtom;
	}

	void ByteArrayObject::setLength(uint32 newLength)
	{
		m_byteArray.SetLength(newLength);
	}

	uint32 ByteArrayObject::get_length()
	{
		return m_byteArray.GetLength();
	}

	void ByteArrayObject::set_length(uint32 value)
	{
		setLength(value);
	}

	int ByteArrayObject::get_position()
	{
		return m_byteArray.GetFilePointer();
	}

	int ByteArrayObject::get_bytesAvailable()
	{
		return m_byteArray.Available();
	}

	void ByteArrayObject::set_position(int offset)
	{
		if (offset >= 0) {
			m_byteArray.Seek(offset);
		}
	}

	String* ByteArrayObject::_toString()
	{
		uint8_t *c = (uint8_t*)m_byteArray.GetBuffer();
		uint32 len = m_byteArray.GetLength();

		if (len >= 3)
		{
			// UTF8 BOM
			if ((c[0] == 0xef) && (c[1] == 0xbb) && (c[2] == 0xbf))
			{
				return core()->newStringUTF8((const char*)c + 3, len - 3);
			}
			else if ((c[0] == 0xfe) && (c[1] == 0xff))
			{
				//UTF-16 big endian
				c += 2;
				len = (len - 2) >> 1;
				return core()->newStringEndianUTF16(/*littleEndian*/false, (const wchar*)c, len);
			}
			else if ((c[0] == 0xff) && (c[1] == 0xfe))
			{
				//UTF-16 little endian
				return core()->newStringEndianUTF16(/*littleEndian*/true, (const wchar*)c, len);
			}
		}

		// Use newStringUTF8() with "strict" explicitly set to false to mimick old,
		// buggy behavior, where malformed UTF-8 sequences are stored as single characters.
		return core()->newStringUTF8((const char*)c, len, false);
	}

	int ByteArrayObject::readByte()
	{
		return (signed char)m_byteArray.ReadU8();
	}

	int ByteArrayObject::readUnsignedByte()
	{
		return m_byteArray.ReadU8();
	}

	int ByteArrayObject::readShort()
	{
		return (short)m_byteArray.ReadU16();
	}

	int ByteArrayObject::readUnsignedShort()
	{
		return m_byteArray.ReadU16();
	}

	int ByteArrayObject::readInt()
	{
		return (int)m_byteArray.ReadU32();
	}

	uint32 ByteArrayObject::readUnsignedInt()
	{
		return m_byteArray.ReadU32();
	}

	double ByteArrayObject::readFloat()
	{
		return m_byteArray.ReadFloat();
	}

	double ByteArrayObject::readDouble()
	{
		return m_byteArray.ReadDouble();
	}

	bool ByteArrayObject::readBoolean()
	{
		return m_byteArray.ReadBoolean();
	}

	void ByteArrayObject::writeBoolean(bool value)
	{
		m_byteArray.WriteBoolean(value);
	}

	void ByteArrayObject::writeByte(int value)
	{
		m_byteArray.WriteU8((U8)value);
	}

	void ByteArrayObject::writeShort(int value)
	{
		m_byteArray.WriteU16((unsigned short)value);
	}

	void ByteArrayObject::writeInt(int value)
	{
		m_byteArray.WriteU32((uint32)value);
	}

	void ByteArrayObject::writeUnsignedInt(uint32 value)
	{
		m_byteArray.WriteU32(value);
	}

	void ByteArrayObject::writeFloat(double value)
	{
		m_byteArray.WriteFloat((float)value);
	}

	void ByteArrayObject::writeDouble(double value)
	{
		m_byteArray.WriteDouble(value);
	}

	void ByteArrayObject::zlib_compress()
	{
		int len = m_byteArray.GetLength();
		if (!len) // empty buffer should give us a empty result
			return;
		unsigned long gzlen = len * 3/2 + 32; // enough for growth plus zlib headers
		U8 *gzdata = new U8[gzlen];

		// Use zlib to compress the data
		compress2((U8*)gzdata, (unsigned long*)&gzlen,
				m_byteArray.GetBuffer(), len, 9);

		// Replace the byte array with the compressed data
		m_byteArray.SetLength(0);
		//m_byteArray.WriteU32((U32)len);
		m_byteArray.Write(gzdata, gzlen);

		delete [] gzdata;
	}

    void ByteArrayObject::zlib_uncompress()
    {
        // Snapshot the compressed data.
        unsigned long gzlen = m_byteArray.GetLength();
		if (!gzlen) // empty buffer should give us a empty result
			return;

		U8 *gzdata = new U8[gzlen];
        VMPI_memcpy(gzdata, m_byteArray.GetBuffer(), gzlen);

        // Clear the buffer
        m_byteArray.Seek(0);
        m_byteArray.SetLength(0);

        // The following block is to force destruction
        // of zstream before potential exception throw.
        int error = Z_OK;
        {
            // Decompress the data
            PlatformZlibStream zstream;
            zstream.SetNextIn(gzdata);
            zstream.SetAvailIn(gzlen);

            const int kBufferSize = 8192;
            U8 *buffer = new U8 [kBufferSize];

            do {
                zstream.SetNextOut(buffer);
                zstream.SetAvailOut(kBufferSize);
                error = zstream.InflateWithStatus();
                m_byteArray.Write(buffer, kBufferSize-zstream.AvailOut());
            } while (error == Z_OK);

            delete [] buffer;
            delete [] gzdata;
        }

		// position byte array at the beginning
		m_byteArray.Seek(0);

        if (error != Z_OK && error != Z_STREAM_END) {
            toplevel()->throwError(kShellCompressedDataError);
        }
    }

	void ByteArrayObject::checkNull(void *instance, const char *name)
	{
		if (instance == NULL) {
			toplevel()->throwTypeError(kNullArgumentError, core()->toErrorString(name));
		}
	}
	void ByteArrayObject::writeBytes(ByteArrayObject *bytes,
									 uint32 offset,
									 uint32 length)
	{
		checkNull(bytes, "bytes");

		if (length == 0) {
			length = bytes->getLength() - offset;
		}

		m_byteArray.WriteByteArray(bytes->GetByteArray(),
								   offset,
								   length);
	}

	void ByteArrayObject::readBytes(ByteArrayObject *bytes,
									uint32 offset,
									uint32 length)
	{
		checkNull(bytes, "bytes");

		if (length == 0) {
			length = m_byteArray.Available();
		}

		m_byteArray.ReadByteArray(bytes->GetByteArray(),
								  offset,
								  length);
	}

	String* ByteArrayObject::readUTF()
	{
		return m_byteArray.ReadUTF();
	}

	String* ByteArrayObject::readUTFBytes(uint32 length)
	{
		return m_byteArray.ReadUTFBytes(length);
	}

	void ByteArrayObject::writeUTF(String *value)
	{
		checkNull(value, "value");
		m_byteArray.WriteUTF(value);
	}

	void ByteArrayObject::writeUTFBytes(String *value)
	{
		checkNull(value, "value");
		m_byteArray.WriteUTFBytes(value);
	}

	void ByteArrayObject::fill(const void *b, uint32_t len)
	{
		m_byteArray.Write(b, len);
	}

 	bool ByteArrayObject::globalMemorySubscribe(const Domain *subscriber, ByteArray::GlobalMemoryNotifyFunc notify)
 	{
 		return m_byteArray.GlobalMemorySubscribe(subscriber, notify);
 	}

 	bool ByteArrayObject::globalMemoryUnsubscribe(const Domain *subscriber)
 	{
 		return m_byteArray.GlobalMemoryUnsubscribe(subscriber);
 	}

	//
	// ByteArrayClass
	//

	ByteArrayClass::ByteArrayClass(VTable *vtable)
		: ClassClosure(vtable)
    {
        prototype = toplevel()->objectClass->construct();
	}

	ScriptObject* ByteArrayClass::createInstance(VTable *ivtable,
												 ScriptObject *prototype)
    {
        return new (core()->GetGC(), ivtable->getExtraSize()) ByteArrayObject(ivtable, prototype);
    }

	ByteArrayObject * ByteArrayClass::readFile(Stringp filename)
	{
		Toplevel* toplevel = this->toplevel();
		if (!filename) {
			toplevel->throwArgumentError(kNullArgumentError, "filename");
		}
		StUTF8String filenameUTF8(filename);

		File* fp = Platform::GetInstance()->createFile();
		if (fp == NULL || !fp->open(filenameUTF8.c_str(), File::OPEN_READ_BINARY))
		{
			if(fp)
			{
				Platform::GetInstance()->destroyFile(fp);
			}
			toplevel->throwError(kFileOpenError, filename);
		}

		int64_t len = fp->size();
		if((uint64_t)len >= UINT32_T_MAX) //ByteArray APIs cannot handle files > 4GB
		{
			toplevel->throwRangeError(kOutOfRangeError, filename);
		}

		uint32_t readCount = (uint32_t)len;

		unsigned char *c = new unsigned char[readCount+1];

		Atom args[1] = {nullObjectAtom};
		ByteArrayObject *b = (ByteArrayObject*)AvmCore::atomToScriptObject(construct(0,args));
		b->setLength(0);

		while (readCount > 0)
		{
			uint32_t actual = (uint32_t) fp->read(c, readCount);
			if (actual > 0)
			{
				b->fill(c, actual);
				readCount -= readCount;
			}
			else
			{
				break;
			}
		}
		b->seek(0);

		delete [] c;

		fp->close();
		Platform::GetInstance()->destroyFile(fp);

		return b;
	}

	Stringp ByteArrayObject::get_endian()
	{
		return (m_byteArray.GetEndian() == kBigEndian) ? core()->internConstantStringLatin1("bigEndian") : core()->internConstantStringLatin1("littleEndian");
	}

	void ByteArrayObject::set_endian(Stringp type)
	{
		AvmCore* core = this->core();
		type = core->internString(type);
		if (type == core->internConstantStringLatin1("bigEndian"))
		{
			m_byteArray.SetEndian(kBigEndian);
		}
		else if (type == core->internConstantStringLatin1("littleEndian"))
		{
			m_byteArray.SetEndian(kLittleEndian);
		}
		else
		{
			toplevel()->throwArgumentError(kInvalidArgumentError, "type");
		}
	}

	void ByteArrayObject::writeFile(Stringp filename)
	{
		Toplevel* toplevel = this->toplevel();
		if (!filename) {
			toplevel->throwArgumentError(kNullArgumentError, "filename");
		}

		StUTF8String filenameUTF8(filename);

		File* fp = Platform::GetInstance()->createFile();
		if (fp == NULL || !fp->open(filenameUTF8.c_str(), File::OPEN_WRITE_BINARY))
		{
			if(fp)
			{
				Platform::GetInstance()->destroyFile(fp);
			}
			toplevel->throwError(kFileWriteError, filename);
		}

		int32_t len = this->get_length();
		bool success = (int32_t)fp->write(&(this->GetByteArray())[0], len) == len;

		fp->close();
		Platform::GetInstance()->destroyFile(fp);

		if (!success) {
			toplevel->throwError(kFileWriteError, filename);
		}
	}

}

namespace avmplus {
 	// memory object glue
 	bool Domain::isMemoryObject(Traits *t) const
 	{
		Traits *cur = t;

		// walk the traits to find a builtin pool
		while(cur && !cur->pool->isBuiltin)
			cur = cur->base;

		// have a traits with a builtin pool
		if(cur)
		{
			Stringp uri = core->internConstantStringLatin1("flash.utils");
			Namespace* ns = core->internNamespace(core->newNamespace(uri));
			// try to get traits from flash.utils.ByteArray
			Traits *baTraits = cur->pool->getTraits(core->internConstantStringLatin1("ByteArray"), ns);
			// and see if the original traits contains it!
			return t->containsInterface(baTraits) != 0;
		}
		return false;
 	}

 	bool Domain::globalMemorySubscribe(ScriptObject *mem) const
 	{
		if(isMemoryObject(mem->traits()))
		{
			avmshell::ByteArray::GlobalMemoryNotifyFunc notify = &Domain::notifyGlobalMemoryChanged;
 			return ((avmshell::ByteArrayObject *)mem)->globalMemorySubscribe(this, notify);
		}
		return false;
 	}

 	bool Domain::globalMemoryUnsubscribe(ScriptObject *mem) const
 	{
		if(isMemoryObject(mem->traits()))
		{
	 		return ((avmshell::ByteArrayObject *)mem)->globalMemoryUnsubscribe(this);
		}
		return false;
 	}
}