text:
package io.card.payment.i18n.locales;

import java.util.HashMap;
import java.util.Map;

import io.card.payment.i18n.StringKey;
import io.card.payment.i18n.SupportedLocale;

// Class autogenerated!  Do not modify.
// Generated on 2014-12-10 11:29:25.124677 via script:
// /Users/twhipple/Documents/buffalo/lib-i18n/i18n/script/generate_android_i18n.py -java_src_path src/ -java_gen_path gen/ -stringkey_path io/card/payment/i18n/ -strings_path ../strings/projects/card.io/strings/ --strict

public class LocalizedStringsDA implements SupportedLocale<StringKey> {

    private static Map<StringKey, String> mDisplay = new HashMap<StringKey, String>();
    private static Map<String, String> mAdapted = new HashMap<String, String>();

    @Override
    public String getName() {
        return "da";
    }

    @Override
    public String getAdaptedDisplay(StringKey key, String country) {
        String adaptedKey = key.toString() + "|" + country;
        if (mAdapted.containsKey(adaptedKey)) {
            return mAdapted.get(adaptedKey);
        } else {
            return mDisplay.get(key);
        }
    }

    public LocalizedStringsDA() {
        mDisplay.put(StringKey.CANCEL, "Annuller");
        mDisplay.put(StringKey.CARDTYPE_AMERICANEXPRESS, "American Express");
        mDisplay.put(StringKey.CARDTYPE_DISCOVER, "Discover");
        mDisplay.put(StringKey.CARDTYPE_JCB, "JCB");
        mDisplay.put(StringKey.CARDTYPE_MASTERCARD, "MasterCard");
        mDisplay.put(StringKey.CARDTYPE_VISA, "Visa");
        mDisplay.put(StringKey.DONE, "Udført");
        mDisplay.put(StringKey.ENTRY_CVV, "CVV");
        mDisplay.put(StringKey.ENTRY_POSTAL_CODE, "Postnummer");
        mDisplay.put(StringKey.ENTRY_EXPIRES, "Udløber");
        mDisplay.put(StringKey.EXPIRES_PLACEHOLDER, "MM/ÅÅ");
        mDisplay.put(StringKey.SCAN_GUIDE, "Hold kortet her.\nDet scannes automatisk.");
        mDisplay.put(StringKey.KEYBOARD, "Tastatur…");
        mDisplay.put(StringKey.ENTRY_CARD_NUMBER, "Kortnummer");
        mDisplay.put(StringKey.MANUAL_ENTRY_TITLE, "Kortoplysninger");
        mDisplay.put(StringKey.ERROR_NO_DEVICE_SUPPORT, "Denne enhed kan ikke anvende kameraet til at læse kortnumre.");
        mDisplay.put(StringKey.ERROR_CAMERA_CONNECT_FAIL, "Enhed kamera ikke er tilgængelig.");
        mDisplay.put(StringKey.ERROR_CAMERA_UNEXPECTED_FAIL, "Enheden havde en uventet fejl under åbning af kamera.");

        // no adapted_translations found
    }
}


text:
using System.Threading.Tasks;

using EnergonSoftware.Backend.MessageHandlers;
using EnergonSoftware.Backend.Messages;
using EnergonSoftware.Backend.Messages.Auth;

using EnergonSoftware.Core.Net.Sessions;

using EnergonSoftware.Launcher.Net;

namespace EnergonSoftware.Launcher.MessageHandlers.Auth
{
    internal sealed class FailureMessageHandler : MessageHandler
    {
        protected async override Task OnHandleMessageAsync(Message message, NetworkSession session)
        {
            FailureMessage failureMessage = (FailureMessage)message;
            AuthSession authSession = (AuthSession)session;

            await authSession.AuthFailedAsync(failureMessage.Reason).ConfigureAwait(false);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package errors

type CodedError interface {
	error
	ErrorCode() *Code
	// The error message excluding the code
	ErrorMessage() string
}

// Error sinks are useful for recording errors but continuing with computation. Implementations may choose to just store
// the first error pushed and ignore subsequent ones or they may record an error trace. Pushing a nil error should have
// no effects.
type Sink interface {
	// Push an error to the error. If a nil error is passed then that value should not be pushed. Returns true iff error
	// is non nil.
	PushError(error) bool
}

type Source interface {
	// Returns the an error if errors occurred some execution or nil if none occurred
	Error() error
}

var Codes = &codes{
	None:                   code("none"),
	UnknownAddress:         code("unknown address"),
	InsufficientBalance:    code("insufficient balance"),
	InvalidJumpDest:        code("invalid jump destination"),
	InsufficientGas:        code("insufficient gas"),
	MemoryOutOfBounds:      code("memory out of bounds"),
	CodeOutOfBounds:        code("code out of bounds"),
	InputOutOfBounds:       code("input out of bounds"),
	ReturnDataOutOfBounds:  code("data out of bounds"),
	CallStackOverflow:      code("call stack overflow"),
	CallStackUnderflow:     code("call stack underflow"),
	DataStackOverflow:      code("data stack overflow"),
	DataStackUnderflow:     code("data stack underflow"),
	InvalidContract:        code("invalid contract"),
	PermissionDenied:       code("permission denied"),
	NativeContractCodeCopy: code("tried to copy native contract code"),
	ExecutionAborted:       code("execution aborted"),
	ExecutionReverted:      code("execution reverted"),
	NativeFunction:         code("native function error"),
	EventPublish:           code("event publish error"),
	InvalidString:          code("invalid string"),
	EventMapping:           code("event mapping error"),
	Generic:                code("generic error"),
	InvalidAddress:         code("invalid address"),
	DuplicateAddress:       code("duplicate address"),
	InsufficientFunds:      code("insufficient funds"),
	Overpayment:            code("overpayment"),
	ZeroPayment:            code("zero payment error"),
	InvalidSequence:        code("invalid sequence number"),
	ReservedAddress:        code("address is reserved for SNative or internal use"),
	IllegalWrite:           code("callee attempted to illegally modify state"),
	IntegerOverflow:        code("integer overflow"),
	InvalidProposal:        code("proposal is invalid"),
	ExpiredProposal:        code("proposal is expired since sequence number does not match"),
	ProposalExecuted:       code("proposal has already been executed"),
	NoInputPermission:      code("account has no input permission"),
	InvalidBlockNumber:     code("invalid block number"),
	BlockNumberOutOfRange:  code("block number out of range"),
	AlreadyVoted:           code("vote already registered for this address"),
	UnresolvedSymbols:      code("code has unresolved symbols"),
	InvalidContractCode:    code("contract being created with unexpected code"),
	NonExistentAccount:     code("account does not exist"),
	NotCallable:            code("cannot dispatch call"),
}

func init() {
	err := Codes.init()
	if err != nil {
		panic(err)
	}
}


text:
namespace viz {

namespace {

base::FilePath GetTestFilePath(const base::FilePath::CharType* basename) {
  base::FilePath test_dir;
  base::PathService::Get(Paths::DIR_TEST_DATA, &test_dir);
  return test_dir.Append(base::FilePath(basename));
}

// Creates a packed RGBA (bytes_per_pixel=4) or RGB (bytes_per_pixel=3) bitmap
// in OpenGL byte/row order from the given SkBitmap.
std::unique_ptr<uint8_t[]> CreateGLPixelsFromSkBitmap(SkBitmap bitmap,
                                                      GLuint source_format,
                                                      bool flip_source) {
  // |bitmap| could be of any color type (and is usually BGRA). Convert it to
  // a RGBA bitmap in the GL byte order.
  SkBitmap rgba_bitmap;
  rgba_bitmap.allocPixels(SkImageInfo::Make(bitmap.width(), bitmap.height(),
                                            kRGBA_8888_SkColorType,
                                            kPremul_SkAlphaType));
  SkPixmap pixmap;
  const bool success =
      bitmap.peekPixels(&pixmap) && rgba_bitmap.writePixels(pixmap, 0, 0);
  CHECK(success);

  // Copy the RGBA bitmap into a raw byte array, reversing the row order and
  // maybe stripping-out the alpha channel.
  const int bytes_per_pixel = source_format == GL_RGBA ? 4 : 3;
  std::unique_ptr<uint8_t[]> pixels(
      new uint8_t[rgba_bitmap.width() * rgba_bitmap.height() *
                  bytes_per_pixel]);
  for (int y = 0; y < rgba_bitmap.height(); ++y) {
    const uint8_t* src = static_cast<uint8_t*>(rgba_bitmap.getAddr(0, y));
    const int flipped_y = flip_source ? rgba_bitmap.height() - y - 1 : y;
    uint8_t* dest =
        pixels.get() + flipped_y * rgba_bitmap.width() * bytes_per_pixel;
    for (int x = 0; x < rgba_bitmap.width(); ++x) {
      *(dest++) = *(src++);
      *(dest++) = *(src++);
      *(dest++) = *(src++);
      if (bytes_per_pixel == 4)
        *(dest++) = *(src++);
      else
        ++src;
    }
  }

  return pixels;
}

// Returns a SkBitmap, given a packed RGBA bitmap in OpenGL byte/row order.
SkBitmap CreateSkBitmapFromGLPixels(const uint8_t* pixels,
                                    const gfx::Size& size) {
  SkBitmap bitmap;
  bitmap.allocPixels(
      SkImageInfo::Make(size.width(), size.height(), kRGBA_8888_SkColorType,
                        kPremul_SkAlphaType),
      size.width() * 4);
  for (int y = 0; y < size.height(); ++y) {
    const int flipped_y = size.height() - y - 1;
    const uint8_t* const src_row = pixels + flipped_y * size.width() * 4;
    void* const dest_row = bitmap.getAddr(0, y);
    std::memcpy(dest_row, src_row, size.width() * 4);
  }
  return bitmap;
}

// Reads back the texture in the given |mailbox| to a SkBitmap in Skia-native
// format.
SkBitmap ReadbackToSkBitmap(gpu::gles2::GLES2Interface* gl,
                            const gpu::Mailbox& mailbox,
                            const gpu::SyncToken& sync_token,
                            const gfx::Size& texture_size) {
  // Bind the texture to a framebuffer from which to read the pixels.
  if (sync_token.HasData())
    gl->WaitSyncTokenCHROMIUM(sync_token.GetConstData());
  GLuint texture = gl->CreateAndConsumeTextureCHROMIUM(mailbox.name);
  GLuint framebuffer = 0;
  gl->GenFramebuffers(1, &framebuffer);
  gl->BindFramebuffer(GL_FRAMEBUFFER, framebuffer);
  gl->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                           texture, 0);

  // Read the pixels and convert to SkBitmap form for test comparisons.
  std::unique_ptr<uint8_t[]> pixels(new uint8_t[texture_size.GetArea() * 4]);
  gl->ReadPixels(0, 0, texture_size.width(), texture_size.height(), GL_RGBA,
                 GL_UNSIGNED_BYTE, pixels.get());
  gl->DeleteFramebuffers(1, &framebuffer);
  gl->DeleteTextures(1, &texture);
  return CreateSkBitmapFromGLPixels(pixels.get(), texture_size);
}

// Validates whether all rows are identical (i.e. for each row r != 0, compares
// it with row 0.
void ValidateRows(uint8_t* pixel_data, size_t row_stride, size_t height) {
  for (size_t row = 1; row < height; ++row) {
    for (size_t col = 0; col < row_stride; ++col) {
      EXPECT_NEAR(pixel_data[col], pixel_data[col + row * row_stride], 1)
          << " mismatch in row " << row << ", column " << col;
    }
  }
}

// Returns maximum allowed difference between the expected and actual pixel
// values.
int GetTolerance() {
  return 1;
}

}  // namespace

//
// All tests in this class follow roughly the same pattern::
// - Construct a CopyOutputRequest, with arguments depending on the test
//   parameters and the specific format that is being tested.
// - Upload source texture to GL.
// - Invoke GLRendererCopier::CopyFromTextureOrFramebuffer(), with arguments
//   depending on the test parameters, passing the created CopyOutputRequest.
// - Load the result into memory and compare with baseline.
//
// Parameters:
// 0. GL format to use when uploading source texture.
// 1. True if the copier will also receive the texture in a call to
//    `CopyFromTextureOrFramebuffer()`, false otherwise.
// 2. Destiation for the CopyOutputRequest (native textures or system memory).
// 3. True if the result should be scaled by half in each dimension, false
//    otherwise.
// 4. True if the source texture will be flipped (bottom-up), false otherwise.
class GLRendererCopierPixelTest
    : public cc::PixelTest,
      public testing::WithParamInterface<
          std::tuple<GLenum, bool, CopyOutputResult::Destination, bool, bool>> {
 public:
  // In order to test coordinate calculations and Y-flipping, the tests will
  // issue copy requests for a small region just to the right and below the
  // center of the entire source texture/framebuffer.
  gfx::Rect GetRequestArea() const {
    DCHECK(!source_size_.IsZero());

    gfx::Rect result(source_size_.width() / 2, source_size_.height() / 2,
                     source_size_.width() / 4, source_size_.height() / 4);

    if (scale_by_half_) {
      return gfx::ScaleToEnclosingRect(result, 0.5f);
    }

    return result;
  }

  void SetUp() override {
    SetUpGLWithoutRenderer(gfx::SurfaceOrigin::kBottomLeft);

    texture_deleter_ =
        std::make_unique<TextureDeleter>(base::ThreadTaskRunnerHandle::Get());

    source_gl_format_ = std::get<0>(GetParam());
    have_source_texture_ = std::get<1>(GetParam());
    result_destination_ = std::get<2>(GetParam());
    scale_by_half_ = std::get<3>(GetParam());
    flipped_source_ = std::get<4>(GetParam());

    gl_ = context_provider()->ContextGL();
    copier_ = std::make_unique<GLRendererCopier>(context_provider(),
                                                 texture_deleter_.get());

    ASSERT_TRUE(cc::ReadPNGFile(
        GetTestFilePath(FILE_PATH_LITERAL("16_color_rects.png")),
        &source_bitmap_));
    source_bitmap_.setImmutable();

    source_size_ = gfx::Size(source_bitmap_.width(), source_bitmap_.height());

    source_bitmap_rgba_ =
        GLScalerTestUtil::CopyAndConvertToRGBA(source_bitmap_);
    source_bitmap_rgba_.setImmutable();

    source_bitmap_yuv_ = source_bitmap_rgba_;
    GLScalerTestUtil::ConvertRGBABitmapToYUV(&source_bitmap_yuv_);
    source_bitmap_yuv_.setImmutable();
  }

  void TearDown() override {
    DeleteSourceFramebuffer();
    DeleteSourceTexture();
    copier_.reset();
    texture_deleter_.reset();
  }

  gpu::gles2::GLES2Interface* gl() { return gl_; }

  GLRendererCopier* copier() { return copier_.get(); }

  gfx::Rect DrawToWindowSpace(const gfx::Size& source_size,
                              const gfx::Rect& draw_rect) {
    gfx::Rect window_rect = draw_rect;
    if (flipped_source_)
      window_rect.set_y(source_size.height() - window_rect.bottom());
    return window_rect;
  }

  GLuint CreateSourceTexture(SkBitmap source_bitmap) {
    CHECK_EQ(0u, source_texture_);
    gl_->GenTextures(1, &source_texture_);
    gl_->BindTexture(GL_TEXTURE_2D, source_texture_);
    gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    gl_->TexImage2D(GL_TEXTURE_2D, 0, source_gl_format_, source_bitmap.width(),
                    source_bitmap.height(), 0, source_gl_format_,
                    GL_UNSIGNED_BYTE,
                    CreateGLPixelsFromSkBitmap(source_bitmap, source_gl_format_,
                                               flipped_source_)
                        .get());
    gl_->BindTexture(GL_TEXTURE_2D, 0);
    return source_texture_;
  }

  void DeleteSourceTexture() {
    if (source_texture_ != 0) {
      gl_->DeleteTextures(1, &source_texture_);
      source_texture_ = 0;
    }
  }

  void CreateAndBindSourceFramebuffer(GLuint texture) {
    ASSERT_EQ(0u, source_framebuffer_);
    gl_->GenFramebuffers(1, &source_framebuffer_);
    gl_->BindFramebuffer(GL_FRAMEBUFFER, source_framebuffer_);
    gl_->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                              GL_TEXTURE_2D, texture, 0);
  }

  void DeleteSourceFramebuffer() {
    if (source_framebuffer_ != 0) {
      gl_->DeleteFramebuffers(1, &source_framebuffer_);
      source_framebuffer_ = 0;
    }
  }

 protected:
  // The size of the source texture or framebuffer.
  gfx::Size source_size_;

  GLenum source_gl_format_;
  bool have_source_texture_;
  CopyOutputResult::Destination result_destination_;
  bool scale_by_half_;
  bool flipped_source_;
  SkBitmap source_bitmap_;
  SkBitmap source_bitmap_rgba_;
  SkBitmap source_bitmap_yuv_;

 private:
  gpu::gles2::GLES2Interface* gl_ = nullptr;
  std::unique_ptr<TextureDeleter> texture_deleter_;
  std::unique_ptr<GLRendererCopier> copier_;
  GLuint source_texture_ = 0;
  GLuint source_framebuffer_ = 0;
};

// On Android KitKat bots (but not newer ones), the left column of pixels in the
// result is off-by-one in the red channel. Use the off-by-one camparator as a
// workaround.
#if defined(OS_ANDROID)
#define PIXEL_COMPARATOR() cc::FuzzyPixelOffByOneComparator(false)
#else
#define PIXEL_COMPARATOR() cc::ExactPixelComparator(false)
#endif

TEST_P(GLRendererCopierPixelTest, ExecutesCopyRequestRGBA) {
  // Create and execute a CopyOutputRequest via the GLRendererCopier.
  std::unique_ptr<CopyOutputResult> result;
  {
    base::RunLoop loop;
    auto request = std::make_unique<CopyOutputRequest>(
        CopyOutputRequest::ResultFormat::RGBA, result_destination_,
        base::BindOnce(
            [](std::unique_ptr<CopyOutputResult>* result,
               base::OnceClosure quit_closure,
               std::unique_ptr<CopyOutputResult> result_from_copier) {
              *result = std::move(result_from_copier);
              std::move(quit_closure).Run();
            },
            &result, loop.QuitClosure()));
    if (scale_by_half_) {
      request->SetUniformScaleRatio(2, 1);
    }

    request->set_result_selection(GetRequestArea());

    const GLuint source_texture = CreateSourceTexture(source_bitmap_);
    CreateAndBindSourceFramebuffer(source_texture);

    copy_output::RenderPassGeometry geometry;
    // geometry.result_bounds not used by GLRendererCopier
    geometry.sampling_bounds =
        DrawToWindowSpace(source_size_, gfx::Rect(source_size_));
    geometry.result_selection = request->result_selection();
    geometry.readback_offset =
        DrawToWindowSpace(source_size_, geometry.result_selection)
            .OffsetFromOrigin();

    copier()->CopyFromTextureOrFramebuffer(
        std::move(request), geometry, source_gl_format_,
        have_source_texture_ ? source_texture : 0, source_size_,
        flipped_source_, gfx::ColorSpace::CreateSRGB());
    loop.Run();
  }

  // Check that a result was produced and is of the expected rect/size.
  ASSERT_TRUE(result);
  ASSERT_FALSE(result->IsEmpty());
  ASSERT_EQ(GetRequestArea(), result->rect());

  // Examine the image in the |result|, and compare it to the baseline PNG file.
  absl::optional<CopyOutputResult::ScopedSkBitmap> scoped_bitmap;
  SkBitmap actual;
  if (result_destination_ == CopyOutputResult::Destination::kSystemMemory) {
    scoped_bitmap = result->ScopedAccessSkBitmap();
    actual = scoped_bitmap->bitmap();
  } else {
    actual = ReadbackToSkBitmap(
        gl(), result->GetTextureResult()->planes[0].mailbox,
        result->GetTextureResult()->planes[0].sync_token, result->size());
  }
  const auto png_file_path = GetTestFilePath(
      scale_by_half_ ? FILE_PATH_LITERAL("half_of_one_of_16_color_rects.png")
                     : FILE_PATH_LITERAL("one_of_16_color_rects.png"));
  if (base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kRebaselinePixelTests))
    EXPECT_TRUE(cc::WritePNGFile(actual, png_file_path, false));
  if (!cc::MatchesPNGFile(actual, png_file_path, PIXEL_COMPARATOR())) {
    LOG(ERROR) << "Entire source: " << cc::GetPNGDataUrl(source_bitmap_);
    ADD_FAILURE();
  }
}

TEST_P(GLRendererCopierPixelTest, ExecutesCopyRequestNV12) {
  if (result_destination_ ==
      CopyOutputRequest::ResultDestination::kNativeTextures) {
    // TODO(https://crbug.com/1216287): Enable once textures are supported.
    GTEST_SKIP()
        << "Enable once the GLRenderer supports producing producing results to "
           "a texture for NV12 format.";
  }

  const gfx::Rect request_area = GetRequestArea();

  // Check if request's width and height are even (required for NV12 format).
  // The test case expects the result size to match the request size exactly,
  // which is not possible with NV12 when the request size dimensions aren't
  // even.
  ASSERT_TRUE(request_area.width() % 2 == 0 && request_area.height() % 2 == 0)
      << " request size is not even, request_area.size()="
      << request_area.size().ToString();

  // Additionally, the test uses helpers that assume pixel data can be packed (4
  // 8-bit values in 1 32-bit pixel).
  ASSERT_TRUE(request_area.width() % 4 == 0)
      << " request width is not divisible by 4, request_area.width()="
      << request_area.width();

  // Create and execute a CopyOutputRequest via the GLRendererCopier.
  std::unique_ptr<CopyOutputResult> result;
  {
    base::RunLoop loop;
    auto request = std::make_unique<CopyOutputRequest>(
        CopyOutputRequest::ResultFormat::NV12_PLANES, result_destination_,
        base::BindOnce(
            [](std::unique_ptr<CopyOutputResult>* result,
               base::OnceClosure quit_closure,
               std::unique_ptr<CopyOutputResult> result_from_copier) {
              *result = std::move(result_from_copier);
              std::move(quit_closure).Run();
            },
            &result, loop.QuitClosure()));
    if (scale_by_half_) {
      request->SetUniformScaleRatio(2, 1);
    }

    request->set_result_selection(request_area);

    // Upload source texture to GL - the texture will be converted to RGBA if
    // necessary.
    const GLuint source_texture = CreateSourceTexture(source_bitmap_);
    CreateAndBindSourceFramebuffer(source_texture);

    copy_output::RenderPassGeometry geometry;
    // geometry.result_bounds not used by GLRendererCopier
    geometry.sampling_bounds =
        DrawToWindowSpace(source_size_, gfx::Rect(source_size_));
    geometry.result_selection = request->result_selection();
    geometry.readback_offset =
        DrawToWindowSpace(source_size_, geometry.result_selection)
            .OffsetFromOrigin();

    copier()->CopyFromTextureOrFramebuffer(
        std::move(request), geometry, source_gl_format_,
        have_source_texture_ ? source_texture : 0, source_size_,
        flipped_source_, gfx::ColorSpace::CreateSRGB());
    loop.Run();
  }

  // Check that a result was produced and is of the expected rect/size.
  ASSERT_TRUE(result);
  ASSERT_FALSE(result->IsEmpty());
  ASSERT_EQ(request_area, result->rect());

  // Examine the image in the |result|, and compare it to the baseline PNG file.
  // Approach is the same as the one in GLNV12ConverterPixelTest.

  // Allocate new bitmap, it will then be populated with Y & UV data.
  SkBitmap actual = GLScalerTestUtil::AllocateRGBABitmap(result->size());
  actual.eraseColor(SkColorSetARGB(0xff, 0x00, 0x00, 0x00));

  SkBitmap luma_plane;
  SkBitmap chroma_planes;

  if (result_destination_ == CopyOutputResult::Destination::kSystemMemory) {
    // Create a bitmap with packed Y values:
    luma_plane = GLScalerTestUtil::AllocateRGBABitmap(
        gfx::Size(result->size().width() / 4, result->size().height()));

    chroma_planes = GLScalerTestUtil::AllocateRGBABitmap(
        gfx::Size(luma_plane.width(), luma_plane.height() / 2));

    result->ReadNV12Planes(
        reinterpret_cast<uint8_t*>(luma_plane.getAddr(0, 0)),
        result->size().width(),
        reinterpret_cast<uint8_t*>(chroma_planes.getAddr(0, 0)),
        result->size().width());
  } else {
    LOG(ERROR) << "Texture results for NV12 are not supported yet!";
    ADD_FAILURE();
  }

  GLScalerTestUtil::UnpackPlanarBitmap(luma_plane, 0, &actual);
  GLScalerTestUtil::UnpackUVBitmap(chroma_planes, &actual);

  const auto png_file_path = GetTestFilePath(
      scale_by_half_ ? FILE_PATH_LITERAL("half_of_one_of_16_color_rects.png")
                     : FILE_PATH_LITERAL("one_of_16_color_rects.png"));

  SkBitmap expected;
  if (!cc::ReadPNGFile(png_file_path, &expected)) {
    LOG(ERROR) << "Cannot read reference image: " << png_file_path.value();
    ADD_FAILURE();
    return;
  }

  expected = GLScalerTestUtil::CopyAndConvertToRGBA(expected);
  GLScalerTestUtil::ConvertRGBABitmapToYUV(&expected);

  constexpr float kAvgAbsoluteErrorLimit = 16.f;
  constexpr int kMaxAbsoluteErrorLimit = 0x80;
  if (!cc::MatchesBitmap(
          actual, expected,
          cc::FuzzyPixelComparator(false, 100.f, 0.f, kAvgAbsoluteErrorLimit,
                                   kMaxAbsoluteErrorLimit, 0))) {
    ADD_FAILURE();
    return;
  }
}

#undef PIXEL_COMPARATOR

// These tests work similarly to `GLRendererCopierPixelTest`, but test various
// request dimensions in more depth.
//
// Parameters:
// 0. Destiation for the CopyOutputRequest (native textures or system memory).
// 1. True if the result should be scaled by half in each dimension, false
//    otherwise.
// 2. True if the request should specify odd coordinates for the result
//    selection rectangle, false otherwise.
// 3. True if the request should specify odd dimensions for the result selection
//    rectangle, false otherwise.
class GLRendererCopierDimensionsPixelTest
    : public cc::PixelTest,
      public testing::WithParamInterface<
          std::tuple<CopyOutputResult::Destination, bool, bool>> {
 public:
  void SetUp() override {
    SetUpGLWithoutRenderer(gfx::SurfaceOrigin::kBottomLeft);

    texture_deleter_ =
        std::make_unique<TextureDeleter>(base::ThreadTaskRunnerHandle::Get());

    result_destination_ = std::get<0>(GetParam());
    scale_by_half_ = std::get<1>(GetParam());
    use_odd_offset_ = std::get<2>(GetParam());

    gl_ = context_provider()->ContextGL();
    copier_ = std::make_unique<GLRendererCopier>(context_provider(),
                                                 texture_deleter_.get());

    // For this test, use a generated bitmap, with 4 groups of 4 pixels each.
    const std::vector<SkColor> kCycle = {
        // Red:
        SkColorSetARGB(0xff, 0xff, 0x00, 0x00),
        SkColorSetARGB(0xff, 0xff, 0x00, 0x00),
        SkColorSetARGB(0xff, 0xff, 0x00, 0x00),
        SkColorSetARGB(0xff, 0xff, 0x00, 0x00),
        // Green:
        SkColorSetARGB(0xff, 0x00, 0xff, 0x00),
        SkColorSetARGB(0xff, 0x00, 0xff, 0x00),
        SkColorSetARGB(0xff, 0x00, 0xff, 0x00),
        SkColorSetARGB(0xff, 0x00, 0xff, 0x00),
        // Blue:
        SkColorSetARGB(0xff, 0x00, 0x00, 0xff),
        SkColorSetARGB(0xff, 0x00, 0x00, 0xff),
        SkColorSetARGB(0xff, 0x00, 0x00, 0xff),
        SkColorSetARGB(0xff, 0x00, 0x00, 0xff),
        // White:
        SkColorSetARGB(0xff, 0xff, 0xff, 0xff),
        SkColorSetARGB(0xff, 0xff, 0xff, 0xff),
        SkColorSetARGB(0xff, 0xff, 0xff, 0xff),
        SkColorSetARGB(0xff, 0xff, 0xff, 0xff),
    };
    source_bitmap_ = GLScalerTestUtil::CreateCyclicalTestImage(
        gfx::Size(800, 600), GLScalerTestUtil::VERTICAL_STRIPES, kCycle, 0);
    // source_bitmap_.setImmutable();
    source_bitmap_size_ =
        gfx::Size(source_bitmap_.width(), source_bitmap_.height());
  }

  void TearDown() override {
    DeleteSourceFramebuffer();
    DeleteSourceTexture();
    copier_.reset();
    texture_deleter_.reset();
  }

  gpu::gles2::GLES2Interface* gl() { return gl_; }

  GLRendererCopier* copier() { return copier_.get(); }

  gfx::Rect DrawToWindowSpace(const gfx::Size& source_size,
                              const gfx::Rect& draw_rect) {
    gfx::Rect window_rect = draw_rect;
    if (flipped_source_)
      window_rect.set_y(source_size.height() - window_rect.bottom());
    return window_rect;
  }

  GLuint CreateSourceTexture(SkBitmap source_bitmap) {
    CHECK_EQ(0u, source_texture_);
    gl_->GenTextures(1, &source_texture_);
    gl_->BindTexture(GL_TEXTURE_2D, source_texture_);
    gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    gl_->TexImage2D(GL_TEXTURE_2D, 0, source_gl_format_, source_bitmap.width(),
                    source_bitmap.height(), 0, source_gl_format_,
                    GL_UNSIGNED_BYTE,
                    CreateGLPixelsFromSkBitmap(source_bitmap, source_gl_format_,
                                               flipped_source_)
                        .get());
    gl_->BindTexture(GL_TEXTURE_2D, 0);
    return source_texture_;
  }

  void DeleteSourceTexture() {
    if (source_texture_ != 0) {
      gl_->DeleteTextures(1, &source_texture_);
      source_texture_ = 0;
    }
  }

  void CreateAndBindSourceFramebuffer(GLuint texture) {
    ASSERT_EQ(0u, source_framebuffer_);
    gl_->GenFramebuffers(1, &source_framebuffer_);
    gl_->BindFramebuffer(GL_FRAMEBUFFER, source_framebuffer_);
    gl_->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                              GL_TEXTURE_2D, texture, 0);
  }

  void DeleteSourceFramebuffer() {
    if (source_framebuffer_ != 0) {
      gl_->DeleteFramebuffers(1, &source_framebuffer_);
      source_framebuffer_ = 0;
    }
  }

 protected:
  GLenum source_gl_format_ = GL_RGBA;
  bool have_source_texture_ = false;
  CopyOutputResult::Destination result_destination_;
  bool scale_by_half_;
  bool flipped_source_ = false;
  bool use_odd_offset_;
  SkBitmap source_bitmap_;
  gfx::Size source_bitmap_size_;

 private:
  gpu::gles2::GLES2Interface* gl_ = nullptr;
  std::unique_ptr<TextureDeleter> texture_deleter_;
  std::unique_ptr<GLRendererCopier> copier_;
  GLuint source_texture_ = 0;
  GLuint source_framebuffer_ = 0;
};

TEST_P(GLRendererCopierDimensionsPixelTest, ExecutesCopyRequestNV12) {
  if (result_destination_ ==
      CopyOutputRequest::ResultDestination::kNativeTextures) {
    // TODO(https://crbug.com/1216287): Enable once textures are supported.
    GTEST_SKIP() << "Enable once the NV12 format supports producing results to "
                    "a texture.";
  }

  // Result should contain 1px green strip at the beginning if the offset is
  // supposed to be odd.
  const gfx::Rect request_area = [this]() {
    // Capture 2x2 or 4x4 blue strip fragment, depending on scaling.
    gfx::Rect result =
        scale_by_half_ ? gfx::Rect(4, 0, 2, 2) : gfx::Rect(8, 0, 4, 4);

    // If we are supposed to ask for a rect with odd offset,
    // make sure that we capture 1 green pixel.
    if (use_odd_offset_) {
      result.set_x(result.x() - 1);
    }

    return result;
  }();

  // Create and execute a CopyOutputRequest via the GLRendererCopier.
  std::unique_ptr<CopyOutputResult> result;
  {
    base::RunLoop loop;
    auto request = std::make_unique<CopyOutputRequest>(
        CopyOutputRequest::ResultFormat::NV12_PLANES, result_destination_,
        base::BindOnce(
            [](std::unique_ptr<CopyOutputResult>* result,
               base::OnceClosure quit_closure,
               std::unique_ptr<CopyOutputResult> result_from_copier) {
              *result = std::move(result_from_copier);
              std::move(quit_closure).Run();
            },
            &result, loop.QuitClosure()));

    if (scale_by_half_) {
      request->SetUniformScaleRatio(2, 1);
    }

    request->set_result_selection(gfx::Rect(request_area));

    // Upload source texture to GL:
    const GLuint source_texture = CreateSourceTexture(source_bitmap_);
    CreateAndBindSourceFramebuffer(source_texture);

    copy_output::RenderPassGeometry geometry;
    // geometry.result_bounds not used by GLRendererCopier
    geometry.sampling_bounds =
        DrawToWindowSpace(source_bitmap_size_, gfx::Rect(source_bitmap_size_));
    geometry.result_selection = request->result_selection();
    geometry.readback_offset =
        DrawToWindowSpace(source_bitmap_size_, geometry.result_selection)
            .OffsetFromOrigin();

    copier()->CopyFromTextureOrFramebuffer(
        std::move(request), geometry, source_gl_format_,
        have_source_texture_ ? source_texture : 0, source_bitmap_size_,
        flipped_source_, gfx::ColorSpace::CreateSRGB());
    loop.Run();
  }

  // Check that a result was produced and is of the expected rect/size.
  ASSERT_TRUE(result);
  ASSERT_FALSE(result->IsEmpty());
  ASSERT_EQ(request_area, result->rect());

  const auto luma_nbytes = copy_output::GetLumaPlaneSize(*result);
  const auto luma_stride = copy_output::GetLumaPlaneStride(*result);

  const auto chroma_nbytes = copy_output::GetChromaPlaneSize(*result);
  const auto chroma_stride = copy_output::GetChromaPlaneStride(*result);

  std::unique_ptr<uint8_t[]> luma_plane =
      std::make_unique<uint8_t[]>(luma_nbytes);
  std::unique_ptr<uint8_t[]> chroma_planes =
      std::make_unique<uint8_t[]>(chroma_nbytes);

  // Examine the image in the |result|, and compare it to the baseline.
  if (result_destination_ == CopyOutputResult::Destination::kSystemMemory) {
    result->ReadNV12Planes(luma_plane.get(), luma_stride, chroma_planes.get(),
                           chroma_stride);
  } else {
    LOG(ERROR) << "Texture results for NV12 are not supported yet!";
    ADD_FAILURE();
  }

  SkBitmap source_bitmap_yuv = source_bitmap_;
  GLScalerTestUtil::ConvertRGBABitmapToYUV(&source_bitmap_yuv);

  // We've asked for a region that starts with one green pixel that is followed
  // by all blue pixels, grab the source colors after they have been converted
  // to YUV to have something to validate against:
  SkColor green_yuv = source_bitmap_yuv.getColor(4, 0);
  SkColor blue_yuv = source_bitmap_yuv.getColor(8, 0);

  // Validate first row of luma (first color channel):
  for (int col = 0; col < luma_stride; ++col) {
    if (col == 0 && use_odd_offset_) {
      EXPECT_NEAR(luma_plane[col], SkColorGetR(green_yuv), GetTolerance());
      continue;
    }

    EXPECT_NEAR(luma_plane[col], SkColorGetR(blue_yuv), GetTolerance());
  }

  // All other luma rows must match the first row:
  ValidateRows(luma_plane.get(), luma_stride, result->rect().height());

  // Validate first row of chroma (second and third color channel):
  for (int col = 0; col < chroma_stride; col += 2) {
    if (col == 0 && use_odd_offset_) {
      EXPECT_NEAR(chroma_planes[col], SkColorGetG(green_yuv), GetTolerance());
      EXPECT_NEAR(chroma_planes[col + 1], SkColorGetB(green_yuv),
                  GetTolerance());
      continue;
    }

    EXPECT_NEAR(chroma_planes[col], SkColorGetG(blue_yuv), GetTolerance());
    EXPECT_NEAR(chroma_planes[col + 1], SkColorGetB(blue_yuv), GetTolerance());
  }

  // All other chroma rows must match the first row:
  ValidateRows(chroma_planes.get(), chroma_stride,
               (result->rect().height() + 1) / 2);
}

TEST_P(GLRendererCopierDimensionsPixelTest, ExecutesCopyRequestI420) {
  if (result_destination_ ==
      CopyOutputRequest::ResultDestination::kNativeTextures) {
    // TODO(https://crbug.com/1216287): Enable once textures are supported.
    GTEST_SKIP() << "Enable once the I420 format supports producing results to "
                    "a texture.";
  }

  // Result should contain 1px green strip at the beginning if the offset is
  // supposed to be odd.
  const gfx::Rect request_area = [this]() {
    // Capture 2x2 or 4x4 blue strip fragment, depending on scaling.
    gfx::Rect result =
        scale_by_half_ ? gfx::Rect(4, 0, 2, 2) : gfx::Rect(8, 0, 4, 4);

    // If we are supposed to ask for a rect with odd offset,
    // make sure that we capture 1 green pixel.
    if (use_odd_offset_) {
      result.set_x(result.x() - 1);
    }

    return result;
  }();

  // Create and execute a CopyOutputRequest via the GLRendererCopier.
  std::unique_ptr<CopyOutputResult> result;
  {
    base::RunLoop loop;
    auto request = std::make_unique<CopyOutputRequest>(
        CopyOutputRequest::ResultFormat::I420_PLANES, result_destination_,
        base::BindOnce(
            [](std::unique_ptr<CopyOutputResult>* result,
               base::OnceClosure quit_closure,
               std::unique_ptr<CopyOutputResult> result_from_copier) {
              *result = std::move(result_from_copier);
              std::move(quit_closure).Run();
            },
            &result, loop.QuitClosure()));

    if (scale_by_half_) {
      request->SetUniformScaleRatio(2, 1);
    }

    request->set_result_selection(gfx::Rect(request_area));

    // Upload source texture to GL:
    const GLuint source_texture = CreateSourceTexture(source_bitmap_);
    CreateAndBindSourceFramebuffer(source_texture);

    copy_output::RenderPassGeometry geometry;
    // geometry.result_bounds not used by GLRendererCopier
    geometry.sampling_bounds =
        DrawToWindowSpace(source_bitmap_size_, gfx::Rect(source_bitmap_size_));
    geometry.result_selection = request->result_selection();
    geometry.readback_offset =
        DrawToWindowSpace(source_bitmap_size_, geometry.result_selection)
            .OffsetFromOrigin();

    copier()->CopyFromTextureOrFramebuffer(
        std::move(request), geometry, source_gl_format_,
        have_source_texture_ ? source_texture : 0, source_bitmap_size_,
        flipped_source_, gfx::ColorSpace::CreateSRGB());
    loop.Run();
  }

  // Check that a result was produced and is of the expected rect/size.
  ASSERT_TRUE(result);
  ASSERT_FALSE(result->IsEmpty());
  ASSERT_EQ(request_area, result->rect());

  // Examine the image in the |result|, and compare it to the baseline PNG file.

  const auto luma_nbytes = copy_output::GetLumaPlaneSize(*result);
  const auto luma_stride = copy_output::GetLumaPlaneStride(*result);

  const auto chroma_nbytes = copy_output::GetChromaPlaneSize(*result);
  const auto chroma_stride = copy_output::GetChromaPlaneStride(*result);

  std::unique_ptr<uint8_t[]> luma_plane =
      std::make_unique<uint8_t[]>(luma_nbytes);
  std::unique_ptr<uint8_t[]> chroma_plane_1 =
      std::make_unique<uint8_t[]>(chroma_nbytes);
  std::unique_ptr<uint8_t[]> chroma_plane_2 =
      std::make_unique<uint8_t[]>(chroma_nbytes);

  if (result_destination_ == CopyOutputResult::Destination::kSystemMemory) {
    result->ReadI420Planes(luma_plane.get(), luma_stride, chroma_plane_1.get(),
                           chroma_stride, chroma_plane_2.get(), chroma_stride);
  } else {
    LOG(ERROR) << "Texture results for I420 are not supported yet!";
    ADD_FAILURE();
  }

  SkBitmap source_bitmap_yuv = source_bitmap_;
  GLScalerTestUtil::ConvertRGBABitmapToYUV(&source_bitmap_yuv);

  // We've asked for a region that starts with one green pixel that is followed
  // by all blue pixels, validate:
  SkColor green_yuv = source_bitmap_yuv.getColor(7, 0);
  SkColor blue_yuv = source_bitmap_yuv.getColor(8, 0);

  // Validate first row of luma (first channel):
  for (int col = 0; col < luma_stride; ++col) {
    if (col == 0 && use_odd_offset_) {
      EXPECT_NEAR(luma_plane[col], SkColorGetR(green_yuv), GetTolerance());
      continue;
    }

    EXPECT_NEAR(luma_plane[col], SkColorGetR(blue_yuv), GetTolerance());
  }

  // All other luma rows must match the first row:
  ValidateRows(luma_plane.get(), luma_stride, result->rect().height());

  // Validate first row of chroma_1 (second channel):
  for (int col = 0; col < chroma_stride; ++col) {
    if (col == 0 && use_odd_offset_) {
      EXPECT_NEAR(chroma_plane_1[col], SkColorGetG(green_yuv), GetTolerance());
      continue;
    }

    EXPECT_NEAR(chroma_plane_1[col], SkColorGetG(blue_yuv), GetTolerance());
  }

  // All other chroma_1 rows must match the first row:
  ValidateRows(chroma_plane_1.get(), chroma_stride,
               (result->rect().height() + 1) / 2);

  // Validate first row of chroma_2 (third channel):
  for (int col = 0; col < chroma_stride; ++col) {
    if (col == 0 && use_odd_offset_) {
      EXPECT_NEAR(chroma_plane_2[col], SkColorGetB(green_yuv), GetTolerance());
      continue;
    }

    EXPECT_NEAR(chroma_plane_2[col], SkColorGetB(blue_yuv), GetTolerance());
  }

  // All other chroma_2 rows must match the first row:
  ValidateRows(chroma_plane_2.get(), chroma_stride,
               (result->rect().height() + 1) / 2);
}

// Instantiate parameter sets for all possible combinations of scenarios
// GLRendererCopier will encounter, which will cause it to follow different
// workflows.
INSTANTIATE_TEST_SUITE_P(
    All,
    GLRendererCopierPixelTest,
    testing::Combine(
        // Source framebuffer GL format.
        testing::Values(static_cast<GLenum>(GL_RGBA),
                        static_cast<GLenum>(GL_RGB)),
        // Source: Have texture too?
        testing::Values(false, true),
        // Result destination.
        testing::Values(CopyOutputResult::Destination::kSystemMemory,
                        CopyOutputResult::Destination::kNativeTextures),
        // Result scaling: Scale by half?
        testing::Values(false, true),
        // Source content is vertically flipped?
        testing::Values(false, true)));

// Instantiate parameter sets for all possible combinations of scenarios
// GLRendererCopier will encounter, which will cause it to follow different
// workflows.
INSTANTIATE_TEST_SUITE_P(
    All,
    GLRendererCopierDimensionsPixelTest,
    testing::Combine(
        // Result destination.
        testing::Values(CopyOutputResult::Destination::kSystemMemory,
                        CopyOutputResult::Destination::kNativeTextures),
        // Result scaling: Scale by half?
        testing::Values(false, true),
        // Use odd offset?
        testing::Values(false, true)));

}  // namespace viz


text:
package debop4k.data.orm.mapping.associations.join.model;

import debop4k.data.orm.model.AbstractHibernateEntity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.eclipse.collections.impl.factory.SortedMaps;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.*;

import javax.persistence.CascadeType;
import javax.persistence.*;
import javax.persistence.Entity;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

@Entity(name = "Join_User")
@Cache(region = "associations", usage = CacheConcurrencyStrategy.READ_WRITE)
@DynamicInsert
@DynamicUpdate
@Getter
@Setter
@ToString
public class User extends AbstractHibernateEntity<Integer> {

  @Id
  @GeneratedValue
  @Column(name = "userId")
  Integer id;

  String name;

  @OneToMany(cascade = {CascadeType.ALL}, orphanRemoval = true)
  @JoinTable(name = "JoinUserAddressMap",
             joinColumns = {@JoinColumn(name = "userId")},
             inverseJoinColumns = {@JoinColumn(name = "addressId")})
  @MapKeyColumn(name = "address_name")
  @ElementCollection(targetClass = AddressEntity.class, fetch = FetchType.EAGER)
  @Fetch(FetchMode.JOIN)
  Map<String, AddressEntity> addresses = SortedMaps.mutable.of();

  @JoinTable(name = "JoinUserNicknameSet", joinColumns = {@JoinColumn(name = "userId")})
  @ElementCollection(targetClass = String.class, fetch = FetchType.LAZY)
  @Cascade(org.hibernate.annotations.CascadeType.ALL)
  Set<String> nicknames = new LinkedHashSet<String>();

  private static final long serialVersionUID = -892871535124703571L;
}


text:
namespace storage {
class ViewBlobInternalsJob;

// This class represents a blob in the BlobStorageContext.  It is constructed
// using the internal Builder class.
class InternalBlobData {
 public:
  ~InternalBlobData();

 protected:
  friend class BlobStorageContext;
  friend class BlobStorageRegistry;
  friend class ViewBlobInternalsJob;

  // Removes the given blob uuid from the internal ShareableBlobDataItems.
  // This is called when this blob is being destroyed.
  void RemoveBlobFromShareableItems(const std::string& blob_uuid);

  const std::vector<scoped_refptr<ShareableBlobDataItem>>& items() const;
  const std::string& content_type() const;
  const std::string& content_disposition() const;

  // Gets the memory used by this blob that is not shared by other blobs. This
  // also doesn't count duplicate items.
  size_t GetUnsharedMemoryUsage() const;

  // Gets the memory used by this blob.  Total memory includes memory of items
  // possibly shared with other blobs, or items that appear multiple times in
  // this blob. Unshared memory is memory used by this blob that is not shared
  // by other blobs.
  void GetMemoryUsage(size_t* total_memory, size_t* unshared_memory);

 private:
  friend class Builder;
  InternalBlobData();

  std::string content_type_;
  std::string content_disposition_;
  std::vector<scoped_refptr<ShareableBlobDataItem>> items_;

  class Builder {
   public:
    Builder();
    ~Builder();

    void AppendSharedBlobItem(scoped_refptr<ShareableBlobDataItem> item);
    void set_content_type(const std::string& content_type);
    void set_content_disposition(const std::string& content_disposition);

    // Gets the memory used by this builder that is not shared with other blobs.
    size_t GetNonsharedMemoryUsage() const;

    // Removes the given blob uuid from the internal ShareableBlobDataItems.
    // This is called on destruction of the blob if we're still building it.
    void RemoveBlobFromShareableItems(const std::string& blob_uuid);

    // The builder is invalid after calling this method.
    scoped_ptr<::storage::InternalBlobData> Build();

   private:
    scoped_ptr<::storage::InternalBlobData> data_;

    DISALLOW_COPY_AND_ASSIGN(Builder);
  };

  DISALLOW_COPY_AND_ASSIGN(InternalBlobData);
};

}  // namespace storage
#endif  // STORAGE_BROWSER_BLOB_INTERNAL_BLOB_DATA_H_


text:
<resources>
    <string name="app_name">StoreCredentials</string>
    <string name="serviceUrl">https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/SaveTheBaySync_secured/MapServer</string>

    <string name="loginBtnText">Log In</string>
    <string name="saveBtnText">Save</string>
</resources>


text:
<?php
/**
 * This file is part of the Ghostscript test package
 *
 * @author Simon Schrape <s.schrape@epubli.com>
 */

namespace GravityMedia\GhostscriptTest\Device;

use GravityMedia\Ghostscript\Device\NoDisplay;
use GravityMedia\Ghostscript\Ghostscript;
use GravityMedia\Ghostscript\Process\Argument;
use GravityMedia\Ghostscript\Process\Arguments;
use PHPUnit\Framework\TestCase;

/**
 * The no display device test class.
 *
 * @package GravityMedia\GhostscriptTest\Devices
 *
 * @covers  \GravityMedia\Ghostscript\Device\NoDisplay
 *
 * @uses    \GravityMedia\Ghostscript\Ghostscript
 * @uses    \GravityMedia\Ghostscript\Device\AbstractDevice
 * @uses    \GravityMedia\Ghostscript\Process\Argument
 * @uses    \GravityMedia\Ghostscript\Process\Arguments
 */
class NoDisplayTest extends TestCase
{
    public function testDeviceCreation()
    {
        $ghostscript = new Ghostscript();
        $arguments = new Arguments();

        $device = new NoDisplay($ghostscript, $arguments);

        $this->assertInstanceOf(NoDisplay::class, $device);
        $this->assertInstanceOf(Argument::class, $arguments->getArgument('-dNODISPLAY'));
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../options_results/trait.ResultIter.html">

Redirecting to ../../options_results/trait.ResultIter.html...


text:
using BEPUphysics.BroadPhaseEntries.MobileCollidables;
using BEPUutilities;

namespace BEPUphysics.Entities
{
    ///
    /// Superclass of all entities which have a defined collidable type.
    /// After construction, the collidable on this sort of Entity cannot be changed.
    /// It can be constructed directly, or one of its prefab children (Box, Sphere, etc.) can be used.
    ///
    /// <remarks>If the collidable needs to be changed after construction, consider using the MorphableEntity.</remarks>
    ///<typeparam name="T">Type of EntityCollidable to use for the entity.</typeparam>
    public class Entity<T> : Entity where T : EntityCollidable
    {
        ///
        /// Gets the collidable used by the entity.
        ///
        public new T CollisionInformation
        {
            get { return (T)collisionInformation; }
        }

        protected internal Entity()
        {

        }

        ///
        /// Constructs a kinematic Entity.
        ///
        ///<param name="collisionInformation">Collidable for the entity.</param>
        public Entity(T collisionInformation)
        {
            Initialize(collisionInformation);
        }

        ///
        /// Constructs a dynamic Entity.
        ///
        ///<param name="collisionInformation">Collidable for the entity.</param>
        /// <param name="mass">Mass of the entity.</param>
        public Entity(T collisionInformation, float mass)
        {
            Initialize(collisionInformation, mass);
        }
        ///
        /// Constructs a dynamic Entity.
        ///
        ///<param name="collisionInformation">Collidable for the entity.</param>
        /// <param name="mass">Mass of the entity.</param>
        /// <param name="inertiaTensor">Inertia of the entity.</param>
        public Entity(T collisionInformation, float mass, Matrix3x3 inertiaTensor)
        {
            Initialize(collisionInformation, mass, inertiaTensor);
        }

    }
}


text:
TODAY=`date +"%Y%m%d_%H%M%S"` # todays date Y-M-D
MONGODUMP=/usr/bin/mongodump # Path to mongodump
[ -x "${MONGODUMP}" ] || (echo "${MONGODUMP}" not found or not executable; exit 1)
FIND=/usr/bin/find # Path to find
MONGO_BACKUP=/var/spool/mongobackup # Path to your mongo backup directory
MONGO_BACKUP_TODAY="${MONGO_BACKUP}"/"${TODAY}"/ # Path to the directory per day
DAYS_RETENTION=7 # How many days of backups do you wish to keep

MONGO_HOST='127.0.0.1' # Host
MONGO_PORT=27017 # Port
MONGO_USER='admin' # User with db access
MONGO_PASS='pass' # Password of user
MONGO_DB='db' # Your DB

#RUN MongoDump
${MONGODUMP} -u "${MONGO_USER}" -o "${MONGO_BACKUP_TODAY}" -h "${MONGO_HOST}":"${MONGO_PORT}" -d "${MONGO_DB}" -p "${MONGO_PASS}"

#ARCHIVE FILES
cd "${MONGO_BACKUP_TODAY}"
"${FIND}" ./* -maxdepth 0 -type d -exec echo "Archiving {}" \; -exec tar -czf "{}.tar.gz" "{}" \; -exec rm -rf "{}" \;

# REMOVE old backups based on DAYS_RETENTION
"${FIND}" "${MONGO_BACKUP}" -maxdepth 1 -type d -mtime +"${DAYS_RETENTION}" -exec echo "Removing Directory => {}" \; -exec rm -rf "{}" \;


text:
#import "ImagesCacheTests.h"
#import "ImagesCache.h"
#import "ImageLoader.h"
#import <OCMock/OCMock.h>

#define TEST_URL @"TestImageUrl"

@interface TestLoader :  GHTestCase<ImageLoaderProtocol>
{
}
-(void) startWithUrl:(NSString*)url andCompleteBlock:(CompleteLoadBlock)block;
-(void) cancelDownload;
@end

@implementation TestLoader

-(void) startWithUrl:(NSString*)url andCompleteBlock:(CompleteLoadBlock)block
{
    GHAssertEqualStrings(TEST_URL, url, nil);
    GHAssertNotNil(block, nil);

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"action-bar-icon-like" ofType:@"png"];
    NSData *testImageData = [NSData dataWithContentsOfFile:filePath];
    block(url,testImageData);
}

-(void) cancelDownload
{

}
@end

@implementation ImagesCacheTests

-(void)testGetImageFromEmptyCache
{
    ImagesCache* cache = [[[ImagesCache alloc] init] autorelease];
    GHAssertNil([cache imageFromCache:@"My Test Image URL"], nil);
}

-(void)testloadImageFromUrl
{
    ImagesCache* cache = [[[ImagesCache alloc] init] autorelease];

    [cache loadImageFromUrl:TEST_URL withLoader:[TestLoader class] andCompleteAction:^(ImagesCache* cache){

    }];

    GHAssertNotNil([cache imageFromCache: TEST_URL], nil);

    GHAssertTrue([cache imagesCount] == 1,nil);
    [cache clearCache];
    GHAssertTrue([cache imagesCount] == 0,nil);
}

-(void)testloadImageFromUrlWithBadLoader
{
    ImagesCache* cache = [[[ImagesCache alloc] init] autorelease];

    GHAssertThrows([cache loadImageFromUrl:TEST_URL withLoader:[NSObject class] andCompleteAction:^(ImagesCache* cache){

    }], nil);
}

-(void)testCancelDownload
{
    ImagesCache* cache = [[[ImagesCache alloc] init] autorelease];
    [cache stopOperations];
    GHAssertTrue([cache pendingCount] == 0, nil);
}

@end


text:
import json
import uuid

from keystone.tests import unit
from keystone.tests.unit import test_v3

class PolicyTestCase(test_v3.RestfulTestCase):
    """Test policy CRUD."""

    def setUp(self):
        super(PolicyTestCase, self).setUp()
        self.policy = unit.new_policy_ref()
        self.policy_id = self.policy['id']
        self.policy_api.create_policy(
            self.policy_id,
            self.policy.copy())

    # policy crud tests

    def test_create_policy(self):
        """Call ``POST /policies``."""
        ref = unit.new_policy_ref()
        r = self.post('/policies', body={'policy': ref})
        return self.assertValidPolicyResponse(r, ref)

    def test_list_policies(self):
        """Call ``GET /policies``."""
        r = self.get('/policies')
        self.assertValidPolicyListResponse(r, ref=self.policy)

    def test_get_policy(self):
        """Call ``GET /policies/{policy_id}``."""
        r = self.get(
            '/policies/%(policy_id)s' % {'policy_id': self.policy_id})
        self.assertValidPolicyResponse(r, self.policy)

    def test_update_policy(self):
        """Call ``PATCH /policies/{policy_id}``."""
        self.policy['blob'] = json.dumps({'data': uuid.uuid4().hex, })
        r = self.patch(
            '/policies/%(policy_id)s' % {'policy_id': self.policy_id},
            body={'policy': self.policy})
        self.assertValidPolicyResponse(r, self.policy)

    def test_delete_policy(self):
        """Call ``DELETE /policies/{policy_id}``."""
        self.delete(
            '/policies/%(policy_id)s' % {'policy_id': self.policy_id})


text:
 /*
 * structure.c
 *
 * RO_CSIO_TA2_WDTA_One_Button_Proximity_Sensor example
 * Touch the middle element to turn on/off the center button LED
 * RO method capactiance measurement using Cap sense IO, TimerA2, and WDT+
 *
 * Also provided RO_CSIO_TA2_TA3_One_Button and fRO_CSIO_TA2_TA3_One_Button
 * examples. Users can define by themselves which measuring method is used.
 * All the parameters like threshold are all configured based on specific
 * Launchpad and Boostpack, which may be modified according to user's
 * own applications.
 *
 * Revised by Holly Gu on March 1st
 */
#include "structure.h"

// Proximity Element (P3.4)
const struct Element proximity_element = {
    .inputBits = CAPSIOPOSEL0 + CAPSIOPOSEL1 + CAPSIOPISEL2,   // select 3.4

    // When using an abstracted function to measure the element
    // the 100*(maxResponse - threshold) < 0xFFFF
    // ie maxResponse - threshold < 655

    // RO_CSIO_TA2_WDTA  suggested threshold = 400;
    // RO_CSIO_TA2_TA3   suggested threshold = 750;
    // fRO_CSIO_TA2_TA3   suggested threshold = 500;

    .maxResponse = 400+655,
    .threshold = 400
};

//*** CAP TOUCH HANDLER *******************************************************/
// This defines the grouping of sensors, the method to measure change in
// capacitance, and the function of the group

// One Button Sensor
const struct Sensor proximity_sensor =
{
    /****** For RO_CSIO_TA2_WDTA **************/
    .halDefinition = RO_CSIO_TA2_WDTA,	// RO_CSIO_TA2_WDTA
    .inputCapsioctlRegister = (uint16_t *)&CAPSIO0CTL,
    .numElements = 1,			// # of Elements
    .baseOffset = 0,			// First element index = 0
    // Pointer to elements
    .arrayPtr[0] = &proximity_element,  	// point to middle element
    // Timer Information
    .measGateSource= GATE_WDTA_VLO,         // Gate Clock Source
    .accumulationCycles= WDTA_GATE_64

    /****** For RO_CSIO_TA2_TA3 **************/
    /*.halDefinition = RO_CSIO_TA2_TA3,	// Sensing Method
    .numElements = 1,			// # of Elements
    .baseOffset = 0,			// First element index = 0
    // Pointer to elements
    .arrayPtr[0] = &proximity_element,  	// point to middle element

    // Timer Information, which determine the Gate Time
    .measGateSource= TIMER_SMCLK,     // Clock Source for the Gate Timer A3
    .sourceScale = TIMER_SOURCE_DIV_3,
    .accumulationCycles= 5000        //CCRx for Timer A3*/

    /****** For fRO_CSIO_TA2_TA3 **************/
    /*.halDefinition = fRO_CSIO_TA2_TA3,	// Sensing Method
    .numElements = 1,			// # of Elements
    .baseOffset = 0,			// First element index = 0
    // Pointer to elements
    .arrayPtr[0] = &proximity_element,  // point to middle element

    // Timer Information, which determine the Gate Time
    .measGateSource= TIMER_SMCLK,     // Clock source for Timer A3
    .sourceScale = TIMER_SOURCE_DIV_0,
    .accumulationCycles= 10000
    //CCRx for Gate Timer A2, the clock source is by OSC*/

};


text:
#import <Foundation/Foundation.h>

@class AGSSBJsonTokeniser;
@class AGSSBJsonStreamParser;
@class AGSSBJsonStreamParserState;

typedef enum {
	AGSSBJsonStreamParserComplete,
	AGSSBJsonStreamParserWaitingForData,
	AGSSBJsonStreamParserError,
} AGSSBJsonStreamParserStatus;

/**
 @brief Delegate for interacting directly with the stream parser

 You will most likely find it much more convenient to implement the
 SBJsonStreamParserAdapterDelegate protocol instead.
 */
@protocol AGSSBJsonStreamParserDelegate

/// Called when object start is found
- (void)parserFoundObjectStart:(AGSSBJsonStreamParser*)parser;

/// Called when object key is found
- (void)parser:(AGSSBJsonStreamParser*)parser foundObjectKey:(NSString*)key;

/// Called when object end is found
- (void)parserFoundObjectEnd:(AGSSBJsonStreamParser*)parser;

/// Called when array start is found
- (void)parserFoundArrayStart:(AGSSBJsonStreamParser*)parser;

/// Called when array end is found
- (void)parserFoundArrayEnd:(AGSSBJsonStreamParser*)parser;

/// Called when a boolean value is found
- (void)parser:(AGSSBJsonStreamParser*)parser foundBoolean:(BOOL)x;

/// Called when a null value is found
- (void)parserFoundNull:(AGSSBJsonStreamParser*)parser;

/// Called when a number is found
- (void)parser:(AGSSBJsonStreamParser*)parser foundNumber:(NSNumber*)num;

/// Called when a string is found
- (void)parser:(AGSSBJsonStreamParser*)parser foundString:(NSString*)string;

@end

/**
 @brief Parse a stream of JSON data.

 Using this class directly you can reduce the apparent latency for each
 download/parse cycle of documents over a slow connection. You can start
 parsing *and return chunks of the parsed document* before the entire
 document is downloaded.

 Using this class is also useful to parse huge documents on disk
 bit by bit so you don't have to keep them all in memory.

 @see AGSSBJsonStreamParserAdapter for more information.

 @see @ref objc2json

 */
@interface AGSSBJsonStreamParser : NSObject {
@private
	AGSSBJsonTokeniser *tokeniser;
}

@property (nonatomic, unsafe_unretained) AGSSBJsonStreamParserState *state; // Private
@property (nonatomic, readonly, strong) NSMutableArray *stateStack; // Private

/**
 @brief Expect multiple documents separated by whitespace

 Normally the @p -parse: method returns AGSSBJsonStreamParserComplete when it's found a complete JSON document.
 Attempting to parse any more data at that point is considered an error. ("Garbage after JSON".)

 If you set this property to true the parser will never return AGSSBJsonStreamParserComplete. Rather,
 once an object is completed it will expect another object to immediately follow, separated
 only by (optional) whitespace.

 @see The TweetStream app in the Examples
 */
@property BOOL supportMultipleDocuments;

/**
 @brief Delegate to receive messages

 The object set here receives a series of messages as the parser breaks down the JSON stream
 into valid tokens.

 @note
 Usually this should be an instance of AGSSBJsonStreamParserAdapter, but you can
 substitute your own implementation of the AGSSBJsonStreamParserDelegate protocol if you need to.
 */
@property (unsafe_unretained) id<AGSSBJsonStreamParserDelegate> delegate;

/**
 @brief The max parse depth

 If the input is nested deeper than this the parser will halt parsing and return an error.

 Defaults to 32.
 */
@property NSUInteger maxDepth;

/// Holds the error after AGSSBJsonStreamParserError was returned
@property (copy) NSString *error;

/**
 @brief Parse some JSON

 The JSON is assumed to be UTF8 encoded. This can be a full JSON document, or a part of one.

 @param data An NSData object containing the next chunk of JSON

 @return
 @li AGSSBJsonStreamParserComplete if a full document was found
 @li AGSSBJsonStreamParserWaitingForData if a partial document was found and more data is required to complete it
 @li AGSSBJsonStreamParserError if an error occured. (See the error property for details in this case.)

 */
- (AGSSBJsonStreamParserStatus)parse:(NSData*)data;

@end


text:
import * as React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import { defaultProps, prefix } from '../utils';
import { GridProps } from './Grid.d';

class Grid extends React.Component<GridProps> {
  static propTypes = {
    className: PropTypes.string,
    fluid: PropTypes.bool,
    classPrefix: PropTypes.string,
    componentClass: PropTypes.elementType
  };
  render() {
    const { fluid, componentClass: Component, className, classPrefix, ...props } = this.props;
    const addPrefix = prefix(classPrefix);
    const classes = classNames(fluid ? addPrefix('fluid') : classPrefix, className);
    return <Component {...props} className={classes} />;
  }
}

export default defaultProps<GridProps>({
  componentClass: 'div',
  classPrefix: 'grid-container'
})(Grid);


text:
layout: page
title: "Notebook as Homepage"
description: ""
group: manual
---

{% include JB/setup %}

## Customize your zeppelin homepage
 Zeppelin allows you to use one of the notebooks you create as your zeppelin Homepage.
 With that you can brand your zeppelin installation,
 adjust the instruction to your users needs and even translate to other languages.

### How to set a notebook as your zeppelin homepage

The process for creating your homepage is very simple as shown below:

 1. Create a notebook using zeppelin
 2. Set the notebook id in the config file
 3. Restart zeppelin

#### Create a notebook using zeppelin
  Create a new notebook using zeppelin,
  you can use ```%md``` interpreter for markdown content or any other interpreter you like.

  You can also use the display system to generate [text](../displaysystem/display.html),
  [html](../displaysystem/display.html#html),[table](../displaysystem/table.html) or
   [angular](../displaysystem/angular.html)

   Run (shift+Enter) the notebook and see the output. Optionally, change the notebook view to report to hide
   the code sections.

#### Set the notebook id in the config file
  To set the notebook id in the config file you should copy it from the last word in the notebook url

  for example

  Set the notebook id to the ```ZEPPELIN_NOTEBOOK_HOMESCREEN``` environment variable
  or ```zeppelin.notebook.homescreen``` property.

  You can also set the ```ZEPPELIN_NOTEBOOK_HOMESCREEN_HIDE``` environment variable
  or ```zeppelin.notebook.homescreen.hide``` property to hide the new notebook from the notebook list.

#### Restart zeppelin
  Restart your zeppelin server

  ```
  ./bin/zeppelin-deamon stop
  ./bin/zeppelin-deamon start
  ```
  ####That's it! Open your browser and navigate to zeppelin and see your customized homepage...

### Show notebooks list in your custom homepage
If you want to display the list of notebooks on your custom zeppelin homepage all
you need to do is use our %angular support.

  Add the following code to a paragraph in you home page and run it... walla! you have your notebooks list.

  ```javascript
  println(
  """%angular
    <div class="col-md-4" ng-controller="HomeCtrl as home">
      <h4>Notebooks</h4>
      <div>
        <h5><a href="" data-toggle="modal" data-target="#noteNameModal" style="text-decoration: none;">
          <i style="font-size: 15px;" class="icon-notebook"></i> Create new note</a></h5>
          <ul style="list-style-type: none;">
            <li ng-repeat="note in home.notes.list track by $index"><i style="font-size: 10px;" class="icon-doc"></i>
              <a style="text-decoration: none;" href="#/notebook/{{note.id}}">{{note.name || 'Note ' + note.id}}</a>
            </li>
          </ul>
      </div>
    </div>
  """)
  ```

  After running the notebook you will see output similar to this one:

  The main trick here relays in linking the ```<div>``` to the controller:

  ```javascript
  <div class="col-md-4" ng-controller="HomeCtrl as home">
  ```

  Once we have ```home``` as our controller variable in our ```<div></div>```
  we can use ```home.notes.list``` to get access to the notebook list.


text:
package org.apache.polygene.library.sql.generator.implementation.grammar.query;

import java.util.Objects;
import org.apache.polygene.library.sql.generator.grammar.common.ValueExpression;
import org.apache.polygene.library.sql.generator.grammar.query.Ordering;
import org.apache.polygene.library.sql.generator.grammar.query.SortSpecification;
import org.apache.polygene.library.sql.generator.implementation.grammar.common.SQLSyntaxElementBase;
import org.apache.polygene.library.sql.generator.implementation.transformation.spi.SQLProcessorAggregator;

/**
 * @author Stanislav Muhametsin
 */
public class SortSpecificationImpl extends SQLSyntaxElementBase<SortSpecification, SortSpecification>
    implements SortSpecification
{
    private final Ordering _ordering;

    private final ValueExpression _expression;

    public SortSpecificationImpl( SQLProcessorAggregator processor, ValueExpression expression, Ordering ordering )
    {
        this( processor, SortSpecification.class, expression, ordering );
    }

    protected SortSpecificationImpl( SQLProcessorAggregator processor, Class<? extends SortSpecification> implClass,
                                     ValueExpression expression, Ordering ordering )
    {
        super( processor, implClass );
        Objects.requireNonNull( expression, "expression" );
        Objects.requireNonNull( ordering, "ordering" );

        this._expression = expression;
        this._ordering = ordering;
    }

    public Ordering getOrderingSpecification()
    {
        return this._ordering;
    }

    public ValueExpression getValueExpression()
    {
        return this._expression;
    }

    @Override
    protected boolean doesEqual( SortSpecification another )
    {
        return this._ordering.equals( another.getOrderingSpecification() )
               && this._expression.equals( another.getOrderingSpecification() );
    }
}


text:
package com.dangdang.ddframe.rdb.sharding.example.config.spring.service;

import com.dangdang.ddframe.rdb.sharding.example.config.spring.repository.ConfigRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ConfigServiceImpl implements ConfigService {

    @Resource
    private ConfigRepository configRepository;

    @Override
    public void select() {
        configRepository.select();
    }
}


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

namespace mantis_tests
{
    [TestFixture]
    class ProjectRemovalTests : AuthTestBase
    {
        [Test]
        public void ProjectRemovalTest()

        {
            int index = 0;

            List<ProjectData> oldProjects = app.API.GetAllProjectsByApi(new AccountData());
            if (!app.Project.IsFirstProjecttExist(index))
            {
                ProjectData newProject = new ProjectData { Name = GenerateRandomString(10) };
                app.API.CreateProjectByAPI(newProject, new AccountData());
            }
                app.Project.Remove(index);

            List<ProjectData> newProjects = app.API.GetAllProjectsByApi(new AccountData()); ;

            oldProjects.RemoveAt(index);
            oldProjects.Sort();
            newProjects.Sort();

            Assert.AreEqual(oldProjects, newProjects);
        }

    }
}


text:
const express = require('express');
const sendErrorResponse = require('./utils').sendErrorResponse;

const router = express.Router();
let nextId = 0;
const users = new Map();

// users API Feature
router.get('/', (req, res) => res.json(Array.from(users.values())));
router.get('/:id', (req, res) => {
    const user = users.get(+req.params.id);
    if(!user) {
        sendErrorResponse(req, res, 404, `User with ID=${+req.params.id} does not exist`);
    }
    console.log(user);
    res.json(user);
});

router.post('/', function (req, res) {
    const user = req.body;
    user.id = ++nextId;
    users.set(user.id, user);
    console.log(`Created user: ${user}`);
    res.status(201).location(`/users/${user.id}`).json(user);
})

router.put('/:id', (req, res) => {
    const old = users.get(+req.params.id);
    if(!old) {
        sendErrorResponse(404, `User with ID=${+req.params.id} does not exist`);
    }
    const user = req.body;
    if(old.id !== user.id) {
        sendErrorResponse(400, `User ID=${user.id} does not match URL ID=${+req.params.id}`);
    }

    users.set(user.id, user);
    console.log(`Updated user: ${user}`);
    res.json(user);
});

router.delete('/:id', (req, res) => {
    const old = users.get(+req.params.id);
    if(!old) {
        sendErrorResponse(404, `User with ID=${+req.params.id} does not exist`);
    }

    users.delete(+req.params.id);
    console.log(`Deleted user: ${old}`);
    res.json(old);
});

module.exports = router;


text:
AndroidImageResizer
===================

A Node.js + ImageMagick script for resizing images for Android apps.

## How to Use

Install [ImageMagick for Node.js](https://github.com/rsms/node-imagemagick).

```
npm install imagemagick
```

[ImageMagick for Node.js](https://github.com/rsms/node-imagemagick) requires ImageMagick CLI tools to be installed. There are numerous ways to install them. For instance, if you're on OS X you can use Homebrew:

```
brew install imagemagick
```

Run this script in a directory with some images.

```
node AndroidImageResizer.js
```

Enter starting image size when prompted.

```
Enter current image size [xxxhdpi, xxhdpi, xhdpi, hdpi, mdpi, ldpi]: xxhdpi
```

Enter smallest desired image size when prompted.

```
Enter smallest desired image size [xxxhdpi, xxhdpi, xhdpi, hdpi, mdpi, ldpi]: mdpi
```

Some folders will appear in your directory with all of your resized images.

## License

The MIT License (MIT)

Copyright (c) 2014 Matthew Logan

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
require 'json'
require 'u3d/unity_versions'
require 'u3d/utils'
require 'u3d_core/helper'

module U3d
  module HubModulesParser
    class << self
      HUB_MODULES_NAME = '%<version>s-%<os>s-modules.json'

      def load_modules(version, os: U3dCore::Helper.operating_system, offline: false)
        path = modules_path(version, os)

        # force download if no hub file present
        download_modules(os: os) if !Utils.file_exists_not_empty?(path) && !offline

        unless Utils.file_exists_not_empty?(path)
          UI.verbose "No modules registered for UnityHub for version #{version}"
          # cached_versions.keys.map{|s| UnityVersionNumber.new(s)}
          # searching for closest version
          files = Dir.glob("#{default_modules_path}/*-#{os}-modules.json")

          vn = UnityVersionNumber.new(version)

          versions_and_paths = files.map do |p|
            v = File.basename(p).split('-')[0]
            [UnityVersionNumber.new(v), p]
          end
          # filtered by version major.minor.patch (same major & minor and patch higher or equal)
          versions_and_paths = versions_and_paths.select { |a| a[0].parts[0] == vn.parts[0] && a[0].parts[1] == vn.parts[1] && a[0].parts[2] >= vn.parts[2] }

          if versions_and_paths.empty?
            UI.info "No closest version from UnityHub found for version #{version}"
            return []
          end
          path = versions_and_paths.first[1]
        end

        return JSON.parse(File.read(path))
      end

      def download_modules(os: U3dCore::Helper.operating_system)
        url = UnityVersions.json_url_for(json_os(os))
        builds = UnityVersions.fetch_json(url, UnityVersions::UNITY_LATEST_JSON)
        builds.each { |build| write_modules(build, os) }
        return builds.map { |build| build['versions'] }
      end

      private

      def json_os(os)
        platform_versions = case os
                            when :win
                              UnityVersions::WindowsVersions
                            when :linux
                              UnityVersions::LinuxVersions
                            when :mac
                              UnityVersions::MacVersions
                            end

        return platform_versions::JSON_OS
      end

      def modules_path(version, os)
        file_name = format(HUB_MODULES_NAME, version: version, os: os)
        File.join(default_modules_path, file_name)
      end

      def default_modules_path
        File.join(U3dCore::Helper.data_path, 'unity_hub_modules')
      end

      def write_modules(build, os)
        path = modules_path(build['version'], os)
        Utils.ensure_dir(File.dirname(path))

        File.write(path, build['modules'].to_json)
      end
    end
  end
end


text:
class Editathon < Course
  def wiki_edits_enabled?
    false
  end

  def wiki_title
    nil
  end

  def string_prefix
    'courses_generic'
  end
end


text:
package titlebar.bacy.com.sample;

import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.bacy.view.titlebar.TitleBar;

public class MainActivity extends AppCompatActivity {
    private ImageView mCollectView;
    private boolean mIsSelected;

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        boolean isImmersive = false;
        if (hasKitKat() && !hasLollipop()) {
            isImmersive = true;
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
//                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        } else if (hasLollipop()) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            isImmersive = true;
        }

        final TitleBar titleBar = (TitleBar) findViewById(R.id.title_bar);

        titleBar.setImmersive(isImmersive);

        titleBar.setBackgroundColor(Color.parseColor("#64b4ff"));

        titleBar.setLeftImageResource(R.mipmap.back_green);
        titleBar.setLeftText("返回");
        titleBar.setLeftTextColor(Color.WHITE);
        titleBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        titleBar.setTitle("文章详情\n副标题");
        titleBar.setTitleColor(Color.WHITE);
        titleBar.setSubTitleColor(Color.WHITE);
        titleBar.setDividerColor(Color.GRAY);

        titleBar.setActionTextColor(Color.WHITE);
        mCollectView = (ImageView) titleBar.addAction(new TitleBar.ImageAction(R.mipmap.collect) {
            @Override
            public void performAction(View view) {
                Toast.makeText(MainActivity.this, "点击了收藏", Toast.LENGTH_SHORT).show();
                mCollectView.setImageResource(R.mipmap.fabu);
                titleBar.setTitle(mIsSelected ? "文章详情\n朋友圈" : "帖子详情");
                mIsSelected = !mIsSelected;
            }
        });

        titleBar.addAction(new TitleBar.TextAction("发布") {
            @Override
            public void performAction(View view) {
                Toast.makeText(MainActivity.this, "点击了发布", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public static boolean hasKitKat() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    }

    public static boolean hasLollipop() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
    }
}


text:
CREATE OR REPLACE FUNCTION openclinica_fdw.dm_create_dm_response_set_labels()
  RETURNS VOID AS
  $BODY$
    BEGIN
        EXECUTE $query$
    CREATE MATERIALIZED VIEW dm.response_set_labels AS
        SELECT
            DISTINCT
            md.study_name,
            md.crf_parent_name,
            md.crf_version,
            md.item_group_oid,
            md.item_group_name,
            md.item_form_order,
            md.item_oid,
            md.item_name,
            md.item_description,
            rs.version_id,
            rs.label,
            rs.option_value,
            rs.option_text,
            rs.option_order
        FROM
            dm.metadata AS md
            INNER JOIN
            dm.response_sets AS rs
                ON rs.version_id = md.item_response_set_version
                   AND rs.label = md.item_response_set_label
        ORDER BY
            md.study_name,
            md.crf_parent_name,
            md.crf_version,
            md.item_group_oid,
            md.item_form_order,
            rs.version_id,
            rs.label,
            rs.option_value;
            $query$;
    END;
    $BODY$
LANGUAGE plpgsql VOLATILE;


text:
layout: tagpage
tag: Ciclop
sitemap: false
redirect_from: /category/ciclop/
---


text:
import os
from setuptools import setup

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name = "km3net",
    version = "0.0.1",
    author = "Ben van Werkhoven",
    author_email = "b.vanwerkhoven@esciencecenter.nl",
    description = ("Software for the real-time detection of neutrinos"),
    license = "Apache 2.0",
    keywords = "",
    packages=['km3net'],
    package_dir={'km3net': 'km3net'},
    package_data={"km3net": ['kernels/*.cu']},
    long_description=read('README.md'),
    classifiers=[
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'Intended Audience :: Education',
        'License :: OSI Approved :: Apache Software License',
        'Natural Language :: English',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.5',
        'Topic :: Scientific/Engineering',
        'Development Status :: 2 - Pre-Alpha',
    ],
)


text:
package com.thingtrack.konekti.dao.impl.internal;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.thingtrack.konekti.dao.template.JpaDao;
import com.thingtrack.konekti.dao.api.ProductDao;
import com.thingtrack.konekti.domain.Product;
import com.thingtrack.konekti.domain.User;

/**
 * @author Thingtrack S.L.
 *
 */
@Repository
public class ProductDaoImpl extends JpaDao<Product, Integer> implements ProductDao {
	@Override
	public Product getByCode(String code) throws Exception {
		Product product = (Product)getEntityManager()
				.createQuery("SELECT p FROM " + getEntityName() + " p WHERE p.code = :code")
				.setParameter("code", code).getSingleResult();

		return product;

	}

	@Override
	public Product getByCode(String code, String version) throws Exception {
		Product product = (Product)getEntityManager()
				.createQuery("SELECT p FROM " + getEntityName() + " p WHERE p.code = :code AND p.version = :version")
				.setParameter("code", code)
				.setParameter("version", version).getSingleResult();

		return product;

	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Product> getAll(User user) throws Exception {
		StringBuffer queryString = new StringBuffer("SELECT p FROM " + getEntityName() + " p");

		if (user.getActiveArea() != null)
			queryString.append( " WHERE :area MEMBER OF p.areas");

		Query query = (Query) getEntityManager().createQuery(queryString.toString());

		if (user.getActiveArea() != null)
			query.setParameter("area", user.getActiveArea());

		return query.getResultList();

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getAll(User user, boolean active) throws Exception {
		StringBuffer queryString = new StringBuffer("SELECT p FROM " + getEntityName() + " p");

		queryString.append( " WHERE p.productActive = :active");

		if (user.getActiveArea() != null)
			queryString.append( " AND :area MEMBER OF p.areas");

		Query query = (Query) getEntityManager().createQuery(queryString.toString());

		query.setParameter("active", active);

		if (user.getActiveArea() != null)
			query.setParameter("area", user.getActiveArea());

		// trigger query to refresh the cache.
		query.setHint("javax.persistence.cache.storeMode", "REFRESH");

		return query.getResultList();
	}
}


text:
using EDDiscovery.DB;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;

namespace EDDiscovery2.DB
{
    public class SystemNoteClass
    {
        public long id;
        public long Journalid;              //Journalid = 0, Name set, system marker
        public string Name;                 //Journalid <>0, Name clear, journal marker
        public DateTime Time;
        public string Note;
        public long EdsmId;

        public SystemNoteClass()
        {
        }

        public SystemNoteClass(DataRow dr)
        {
            id = (long)dr["id"];
            Journalid = (long)dr["journalid"];
            Name = (string)dr["Name"];
            Time = (DateTime)dr["Time"];
            Note = (string)dr["Note"];
            EdsmId = (long)dr["EdsmId"];
        }

        public bool Add()
        {
            using (SQLiteConnectionUser cn = new SQLiteConnectionUser())
            {
                bool ret = Add(cn);
                return ret;
            }
        }

        private bool Add(SQLiteConnectionUser cn)
        {
            using (DbCommand cmd = cn.CreateCommand("Insert into SystemNote (Name, Time, Note, journalid, edsmid) values (@name, @time, @note, @journalid, @edsmid)"))
            {
                cmd.AddParameterWithValue("@name", Name);
                cmd.AddParameterWithValue("@time", Time);
                cmd.AddParameterWithValue("@note", Note);
                cmd.AddParameterWithValue("@journalid", Journalid);
                cmd.AddParameterWithValue("@edsmid", EdsmId);

                SQLiteDBClass.SQLNonQueryText(cn, cmd);

                using (DbCommand cmd2 = cn.CreateCommand("Select Max(id) as id from SystemNote"))
                {
                    id = (long)SQLiteDBClass.SQLScalar(cn, cmd2);
                }

                globalSystemNotes.Add(this);
                return true;
            }
        }

        public bool Update()
        {
            using (SQLiteConnectionUser cn = new SQLiteConnectionUser())
            {
                return Update(cn);
            }
        }

        public bool Update(SQLiteConnectionUser cn)
        {
            using (DbCommand cmd = cn.CreateCommand("Update SystemNote set Name=@Name, Time=@Time, Note=@Note, Journalid=@journalid, EdsmId=@EdsmId  where ID=@id"))
            {
                cmd.AddParameterWithValue("@ID", id);
                cmd.AddParameterWithValue("@Name", Name);
                cmd.AddParameterWithValue("@Note", Note);
                cmd.AddParameterWithValue("@Time", Time);
                cmd.AddParameterWithValue("@journalid", Journalid);
                cmd.AddParameterWithValue("@EdsmId", EdsmId);

                SQLiteDBClass.SQLNonQueryText(cn, cmd);
            }

            GetAllSystemNotes();

            return true;
        }

        public static void ClearEDSMID()
        {
            using (SQLiteConnectionUser cn = new SQLiteConnectionUser(utc: true))
            {
                using (DbCommand cmd = cn.CreateCommand("UPDATE SystemNote SET EdsmId=0"))
                {
                    SQLiteDBClass.SQLNonQueryText(cn, cmd);
                }
            }
        }

        public static List<SystemNoteClass> globalSystemNotes = new List<SystemNoteClass>();

        public static bool GetAllSystemNotes()
        {
            try
            {
                using (SQLiteConnectionUser cn = new SQLiteConnectionUser(mode: EDDbAccessMode.Reader))
                {
                    using (DbCommand cmd = cn.CreateCommand("select * from SystemNote"))
                    {
                        DataSet ds = SQLiteDBClass.SQLQueryText(cn, cmd);
                        if (ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                        {
                            return false;
                        }

                        globalSystemNotes.Clear();

                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            SystemNoteClass sys = new SystemNoteClass(dr);
                            globalSystemNotes.Add(sys);
                        }

                        return true;

                    }
                }
            }
            catch
            {
                return false;
            }
        }

        public static SystemNoteClass GetNoteOnSystem(string name, long edsmid = -1)      // case insensitive.. null if not there
        {
            return globalSystemNotes.FindLast(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase) && (edsmid <= 0 || x.EdsmId <= 0 || x.EdsmId == edsmid) );
        }

        public static SystemNoteClass GetNoteOnJournalEntry(long jid)
        {
            if (jid > 0)
                return globalSystemNotes.FindLast(x => x.Journalid == jid);
            else
                return null;
        }

    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/metastore/v1beta/metastore.proto

namespace Google\Cloud\Metastore\V1beta;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Request message for
 * [DataprocMetastore.GetMetadataImport][google.cloud.metastore.v1beta.DataprocMetastore.GetMetadataImport].
 *
 * Generated from protobuf message google.cloud.metastore.v1beta.GetMetadataImportRequest
 */
class GetMetadataImportRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. The relative resource name of the metadata import to retrieve, in
     * the following form:
     * `projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $name = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Required. The relative resource name of the metadata import to retrieve, in
     *           the following form:
     *           `projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}`.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Metastore\V1Beta\Metastore::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. The relative resource name of the metadata import to retrieve, in
     * the following form:
     * `projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. The relative resource name of the metadata import to retrieve, in
     * the following form:
     * `projects/{project_number}/locations/{location_id}/services/{service_id}/metadataImports/{import_id}`.
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

}


text:
RSpec.shared_examples "a git flow repo" do
  let(:repo) { create( described_class.to_s.underscore.to_sym ) }
  context "initialize repo" do
    before(:each) { repo }
    it "should initialize a canonical repo with repo()" do
      expect( repo.repo? ).to be false
      repo.repo
      expect( repo.repo? ).to be true
    end
    it "should create a canonical working directory with working_repo()" do
      expect( repo.working_repo? ).to be false
      repo.working_repo
      expect( repo.working_repo? ).to be true
    end
    it "should create canonical repo and working directory on queue run" do
      expect( repo.repo? ).to be false
      expect( repo.working_repo? ).to be false
      Delayed::Worker.new.work_off
      expect( repo.repo? ).to be true
      expect( repo.working_repo? ).to be true
    end
    it "should destroy canonical repo and working directory on queue run after destroy" do
      repo.working_repo
      repo_path = repo.repo_path
      working_repo_path = repo.working_repo_path
      expect(File.exist? repo_path ).to be true
      expect(File.exist? working_repo_path ).to be true
      repo.destroy
      Delayed::Worker.new.work_off
      expect(File.exist? repo_path ).to be false
      expect(File.exist? working_repo_path ).to be false
    end
  end
  # context "working_file" do
  #   it "should handle repo root" do
  #     file = repo.working_file( "" )
  #     expect( file.exists? ).to be false
  #     repo.working_repo
  #     expect( file.file_name ).to eq ""
  #     expect( file.exists? ).to be true
  #     expect( file.type ).to eq 'dir'
  #     expect( file.content.class ).to be Array
  #     file.content.each do |entry|
  #       expect( entry.class ).to be repo.class.const_get(:WORKING_FILE_CLASS)
  #     end
  #     expect( file.metadata ).to be false
  #     expect( file.ancestors.length ).to eq 1
  #   end
  #   it "should handle repo subdir with metadata" do
  #     repo.working_repo
  #     file = repo.working_file( "laws" )
  #     expect( file.type ).to eq 'dir'
  #     expect( file.metadata.class ).to be Hash
  #     expect( file.ancestors.length ).to eq 2
  #   end
  # end
end


text: Snippets of addon code


text:
<es:model xmlns:es="http://marklogic.com/entity-services">
  <es:info>
      <es:title>Northwind</es:title>
      <es:version>0.0.1</es:version>
      <es:base-uri>http://marklogic.com/test</es:base-uri>
  </es:info>
  <es:definitions/>
</es:model>


text:
/

#endregion

using System;

namespace GSF.ASN1.Attributes.Constraints
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class ASN1SizeConstraint : Attribute
    {
        private long max;

        public long Max
        {
            get
            {
                return max;
            }
            set
            {
                max = value;
            }
        }
    }
}


text:
package co.cask.cdap.security;

import co.cask.cdap.common.security.ImpersonationInfo;
import co.cask.cdap.common.security.UGIProvider;
import org.apache.hadoop.security.UserGroupInformation;

import java.io.IOException;

/**
 * A UGIProvider that always returns the current user.
 */
public class CurrentUGIProvider implements UGIProvider {

  @Override
  public UserGroupInformation getConfiguredUGI(ImpersonationInfo impersonationInfo) throws IOException {
    return UserGroupInformation.getCurrentUser();
  }
}


text:
This script copies backups to mirror directories, optionally using ssh to pull from remote ("target") servers.

Default config:

`/opt/etc/bkp-mirror`

Default source backups:

`/opt/var/bkp`

Default mirror directories:

`/opt/var/bkp-mirror*` (multiple copies)

Default log:

`/opt/var/log/bkp-mirror.log`

## Setting up remote mirroring

1. Setup target server:
```
adduser bkp
chown .bkp /opt/var/bkp
```

2. Setup mirroring server:
```
adduser bkp
su bkp
ssh-keygen -t rsa -b 4096
ssh-copy-id <target_server> -p <target_port>
```

Register target server to "known_hosts" as sudo user or root:
```
sudo ssh <target_server> -p <target_port>
```

Add target server to "/opt/etc/bkp-mirror" config:
```
pull bkp@<target_server:target_port>
```

Test with:
```
/opt/bin/bkp-mirror
```


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">

<link rel="import" href="../../bower_components/paper-dialog/paper-dialog.html">
<link rel="import" href="../../bower_components/paper-dropdown-menu/paper-dropdown-menu.html">
<link rel="import" href="../../bower_components/paper-listbox/paper-listbox.html">
<link rel="import" href="../../bower_components/paper-item/paper-item.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">

<link rel="import" href="../imports/file-saver.html">
<link rel="import" href="../imports/pako.html">

<dom-module id="dtile-map-exporter">
    <template>
        <paper-dialog id="dialog">

Export map

            <paper-dropdown-menu label="Exporter" autofocus>
                <paper-listbox slot="dropdown-content" selected="{{_selectedExporter}}">
                    <template is="dom-repeat" items="[[exporters]]">
                        <paper-item>[[item.exporterName]]</paper-item>
                    </template>
                </paper-listbox>
            </paper-dropdown-menu>

                <paper-button dialog-dismiss>Cancel</paper-button>
                <paper-button dialog-confirm on-tap="_exportTapped">Export</paper-button>

        </paper-dialog>
    </template>
</dom-module>


text:
#include "Step10.h"
#include "mitkInternalEvent.h"
#include "mitkMouseMoveEvent.h"
#include "mitkRenderingManager.h"
#include <mitkPointOperation.h>
//
#include "mitkBaseRenderer.h"
#include "mitkDispatcher.h"
#include <mitkPropertyList.h>

void mitk::ExampleInteractor::ConnectActionsAndFunctions()
{
  // connect the action and condition names of the state machine pattern with function within
  // this DataInteractor
  CONNECT_CONDITION("checkPoint", CheckPoint);
  CONNECT_FUNCTION("addPoint", AddPoint);
  CONNECT_FUNCTION("enoughPoints", EnoughPoints);
}

bool mitk::ExampleInteractor::CheckPoint(const InteractionEvent *interactionEvent)
{
  // check if a point close to the clicked position already exists
  float epsilon = 0.3; // do not accept new points within 3mm range of existing points
  InteractionPositionEvent *positionEvent = dynamic_cast<InteractionPositionEvent *>(interactionEvent);
  if (positionEvent != nullptr)
  {
    // query the position of the mouse in the world geometry
    mitk::Point3D point = positionEvent->GetPositionInWorld();
    int retVal = m_PointSet->SearchPoint(point, epsilon);
    if (retVal == -1) // SearchPoint returns -1 if no point was found within given range
      return true;
  }
  return false; // if the positionEvent is nullptr or a point was found return false. AddPoint will not be executed
  // end
}

bool mitk::ExampleInteractor::AddPoint(StateMachineAction *, InteractionEvent *interactionEvent)
{
  // cast InteractionEvent to a position event in order to read out the mouse position
  // we stay here as general as possible so that a different state machine pattern
  // can reuse this code with MouseRelease or MouseMoveEvents.
  InteractionPositionEvent *positionEvent = dynamic_cast<InteractionPositionEvent *>(interactionEvent);
  if (positionEvent != nullptr)
  {
    // query the position of the mouse in the world geometry
    mitk::Point3D point = positionEvent->GetPositionInWorld();
    m_PointSet->InsertPoint(m_NumberOfPoints, point, 0);
    m_NumberOfPoints++;
    GetDataNode()->SetData(m_PointSet);
    GetDataNode()->Modified();

    if (m_NumberOfPoints != 0 && m_NumberOfPoints >= m_MaximalNumberOfPoints)
    {
      // create internal event that signal that the maximal number of points is reached
      InternalEvent::Pointer event = InternalEvent::New(nullptr, this, "enoughPointsAdded");
      // add the internal event to the event queue of the Dispatcher
      positionEvent->GetSender()->GetDispatcher()->QueueEvent(event.GetPointer());
    }
    // update the RenderWindow to show new points
    mitk::RenderingManager::GetInstance()->RequestUpdateAll();
    return true;
  }
  else
  {
    return false;
  }
}

bool mitk::ExampleInteractor::EnoughPoints(StateMachineAction *, InteractionEvent *)
{
  GetDataNode()->SetProperty("contourcolor", ColorProperty::New(1.0, 1.0, 0.0));
  mitk::RenderingManager::GetInstance()->RequestUpdateAll();
  return true;
} //-

mitk::ExampleInteractor::ExampleInteractor()
{
  m_NumberOfPoints = 0;
  m_MaximalNumberOfPoints = 0;
  m_PointSet = PointSet::New(); // create PointSet to store our point in
}

mitk::ExampleInteractor::~ExampleInteractor()
{
}

void mitk::ExampleInteractor::ConfigurationChanged()
{
  // read how many points we accept from the config properties
  mitk::PropertyList::Pointer properties = GetPropertyList();
  std::string maxNumber;
  properties->GetStringProperty("NumberOfPoints", maxNumber);
  m_MaximalNumberOfPoints = atoi(maxNumber.c_str());
}


text:
class CreateSpaces < ActiveRecord::Migration
  def up
    create_table :spaces do |t|
      t.string :url, :name
    end
    add_index :spaces, :url
    add_index :spaces, :name
  end

  def down
    drop_table :spaces
  end
end