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

#include "flutter/shell/platform/android/platform_view_android_jni_impl.h"

#include <android/native_window_jni.h>
#include <jni.h>
#include <utility>

#include "unicode/uchar.h"

#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/common/settings.h"
#include "flutter/fml/file.h"
#include "flutter/fml/platform/android/jni_util.h"
#include "flutter/fml/platform/android/jni_weak_ref.h"
#include "flutter/fml/platform/android/scoped_java_ref.h"
#include "flutter/fml/size.h"
#include "flutter/lib/ui/plugins/callback_cache.h"
#include "flutter/runtime/dart_service_isolate.h"
#include "flutter/shell/common/run_configuration.h"
#include "flutter/shell/platform/android/android_external_texture_gl.h"
#include "flutter/shell/platform/android/android_shell_holder.h"
#include "flutter/shell/platform/android/apk_asset_provider.h"
#include "flutter/shell/platform/android/flutter_main.h"
#include "flutter/shell/platform/android/jni/platform_view_android_jni.h"
#include "flutter/shell/platform/android/platform_view_android.h"

#define ANDROID_SHELL_HOLDER \
  (reinterpret_cast<AndroidShellHolder*>(shell_holder))

namespace flutter {

namespace {

bool CheckException(JNIEnv* env) {
  if (env->ExceptionCheck() == JNI_FALSE)
    return true;

  jthrowable exception = env->ExceptionOccurred();
  env->ExceptionClear();
  FML_LOG(ERROR) << fml::jni::GetJavaExceptionInfo(env, exception);
  env->DeleteLocalRef(exception);
  return false;
}

}  // anonymous namespace

static fml::jni::ScopedJavaGlobalRef<jclass>* g_flutter_callback_info_class =
    nullptr;

static fml::jni::ScopedJavaGlobalRef<jclass>* g_flutter_jni_class = nullptr;

static fml::jni::ScopedJavaGlobalRef<jclass>* g_surface_texture_class = nullptr;

// Called By Native

static jmethodID g_flutter_callback_info_constructor = nullptr;
jobject CreateFlutterCallbackInformation(
    JNIEnv* env,
    const std::string& callbackName,
    const std::string& callbackClassName,
    const std::string& callbackLibraryPath) {
  return env->NewObject(g_flutter_callback_info_class->obj(),
                        g_flutter_callback_info_constructor,
                        env->NewStringUTF(callbackName.c_str()),
                        env->NewStringUTF(callbackClassName.c_str()),
                        env->NewStringUTF(callbackLibraryPath.c_str()));
}

static jmethodID g_handle_platform_message_method = nullptr;

static jmethodID g_handle_platform_message_response_method = nullptr;

static jmethodID g_update_semantics_method = nullptr;

static jmethodID g_update_custom_accessibility_actions_method = nullptr;

static jmethodID g_on_first_frame_method = nullptr;

static jmethodID g_on_engine_restart_method = nullptr;

static jmethodID g_create_overlay_surface_method = nullptr;

static jmethodID g_destroy_overlay_surfaces_method = nullptr;

static jmethodID g_on_begin_frame_method = nullptr;

static jmethodID g_on_end_frame_method = nullptr;

static jmethodID g_attach_to_gl_context_method = nullptr;

static jmethodID g_update_tex_image_method = nullptr;

static jmethodID g_get_transform_matrix_method = nullptr;

static jmethodID g_detach_from_gl_context_method = nullptr;

static jmethodID g_compute_platform_resolved_locale_method = nullptr;

// Called By Java
static jmethodID g_on_display_platform_view_method = nullptr;

// static jmethodID g_on_composite_platform_view_method = nullptr;

static jmethodID g_on_display_overlay_surface_method = nullptr;

static jmethodID g_overlay_surface_id_method = nullptr;

static jmethodID g_overlay_surface_surface_method = nullptr;

// Mutators
static fml::jni::ScopedJavaGlobalRef<jclass>* g_mutators_stack_class = nullptr;
static jmethodID g_mutators_stack_init_method = nullptr;
static jmethodID g_mutators_stack_push_transform_method = nullptr;
static jmethodID g_mutators_stack_push_cliprect_method = nullptr;

// Called By Java
static jlong AttachJNI(JNIEnv* env,
                       jclass clazz,
                       jobject flutterJNI,
                       jboolean is_background_view) {
  fml::jni::JavaObjectWeakGlobalRef java_object(env, flutterJNI);
  std::shared_ptr<PlatformViewAndroidJNI> jni_facade =
      std::make_shared<PlatformViewAndroidJNIImpl>(java_object);
  auto shell_holder = std::make_unique<AndroidShellHolder>(
      FlutterMain::Get().GetSettings(), jni_facade, is_background_view);
  if (shell_holder->IsValid()) {
    return reinterpret_cast<jlong>(shell_holder.release());
  } else {
    return 0;
  }
}

static void DestroyJNI(JNIEnv* env, jobject jcaller, jlong shell_holder) {
  delete ANDROID_SHELL_HOLDER;
}

static void SurfaceCreated(JNIEnv* env,
                           jobject jcaller,
                           jlong shell_holder,
                           jobject jsurface) {
  // Note: This frame ensures that any local references used by
  // ANativeWindow_fromSurface are released immediately. This is needed as a
  // workaround for https://code.google.com/p/android/issues/detail?id=68174
  fml::jni::ScopedJavaLocalFrame scoped_local_reference_frame(env);
  auto window = fml::MakeRefCounted<AndroidNativeWindow>(
      ANativeWindow_fromSurface(env, jsurface));
  ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyCreated(std::move(window));
}

static void SurfaceWindowChanged(JNIEnv* env,
                                 jobject jcaller,
                                 jlong shell_holder,
                                 jobject jsurface) {
  // Note: This frame ensures that any local references used by
  // ANativeWindow_fromSurface are released immediately. This is needed as a
  // workaround for https://code.google.com/p/android/issues/detail?id=68174
  fml::jni::ScopedJavaLocalFrame scoped_local_reference_frame(env);
  auto window = fml::MakeRefCounted<AndroidNativeWindow>(
      ANativeWindow_fromSurface(env, jsurface));
  ANDROID_SHELL_HOLDER->GetPlatformView()->NotifySurfaceWindowChanged(
      std::move(window));
}

static void SurfaceChanged(JNIEnv* env,
                           jobject jcaller,
                           jlong shell_holder,
                           jint width,
                           jint height) {
  ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyChanged(
      SkISize::Make(width, height));
}

static void SurfaceDestroyed(JNIEnv* env, jobject jcaller, jlong shell_holder) {
  ANDROID_SHELL_HOLDER->GetPlatformView()->NotifyDestroyed();
}

static void RunBundleAndSnapshotFromLibrary(JNIEnv* env,
                                            jobject jcaller,
                                            jlong shell_holder,
                                            jstring jBundlePath,
                                            jstring jEntrypoint,
                                            jstring jLibraryUrl,
                                            jobject jAssetManager) {
  auto asset_manager = std::make_shared<flutter::AssetManager>();

  asset_manager->PushBack(std::make_unique<flutter::APKAssetProvider>(
      env,                                             // jni environment
      jAssetManager,                                   // asset manager
      fml::jni::JavaStringToString(env, jBundlePath))  // apk asset dir
  );

  std::unique_ptr<IsolateConfiguration> isolate_configuration;
  if (flutter::DartVM::IsRunningPrecompiledCode()) {
    isolate_configuration = IsolateConfiguration::CreateForAppSnapshot();
  } else {
    std::unique_ptr<fml::Mapping> kernel_blob =
        fml::FileMapping::CreateReadOnly(
            ANDROID_SHELL_HOLDER->GetSettings().application_kernel_asset);
    if (!kernel_blob) {
      FML_DLOG(ERROR) << "Unable to load the kernel blob asset.";
      return;
    }
    isolate_configuration =
        IsolateConfiguration::CreateForKernel(std::move(kernel_blob));
  }

  RunConfiguration config(std::move(isolate_configuration),
                          std::move(asset_manager));

  {
    auto entrypoint = fml::jni::JavaStringToString(env, jEntrypoint);
    auto libraryUrl = fml::jni::JavaStringToString(env, jLibraryUrl);

    if ((entrypoint.size() > 0) && (libraryUrl.size() > 0)) {
      config.SetEntrypointAndLibrary(std::move(entrypoint),
                                     std::move(libraryUrl));
    } else if (entrypoint.size() > 0) {
      config.SetEntrypoint(std::move(entrypoint));
    }
  }

  ANDROID_SHELL_HOLDER->Launch(std::move(config));
}

static jobject LookupCallbackInformation(JNIEnv* env,
                                         /* unused */ jobject,
                                         jlong handle) {
  auto cbInfo = flutter::DartCallbackCache::GetCallbackInformation(handle);
  if (cbInfo == nullptr) {
    return nullptr;
  }
  return CreateFlutterCallbackInformation(env, cbInfo->name, cbInfo->class_name,
                                          cbInfo->library_path);
}

static void SetViewportMetrics(JNIEnv* env,
                               jobject jcaller,
                               jlong shell_holder,
                               jfloat devicePixelRatio,
                               jint physicalWidth,
                               jint physicalHeight,
                               jint physicalPaddingTop,
                               jint physicalPaddingRight,
                               jint physicalPaddingBottom,
                               jint physicalPaddingLeft,
                               jint physicalViewInsetTop,
                               jint physicalViewInsetRight,
                               jint physicalViewInsetBottom,
                               jint physicalViewInsetLeft,
                               jint systemGestureInsetTop,
                               jint systemGestureInsetRight,
                               jint systemGestureInsetBottom,
                               jint systemGestureInsetLeft) {
  const flutter::ViewportMetrics metrics{
      static_cast<double>(devicePixelRatio),
      static_cast<double>(physicalWidth),
      static_cast<double>(physicalHeight),
      static_cast<double>(physicalPaddingTop),
      static_cast<double>(physicalPaddingRight),
      static_cast<double>(physicalPaddingBottom),
      static_cast<double>(physicalPaddingLeft),
      static_cast<double>(physicalViewInsetTop),
      static_cast<double>(physicalViewInsetRight),
      static_cast<double>(physicalViewInsetBottom),
      static_cast<double>(physicalViewInsetLeft),
      static_cast<double>(systemGestureInsetTop),
      static_cast<double>(systemGestureInsetRight),
      static_cast<double>(systemGestureInsetBottom),
      static_cast<double>(systemGestureInsetLeft),
  };

  ANDROID_SHELL_HOLDER->GetPlatformView()->SetViewportMetrics(metrics);
}

static jobject GetBitmap(JNIEnv* env, jobject jcaller, jlong shell_holder) {
  auto screenshot = ANDROID_SHELL_HOLDER->Screenshot(
      Rasterizer::ScreenshotType::UncompressedImage, false);
  if (screenshot.data == nullptr) {
    return nullptr;
  }

  const SkISize& frame_size = screenshot.frame_size;
  jsize pixels_size = frame_size.width() * frame_size.height();
  jintArray pixels_array = env->NewIntArray(pixels_size);
  if (pixels_array == nullptr) {
    return nullptr;
  }

  jint* pixels = env->GetIntArrayElements(pixels_array, nullptr);
  if (pixels == nullptr) {
    return nullptr;
  }

  auto* pixels_src = static_cast<const int32_t*>(screenshot.data->data());

  // Our configuration of Skia does not support rendering to the
  // BitmapConfig.ARGB_8888 format expected by android.graphics.Bitmap.
  // Convert from kRGBA_8888 to kBGRA_8888 (equivalent to ARGB_8888).
  for (int i = 0; i < pixels_size; i++) {
    int32_t src_pixel = pixels_src[i];
    uint8_t* src_bytes = reinterpret_cast<uint8_t*>(&src_pixel);
    std::swap(src_bytes[0], src_bytes[2]);
    pixels[i] = src_pixel;
  }

  env->ReleaseIntArrayElements(pixels_array, pixels, 0);

  jclass bitmap_class = env->FindClass("android/graphics/Bitmap");
  if (bitmap_class == nullptr) {
    return nullptr;
  }

  jmethodID create_bitmap = env->GetStaticMethodID(
      bitmap_class, "createBitmap",
      "([IIILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
  if (create_bitmap == nullptr) {
    return nullptr;
  }

  jclass bitmap_config_class = env->FindClass("android/graphics/Bitmap$Config");
  if (bitmap_config_class == nullptr) {
    return nullptr;
  }

  jmethodID bitmap_config_value_of = env->GetStaticMethodID(
      bitmap_config_class, "valueOf",
      "(Ljava/lang/String;)Landroid/graphics/Bitmap$Config;");
  if (bitmap_config_value_of == nullptr) {
    return nullptr;
  }

  jstring argb = env->NewStringUTF("ARGB_8888");
  if (argb == nullptr) {
    return nullptr;
  }

  jobject bitmap_config = env->CallStaticObjectMethod(
      bitmap_config_class, bitmap_config_value_of, argb);
  if (bitmap_config == nullptr) {
    return nullptr;
  }

  return env->CallStaticObjectMethod(bitmap_class, create_bitmap, pixels_array,
                                     frame_size.width(), frame_size.height(),
                                     bitmap_config);
}

static void DispatchPlatformMessage(JNIEnv* env,
                                    jobject jcaller,
                                    jlong shell_holder,
                                    jstring channel,
                                    jobject message,
                                    jint position,
                                    jint responseId) {
  ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchPlatformMessage(
      env,                                         //
      fml::jni::JavaStringToString(env, channel),  //
      message,                                     //
      position,                                    //
      responseId                                   //
  );
}

static void DispatchEmptyPlatformMessage(JNIEnv* env,
                                         jobject jcaller,
                                         jlong shell_holder,
                                         jstring channel,
                                         jint responseId) {
  ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchEmptyPlatformMessage(
      env,                                         //
      fml::jni::JavaStringToString(env, channel),  //
      responseId                                   //
  );
}

static void DispatchPointerDataPacket(JNIEnv* env,
                                      jobject jcaller,
                                      jlong shell_holder,
                                      jobject buffer,
                                      jint position) {
  uint8_t* data = static_cast<uint8_t*>(env->GetDirectBufferAddress(buffer));
  auto packet = std::make_unique<flutter::PointerDataPacket>(data, position);
  ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchPointerDataPacket(
      std::move(packet));
}

static void DispatchSemanticsAction(JNIEnv* env,
                                    jobject jcaller,
                                    jlong shell_holder,
                                    jint id,
                                    jint action,
                                    jobject args,
                                    jint args_position) {
  ANDROID_SHELL_HOLDER->GetPlatformView()->DispatchSemanticsAction(
      env,           //
      id,            //
      action,        //
      args,          //
      args_position  //
  );
}

static void SetSemanticsEnabled(JNIEnv* env,
                                jobject jcaller,
                                jlong shell_holder,
                                jboolean enabled) {
  ANDROID_SHELL_HOLDER->GetPlatformView()->SetSemanticsEnabled(enabled);
}

static void SetAccessibilityFeatures(JNIEnv* env,
                                     jobject jcaller,
                                     jlong shell_holder,
                                     jint flags) {
  ANDROID_SHELL_HOLDER->GetPlatformView()->SetAccessibilityFeatures(flags);
}

static jboolean GetIsSoftwareRendering(JNIEnv* env, jobject jcaller) {
  return FlutterMain::Get().GetSettings().enable_software_rendering;
}

static void RegisterTexture(JNIEnv* env,
                            jobject jcaller,
                            jlong shell_holder,
                            jlong texture_id,
                            jobject surface_texture) {
  ANDROID_SHELL_HOLDER->GetPlatformView()->RegisterExternalTexture(
      static_cast<int64_t>(texture_id),                        //
      fml::jni::JavaObjectWeakGlobalRef(env, surface_texture)  //
  );
}

static void MarkTextureFrameAvailable(JNIEnv* env,
                                      jobject jcaller,
                                      jlong shell_holder,
                                      jlong texture_id) {
  ANDROID_SHELL_HOLDER->GetPlatformView()->MarkTextureFrameAvailable(
      static_cast<int64_t>(texture_id));
}

static void UnregisterTexture(JNIEnv* env,
                              jobject jcaller,
                              jlong shell_holder,
                              jlong texture_id) {
  ANDROID_SHELL_HOLDER->GetPlatformView()->UnregisterTexture(
      static_cast<int64_t>(texture_id));
}

static void InvokePlatformMessageResponseCallback(JNIEnv* env,
                                                  jobject jcaller,
                                                  jlong shell_holder,
                                                  jint responseId,
                                                  jobject message,
                                                  jint position) {
  ANDROID_SHELL_HOLDER->GetPlatformView()
      ->InvokePlatformMessageResponseCallback(env,         //
                                              responseId,  //
                                              message,     //
                                              position     //
      );
}

static void InvokePlatformMessageEmptyResponseCallback(JNIEnv* env,
                                                       jobject jcaller,
                                                       jlong shell_holder,
                                                       jint responseId) {
  ANDROID_SHELL_HOLDER->GetPlatformView()
      ->InvokePlatformMessageEmptyResponseCallback(env,        //
                                                   responseId  //
      );
}

static void NotifyLowMemoryWarning(JNIEnv* env,
                                   jobject obj,
                                   jlong shell_holder) {
  ANDROID_SHELL_HOLDER->NotifyLowMemoryWarning();
}

static jboolean FlutterTextUtilsIsEmoji(JNIEnv* env,
                                        jobject obj,
                                        jint codePoint) {
  return u_hasBinaryProperty(codePoint, UProperty::UCHAR_EMOJI);
}

static jboolean FlutterTextUtilsIsEmojiModifier(JNIEnv* env,
                                                jobject obj,
                                                jint codePoint) {
  return u_hasBinaryProperty(codePoint, UProperty::UCHAR_EMOJI_MODIFIER);
}

static jboolean FlutterTextUtilsIsEmojiModifierBase(JNIEnv* env,
                                                    jobject obj,
                                                    jint codePoint) {
  return u_hasBinaryProperty(codePoint, UProperty::UCHAR_EMOJI_MODIFIER_BASE);
}

static jboolean FlutterTextUtilsIsVariationSelector(JNIEnv* env,
                                                    jobject obj,
                                                    jint codePoint) {
  return u_hasBinaryProperty(codePoint, UProperty::UCHAR_VARIATION_SELECTOR);
}

static jboolean FlutterTextUtilsIsRegionalIndicator(JNIEnv* env,
                                                    jobject obj,
                                                    jint codePoint) {
  return u_hasBinaryProperty(codePoint, UProperty::UCHAR_REGIONAL_INDICATOR);
}
bool RegisterApi(JNIEnv* env) {
  static const JNINativeMethod flutter_jni_methods[] = {
      // Start of methods from FlutterJNI
      {
          .name = "nativeAttach",
          .signature = "(Lio/flutter/embedding/engine/FlutterJNI;Z)J",
          .fnPtr = reinterpret_cast<void*>(&AttachJNI),
      },
      {
          .name = "nativeDestroy",
          .signature = "(J)V",
          .fnPtr = reinterpret_cast<void*>(&DestroyJNI),
      },
      {
          .name = "nativeRunBundleAndSnapshotFromLibrary",
          .signature = "(JLjava/lang/String;Ljava/lang/String;"
                       "Ljava/lang/String;Landroid/content/res/AssetManager;)V",
          .fnPtr = reinterpret_cast<void*>(&RunBundleAndSnapshotFromLibrary),
      },
      {
          .name = "nativeDispatchEmptyPlatformMessage",
          .signature = "(JLjava/lang/String;I)V",
          .fnPtr = reinterpret_cast<void*>(&DispatchEmptyPlatformMessage),
      },
      {
          .name = "nativeDispatchPlatformMessage",
          .signature = "(JLjava/lang/String;Ljava/nio/ByteBuffer;II)V",
          .fnPtr = reinterpret_cast<void*>(&DispatchPlatformMessage),
      },
      {
          .name = "nativeInvokePlatformMessageResponseCallback",
          .signature = "(JILjava/nio/ByteBuffer;I)V",
          .fnPtr =
              reinterpret_cast<void*>(&InvokePlatformMessageResponseCallback),
      },
      {
          .name = "nativeInvokePlatformMessageEmptyResponseCallback",
          .signature = "(JI)V",
          .fnPtr = reinterpret_cast<void*>(
              &InvokePlatformMessageEmptyResponseCallback),
      },
      {
          .name = "nativeNotifyLowMemoryWarning",
          .signature = "(J)V",
          .fnPtr = reinterpret_cast<void*>(&NotifyLowMemoryWarning),
      },

      // Start of methods from FlutterView
      {
          .name = "nativeGetBitmap",
          .signature = "(J)Landroid/graphics/Bitmap;",
          .fnPtr = reinterpret_cast<void*>(&GetBitmap),
      },
      {
          .name = "nativeSurfaceCreated",
          .signature = "(JLandroid/view/Surface;)V",
          .fnPtr = reinterpret_cast<void*>(&SurfaceCreated),
      },
      {
          .name = "nativeSurfaceWindowChanged",
          .signature = "(JLandroid/view/Surface;)V",
          .fnPtr = reinterpret_cast<void*>(&SurfaceWindowChanged),
      },
      {
          .name = "nativeSurfaceChanged",
          .signature = "(JII)V",
          .fnPtr = reinterpret_cast<void*>(&SurfaceChanged),
      },
      {
          .name = "nativeSurfaceDestroyed",
          .signature = "(J)V",
          .fnPtr = reinterpret_cast<void*>(&SurfaceDestroyed),
      },
      {
          .name = "nativeSetViewportMetrics",
          .signature = "(JFIIIIIIIIIIIIII)V",
          .fnPtr = reinterpret_cast<void*>(&SetViewportMetrics),
      },
      {
          .name = "nativeDispatchPointerDataPacket",
          .signature = "(JLjava/nio/ByteBuffer;I)V",
          .fnPtr = reinterpret_cast<void*>(&DispatchPointerDataPacket),
      },
      {
          .name = "nativeDispatchSemanticsAction",
          .signature = "(JIILjava/nio/ByteBuffer;I)V",
          .fnPtr = reinterpret_cast<void*>(&DispatchSemanticsAction),
      },
      {
          .name = "nativeSetSemanticsEnabled",
          .signature = "(JZ)V",
          .fnPtr = reinterpret_cast<void*>(&SetSemanticsEnabled),
      },
      {
          .name = "nativeSetAccessibilityFeatures",
          .signature = "(JI)V",
          .fnPtr = reinterpret_cast<void*>(&SetAccessibilityFeatures),
      },
      {
          .name = "nativeGetIsSoftwareRenderingEnabled",
          .signature = "()Z",
          .fnPtr = reinterpret_cast<void*>(&GetIsSoftwareRendering),
      },
      {
          .name = "nativeRegisterTexture",
          .signature = "(JJLandroid/graphics/SurfaceTexture;)V",
          .fnPtr = reinterpret_cast<void*>(&RegisterTexture),
      },
      {
          .name = "nativeMarkTextureFrameAvailable",
          .signature = "(JJ)V",
          .fnPtr = reinterpret_cast<void*>(&MarkTextureFrameAvailable),
      },
      {
          .name = "nativeUnregisterTexture",
          .signature = "(JJ)V",
          .fnPtr = reinterpret_cast<void*>(&UnregisterTexture),
      },

      // Methods for Dart callback functionality.
      {
          .name = "nativeLookupCallbackInformation",
          .signature = "(J)Lio/flutter/view/FlutterCallbackInformation;",
          .fnPtr = reinterpret_cast<void*>(&LookupCallbackInformation),
      },

      // Start of methods for FlutterTextUtils
      {
          .name = "nativeFlutterTextUtilsIsEmoji",
          .signature = "(I)Z",
          .fnPtr = reinterpret_cast<void*>(&FlutterTextUtilsIsEmoji),
      },
      {
          .name = "nativeFlutterTextUtilsIsEmojiModifier",
          .signature = "(I)Z",
          .fnPtr = reinterpret_cast<void*>(&FlutterTextUtilsIsEmojiModifier),
      },
      {
          .name = "nativeFlutterTextUtilsIsEmojiModifierBase",
          .signature = "(I)Z",
          .fnPtr =
              reinterpret_cast<void*>(&FlutterTextUtilsIsEmojiModifierBase),
      },
      {
          .name = "nativeFlutterTextUtilsIsVariationSelector",
          .signature = "(I)Z",
          .fnPtr =
              reinterpret_cast<void*>(&FlutterTextUtilsIsVariationSelector),
      },
      {
          .name = "nativeFlutterTextUtilsIsRegionalIndicator",
          .signature = "(I)Z",
          .fnPtr =
              reinterpret_cast<void*>(&FlutterTextUtilsIsRegionalIndicator),
      },
  };

  if (env->RegisterNatives(g_flutter_jni_class->obj(), flutter_jni_methods,
                           fml::size(flutter_jni_methods)) != 0) {
    FML_LOG(ERROR) << "Failed to RegisterNatives with FlutterJNI";
    return false;
  }

  g_handle_platform_message_method =
      env->GetMethodID(g_flutter_jni_class->obj(), "handlePlatformMessage",
                       "(Ljava/lang/String;[BI)V");

  if (g_handle_platform_message_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate handlePlatformMessage method";
    return false;
  }

  g_handle_platform_message_response_method = env->GetMethodID(
      g_flutter_jni_class->obj(), "handlePlatformMessageResponse", "(I[B)V");

  if (g_handle_platform_message_response_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate handlePlatformMessageResponse method";
    return false;
  }

  g_update_semantics_method =
      env->GetMethodID(g_flutter_jni_class->obj(), "updateSemantics",
                       "(Ljava/nio/ByteBuffer;[Ljava/lang/String;)V");

  if (g_update_semantics_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate updateSemantics method";
    return false;
  }

  g_update_custom_accessibility_actions_method = env->GetMethodID(
      g_flutter_jni_class->obj(), "updateCustomAccessibilityActions",
      "(Ljava/nio/ByteBuffer;[Ljava/lang/String;)V");

  if (g_update_custom_accessibility_actions_method == nullptr) {
    FML_LOG(ERROR)
        << "Could not locate updateCustomAccessibilityActions method";
    return false;
  }

  g_on_first_frame_method =
      env->GetMethodID(g_flutter_jni_class->obj(), "onFirstFrame", "()V");

  if (g_on_first_frame_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate onFirstFrame method";
    return false;
  }

  g_on_engine_restart_method =
      env->GetMethodID(g_flutter_jni_class->obj(), "onPreEngineRestart", "()V");

  if (g_on_engine_restart_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate onEngineRestart method";
    return false;
  }

  g_create_overlay_surface_method =
      env->GetMethodID(g_flutter_jni_class->obj(), "createOverlaySurface",
                       "()Lio/flutter/embedding/engine/FlutterOverlaySurface;");

  if (g_create_overlay_surface_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate createOverlaySurface method";
    return false;
  }

  g_destroy_overlay_surfaces_method = env->GetMethodID(
      g_flutter_jni_class->obj(), "destroyOverlaySurfaces", "()V");

  if (g_destroy_overlay_surfaces_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate destroyOverlaySurfaces method";
    return false;
  }

  fml::jni::ScopedJavaLocalRef<jclass> overlay_surface_class(
      env, env->FindClass("io/flutter/embedding/engine/FlutterOverlaySurface"));
  if (overlay_surface_class.is_null()) {
    FML_LOG(ERROR) << "Could not locate FlutterOverlaySurface class";
    return false;
  }
  g_overlay_surface_id_method =
      env->GetMethodID(overlay_surface_class.obj(), "getId", "()I");
  if (g_overlay_surface_id_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate FlutterOverlaySurface#getId() method";
    return false;
  }
  g_overlay_surface_surface_method = env->GetMethodID(
      overlay_surface_class.obj(), "getSurface", "()Landroid/view/Surface;");
  if (g_overlay_surface_surface_method == nullptr) {
    FML_LOG(ERROR)
        << "Could not locate FlutterOverlaySurface#getSurface() method";
    return false;
  }

  return true;
}

bool PlatformViewAndroid::Register(JNIEnv* env) {
  if (env == nullptr) {
    FML_LOG(ERROR) << "No JNIEnv provided";
    return false;
  }

  g_flutter_callback_info_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
      env, env->FindClass("io/flutter/view/FlutterCallbackInformation"));
  if (g_flutter_callback_info_class->is_null()) {
    FML_LOG(ERROR) << "Could not locate FlutterCallbackInformation class";
    return false;
  }

  g_flutter_callback_info_constructor = env->GetMethodID(
      g_flutter_callback_info_class->obj(), "<init>",
      "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
  if (g_flutter_callback_info_constructor == nullptr) {
    FML_LOG(ERROR) << "Could not locate FlutterCallbackInformation constructor";
    return false;
  }

  g_flutter_jni_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
      env, env->FindClass("io/flutter/embedding/engine/FlutterJNI"));
  if (g_flutter_jni_class->is_null()) {
    FML_LOG(ERROR) << "Failed to find FlutterJNI Class.";
    return false;
  }

  g_mutators_stack_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
      env,
      env->FindClass(
          "io/flutter/embedding/engine/mutatorsstack/FlutterMutatorsStack"));
  if (g_mutators_stack_class == nullptr) {
    FML_LOG(ERROR) << "Could not locate FlutterMutatorsStack";
    return false;
  }

  g_mutators_stack_init_method =
      env->GetMethodID(g_mutators_stack_class->obj(), "<init>", "()V");
  if (g_mutators_stack_init_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate FlutterMutatorsStack.init method";
    return false;
  }

  g_mutators_stack_push_transform_method =
      env->GetMethodID(g_mutators_stack_class->obj(), "pushTransform", "([F)V");
  if (g_mutators_stack_push_transform_method == nullptr) {
    FML_LOG(ERROR)
        << "Could not locate FlutterMutatorsStack.pushTransform method";
    return false;
  }

  g_mutators_stack_push_cliprect_method = env->GetMethodID(
      g_mutators_stack_class->obj(), "pushClipRect", "(IIII)V");
  if (g_mutators_stack_push_cliprect_method == nullptr) {
    FML_LOG(ERROR)
        << "Could not locate FlutterMutatorsStack.pushCilpRect method";
    return false;
  }

  g_on_display_platform_view_method =
      env->GetMethodID(g_flutter_jni_class->obj(), "onDisplayPlatformView",
                       "(IIIIIIILio/flutter/embedding/engine/mutatorsstack/"
                       "FlutterMutatorsStack;)V");

  if (g_on_display_platform_view_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate onDisplayPlatformView method";
    return false;
  }

  g_on_begin_frame_method =
      env->GetMethodID(g_flutter_jni_class->obj(), "onBeginFrame", "()V");

  if (g_on_begin_frame_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate onBeginFrame method";
    return false;
  }

  g_on_end_frame_method =
      env->GetMethodID(g_flutter_jni_class->obj(), "onEndFrame", "()V");

  if (g_on_end_frame_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate onEndFrame method";
    return false;
  }

  g_on_display_overlay_surface_method = env->GetMethodID(
      g_flutter_jni_class->obj(), "onDisplayOverlaySurface", "(IIIII)V");

  if (g_on_display_overlay_surface_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate onDisplayOverlaySurface method";
    return false;
  }

  g_surface_texture_class = new fml::jni::ScopedJavaGlobalRef<jclass>(
      env, env->FindClass("android/graphics/SurfaceTexture"));
  if (g_surface_texture_class->is_null()) {
    FML_LOG(ERROR) << "Could not locate SurfaceTexture class";
    return false;
  }

  g_attach_to_gl_context_method = env->GetMethodID(
      g_surface_texture_class->obj(), "attachToGLContext", "(I)V");

  if (g_attach_to_gl_context_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate attachToGlContext method";
    return false;
  }

  g_update_tex_image_method =
      env->GetMethodID(g_surface_texture_class->obj(), "updateTexImage", "()V");

  if (g_update_tex_image_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate updateTexImage method";
    return false;
  }

  g_get_transform_matrix_method = env->GetMethodID(
      g_surface_texture_class->obj(), "getTransformMatrix", "([F)V");

  if (g_get_transform_matrix_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate getTransformMatrix method";
    return false;
  }

  g_detach_from_gl_context_method = env->GetMethodID(
      g_surface_texture_class->obj(), "detachFromGLContext", "()V");

  if (g_detach_from_gl_context_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate detachFromGlContext method";
    return false;
  }

  g_compute_platform_resolved_locale_method = env->GetMethodID(
      g_flutter_jni_class->obj(), "computePlatformResolvedLocale",
      "([Ljava/lang/String;)[Ljava/lang/String;");

  if (g_compute_platform_resolved_locale_method == nullptr) {
    FML_LOG(ERROR) << "Could not locate computePlatformResolvedLocale method";
    return false;
  }

  return RegisterApi(env);
}

PlatformViewAndroidJNIImpl::PlatformViewAndroidJNIImpl(
    fml::jni::JavaObjectWeakGlobalRef java_object)
    : java_object_(java_object) {}

PlatformViewAndroidJNIImpl::~PlatformViewAndroidJNIImpl() = default;

void PlatformViewAndroidJNIImpl::FlutterViewHandlePlatformMessage(
    fml::RefPtr<flutter::PlatformMessage> message,
    int responseId) {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return;
  }

  fml::jni::ScopedJavaLocalRef<jstring> java_channel =
      fml::jni::StringToJavaString(env, message->channel());

  if (message->hasData()) {
    fml::jni::ScopedJavaLocalRef<jbyteArray> message_array(
        env, env->NewByteArray(message->data().size()));
    env->SetByteArrayRegion(
        message_array.obj(), 0, message->data().size(),
        reinterpret_cast<const jbyte*>(message->data().data()));
    env->CallVoidMethod(java_object.obj(), g_handle_platform_message_method,
                        java_channel.obj(), message_array.obj(), responseId);
  } else {
    env->CallVoidMethod(java_object.obj(), g_handle_platform_message_method,
                        java_channel.obj(), nullptr, responseId);
  }

  FML_CHECK(CheckException(env));
}

void PlatformViewAndroidJNIImpl::FlutterViewHandlePlatformMessageResponse(
    int responseId,
    std::unique_ptr<fml::Mapping> data) {
  // We are on the platform thread. Attempt to get the strong reference to
  // the Java object.
  JNIEnv* env = fml::jni::AttachCurrentThread();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    // The Java object was collected before this message response got to
    // it. Drop the response on the floor.
    return;
  }
  if (data == nullptr) {  // Empty response.
    env->CallVoidMethod(java_object.obj(),
                        g_handle_platform_message_response_method, responseId,
                        nullptr);
  } else {
    // Convert the vector to a Java byte array.
    fml::jni::ScopedJavaLocalRef<jbyteArray> data_array(
        env, env->NewByteArray(data->GetSize()));
    env->SetByteArrayRegion(data_array.obj(), 0, data->GetSize(),
                            reinterpret_cast<const jbyte*>(data->GetMapping()));

    env->CallVoidMethod(java_object.obj(),
                        g_handle_platform_message_response_method, responseId,
                        data_array.obj());
  }

  FML_CHECK(CheckException(env));
}

void PlatformViewAndroidJNIImpl::FlutterViewUpdateSemantics(
    std::vector<uint8_t> buffer,
    std::vector<std::string> strings) {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return;
  }

  fml::jni::ScopedJavaLocalRef<jobject> direct_buffer(
      env, env->NewDirectByteBuffer(buffer.data(), buffer.size()));
  fml::jni::ScopedJavaLocalRef<jobjectArray> jstrings =
      fml::jni::VectorToStringArray(env, strings);

  env->CallVoidMethod(java_object.obj(), g_update_semantics_method,
                      direct_buffer.obj(), jstrings.obj());

  FML_CHECK(CheckException(env));
}

void PlatformViewAndroidJNIImpl::FlutterViewUpdateCustomAccessibilityActions(
    std::vector<uint8_t> actions_buffer,
    std::vector<std::string> strings) {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return;
  }

  fml::jni::ScopedJavaLocalRef<jobject> direct_actions_buffer(
      env,
      env->NewDirectByteBuffer(actions_buffer.data(), actions_buffer.size()));

  fml::jni::ScopedJavaLocalRef<jobjectArray> jstrings =
      fml::jni::VectorToStringArray(env, strings);

  env->CallVoidMethod(java_object.obj(),
                      g_update_custom_accessibility_actions_method,
                      direct_actions_buffer.obj(), jstrings.obj());

  FML_CHECK(CheckException(env));
}

void PlatformViewAndroidJNIImpl::FlutterViewOnFirstFrame() {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return;
  }

  env->CallVoidMethod(java_object.obj(), g_on_first_frame_method);

  FML_CHECK(CheckException(env));
}

void PlatformViewAndroidJNIImpl::FlutterViewOnPreEngineRestart() {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return;
  }

  env->CallVoidMethod(java_object.obj(), g_on_engine_restart_method);

  FML_CHECK(CheckException(env));
}

void PlatformViewAndroidJNIImpl::SurfaceTextureAttachToGLContext(
    JavaWeakGlobalRef surface_texture,
    int textureId) {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  fml::jni::ScopedJavaLocalRef<jobject> surface_texture_local_ref =
      surface_texture.get(env);
  if (surface_texture_local_ref.is_null()) {
    return;
  }

  env->CallVoidMethod(surface_texture_local_ref.obj(),
                      g_attach_to_gl_context_method, textureId);

  FML_CHECK(CheckException(env));
}

void PlatformViewAndroidJNIImpl::SurfaceTextureUpdateTexImage(
    JavaWeakGlobalRef surface_texture) {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  fml::jni::ScopedJavaLocalRef<jobject> surface_texture_local_ref =
      surface_texture.get(env);
  if (surface_texture_local_ref.is_null()) {
    return;
  }

  env->CallVoidMethod(surface_texture_local_ref.obj(),
                      g_update_tex_image_method);

  FML_CHECK(CheckException(env));
}

// The bounds we set for the canvas are post composition.
// To fill the canvas we need to ensure that the transformation matrix
// on the `SurfaceTexture` will be scaled to fill. We rescale and preseve
// the scaled aspect ratio.
SkSize ScaleToFill(float scaleX, float scaleY) {
  const double epsilon = std::numeric_limits<double>::epsilon();
  // scaleY is negative.
  const double minScale = fmin(scaleX, fabs(scaleY));
  const double rescale = 1.0f / (minScale + epsilon);
  return SkSize::Make(scaleX * rescale, scaleY * rescale);
}

void PlatformViewAndroidJNIImpl::SurfaceTextureGetTransformMatrix(
    JavaWeakGlobalRef surface_texture,
    SkMatrix& transform) {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  fml::jni::ScopedJavaLocalRef<jobject> surface_texture_local_ref =
      surface_texture.get(env);
  if (surface_texture_local_ref.is_null()) {
    return;
  }

  fml::jni::ScopedJavaLocalRef<jfloatArray> transformMatrix(
      env, env->NewFloatArray(16));

  env->CallVoidMethod(surface_texture_local_ref.obj(),
                      g_get_transform_matrix_method, transformMatrix.obj());
  FML_CHECK(CheckException(env));

  float* m = env->GetFloatArrayElements(transformMatrix.obj(), nullptr);
  float scaleX = m[0], scaleY = m[5];
  const SkSize scaled = ScaleToFill(scaleX, scaleY);
  SkScalar matrix3[] = {
      scaled.fWidth, m[1],           m[2],   //
      m[4],          scaled.fHeight, m[6],   //
      m[8],          m[9],           m[10],  //
  };
  env->ReleaseFloatArrayElements(transformMatrix.obj(), m, JNI_ABORT);
  transform.set9(matrix3);
}

void PlatformViewAndroidJNIImpl::SurfaceTextureDetachFromGLContext(
    JavaWeakGlobalRef surface_texture) {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  fml::jni::ScopedJavaLocalRef<jobject> surface_texture_local_ref =
      surface_texture.get(env);
  if (surface_texture_local_ref.is_null()) {
    return;
  }

  env->CallVoidMethod(surface_texture_local_ref.obj(),
                      g_detach_from_gl_context_method);

  FML_CHECK(CheckException(env));
}

void PlatformViewAndroidJNIImpl::FlutterViewOnDisplayPlatformView(
    int view_id,
    int x,
    int y,
    int width,
    int height,
    int viewWidth,
    int viewHeight,
    MutatorsStack mutators_stack) {
  JNIEnv* env = fml::jni::AttachCurrentThread();
  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return;
  }

  jobject mutatorsStack = env->NewObject(g_mutators_stack_class->obj(),
                                         g_mutators_stack_init_method);

  std::vector<std::shared_ptr<Mutator>>::const_iterator iter =
      mutators_stack.Begin();
  while (iter != mutators_stack.End()) {
    switch ((*iter)->GetType()) {
      case transform: {
        const SkMatrix& matrix = (*iter)->GetMatrix();
        SkScalar matrix_array[9];
        matrix.get9(matrix_array);
        fml::jni::ScopedJavaLocalRef<jfloatArray> transformMatrix(
            env, env->NewFloatArray(9));

        env->SetFloatArrayRegion(transformMatrix.obj(), 0, 9, matrix_array);
        env->CallVoidMethod(mutatorsStack,
                            g_mutators_stack_push_transform_method,
                            transformMatrix.obj());
        break;
      }
      case clip_rect: {
        const SkRect& rect = (*iter)->GetRect();
        env->CallVoidMethod(mutatorsStack,
                            g_mutators_stack_push_cliprect_method,
                            (int)rect.left(), (int)rect.top(),
                            (int)rect.right(), (int)rect.bottom());
        break;
      }
      // TODO(cyanglaz): Implement other mutators.
      // https://github.com/flutter/flutter/issues/58426
      case clip_rrect:
      case clip_path:
      case opacity:
        break;
    }
    ++iter;
  }

  env->CallVoidMethod(java_object.obj(), g_on_display_platform_view_method,
                      view_id, x, y, width, height, viewWidth, viewHeight,
                      mutatorsStack);

  FML_CHECK(CheckException(env));
}

void PlatformViewAndroidJNIImpl::FlutterViewDisplayOverlaySurface(
    int surface_id,
    int x,
    int y,
    int width,
    int height) {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return;
  }

  env->CallVoidMethod(java_object.obj(), g_on_display_overlay_surface_method,
                      surface_id, x, y, width, height);

  FML_CHECK(CheckException(env));
}

void PlatformViewAndroidJNIImpl::FlutterViewBeginFrame() {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return;
  }

  env->CallVoidMethod(java_object.obj(), g_on_begin_frame_method);

  FML_CHECK(CheckException(env));
}

void PlatformViewAndroidJNIImpl::FlutterViewEndFrame() {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return;
  }

  env->CallVoidMethod(java_object.obj(), g_on_end_frame_method);

  FML_CHECK(CheckException(env));
}

std::unique_ptr<PlatformViewAndroidJNI::OverlayMetadata>
PlatformViewAndroidJNIImpl::FlutterViewCreateOverlaySurface() {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return nullptr;
  }

  fml::jni::ScopedJavaLocalRef<jobject> overlay(
      env, env->CallObjectMethod(java_object.obj(),
                                 g_create_overlay_surface_method));
  FML_CHECK(CheckException(env));

  if (overlay.is_null()) {
    return std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>(0,
                                                                     nullptr);
  }

  jint overlay_id =
      env->CallIntMethod(overlay.obj(), g_overlay_surface_id_method);

  jobject overlay_surface =
      env->CallObjectMethod(overlay.obj(), g_overlay_surface_surface_method);

  auto overlay_window = fml::MakeRefCounted<AndroidNativeWindow>(
      ANativeWindow_fromSurface(env, overlay_surface));

  return std::make_unique<PlatformViewAndroidJNI::OverlayMetadata>(
      overlay_id, std::move(overlay_window));
}

void PlatformViewAndroidJNIImpl::FlutterViewDestroyOverlaySurfaces() {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return;
  }

  env->CallVoidMethod(java_object.obj(), g_destroy_overlay_surfaces_method);

  FML_CHECK(CheckException(env));
}

std::unique_ptr<std::vector<std::string>>
PlatformViewAndroidJNIImpl::FlutterViewComputePlatformResolvedLocale(
    std::vector<std::string> supported_locales_data) {
  JNIEnv* env = fml::jni::AttachCurrentThread();

  std::unique_ptr<std::vector<std::string>> out =
      std::make_unique<std::vector<std::string>>();

  auto java_object = java_object_.get(env);
  if (java_object.is_null()) {
    return out;
  }
  fml::jni::ScopedJavaLocalRef<jobjectArray> j_locales_data =
      fml::jni::VectorToStringArray(env, supported_locales_data);
  jobjectArray result = (jobjectArray)env->CallObjectMethod(
      java_object.obj(), g_compute_platform_resolved_locale_method,
      j_locales_data.obj());

  FML_CHECK(CheckException(env));

  int length = env->GetArrayLength(result);
  for (int i = 0; i < length; i++) {
    out->emplace_back(fml::jni::JavaStringToString(
        env, (jstring)env->GetObjectArrayElement(result, i)));
  }
  return out;
}

}  // namespace flutter


text:
package cn.felord.wepay.ali.sdk.api.domain;

import cn.felord.wepay.ali.sdk.api.AlipayObject;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField;

/**
 * 会员卡删卡
 *
 * @author auto create
 * @version $Id: $Id
 */
public class AlipayMarketingCardDeleteModel extends AlipayObject {

	private static final long serialVersionUID = 6787369691897918861L;

	/**
	 * 删卡扩展参数,json格式。
用于商户的特定业务信息的传递,只有商户与支付宝约定了传递此参数且约定了参数含义,此参数才有效。
目前支持如下key:
new_card_no:新卡号
donee_user_id:受赠人userId
	 */
	@ApiField("ext_info")
	private String extInfo;

	/**
	 * 商户端删卡业务流水号(商户确保流水号唯一性)
	 */
	@ApiField("out_serial_no")
	private String outSerialNo;

	/**
	 * 删卡原因
USER_UNBUND:用户解绑(可以重新绑定)
CANCEL:销户(完成销户后,就不能再重新绑定)
PRESENT:转赠(可以重新绑定)
	 */
	@ApiField("reason_code")
	private String reasonCode;

	/**
	 * 支付宝业务卡号,开卡接口中返回获取
	 */
	@ApiField("target_card_no")
	private String targetCardNo;

	/**
	 * 卡号ID类型
BIZ_CARD:支付宝卡号
	 */
	@ApiField("target_card_no_type")
	private String targetCardNoType;

	/**
	 *
Getter for the field extInfo.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getExtInfo() {
		return this.extInfo;
	}
	/**
	 *
Setter for the field extInfo.

	 *
	 * @param extInfo a {@link java.lang.String} object.
	 */
	public void setExtInfo(String extInfo) {
		this.extInfo = extInfo;
	}

	/**
	 *
Getter for the field outSerialNo.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getOutSerialNo() {
		return this.outSerialNo;
	}
	/**
	 *
Setter for the field outSerialNo.

	 *
	 * @param outSerialNo a {@link java.lang.String} object.
	 */
	public void setOutSerialNo(String outSerialNo) {
		this.outSerialNo = outSerialNo;
	}

	/**
	 *
Getter for the field reasonCode.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getReasonCode() {
		return this.reasonCode;
	}
	/**
	 *
Setter for the field reasonCode.

	 *
	 * @param reasonCode a {@link java.lang.String} object.
	 */
	public void setReasonCode(String reasonCode) {
		this.reasonCode = reasonCode;
	}

	/**
	 *
Getter for the field targetCardNo.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getTargetCardNo() {
		return this.targetCardNo;
	}
	/**
	 *
Setter for the field targetCardNo.

	 *
	 * @param targetCardNo a {@link java.lang.String} object.
	 */
	public void setTargetCardNo(String targetCardNo) {
		this.targetCardNo = targetCardNo;
	}

	/**
	 *
Getter for the field targetCardNoType.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getTargetCardNoType() {
		return this.targetCardNoType;
	}
	/**
	 *
Setter for the field targetCardNoType.

	 *
	 * @param targetCardNoType a {@link java.lang.String} object.
	 */
	public void setTargetCardNoType(String targetCardNoType) {
		this.targetCardNoType = targetCardNoType;
	}

}

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace Slight.Alexa.Framework.Models.Requests.RequestTypes
{
    public class RequestBundle : IIntentRequest, ILaunchRequest, ISessionEndedRequest
    {
        /// <summary>
        /// Describes the request type with the value as:
        /// LaunchRequest, IntentRequest, or SessionEndedRequest
        /// </summary>
        public string Type { get; set; }

        /// <summary>
        /// Represents a unique identifier for the specific request.
        /// </summary>
        public string RequestId { get; set; }

        /// <summary>
        /// Provides the date and time when Alexa sent the request.
        /// Use this to verify that the request is current and not
        /// part of a "replay" attack. Timestamp is provided as an
        /// ISO 8601 formatted string (for example, 2015-05-13T12:34:56Z).
        /// </summary>
        public DateTime Timestamp { get; set; }

        /// <summary>
        /// An object that represents what the user wants.
        /// </summary>
        public Intent Intent { get; set; }

        /// <summary>
        /// Describes why the session ended. Possible values:
        ///
        /// - USER_INITIATED - The user explicitly ended the session.
        /// - ERROR - An error occurred that caused the session to end.
        /// - EXCEEDED_MAX_REPROMPTS - The user either did not respond or
        ///   responded with an utterance that did not match any of the intents
        ///   defined in your voice interface.
        /// </summary>
        public string Reason { get; set; }

        public Type GetRequestType()
        {
            switch (Type)
            {
                case "IntentRequest":
                    return typeof(IIntentRequest);
                case "LaunchRequest":
                    return typeof(ILaunchRequest);
                case "SessionEndedRequest":
                    return typeof(ISessionEndedRequest);
                default:
                    throw new ArgumentOutOfRangeException(nameof(Type), $"Unknown request type: {Type}.");
            }
        }
    }
}


text:
export { ALLOW_MULTIPLE_PLATFORMS as ɵALLOW_MULTIPLE_PLATFORMS } from './application_ref';
export { APP_ID_RANDOM_PROVIDER as ɵAPP_ID_RANDOM_PROVIDER } from './application_tokens';
export { ValueUnwrapper as ɵValueUnwrapper, devModeEqual as ɵdevModeEqual } from './change_detection/change_detection_util';
export { isListLikeIterable as ɵisListLikeIterable } from './change_detection/change_detection_util';
export { ChangeDetectorStatus as ɵChangeDetectorStatus, isDefaultChangeDetectionStrategy as ɵisDefaultChangeDetectionStrategy } from './change_detection/constants';
export { Console as ɵConsole } from './console';
export { ERROR_COMPONENT_TYPE as ɵERROR_COMPONENT_TYPE } from './errors';
export { ComponentFactory as ɵComponentFactory } from './linker/component_factory';
export { CodegenComponentFactoryResolver as ɵCodegenComponentFactoryResolver } from './linker/component_factory_resolver';
export { LIFECYCLE_HOOKS_VALUES as ɵLIFECYCLE_HOOKS_VALUES, LifecycleHooks as ɵLifecycleHooks } from './metadata/lifecycle_hooks';
export { ViewMetadata as ɵViewMetadata } from './metadata/view';
export { Reflector as ɵReflector, reflector as ɵreflector } from './reflection/reflection';
export { ReflectionCapabilities as ɵReflectionCapabilities } from './reflection/reflection_capabilities';
export { ReflectorReader as ɵReflectorReader } from './reflection/reflector_reader';
export { GetterFn as ɵGetterFn, MethodFn as ɵMethodFn, SetterFn as ɵSetterFn } from './reflection/types';
export { DirectRenderer as ɵDirectRenderer, RenderDebugInfo as ɵRenderDebugInfo } from './render/api';
export { global as ɵglobal, looseIdentical as ɵlooseIdentical, stringify as ɵstringify } from './util';
export { makeDecorator as ɵmakeDecorator } from './util/decorators';
export { isObservable as ɵisObservable, isPromise as ɵisPromise } from './util/lang';
export { NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR as ɵNOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR } from './view/provider';


text:
require 'spec_helper'

RSpec.describe Hsquare::Application do
  describe '#admin_client' do
    let(:application) { Hsquare::Application.new }

    context 'when admin key is set' do
      let(:admin_key) { 'admin-key' }
      let(:application) { Hsquare::Application.new admin_key: admin_key }

      it { expect(application.admin_client.default_options).not_to be_empty }
      it { expect(application.admin_client.default_options[:headers]).not_to be_empty }
      it { expect(application.admin_client.default_options[:headers]['Authorization']).to eq("KakaoAK #{admin_key}") }
    end

    context 'when base_uri is set' do
      let(:base_uri) { 'http://localhost:3000' }
      let(:application) { Hsquare::Application.new base_uri: base_uri }

      it { expect(application.admin_client.default_options).not_to be_empty }
      it { expect(application.admin_client.default_options[:base_uri]).to eq(base_uri) }
    end

    context 'when proxy is set' do
      let(:configuration) { Hsquare::Configuration.new.tap { |c| c.http_proxy = 'http://proxy.com:80' } }

      before { Hsquare.apply(configuration) }

      it { expect(application.admin_client.default_options).not_to be_empty }
      it { expect(application.admin_client.default_options[:http_proxyaddr]).to eq('proxy.com') }
    end
  end
end


text:
/* twofish.hpp defines Twofish
*/

#ifndef TAO_CRYPT_TWOFISH_HPP
#define TAO_CRYPT_TWOFISH_HPP

#include "misc.hpp"
#include "modes.hpp"
#ifdef USE_SYS_STL
    #include <algorithm>
#else
    #include "algorithm.hpp"
#endif

namespace STL = STL_NAMESPACE;

#if defined(TAOCRYPT_X86ASM_AVAILABLE) && defined(TAO_ASM)
    #define DO_TWOFISH_ASM
#endif

namespace TaoCrypt {

enum { TWOFISH_BLOCK_SIZE = 16 };

// Twofish encryption and decryption, see
class Twofish : public Mode_BASE {
public:
    enum { BLOCK_SIZE = TWOFISH_BLOCK_SIZE };

    Twofish(CipherDir DIR, Mode MODE)
        : Mode_BASE(BLOCK_SIZE, DIR, MODE) {}

#ifdef DO_TWOFISH_ASM
    void Process(byte*, const byte*, word32);
#endif
    void SetKey(const byte* key, word32 sz, CipherDir fake = ENCRYPTION);
    void SetIV(const byte* iv) { memcpy(r_, iv, BLOCK_SIZE); }
private:
	static const byte     q_[2][256];
	static const word32 mds_[4][256];

	word32 k_[40];
	word32 s_[4][256];

	static word32 h0(word32 x, const word32 *key, unsigned int kLen);
	static word32 h(word32 x, const word32 *key, unsigned int kLen);

    void ProcessAndXorBlock(const byte*, const byte*, byte*) const;

    void encrypt(const byte*, const byte*, byte*) const;
    void decrypt(const byte*, const byte*, byte*) const;

    void AsmEncrypt(const byte* inBlock, byte* outBlock) const;
    void AsmDecrypt(const byte* inBlock, byte* outBlock) const;

    Twofish(const Twofish&);            // hide copy
    Twofish& operator=(const Twofish&); // and assign
};

typedef BlockCipher<ENCRYPTION, Twofish, ECB> Twofish_ECB_Encryption;
typedef BlockCipher<DECRYPTION, Twofish, ECB> Twofish_ECB_Decryption;

typedef BlockCipher<ENCRYPTION, Twofish, CBC> Twofish_CBC_Encryption;
typedef BlockCipher<DECRYPTION, Twofish, CBC> Twofish_CBC_Decryption;

} // naemspace

#endif // TAO_CRYPT_TWOFISH_HPP


text:
require 'redis_stream_broker'

class User
  include ActiveModel::Validations
  include ActiveModel::Conversion
  #include ActionView::Helpers

  extend ActiveModel::Naming

  SESSION_EXPIRATION = 1.week.from_now

  #attr_accessor(:id, :name, :image, :nickname)
  #TODO validations

  def self.create_with_omniauth(auth)
    @user = {
      :id => auth["uid"],
      :name => auth['info']['name'],
      :image => auth['info']['image'],
      :nickname => auth['info']['nickname'],
      :oauth_token => auth['credentials']['token'],
      :oauth_secret => auth['credentials']['secret'],
      :session_token => User.new_token,
      :session_token_expires_at => Time.at( SESSION_EXPIRATION ).to_s,
      :created_at => Time.now.to_s
    }
    RedisStreamBroker.save_user_hash( auth["uid"], @user )
    RedisStreamBroker.add_user_stream( auth["uid"] )
    @user
  end

  def self.new_token
    SecureRandom.urlsafe_base64(15).tr('lIO0', 'sxyz')
  end

  def self.find_by_id(id)
    @user = RedisStreamBroker.get_user_hash( id, "id", "name", "image", "nickname", "oauth_token", "oauth_secret" )
  end

  private

    ## TODO better ACL checks

    #def self._can_subscribe_to_stream stream
      #current_user.exists? and current_user.tw_id == stream.tw_id
    #end

    #def self._can_publish_to_stream stream
      #self.superclass == 'TwitterStreamWorker'
      ##or @current_user.tw_id == stream.tw_id
    #end

end


text:
'use strict'
const chalk = require('chalk');
const { loadLibraryFor, loadUser, printTotalTime } = require('./services/CliService');
async function run(username) {
  let user = await loadUser(username)

  console.log(chalk.green(`Welcome ${user.name}.`));
  console.log(chalk.yellow("We're fetching your stats"));

  let userId = parseInt(user.id, 10)

  let currentTime = await loadLibraryFor(userId, {type: 'current'})
  let onHoldTime = await loadLibraryFor(userId, {type: 'on_hold'})
  let droppedTime = await loadLibraryFor(userId, {type: 'dropped'})
  let completedTime = await loadLibraryFor(userId, {type: 'completed'})
  printTotalTime([currentTime, completedTime, onHoldTime, droppedTime])
}

module.exports = { run }


text:
package siesta

import (
	"flag"
	"fmt"
	"net/url"
	"strconv"
	"strings"
	"time"
)

// Params represents a set of URL parameters from a request's query string.
// The interface is similar to a flag.FlagSet, but a) there is no usage string,
// b) there are no custom Var()s, and c) there are SliceXXX types. Sliced types
// support two ways of generating a multi-valued parameter: setting the parameter
// multiple times, and using a comma-delimited string. This adds the limitation
// that you can't have a value with a comma if in a Sliced type.
// Under the covers, Params uses flag.FlagSet.
type Params struct {
	fset *flag.FlagSet
}

// Parse parses URL parameters from a http.Request.URL.Query(), which is a
// url.Values, which is just a map[string][string].
func (rp *Params) Parse(args url.Values) error {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}

	// Parse items from URL query string
FLAG_LOOP:
	for name, vals := range args {
		for _, v := range vals {

			f := rp.fset.Lookup(name)
			if f == nil {
				// Flag wasn't found.
				continue FLAG_LOOP
			}

			// Check if the value is empty
			if v == "" {
				if bv, ok := f.Value.(boolFlag); ok && bv.IsBoolFlag() {
					bv.Set("true")

					continue FLAG_LOOP
				}
			}

			err := rp.fset.Set(name, v)
			if err != nil {
				// Remove the "flag" error message and make a "params" one.
				// TODO: optionally allow undefined params to be given, but ignored?
				if !strings.Contains(err.Error(), "no such flag -") {
					// Give a helpful message about which param caused the error
					err = fmt.Errorf("bad param '%s': %s", name, err.Error())
					return err
				}
			}
		}
	}

	return nil
}

// Usage returns a map keyed on parameter names. The map values are an array of
// name, type, and usage information for each parameter.
func (rp *Params) Usage() map[string][3]string {
	docs := make(map[string][3]string)
	var translations map[string]string = map[string]string{
		"*flag.stringValue":   "string",
		"*flag.durationValue": "duration",
		"*flag.intValue":      "int",
		"*flag.boolValue":     "bool",
		"*flag.float64Value":  "float64",
		"*flag.int64Value":    "int64",
		"*flag.uintValue":     "uint",
		"*flag.uint64Value":   "uint64",
		"*siesta.SString":     "[]string",
		"*siesta.SDuration":   "[]duration",
		"*siesta.SInt":        "[]int",
		"*siesta.SBool":       "[]bool",
		"*siesta.SFloat64":    "[]float64",
		"*siesta.SInt64":      "[]int64",
		"*siesta.SUint":       "[]uint",
		"*siesta.SUint64":     "[]uint64",
	}
	rp.fset.VisitAll(func(flag *flag.Flag) {
		niceName := translations[fmt.Sprintf("%T", flag.Value)]
		if niceName == "" {
			niceName = fmt.Sprintf("%T", flag.Value)
		}
		docs[flag.Name] = [...]string{flag.Name, niceName, flag.Usage}
	})
	return docs
}

type boolFlag interface {
	flag.Value
	IsBoolFlag() bool
}

// Bool defines a bool param with specified name and default value.
// The return value is the address of a bool variable that stores the value of the param.
func (rp *Params) Bool(name string, value bool, usage string) *bool {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(bool)
	rp.fset.BoolVar(p, name, value, usage)
	return p
}

// SBool is a slice of bool.
type SBool []bool

// String is the method to format the param's value, part of the flag.Value interface.
// The String method's output will be used in diagnostics.
func (s *SBool) String() string {
	return fmt.Sprint(*s)
}

// Set is the method to set the param value, part of the flag.Value interface.
// Set's argument is a string to be parsed to set the param.
// It's a comma-separated list, so we split it.
func (s *SBool) Set(value string) error {
	for _, dt := range strings.Split(value, ",") {
		if len(dt) > 0 {
			parsed, err := strconv.ParseBool(dt)
			if err != nil {
				return err
			}
			*s = append(*s, parsed)
		}
	}
	return nil
}

// SliceBool defines a multi-value bool param with specified name and default value.
// The return value is the address of a SBool variable that stores the values of the param.
func (rp *Params) SliceBool(name string, value bool, usage string) *SBool {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(SBool)
	rp.fset.Var(p, name, usage)
	return p
}

// Int defines an int param with specified name and default value.
// The return value is the address of an int variable that stores the value of the param.
func (rp *Params) Int(name string, value int, usage string) *int {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(int)
	rp.fset.IntVar(p, name, value, usage)
	return p
}

// SInt is a slice of int.
type SInt []int

// String is the method to format the param's value, part of the flag.Value interface.
// The String method's output will be used in diagnostics.
func (s *SInt) String() string {
	return fmt.Sprint(*s)
}

// Set is the method to set the param value, part of the flag.Value interface.
// Set's argument is a string to be parsed to set the param.
// It's a comma-separated list, so we split it.
func (s *SInt) Set(value string) error {
	for _, dt := range strings.Split(value, ",") {
		if len(dt) > 0 {
			parsed, err := strconv.ParseInt(dt, 0, 64)
			if err != nil {
				return err
			}
			*s = append(*s, int(parsed))
		}
	}
	return nil
}

// SliceInt defines a multi-value int param with specified name and default value.
// The return value is the address of a SInt variable that stores the values of the param.
func (rp *Params) SliceInt(name string, value int, usage string) *SInt {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(SInt)
	rp.fset.Var(p, name, usage)
	return p
}

// Int64 defines an int64 param with specified name and default value.
// The return value is the address of an int64 variable that stores the value of the param.
func (rp *Params) Int64(name string, value int64, usage string) *int64 {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(int64)
	rp.fset.Int64Var(p, name, value, usage)
	return p
}

// SInt64 is a slice of int64.
type SInt64 []int64

// String is the method to format the param's value, part of the flag.Value interface.
// The String method's output will be used in diagnostics.
func (s *SInt64) String() string {
	return fmt.Sprint(*s)
}

// Set is the method to set the param value, part of the flag.Value interface.
// Set's argument is a string to be parsed to set the param.
// It's a comma-separated list, so we split it.
func (s *SInt64) Set(value string) error {
	for _, dt := range strings.Split(value, ",") {
		if len(dt) > 0 {
			parsed, err := strconv.ParseInt(dt, 0, 64)
			if err != nil {
				return err
			}
			*s = append(*s, int64(parsed))
		}
	}
	return nil
}

// SliceInt64 defines a multi-value int64 param with specified name and default value.
// The return value is the address of a SInt64 variable that stores the values of the param.
func (rp *Params) SliceInt64(name string, value int64, usage string) *SInt64 {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(SInt64)
	rp.fset.Var(p, name, usage)
	return p
}

// Uint defines a uint param with specified name and default value.
// The return value is the address of a uint variable that stores the value of the param.
func (rp *Params) Uint(name string, value uint, usage string) *uint {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(uint)
	rp.fset.UintVar(p, name, value, usage)
	return p
}

// SUint is a slice of uint.
type SUint []uint

// String is the method to format the param's value, part of the flag.Value interface.
// The String method's output will be used in diagnostics.
func (s *SUint) String() string {
	return fmt.Sprint(*s)
}

// Set is the method to set the param value, part of the flag.Value interface.
// Set's argument is a string to be parsed to set the param.
// It's a comma-separated list, so we split it.
func (s *SUint) Set(value string) error {
	for _, dt := range strings.Split(value, ",") {
		if len(dt) > 0 {
			parsed, err := strconv.ParseUint(dt, 10, 64)
			if err != nil {
				return err
			}
			*s = append(*s, uint(parsed))
		}
	}
	return nil
}

// SliceUint defines a multi-value uint param with specified name and default value.
// The return value is the address of a SUint variable that stores the values of the param.
func (rp *Params) SliceUint(name string, value uint, usage string) *SUint {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(SUint)
	rp.fset.Var(p, name, usage)
	return p
}

// Uint64 defines a uint64 param with specified name and default value.
// The return value is the address of a uint64 variable that stores the value of the param.
func (rp *Params) Uint64(name string, value uint64, usage string) *uint64 {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(uint64)
	rp.fset.Uint64Var(p, name, value, usage)
	return p
}

// SUint64 is a slice of uint64.
type SUint64 []uint64

// String is the method to format the param's value, part of the flag.Value interface.
// The String method's output will be used in diagnostics.
func (s *SUint64) String() string {
	return fmt.Sprint(*s)
}

// Set is the method to set the param value, part of the flag.Value interface.
// Set's argument is a string to be parsed to set the param.
// It's a comma-separated list, so we split it.
func (s *SUint64) Set(value string) error {
	for _, dt := range strings.Split(value, ",") {
		if len(dt) > 0 {
			parsed, err := strconv.ParseUint(dt, 10, 64)
			if err != nil {
				return err
			}
			*s = append(*s, parsed)
		}
	}
	return nil
}

// SliceUint64 defines a multi-value uint64 param with specified name and default value.
// The return value is the address of a SUint64 variable that stores the values of the param.
func (rp *Params) SliceUint64(name string, value uint64, usage string) *SUint64 {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(SUint64)
	rp.fset.Var(p, name, usage)
	return p
}

// String defines a string param with specified name and default value.
// The return value is the address of a string variable that stores the value of the param.
func (rp *Params) String(name string, value string, usage string) *string {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(string)
	rp.fset.StringVar(p, name, value, usage)
	return p
}

// SString is a slice of string.
type SString []string

// String is the method to format the param's value, part of the flag.Value interface.
// The String method's output will be used in diagnostics.
func (s *SString) String() string {
	return strings.Join(*s, ",")
}

// Set is the method to set the param value, part of the flag.Value interface.
// Set's argument is a string to be parsed to set the param.
// It's a comma-separated list, so we split it.
func (s *SString) Set(value string) error {
	for _, dt := range strings.Split(value, ",") {
		*s = append(*s, dt)
	}
	return nil
}

// SliceString defines a multi-value string param with specified name and default value.
// The return value is the address of a SString variable that stores the values of the param.
func (rp *Params) SliceString(name string, value string, usage string) *SString {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(SString)
	rp.fset.Var(p, name, usage)
	return p
}

// Float64 defines a float64 param with specified name and default value.
// The return value is the address of a float64 variable that stores the value of the param.
func (rp *Params) Float64(name string, value float64, usage string) *float64 {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(float64)
	rp.fset.Float64Var(p, name, value, usage)
	return p
}

// SFloat64 is a slice of float64.
type SFloat64 []float64

// String is the method to format the param's value, part of the flag.Value interface.
// The String method's output will be used in diagnostics.
func (s *SFloat64) String() string {
	return fmt.Sprintf("%f", *s)
}

// Set is the method to set the param value, part of the flag.Value interface.
// Set's argument is a string to be parsed to set the param.
// It's a comma-separated list, so we split it.
func (s *SFloat64) Set(value string) error {
	for _, dt := range strings.Split(value, ",") {
		if len(dt) > 0 {
			parsed, err := strconv.ParseFloat(dt, 64)
			if err != nil {
				return err
			}
			*s = append(*s, parsed)
		}
	}
	return nil
}

// SliceFloat64 defines a multi-value float64 param with specified name and default value.
// The return value is the address of a SFloat64 variable that stores the values of the param.
func (rp *Params) SliceFloat64(name string, value float64, usage string) *SFloat64 {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(SFloat64)
	rp.fset.Var(p, name, usage)
	return p
}

// Duration defines a time.Duration param with specified name and default value.
// The return value is the address of a time.Duration variable that stores the value of the param.
func (rp *Params) Duration(name string, value time.Duration, usage string) *time.Duration {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(time.Duration)
	rp.fset.DurationVar(p, name, value, usage)
	return p
}

// SDuration is a slice of time.Duration.
type SDuration []time.Duration

// String is the method to format the param's value, part of the flag.Value interface.
// The String method's output will be used in diagnostics.
func (s *SDuration) String() string {
	return fmt.Sprint(*s)
}

// Set is the method to set the param value, part of the flag.Value interface.
// Set's argument is a string to be parsed to set the param.
// It's a comma-separated list, so we split it.
func (s *SDuration) Set(value string) error {
	for _, dt := range strings.Split(value, ",") {
		if len(dt) > 0 {
			parsed, err := time.ParseDuration(dt)
			if err != nil {
				return err
			}
			*s = append(*s, parsed)
		}
	}
	return nil
}

// SliceDuration defines a multi-value time.Duration param with specified name and default value.
// The return value is the address of a SDuration variable that stores the values of the param.
func (rp *Params) SliceDuration(name string, value time.Duration, usage string) *SDuration {
	if rp.fset == nil {
		rp.fset = flag.NewFlagSet("anonymous", flag.ExitOnError) // both args are unused.
	}
	p := new(SDuration)
	rp.fset.Var(p, name, usage)
	return p
}


text:
package org.agrona.collections;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
    Int2ObjectHashMapConformanceTest.class,
    Int2IntHashMapConformanceTest.class,
    Int2NullableObjectHashMapConformanceTest.class,
    Long2ObjectHashMapConformanceTest.class,
    Long2LongHashMapConformanceTest.class,
    Long2NullableObjectHashMapConformanceTest.class,
    Object2IntHashMapConformanceTest.class,
    Object2LongHashMapConformanceTest.class,
    Object2ObjectHashMapConformanceTest.class,
    Object2NullableObjectHashMapConformanceTest.class})
public class ConformanceTestsSuite
{
    // This is required so that the suites are picked up by gradle
}


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

<title>Keys</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="date" content="2018-04-23">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

SEARCH:
<input type="text" id="search" value=" " disabled="disabled">
<input type="reset" id="reset" value=" " disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package lejos.hardware

Interface Keys

<map id="G" name="G">
<area shape="rect" id="node1_0" href="./Keys.html" title="lejos.hardware.Keys" alt="" coords="16,11,231,416"/>
<area shape="rect" id="node1" href="./Keys.html" title="<TABLE>" alt="" coords="5,5,241,421"/>
</map>

public interface Keys

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
FREQ_SETTING

static int
ID_ALL

static int
ID_DOWN

static int
ID_ENTER

static int
ID_ESCAPE

static int
ID_LEFT

static int
ID_RIGHT

static int
ID_UP

static java.lang.String
LEN_SETTING

static int
NUM_KEYS

static java.lang.String
VOL_SETTING

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

void
discardEvents()

int
getButtons()

int
getKeyClickLength()

int
getKeyClickTone(int key)

int
getKeyClickVolume()

int
readButtons()

void
setKeyClickLength(int len)

void
setKeyClickTone(int key,
               int freq)

void
setKeyClickVolume(int vol)

int
waitForAnyEvent()

int
waitForAnyEvent(int timeout)

int
waitForAnyPress()

int
waitForAnyPress(int timeout)

Field Detail

ID_UP

static final int ID_UP

See Also:

Constant Field Values

ID_ENTER

static final int ID_ENTER

See Also:

Constant Field Values

ID_DOWN

static final int ID_DOWN

See Also:

Constant Field Values

ID_RIGHT

static final int ID_RIGHT

See Also:

Constant Field Values

ID_LEFT

static final int ID_LEFT

See Also:

Constant Field Values

ID_ESCAPE

static final int ID_ESCAPE

See Also:

Constant Field Values

ID_ALL

static final int ID_ALL

See Also:

Constant Field Values

NUM_KEYS

static final int NUM_KEYS

See Also:

Constant Field Values

VOL_SETTING

static final java.lang.String VOL_SETTING

See Also:

Constant Field Values

LEN_SETTING

static final java.lang.String LEN_SETTING

See Also:

Constant Field Values

FREQ_SETTING

static final java.lang.String FREQ_SETTING

See Also:

Constant Field Values

Method Detail

discardEvents

void discardEvents()

waitForAnyEvent

int waitForAnyEvent()

waitForAnyEvent

int waitForAnyEvent(int timeout)

waitForAnyPress

int waitForAnyPress(int timeout)

waitForAnyPress

int waitForAnyPress()

getButtons

int getButtons()

readButtons

int readButtons()

setKeyClickVolume

void setKeyClickVolume(int vol)

getKeyClickVolume

int getKeyClickVolume()

setKeyClickLength

void setKeyClickLength(int len)

getKeyClickLength

int getKeyClickLength()

setKeyClickTone

void setKeyClickTone(int key,
                     int freq)

getKeyClickTone

int getKeyClickTone(int key)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
/**
 * @providesModule Doc
 * @jsx React.DOM
 */

var React = require('React');
var Marked = require('Marked');

class Doc extends React.Component {
  render() {
    return (

          Edit on GitHub

{this.props.title}

          <Marked>{this.props.content}</Marked>

    )
  }
}

module.exports = Doc;


text:
define(['./Store', 'dojo/when', 'dojo/_base/declare'], function (Store, when, declare) {
	// module:
	//		dstore/Validating
	//	summary:
	//		This module provides a store mixin that enforces validation of objects on put and add
	return declare(Store, {
		validate: function (object) {
			//	summary:
			//		Validates the given object (by making it an instance of the
			//		current model, and calling validate() on it)
			//	object: Object
			//		The object to validate
			//	isNew: Boolean
			//		Indicates whether or not to assume the object is new or not
			if (!(object instanceof this.model)) {
				object = this._restore(object);
			}
			return when(object.validate()).then(function (isValid) {
				if (!isValid) {
					// create and throw a validation error
					var validationError = new TypeError('Invalid property');
					validationError.errors = object.errors;
					throw validationError;
				}
					// return the object since it has had its prototype assigned
				return object;
			});
		},
		put: function (object, options) {
			var inheritedPut = this.getInherited(arguments);
			var store = this;
			return when(this.validate(object), function (object) {
				return inheritedPut.call(store, object, options);
			});
		},
		add: function (object, options) {
			var inheritedAdd = this.getInherited(arguments);
			var store = this;
			return when(this.validate(object, true), function (object) {
				return inheritedAdd.call(store, object, options);
			});
		}
	});
});


text:
package science.atlarge.granula.modeller.platform.operation;

import science.atlarge.granula.modeller.Type;
import science.atlarge.granula.modeller.rule.derivation.SimpleSummaryDerivation;
import science.atlarge.granula.modeller.rule.linking.EmptyLinking;
import science.atlarge.granula.modeller.rule.linking.IdentifierParentLinking;
import science.atlarge.granula.modeller.rule.linking.UniqueParentLinking;

public class WorkerPreCompute extends RealtimeOperationModel {

    public WorkerPreCompute() {
        super(Type.Worker, Type.PreCompute);
    }

    public void loadRules() {
        super.loadRules();

//        addLinkingRule(new UniqueParentLinking(Type.Giraph, Type.Execute));
        addLinkingRule(new IdentifierParentLinking(Type.Worker, Type.Equal, Type.LocalSuperstep, Type.Equal));

        String summary = "PreCompute.";
        addInfoDerivation(new SimpleSummaryDerivation(11, summary));
    }
}


text:
package org.apache.hive.hcatalog.api.repl.exim;

import org.apache.hive.hcatalog.api.HCatNotificationEvent;
import org.apache.hive.hcatalog.api.repl.Command;
import org.apache.hive.hcatalog.api.repl.ReplicationTask;
import org.apache.hive.hcatalog.api.repl.ReplicationUtils;
import org.apache.hive.hcatalog.api.repl.commands.ExportCommand;
import org.apache.hive.hcatalog.api.repl.commands.ImportCommand;
import org.apache.hive.hcatalog.common.HCatConstants;
import org.apache.hive.hcatalog.messaging.CreateTableMessage;

import java.util.Collections;

public class CreateTableReplicationTask extends ReplicationTask {

  private CreateTableMessage createTableMessage = null;

  public CreateTableReplicationTask(HCatNotificationEvent event) {
    super(event);
    validateEventType(event, HCatConstants.HCAT_CREATE_TABLE_EVENT);
    createTableMessage = messageFactory.getDeserializer().getCreateTableMessage(event.getMessage());
  }

  public boolean needsStagingDirs(){
    return true;
  }

  public Iterable<? extends Command> getSrcWhCommands() {
    verifyActionable();
    final String dbName = createTableMessage.getDB();
    final String tableName = createTableMessage.getTable();
    return Collections.singletonList(new ExportCommand(
        dbName,
        tableName,
        null,
        srcStagingDirProvider.getStagingDirectory(
            ReplicationUtils.getUniqueKey(
                getEvent().getEventId(),
                dbName,
                tableName,
                null)
        ),
        false,
        event.getEventId()
    ));
  }

  public Iterable<? extends Command> getDstWhCommands() {
    verifyActionable();
    final String dbName = createTableMessage.getDB();
    final String tableName = createTableMessage.getTable();
    return Collections.singletonList(new ImportCommand(
        ReplicationUtils.mapIfMapAvailable(dbName, dbNameMapping),
        ReplicationUtils.mapIfMapAvailable(tableName, tableNameMapping),
        null,
        dstStagingDirProvider.getStagingDirectory(
            ReplicationUtils.getUniqueKey(
                getEvent().getEventId(),
                dbName, // Note - important to retain the same key as the export
                tableName,
                null)
        ),
        false,
        event.getEventId()
    ));
  }
}


text:
package com.spike.giantdataanalysis.procedure.mw;

import java.util.Date;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 管理客户端
 * @author zhoujiagen
 */
public class AdminClient {
  private static final Logger LOG = LoggerFactory.getLogger(AdminClient.class);

  // the Zookeeper handle
  private ZooKeeper zk;

  public static void main(String[] args) throws Exception {
    AdminClient ac = new AdminClient();

    ac.start();

    ac.listState();
  }

  private static final class AdminClientWatcher implements Watcher {
    @Override
    public void process(WatchedEvent event) {
      LOG.info("watched event: " + event);
    }
  }

  /**
   * construct the Zookeeper handle
   * @throws Exception
   */
  public void start() throws Exception {
    zk = new ZooKeeper(MasterWorkerConstants.DEFAULT_CONN_STRING, 15000, new AdminClientWatcher());
  }

  /**
   * list status of the system record in Zookeeper service
   */
  public void listState() {
    Stat stat = new Stat();
    try {
      byte[] masterData = zk.getData(//
        MasterWorkerConstants.MASTER_ZNODE_PATH, //
        false, //
        stat//
          );

      Date startDate = new Date(stat.getCtime());

      LOG.info("Master: " + new String(masterData) + " since" + startDate);

    } catch (KeeperException | InterruptedException e) {
      if (e instanceof NoNodeException) {
        LOG.info("no master");
      }
    }

    try {
      LOG.info("Workers: ");
      for (String worker : zk.getChildren("/workers", false)) {
        byte[] data = zk.getData(//
          MasterWorkerConstants.WORKER_PARENT_ZNODE_PATH + worker, //
          false, //
          null//
            );
        String status = new String(data);
        LOG.info("\t" + worker + ": " + status);
      }

      LOG.info("Tasks:");
      for (String task : zk.getChildren("/assign", false)) {
        LOG.info("\t" + task);
      }
    } catch (KeeperException | InterruptedException e) {
      e.printStackTrace();
    }
  }

}


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS -Wall -fno-warn-unused-do-bind #-}

module Scope.Cairo.Events (
      scopeCairoDefaultEvents
) where

import Prelude hiding (catch)

import Control.Applicative ((<$>))
import Control.Monad.Reader
import Data.IORef
import qualified Graphics.UI.Gtk as G

import Scope.Types hiding (m, b)
import Scope.View

import Scope.Cairo.IORef
import Scope.Cairo.Plot
import Scope.Cairo.Types

----------------------------------------------------------------

scopeCairoDefaultEvents :: IORef (Scope ViewCairo) -> IO ()
scopeCairoDefaultEvents scopeRef = do
    ViewCairo{..} <- viewUI . view <$> readIORef scopeRef

    adj `G.onValueChanged` (scroll scopeRef)

    canvas `G.on` G.buttonPressEvent $ G.tryEvent $ buttonDown scopeRef
    canvas `G.on` G.buttonReleaseEvent $ G.tryEvent $ buttonRelease scopeRef
    canvas `G.on` G.scrollEvent $ G.tryEvent $ wheel scopeRef
    canvas `G.on` G.motionNotifyEvent $ G.tryEvent $ motion scopeRef
    canvas `G.on` G.keyPressEvent $ G.tryEvent $ keyDown scopeRef
    G.widgetAddEvents canvas
        [ G.KeyPressMask
        , G.KeyReleaseMask
        , G.PointerMotionMask
        , G.ButtonMotionMask
        , G.ScrollMask
        ]

    G.widgetSetCanFocus canvas True

    canvas `G.on` G.exposeEvent $ G.tryEvent $ do
      liftIO $ updateCanvas scopeRef
      return ()

    return ()

----------------------------------------------------------------

scroll :: IORef (Scope ViewCairo) -> IO ()
scroll ref = do
    val <- G.adjustmentGetValue =<< adj . viewUI . view <$> readIORef ref
    scopeModifyUpdate ref (viewMoveTo val)

----------------------------------------------------------------

_canvasToScreen :: G.DrawingArea -> CanvasX -> IO ScreenX
_canvasToScreen c (CanvasX cX) = do
    (width, _height) <- G.widgetGetSize c
    return $ ScreenX (fromIntegral width * cX)

screenToCanvas :: ViewCairo -> ScreenX -> IO CanvasX
screenToCanvas vc (ScreenX sX) = do
    (width, _height) <- G.widgetGetSize (canvas vc)
    return $ CanvasX (sX / fromIntegral width)

----------------------------------------------------------------

buttonDown :: IORef (Scope ViewCairo) -> G.EventM G.EButton ()
buttonDown ref = do
    (x, _y) <- G.eventCoordinates
    liftIO $ do
        vc <- viewUI . view <$> readIORef ref
        cX <- screenToCanvas vc (ScreenX x)
        scopeModifyUpdate ref (viewButtonDown cX)

buttonRelease :: IORef (Scope ViewCairo) -> G.EventM G.EButton ()
buttonRelease ref = liftIO $ modifyIORef ref (scopeModifyView viewButtonRelease)

motion :: IORef (Scope ViewCairo) -> G.EventM G.EMotion ()
motion ref = do
    (x, _y) <- G.eventCoordinates
    liftIO $ do
        View{..} <- view <$> readIORef ref
        cX <- screenToCanvas viewUI (ScreenX x)
        scopeModifyUpdate ref (viewButtonMotion cX)

wheel :: IORef (Scope ViewCairo) -> G.EventM G.EScroll ()
wheel ref = do
    (x, _y) <- G.eventCoordinates
    dir <- G.eventScrollDirection
    liftIO $ do
        scope <- readIORef ref
        let View{..} = view scope
        cX <- screenToCanvas viewUI (ScreenX x)
        case dir of
            G.ScrollUp   -> scopeModifyUpdate ref (viewZoomInOn cX 1.2)
            G.ScrollDown -> scopeModifyUpdate ref (viewZoomOutOn cX 1.2)
            _            -> return ()

----------------------------------------------------------------

-- Some keys we are interested in, from:
-- http://cgit.freedesktop.org/xorg/proto/x11proto/plain/keysymdef.h
#define XK_Home                          0xff50
#define XK_Left                          0xff51  /* Move left, left arrow */
#define XK_Up                            0xff52  /* Move up, up arrow */
#define XK_Right                         0xff53  /* Move right, right arrow */
#define XK_Down                          0xff54  /* Move down, down arrow */
#define XK_Page_Up                       0xff55
#define XK_Page_Down                     0xff56
#define XK_End                           0xff57  /* EOL */

keyDown :: IORef (Scope ViewCairo) -> G.EventM G.EKey ()
keyDown ref = do
    v <- G.eventKeyVal
    -- n <- G.eventKeyName
    -- liftIO . putStrLn $ printf "Key %s (%d) pressed" n v
    let f = case v of
                XK_Home -> Just viewMoveStart
                XK_End  -> Just viewMoveEnd
                XK_Up   -> Just $ viewZoomIn 2.0
                XK_Down -> Just $ viewZoomOut 2.0
                XK_Left  -> Just viewMoveRight
                XK_Right -> Just viewMoveLeft
                _ -> Nothing

    maybe (return ()) (liftIO . scopeModifyUpdate ref) f


text:
package com.hardik.hibernate.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name = "Course")
public class Course {

	private long courseId;
	private String courseName;
	private Set<Student> students = new HashSet<Student>(0);

	public Course() {
	}

	public Course(String courseName) {
		this.courseName = courseName;
	}

	public Course(String courseName, Set<Student> students) {
		this.courseName = courseName;
		this.students = students;
	}

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "course_id")
	public long getCourseId() {
		return courseId;
	}

	public void setCourseId(long courseId) {
		this.courseId = courseId;
	}

	@Column(name = "course_name", nullable = false)
	public String getCourseName() {
		return courseName;
	}

	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}

	@ManyToMany(fetch = FetchType.LAZY, mappedBy = "courses")
	public Set<Student> getStudents() {
		return students;
	}

	public void setStudents(Set<Student> students) {
		this.students = students;
	}

}


text:
package helloworld;

public class HelloWorldServiceImpl implements HelloWorldService {
    public String getMessage(String greeting, String subject) {
        return greeting + ", " + subject;
    }
}