text:
namespace extensions {

namespace system_display = api::system_display;

namespace {

int64_t GetDisplayId(const std::string& display_id_str) {
  int64_t display_id;
  if (!base::StringToInt64(display_id_str, &display_id))
    display_id = display::kInvalidDisplayId;
  return display_id;
}

display::Display GetDisplayForId(const std::string& display_id_str) {
  int64_t id = GetDisplayId(display_id_str);
  display::Display display;
  display::Screen::GetScreen()->GetDisplayWithDisplayId(id, &display);
  return display;
}

crosapi::mojom::DisplayLayoutPosition GetDisplayLayoutPosition(
    system_display::LayoutPosition position) {
  switch (position) {
    case system_display::LAYOUT_POSITION_TOP:
      return crosapi::mojom::DisplayLayoutPosition::kTop;
    case system_display::LAYOUT_POSITION_RIGHT:
      return crosapi::mojom::DisplayLayoutPosition::kRight;
    case system_display::LAYOUT_POSITION_BOTTOM:
      return crosapi::mojom::DisplayLayoutPosition::kBottom;
    case system_display::LAYOUT_POSITION_LEFT:
    case system_display::LAYOUT_POSITION_NONE:
      return crosapi::mojom::DisplayLayoutPosition::kLeft;
  }
  NOTREACHED();
  return crosapi::mojom::DisplayLayoutPosition::kLeft;
}

gfx::Insets GetInsets(const system_display::Insets& insets) {
  return gfx::Insets::TLBR(insets.top, insets.left, insets.bottom,
                           insets.right);
}

bool IsValidRotation(int rotation) {
  return rotation == -1 || rotation == 0 || rotation == 90 || rotation == 180 ||
         rotation == 270;
}

crosapi::mojom::DisplayRotationOptions GetMojomDisplayRotationOptions(
    int rotation_value) {
  DCHECK(IsValidRotation(rotation_value));

  switch (rotation_value) {
    case -1:
      return crosapi::mojom::DisplayRotationOptions::kAutoRotate;
    case 0:
      return crosapi::mojom::DisplayRotationOptions::kZeroDegrees;
    case 90:
      return crosapi::mojom::DisplayRotationOptions::k90Degrees;
    case 180:
      return crosapi::mojom::DisplayRotationOptions::k180Degrees;
    case 270:
      return crosapi::mojom::DisplayRotationOptions::k270Degrees;
    default:
      NOTREACHED();
      return crosapi::mojom::DisplayRotationOptions::kZeroDegrees;
  }
}

int GetRotationFromMojomDisplayRotationInfo(
    crosapi::mojom::DisplayRotationOptions rotation_options) {
  switch (rotation_options) {
    case crosapi::mojom::DisplayRotationOptions::kAutoRotate:
      return -1;
    case crosapi::mojom::DisplayRotationOptions::kZeroDegrees:
      return 0;
    case crosapi::mojom::DisplayRotationOptions::k90Degrees:
      return 90;
    case crosapi::mojom::DisplayRotationOptions::k180Degrees:
      return 180;
    case crosapi::mojom::DisplayRotationOptions::k270Degrees:
      return 270;
  }
}

// Validates the DisplayProperties input. Does not perform any tests with
// DisplayManager dependencies. Returns an error string on failure or nullopt
// on success.
absl::optional<std::string> ValidateDisplayPropertiesInput(
    const std::string& display_id_str,
    const system_display::DisplayProperties& info) {
  int64_t id = GetDisplayId(display_id_str);
  if (id == display::kInvalidDisplayId)
    return "Invalid display id";

  const display::Display& primary =
      display::Screen::GetScreen()->GetPrimaryDisplay();
  bool is_primary = id == primary.id() || (info.is_primary && *info.is_primary);

  if (info.is_unified) {
    if (!is_primary)
      return "Unified desktop mode can only be set for the primary display.";
    // Setting isUnfied may change the display layout so no other properties
    // should be set.
    if (info.mirroring_source_id)
      return "Unified desktop mode can not be set with mirroringSourceId.";
    if (info.bounds_origin_x || info.bounds_origin_y || info.rotation ||
        info.overscan || info.display_mode || info.display_zoom_factor) {
      LOG(WARNING)
          << "Unified mode set with other properties which will be ignored.";
    }
    return absl::nullopt;
  }

  // If mirroring source parameter is specified, no other properties should be
  // set the display list may change when mirroring is applied.
  if (info.mirroring_source_id &&
      (info.is_primary || info.bounds_origin_x || info.bounds_origin_y ||
       info.rotation || info.overscan || info.display_mode ||
       info.display_zoom_factor)) {
    return "No other parameter should be set with mirroringSourceId.";
  }

  // Verify the rotation value is valid.
  if (info.rotation && !IsValidRotation(*info.rotation))
    return "Invalid rotation.";

  return absl::nullopt;
}

system_display::DisplayMode GetDisplayModeFromMojo(
    const crosapi::mojom::DisplayMode mode) {
  system_display::DisplayMode result;
  result.width = mode.size.width();
  result.height = mode.size.height();
  result.width_in_native_pixels = mode.size_in_native_pixels.width();
  result.height_in_native_pixels = mode.size_in_native_pixels.height();
  result.device_scale_factor = mode.device_scale_factor;
  result.refresh_rate = mode.refresh_rate;
  result.is_native = mode.is_native;
  result.is_interlaced = mode.is_interlaced;
  return result;
}

system_display::DisplayUnitInfo GetDisplayUnitInfoFromMojo(
    const crosapi::mojom::DisplayUnitInfo& mojo_info) {
  system_display::DisplayUnitInfo info;
  info.id = mojo_info.id;
  info.name = mojo_info.name;
  if (mojo_info.edid) {
    info.edid.emplace();
    info.edid->manufacturer_id = mojo_info.edid->manufacturer_id;
    info.edid->product_id = mojo_info.edid->product_id;
    info.edid->year_of_manufacture = mojo_info.edid->year_of_manufacture;
  }
  info.is_primary = mojo_info.is_primary;
  info.is_internal = mojo_info.is_internal;
  info.is_enabled = mojo_info.is_enabled;
  info.is_auto_rotation_allowed = mojo_info.is_auto_rotation_allowed;
  info.dpi_x = mojo_info.dpi_x;
  info.dpi_y = mojo_info.dpi_y;
  info.rotation =
      GetRotationFromMojomDisplayRotationInfo(mojo_info.rotation_options);
  const gfx::Rect& bounds = mojo_info.bounds;
  info.bounds.left = bounds.x();
  info.bounds.top = bounds.y();
  info.bounds.width = bounds.width();
  info.bounds.height = bounds.height();
  const gfx::Insets& overscan = mojo_info.overscan;
  info.overscan.left = overscan.left();
  info.overscan.top = overscan.top();
  info.overscan.right = overscan.right();
  info.overscan.bottom = overscan.bottom();
  const gfx::Rect& work_area = mojo_info.work_area;
  info.work_area.left = work_area.x();
  info.work_area.top = work_area.y();
  info.work_area.width = work_area.width();
  info.work_area.height = work_area.height();
  for (const crosapi::mojom::DisplayModePtr& mode :
       mojo_info.available_display_modes) {
    info.modes.emplace_back(GetDisplayModeFromMojo(*mode));
  }
  if (!info.modes.empty()) {
    int index = mojo_info.selected_display_mode_index;
    if (index < 0 || index >= static_cast<int>(info.modes.size()))
      index = 0;
    info.modes[index].is_selected = true;
  }
  info.has_touch_support = mojo_info.has_touch_support;
  info.has_accelerometer_support = mojo_info.has_accelerometer_support;
  info.available_display_zoom_factors =
      mojo_info.available_display_zoom_factors;
  info.display_zoom_factor = mojo_info.display_zoom_factor;
  return info;
}

crosapi::mojom::TouchCalibrationPairPtr GetTouchCalibrationPair(
    const system_display::TouchCalibrationPair& pair) {
  auto result = crosapi::mojom::TouchCalibrationPair::New();
  result->display_point =
      gfx::Point(pair.display_point.x, pair.display_point.y);
  result->touch_point = gfx::Point(pair.touch_point.x, pair.touch_point.y);
  return result;
}

void SetDisplayUnitInfoLayoutProperties(
    const crosapi::mojom::DisplayLayoutInfo& layout,
    system_display::DisplayUnitInfo* display) {
  display->is_unified =
      layout.layout_mode == crosapi::mojom::DisplayLayoutMode::kUnified;
  if (layout.mirror_source_id) {
    display->mirroring_source_id = *layout.mirror_source_id;
    if (layout.mirror_destination_ids) {
      for (const std::string& id : *layout.mirror_destination_ids)
        display->mirroring_destination_ids.push_back(id);
    }
  }
}

void RunResultCallback(DisplayInfoProvider::ErrorCallback callback,
                       absl::optional<std::string> error) {
  if (error)
    LOG(ERROR) << "API call failed: " << *error;
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::BindOnce(std::move(callback), std::move(error)));
}

absl::optional<std::string> GetStringResult(
    crosapi::mojom::DisplayConfigResult result) {
  switch (result) {
    case crosapi::mojom::DisplayConfigResult::kSuccess:
      return absl::nullopt;
    case crosapi::mojom::DisplayConfigResult::kInvalidOperationError:
      return "Invalid operation";
    case crosapi::mojom::DisplayConfigResult::kInvalidDisplayIdError:
      return "Invalid display id";
    case crosapi::mojom::DisplayConfigResult::kUnifiedNotEnabledError:
      return "enableUnifiedDesktop must be called before setting is_unified";
    case crosapi::mojom::DisplayConfigResult::kPropertyValueOutOfRangeError:
      return "Property value out of range";
    case crosapi::mojom::DisplayConfigResult::
        kNotSupportedOnInternalDisplayError:
      return "Not supported for internal displays";
    case crosapi::mojom::DisplayConfigResult::kNegativeValueError:
      return "Negative values not supported";
    case crosapi::mojom::DisplayConfigResult::kSetDisplayModeError:
      return "Setting the display mode failed";
    case crosapi::mojom::DisplayConfigResult::kInvalidDisplayLayoutError:
      return "Invalid display layout";
    case crosapi::mojom::DisplayConfigResult::kSingleDisplayError:
      return "This mode requires multiple displays";
    case crosapi::mojom::DisplayConfigResult::kMirrorModeSourceIdError:
      return "Mirror mode source id invalid";
    case crosapi::mojom::DisplayConfigResult::kMirrorModeDestIdError:
      return "Mirror mode destination id invalid";
    case crosapi::mojom::DisplayConfigResult::kCalibrationNotAvailableError:
      return "Calibration not available";
    case crosapi::mojom::DisplayConfigResult::kCalibrationNotStartedError:
      return "Calibration not started";
    case crosapi::mojom::DisplayConfigResult::kCalibrationInProgressError:
      return "Calibration in progress";
    case crosapi::mojom::DisplayConfigResult::kCalibrationInvalidDataError:
      return "Calibration data invalid";
    case crosapi::mojom::DisplayConfigResult::kCalibrationFailedError:
      return "Calibration failed";
  }
  return "Unknown error";
}

void LogErrorResult(crosapi::mojom::DisplayConfigResult result) {
  absl::optional<std::string> str_result = GetStringResult(result);
  if (!str_result)
    return;
  LOG(ERROR) << *str_result;
}

}  // namespace

DisplayInfoProviderChromeOS::DisplayInfoProviderChromeOS(
    mojo::PendingRemote<crosapi::mojom::CrosDisplayConfigController>
        display_config)
    : cros_display_config_(std::move(display_config)) {}

DisplayInfoProviderChromeOS::~DisplayInfoProviderChromeOS() = default;

void DisplayInfoProviderChromeOS::SetDisplayProperties(
    const std::string& display_id_str,
    const api::system_display::DisplayProperties& properties,
    ErrorCallback callback) {
  absl::optional<std::string> error =
      ValidateDisplayPropertiesInput(display_id_str, properties);
  if (error) {
    RunResultCallback(std::move(callback), std::move(*error));
    return;
  }

  // Process the 'isUnified' property.
  if (properties.is_unified) {
    auto layout_info = crosapi::mojom::DisplayLayoutInfo::New();
    layout_info->layout_mode = *properties.is_unified
                                   ? crosapi::mojom::DisplayLayoutMode::kUnified
                                   : crosapi::mojom::DisplayLayoutMode::kNormal;
    cros_display_config_->SetDisplayLayoutInfo(
        std::move(layout_info),
        base::BindOnce(
            [](ErrorCallback callback,
               crosapi::mojom::DisplayConfigResult result) {
              std::move(callback).Run(GetStringResult(result));
            },
            std::move(callback)));
    // Note: If other properties are set they will be ignored.
    return;
  }

  // Process the deprecated 'mirroringSourceId' property. Validation ensures
  // that no other properties are set.
  if (properties.mirroring_source_id) {
    bool mirror = !properties.mirroring_source_id->empty();
    if (mirror) {
      // A display with the given id should exist and if should not be the same
      // as the target display's id.

      int64_t mirroring_id =
          GetDisplayForId(*properties.mirroring_source_id).id();
      if (mirroring_id == display::kInvalidDisplayId)
        RunResultCallback(std::move(callback), "Invalid mirroring source id");
      if (mirroring_id == GetDisplayId(display_id_str))
        RunResultCallback(std::move(callback), "Not allowed to mirror self");
    }
    api::system_display::MirrorModeInfo info;
    info.mode = system_display::MIRROR_MODE_NORMAL;
    SetMirrorMode(info, std::move(callback));
    return;
  }

  // Global config properties.
  auto config_properties = crosapi::mojom::DisplayConfigProperties::New();
  config_properties->set_primary =
      properties.is_primary ? *properties.is_primary : false;
  if (properties.overscan)
    config_properties->overscan = GetInsets(*properties.overscan);
  if (properties.rotation) {
    config_properties->rotation = crosapi::mojom::DisplayRotation::New(
        GetMojomDisplayRotationOptions(*properties.rotation));
  }
  if (properties.bounds_origin_x || properties.bounds_origin_y) {
    gfx::Point bounds_origin;
    display::Display display = GetDisplayForId(display_id_str);
    if (display.id() != display::kInvalidDisplayId)
      bounds_origin = display.bounds().origin();
    else
      DLOG(ERROR) << "Unable to get origin for display: " << display_id_str;
    if (properties.bounds_origin_x)
      bounds_origin.set_x(*properties.bounds_origin_x);
    if (properties.bounds_origin_y)
      bounds_origin.set_y(*properties.bounds_origin_y);
    LOG(ERROR) << "Bounds origin: " << bounds_origin.ToString();
    config_properties->bounds_origin = std::move(bounds_origin);
  }
  config_properties->display_zoom_factor =
      properties.display_zoom_factor ? *properties.display_zoom_factor : 0;

  // Display mode.
  if (properties.display_mode) {
    auto mojo_display_mode = crosapi::mojom::DisplayMode::New();
    const api::system_display::DisplayMode& api_display_mode =
        *properties.display_mode;
    mojo_display_mode->size =
        gfx::Size(api_display_mode.width, api_display_mode.height);
    mojo_display_mode->size_in_native_pixels =
        gfx::Size(api_display_mode.width_in_native_pixels,
                  api_display_mode.height_in_native_pixels);
    mojo_display_mode->device_scale_factor =
        api_display_mode.device_scale_factor;
    mojo_display_mode->refresh_rate = api_display_mode.refresh_rate;
    mojo_display_mode->is_native = api_display_mode.is_native;
    mojo_display_mode->is_interlaced =
        api_display_mode.is_interlaced && *(api_display_mode.is_interlaced);
    config_properties->display_mode = std::move(mojo_display_mode);
  }

  cros_display_config_->SetDisplayProperties(
      display_id_str, std::move(config_properties),
      crosapi::mojom::DisplayConfigSource::kUser,
      base::BindOnce(
          [](ErrorCallback callback,
             crosapi::mojom::DisplayConfigResult result) {
            std::move(callback).Run(GetStringResult(result));
          },
          std::move(callback)));
}

void DisplayInfoProviderChromeOS::SetDisplayLayout(
    const DisplayLayoutList& layout_list,
    ErrorCallback callback) {
  auto layout_info = crosapi::mojom::DisplayLayoutInfo::New();
  // Generate the new list of layouts.
  std::vector<crosapi::mojom::DisplayLayoutPtr> display_layouts;
  for (const system_display::DisplayLayout& layout : layout_list) {
    auto display_layout = crosapi::mojom::DisplayLayout::New();
    display_layout->id = layout.id;
    display_layout->parent_id = layout.parent_id;
    display_layout->position = GetDisplayLayoutPosition(layout.position);
    display_layout->offset = layout.offset;
    display_layouts.emplace_back(std::move(display_layout));
  }
  layout_info->layouts = std::move(display_layouts);
  // We need to get the current layout info to provide the layout mode.
  cros_display_config_->GetDisplayLayoutInfo(
      base::BindOnce(&DisplayInfoProviderChromeOS::CallSetDisplayLayoutInfo,
                     weak_ptr_factory_.GetWeakPtr(), std::move(layout_info),
                     std::move(callback)));
}

void DisplayInfoProviderChromeOS::CallSetDisplayLayoutInfo(
    crosapi::mojom::DisplayLayoutInfoPtr layout_info,
    ErrorCallback callback,
    crosapi::mojom::DisplayLayoutInfoPtr cur_info) {
  // Copy the existing layout_mode.
  layout_info->layout_mode = cur_info->layout_mode;
  cros_display_config_->SetDisplayLayoutInfo(
      std::move(layout_info),
      base::BindOnce(
          [](ErrorCallback callback,
             crosapi::mojom::DisplayConfigResult result) {
            std::move(callback).Run(GetStringResult(result));
          },
          std::move(callback)));
}

void DisplayInfoProviderChromeOS::EnableUnifiedDesktop(bool enable) {
  cros_display_config_->SetUnifiedDesktopEnabled(enable);
}

void DisplayInfoProviderChromeOS::GetAllDisplaysInfo(
    bool single_unified,
    base::OnceCallback<void(DisplayUnitInfoList result)> callback) {
  cros_display_config_->GetDisplayLayoutInfo(base::BindOnce(
      &DisplayInfoProviderChromeOS::CallGetDisplayUnitInfoList,
      weak_ptr_factory_.GetWeakPtr(), single_unified, std::move(callback)));
}

void DisplayInfoProviderChromeOS::CallGetDisplayUnitInfoList(
    bool single_unified,
    base::OnceCallback<void(DisplayUnitInfoList result)> callback,
    crosapi::mojom::DisplayLayoutInfoPtr layout) {
  cros_display_config_->GetDisplayUnitInfoList(
      single_unified,
      base::BindOnce(&DisplayInfoProviderChromeOS::OnGetDisplayUnitInfoList,
                     weak_ptr_factory_.GetWeakPtr(), std::move(layout),
                     std::move(callback)));
}

void DisplayInfoProviderChromeOS::OnGetDisplayUnitInfoList(
    crosapi::mojom::DisplayLayoutInfoPtr layout,
    base::OnceCallback<void(DisplayUnitInfoList)> callback,
    std::vector<crosapi::mojom::DisplayUnitInfoPtr> info_list) {
  DisplayUnitInfoList all_displays;
  for (const crosapi::mojom::DisplayUnitInfoPtr& info : info_list) {
    system_display::DisplayUnitInfo display = GetDisplayUnitInfoFromMojo(*info);
    SetDisplayUnitInfoLayoutProperties(*layout, &display);
    all_displays.push_back(std::move(display));
  }
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::BindOnce(std::move(callback), std::move(all_displays)));
}

void DisplayInfoProviderChromeOS::GetDisplayLayout(
    base::OnceCallback<void(DisplayLayoutList)> callback) {
  cros_display_config_->GetDisplayLayoutInfo(
      base::BindOnce(&OnGetDisplayLayoutResult, std::move(callback)));
}

bool DisplayInfoProviderChromeOS::OverscanCalibrationStart(
    const std::string& id) {
  cros_display_config_->OverscanCalibration(
      id, crosapi::mojom::DisplayConfigOperation::kStart, absl::nullopt,
      base::BindOnce(&LogErrorResult));
  return true;
}

bool DisplayInfoProviderChromeOS::OverscanCalibrationAdjust(
    const std::string& id,
    const system_display::Insets& delta) {
  cros_display_config_->OverscanCalibration(
      id, crosapi::mojom::DisplayConfigOperation::kAdjust, GetInsets(delta),
      base::BindOnce(&LogErrorResult));
  return true;
}

bool DisplayInfoProviderChromeOS::OverscanCalibrationReset(
    const std::string& id) {
  cros_display_config_->OverscanCalibration(
      id, crosapi::mojom::DisplayConfigOperation::kReset, absl::nullopt,
      base::BindOnce(&LogErrorResult));
  return true;
}

bool DisplayInfoProviderChromeOS::OverscanCalibrationComplete(
    const std::string& id) {
  cros_display_config_->OverscanCalibration(
      id, crosapi::mojom::DisplayConfigOperation::kComplete, absl::nullopt,
      base::BindOnce(&LogErrorResult));
  return true;
}

void DisplayInfoProviderChromeOS::ShowNativeTouchCalibration(
    const std::string& id,
    ErrorCallback callback) {
  CallTouchCalibration(id, crosapi::mojom::DisplayConfigOperation::kShowNative,
                       nullptr, std::move(callback));
}

bool DisplayInfoProviderChromeOS::StartCustomTouchCalibration(
    const std::string& id) {
  touch_calibration_target_id_ = id;
  CallTouchCalibration(id, crosapi::mojom::DisplayConfigOperation::kStart,
                       nullptr, ErrorCallback());
  return true;
}

bool DisplayInfoProviderChromeOS::CompleteCustomTouchCalibration(
    const api::system_display::TouchCalibrationPairQuad& pairs,
    const api::system_display::Bounds& bounds) {
  auto calibration = crosapi::mojom::TouchCalibration::New();
  calibration->pairs.emplace_back(GetTouchCalibrationPair(pairs.pair1));
  calibration->pairs.emplace_back(GetTouchCalibrationPair(pairs.pair2));
  calibration->pairs.emplace_back(GetTouchCalibrationPair(pairs.pair3));
  calibration->pairs.emplace_back(GetTouchCalibrationPair(pairs.pair4));
  calibration->bounds = gfx::Size(bounds.width, bounds.height);
  CallTouchCalibration(touch_calibration_target_id_,
                       crosapi::mojom::DisplayConfigOperation::kComplete,
                       std::move(calibration), ErrorCallback());
  return true;
}

bool DisplayInfoProviderChromeOS::ClearTouchCalibration(const std::string& id) {
  CallTouchCalibration(id, crosapi::mojom::DisplayConfigOperation::kReset,
                       nullptr, ErrorCallback());
  return true;
}

void DisplayInfoProviderChromeOS::CallTouchCalibration(
    const std::string& id,
    crosapi::mojom::DisplayConfigOperation op,
    crosapi::mojom::TouchCalibrationPtr calibration,
    ErrorCallback callback) {
  cros_display_config_->TouchCalibration(
      id, op, std::move(calibration),
      base::BindOnce(
          [](ErrorCallback callback,
             crosapi::mojom::DisplayConfigResult result) {
            if (!callback)
              return;
            std::move(callback).Run(
                result == crosapi::mojom::DisplayConfigResult::kSuccess
                    ? absl::nullopt
                    : GetStringResult(result));
          },
          std::move(callback)));
}

void DisplayInfoProviderChromeOS::SetMirrorMode(
    const api::system_display::MirrorModeInfo& info,
    ErrorCallback callback) {
  auto display_layout_info = crosapi::mojom::DisplayLayoutInfo::New();
  if (info.mode == api::system_display::MIRROR_MODE_OFF) {
    display_layout_info->layout_mode =
        crosapi::mojom::DisplayLayoutMode::kNormal;
  } else {
    display_layout_info->layout_mode =
        crosapi::mojom::DisplayLayoutMode::kMirrored;
    if (info.mode == api::system_display::MIRROR_MODE_MIXED) {
      if (!info.mirroring_source_id) {
        RunResultCallback(std::move(callback), "Mirror mode source id invalid");
        return;
      }
      if (!info.mirroring_destination_ids) {
        RunResultCallback(std::move(callback),
                          "Mixed mirror mode requires destination ids");
        return;
      }
      display_layout_info->mirror_source_id = *info.mirroring_source_id;
      display_layout_info->mirror_destination_ids =
          absl::make_optional<std::vector<std::string>>(
              *info.mirroring_destination_ids);
    }
  }
  cros_display_config_->SetDisplayLayoutInfo(
      std::move(display_layout_info),
      base::BindOnce(
          [](ErrorCallback callback,
             crosapi::mojom::DisplayConfigResult result) {
            std::move(callback).Run(GetStringResult(result));
          },
          std::move(callback)));
}

void DisplayInfoProviderChromeOS::StartObserving() {
  DisplayInfoProvider::StartObserving();

  mojo::PendingAssociatedRemote<crosapi::mojom::CrosDisplayConfigObserver>
      observer;
  cros_display_config_observer_receiver_.Bind(
      observer.InitWithNewEndpointAndPassReceiver());
  cros_display_config_->AddObserver(std::move(observer));
}

void DisplayInfoProviderChromeOS::StopObserving() {
  DisplayInfoProvider::StopObserving();

  cros_display_config_observer_receiver_.reset();
}

void DisplayInfoProviderChromeOS::OnDisplayConfigChanged() {
  DispatchOnDisplayChangedEvent();
}

#if BUILDFLAG(IS_CHROMEOS_ASH)

std::unique_ptr<DisplayInfoProvider> CreateChromeDisplayInfoProvider() {
  mojo::PendingRemote<crosapi::mojom::CrosDisplayConfigController>
      display_config;
  ash::BindCrosDisplayConfigController(
      display_config.InitWithNewPipeAndPassReceiver());
  return std::make_unique<DisplayInfoProviderChromeOS>(
      std::move(display_config));
}

#elif BUILDFLAG(IS_CHROMEOS_LACROS)

std::unique_ptr<DisplayInfoProvider> CreateChromeDisplayInfoProvider() {
  // Assume that LacrosService has already been initialized.
  auto* lacros_service = chromeos::LacrosService::Get();
  if (lacros_service &&
      lacros_service
          ->IsAvailable<crosapi::mojom::CrosDisplayConfigController>()) {
    auto& remote =
        lacros_service
            ->GetRemote<crosapi::mojom::CrosDisplayConfigController>();
    return std::make_unique<DisplayInfoProviderChromeOS>(remote.Unbind());
  }

  LOG(ERROR) << "Cannot create a DisplayInfoProvider instance in Lacros. "
                "CrosDisplayConfigController interface is not available.";
  return nullptr;
}

#endif

}  // namespace extensions


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ann. Mus. Hist. Nat. 9:396, t. 30. 1807

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
#include "Precompiled.h"

#include "VariantBase.h"

#include "ArrayWrapper.h"

namespace ursine
{
    namespace meta
    {
        bool VariantBase::IsArray(void) const
        {
            return false;
        }

        ArrayWrapper VariantBase::GetArray(void) const
        {
            // invalid wrapper
            return { };
        }
    }
}


text:
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>fr.unice.spinefm</groupId>
    <artifactId>spinefm-eclipseplugins-root</artifactId>
    <version>1.1.1-SNAPSHOT</version>
	</parent>
	<groupId>fr.unice.spinefm.rest</groupId>
	<artifactId>spinefm-rest-service</artifactId>
	<name>spinefm-rest-service Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<packaging>eclipse-plugin</packaging>
	<properties>
		<output-directory>${basedir}/target/WEB-INF</output-directory>
	</properties>
	<build>
		<finalName>spinefm-rest-service</finalName>
		<plugins>

			<plugin>
				<groupId>org.eclipse.tycho</groupId>
				<artifactId>tycho-packaging-plugin</artifactId>
				<version>0.19.0</version>
				<configuration>
					<deployableFeature>true</deployableFeature>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>${project.build.directory}/dependency</outputDirectory>
							<overWriteReleases>false</overWriteReleases>
							<overWriteSnapshots>true</overWriteSnapshots>
						</configuration>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<artifactId>maven-resources-plugin</artifactId>
				<version>2.4.3</version>
				<executions>
					<execution>
						<id>copy-web-inf</id>
						<phase>package</phase>
						<goals>
							<goal>copy-resources</goal>
						</goals>
						<configuration>
							<outputDirectory>${output-directory}</outputDirectory>
							<resources>
								<resource>
									<directory>${basedir}/src/main/webapp/WEB-INF</directory>
									<includes>
										<include>**</include>
									</includes>
								</resource>
							</resources>
						</configuration>
					</execution>
					<execution>
						<id>copy-plugins</id>
						<phase>package</phase>
						<goals>
							<goal>copy-resources</goal>
						</goals>
						<configuration>
							<outputDirectory>${output-directory}/classes</outputDirectory>
							<resources>
								<resource>
									<directory>${basedir}/target/classes</directory>
									<includes>
										<include>*/**</include>
									</includes>
									<excludes>
										<exclude>*.jar</exclude>
									</excludes>
								</resource>
							</resources>
						</configuration>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.2-beta-5</version>
				<configuration>
					<descriptors>
						<descriptor>assembly.xml</descriptor>
					</descriptors>
					<finalName>spinefm-rest-service</finalName>
				</configuration>
				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>8.1.10.v20130312</version>
			</plugin>
		</plugins>
		<pluginManagement>
			<plugins>
				<!--This plugin's configuration is used to store Eclipse m2e settings
					only. It has no influence on the Maven build itself. -->
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>
											org.apache.maven.plugins
										</groupId>
										<artifactId>
											maven-dependency-plugin
										</artifactId>
										<versionRange>[2.5,)</versionRange>
										<goals>
											<goal>copy-dependencies</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore></ignore>
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>


text:
local Errors = require "kong.dao.errors"

return {
  fields = {
    status_code = { type = "number", default = 503 },
    message = { type = "string" },
    content_type = { type = "string" },
    body = { type = "string" },
  },
  self_check = function(schema, plugin_t, dao, is_updating)
    if plugin_t.status_code then
      if plugin_t.status_code < 100 or plugin_t.status_code > 599 then
        return false, Errors.schema("status_code must be between 100 .. 599")
      end
    end

    if plugin_t.message then
      if plugin_t.content_type or plugin_t.body then
        return false, Errors.schema("message cannot be used with content_type or body")
      end
    else
      if plugin_t.content_type and not plugin_t.body then
        return false, Errors.schema("content_type requires a body")
      end
    end

    return true
  end
}


text:
function Get-IndexColumn
{
    <#
    .SYNOPSIS
    Gets the columns that are part of an index.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        $InputObject
    )

    begin
    {
    }

    process
    {
        $query = @'
    select
        c.name column_name, i.*, ic.*, c.*
    from
        sys.indexes i
        inner join sys.index_columns ic on ic.index_id = i.index_id and ic.object_id=i.object_id
        inner join sys.columns c on ic.object_id = c.object_id and c.column_id = ic.column_id
    where
        i.object_id = {0} and i.index_id={1}
    order by
        ic.key_ordinal
'@ -f $InputObject.object_id, $InputObject.index_id

        [Object[]]$columns = Invoke-RivetTestQuery -Query $query
        Add-Member -InputObject $InputObject -MemberType NoteProperty -Name 'Columns' -Value $columns -PassThru
    }

    end
    {
    }

}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="none">
    <title>404 Not Found</title>

404 Not Found

      The page or file you requested wasn't found on our site. It's possible
      that you clicked a link that's out of date, or typed in the address
      incorrectly.

If you typed in the address, please double check the spelling.

Visit games.mozilla.org.


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Elasticsearch.Net
{
	public interface ITransport<out TConnectionSettings>
		where TConnectionSettings : IConnectionConfigurationValues
	{
		TConnectionSettings Settings { get; }

		ElasticsearchResponse<T> Request<T>(HttpMethod method, string path, PostData<object> data = null, IRequestParameters requestParameters = null)
			where T : class;
		Task<ElasticsearchResponse<T>> RequestAsync<T>(HttpMethod method, string path, CancellationToken cancellationToken, PostData<object> data = null, IRequestParameters requestParameters = null)
			where T : class;
	}

}


text:
#import <Foundation/Foundation.h>

@class TINKKeysetHandle;
@protocol TINKPublicKeyVerify;

NS_ASSUME_NONNULL_BEGIN;

/**
 * TINKPublicKeyVerifyFactory allows for obtaining a TINKPublicKeyVerify primitive from a
 * TINKKeysetHandle.
 *
 * TINKPublicKeyVerifyFactory gets primitives from the Registry, which can be initialized via
 * convenience methods from the TINKSignatureConfig class. Here is an example how one can obtain and
 * use a TINKPublicKeyVerify primitive:
 *
 * NSError *error = nil;
 * TINKSignatureConfig *signatureConfig = [[TINKSignatureConfig alloc] initWithError:&error];
 * if (!signatureConfig || error) {
 *   // handle error.
 * }
 *
 * if (![TINKConfig registerConfig:signatureConfig error:&error]) {
 *   // handle error.
 * }
 *
 * TINKKeysetHandle keysetHandle = ...;
 * id<TINKPublicKeyVerify> publicKeyVerify = [TINKPublicKeyVerifyFactory
 *                                               primitiveWithKeysetHandle:keysetHandle
 *                                                                   error:&error];
 * if (!publicKeyVerify || error) {
 *   // handle error.
 * }
 *
 * NSData *data = ...;
 * NSData *signature = ...;
 * BOOL result = [publicKeyVerify verifySignature:signature forData:data error:&error];
 * if (!result) {
 *   // Signature was not correct.
 *   // ...
 * }
 */
@interface TINKPublicKeyVerifyFactory : NSObject
/**
 * Returns an object that conforms to the TINKPublicKeyVerify protocol. It uses key material from
 * the keyset specified via @c keysetHandle.
 */
+ (nullable id<TINKPublicKeyVerify>)primitiveWithKeysetHandle:(TINKKeysetHandle *)keysetHandle
                                                        error:(NSError **)error;
@end

NS_ASSUME_NONNULL_END;


text:
/* @flow */
export default {
  id: 'import-syntax',
  title: 'Import Syntax',
  description: `\`\`\`
import TextArea from 'mineral-ui/TextArea';
\`\`\`

<Callout title="Note">

    TextAreas should be wrapped in a FormField to
    provide an accessible label and other features. Examples here omit labels for
    clarity and brevity.

</Callout>
`
};


text:
<form id="imagesaddfm" method="post">
<input type="hidden" name="id" value="<?php echo $dataset['id'];?>" />

			标题:
			<input name="title" type="text" style="width:400px;" class="textbox-text validatebox-text textbox-prompt easyui-validatebox" placeholder="请输入标题.."  required="true"  value="<?php echo $dataset['title'];?>" >

			链接:
			<input name="links" type="text" style="width:400px;"  class="textbox-text validatebox-text textbox-prompt easyui-validatebox" placeholder="请输入链接.." value="<?php echo $dataset['links'];?>" >

			排序:
			<input name="sortorder" type="text" class="textbox-text validatebox-text textbox-prompt easyui-validatebox" placeholder="请输入排序.." value="<?php echo $dataset['sortorder'];?>" >

			类别:

				<input name="type" type="radio" class="textbox-prompt" value="1" <?php if($dataset['type']==1){echo 'checked="checked"';}?> >APP引导图
				<input name="type" type="radio" class="textbox-prompt" value="2" <?php if($dataset['type']==2){echo 'checked="checked"';}?> >广告图片
				<input name="type" type="radio" class="textbox-prompt" value="3" <?php if($dataset['type']==3){echo 'checked="checked"';}?> >首页动图

			状态:
			<input name="status" type="checkbox" class="textbox-prompt" value="1" >激活

			图片:

点击上传图片,或者将图片拖至此处。

						队列全部文件处理完毕

							图片
							字节
							网络文件

</form>


text:
/*
 * Right-To-Left (RTL) Support
 * ----------
 */

/*login page*/
[dir="rtl"] body.login .logo-title-container
{
    right: 30px;
    left: auto;
}
[dir="rtl"] body.login .copy h1
{
    margin: 20px 14px 0 0;
}
[dir="rtl"] body.login .copy p
{
    right: 15px;
    left: auto;
}
[dir="rtl"] body.login .login-container p
{
    text-align: right;
}

/*other app pages*/

[dir="rtl"] .site-footer-right {
    text-align: left;
    padding-left: 20px;
}
[dir="rtl"] .side-body > .language-selector
{
    float: left !important;
    padding: 28px 0 0 15px;
}
[dir="rtl"] .voyager div.dataTables_paginate li.next a::after,
[dir="rtl"] .voyager div.dataTables_paginate li.previous a::before {
    content: none;
}
[dir="rtl"] .voyager div.dataTables_paginate li.previous a::before {
    content: "\e046";
    font-family: Voyager;
    right: 10px;
    left: auto;
}
[dir="rtl"] div.dataTables_paginate li.first > a, div.dataTables_paginate li.previous > a
{
    padding-right: 24px;
    padding-left: 10px;
}

[dir="rtl"] div.dataTables_paginate li.last > a, div.dataTables_paginate li.next > a
{
    padding-left: 24px;
    padding-right: 10px;
}
[dir="rtl"] .voyager div.dataTables_paginate li.next a::after {
    content: "\e039";
    font-family: Voyager;
    left: 10px;
    right: auto;
}

[dir="rtl"] .dropdown-menu > li > form .voyager-power
{
    float: right;
}
[dir="rtl"] .dropdown-menu > li > a i
{
    float: right;
    padding-left: 10px;
}

/*imported and validated with v 1.0*/
[dir="rtl"] .app-container .content-container .navbar-top .hamburger {
    float: right;
}

[dir="rtl"] .breadcrumb > li + li:before {
    display: none;
}

[dir="rtl"] .breadcrumb li+li:after {
    padding: 0 5px;
}
[dir="rtl"] .breadcrumb > li + li:after {
    font-family: Voyager;
    content: '\e039';
    position: relative;
    top: 1px;
    margin-left: 3px;
}

/*imported from v0.11*/
[dir="rtl"] .navbar {
    padding-left: 0px;
    padding-right: 60px;}

[dir="rtl"] .app-container .side-body{
    margin-left: 15px;
    margin-right: 75px;
}

[dir="rtl"] .navbar-header {
    float: right;
}

[dir="rtl"] .app-container.expanded .content-container .navbar-top {
    padding-left: 0px;
    padding-right: 250px;
}

[dir="rtl"] #sidebar-anchor {
    margin-left: 10px;
    margin-right: auto;
    float: right;
}

[dir="rtl"] .app-container .content-container .side-menu .navbar, .nav.navbar-nav {
    padding-right: 0px;
}

[dir="rtl"] table th{
    text-align: right;
}

[dir="rtl"] table.dataTable thead .sorting:after, table.dataTable thead .sorting_asc:after, table.dataTable thead .sorting_desc:after{
    right: unset;
    left: 4px;
}

[dir="rtl"] .dataTables_length {
    float: left
}

[dir="rtl"] .app-container .content-container .side-menu {
    right: 0;
}

[dir="rtl"] .page-title {
  padding-right: 25px
}

[dir="rtl"] .page-title > i {
    position: unset;
    margin-right: unset;
    font-size: 36px;
    margin-left: 10px;
    float: right;
}

[dir="rtl"] .page-title .btn.btn-success {
    left: unset;
    right: 15px;
}

[dir="rtl"] .dropdown-menu.dropdown-menu-animated {
    position: absolute !important;
}

[dir="rtl"] .navbar-nav.navbar-right, .navbar-nav.navbar-left {
    right: unset;
    left: 10px;
}

[dir="rtl"] .app-container .side-menu .panel.widget .avatar {
    float: right;
    margin-left: 0px;
    margin-right: 10px;
}

[dir="rtl"] .app-container .side-menu .panel.widget h4 {
    float: right;
    text-align: right;
    right: 56px;
    left:auto;
}

[dir="rtl"] .text-right {
    text-align: left !important;
}

[dir="rtl"] .app-container.expanded .side-body {
    margin-right: 235px;
}

[dir="rtl"] .panel-title{
    padding: 20px 30px;
    padding-right: 15px;
    text-align: right;
}

[dir="rtl"] .panel-actions{
    left: 30px;
    right: unset !important;
}

[dir="rtl"] code{
    direction: ltr;
    display: inline-block;
}

[dir="rtl"] .pull-right {
    float: left !important;
}

[dir="rtl"] .delete, [dir="rtl"] .edit {
    margin-right: 5px;
    margin-left: auto;
}

[dir="rtl"] .app-container .content-container .side-menu .navbar-nav li.dropdown > a:after {
    right: auto !important;
    left: 1em;
}

[dir="rtl"] .dd .item_actions{
    right: auto;
    left: 10px;
}

[dir="rtl"] .dd .dd-handle .url {
    display: inline-block;
}

[dir="rtl"] .panel-actions .voyager-trash, [dir="rtl"] .voyager-sort-desc, [dir="rtl"] .voyager-sort-asc {
    display: inline-block;
}

[dir="rtl"] .voyager-sort-desc {
    margin-left: 10px;
    margin-right: auto;
}

[dir="rtl"] .database-tables .name{
    float: right;
}

[dir="rtl"] .database-tables .voyager-bread{
    margin-right: 10px;
    margin-left: auto;
    right: 100%;
    left: auto;
}

[dir="rtl"] .database-tables .actions .btn-warning, [dir="rtl"] .database-tables .actions .btn-primary{
    margin-left: 10px !important;
    margin-right: auto !important;
}

[dir="rtl"] .toast-top-right {
    top: 12px;
    right: auto;
    left: 12px;
}

[dir="rtl"] #toast-container>div {
    background-position: calc(100% - 15px) center;
    padding: 15px 50px 15px 15px;
}

[dir="rtl"] .dropdown-menu>li>a {
    text-align: right;
}

[dir="rtl"] .navbar .dropdown.profile .dropdown-menu li.profile-img img.profile-img {
    float: right;
    margin-right: auto;
    margin-left: 10px;
}

[dir="rtl"] .navbar .dropdown.profile .dropdown-menu h5, [dir="rtl"] .navbar .dropdown.profile .dropdown-menu h6 {
    float: right;
}

[dir="rtl"] .breadcrumb-container .toggle{
    float: left;
    right: auto;
    left: 5px;
}

[dir="rtl"] .breadcrumb-container .toggle span {
    float: right;
    left: 10px;
    right: auto;
}

[dir="rtl"] .breadcrumb-container .toggle i {
    float: left;
    margin-right: auto;
    margin-left: 5px;
    top: -8px;
    -ms-transform: rotate(180deg);
    -webkit-transform: rotate(180deg);
    transform: rotate(180deg);
 }

[dir="rtl"] .detail_info h4 {
    float: right;
    margin-right: auto;
    margin-left: 8px;
}

[dir="rtl"] .detail_info p {
     float: right;
     color: #444;
     padding-bottom: 3px;
     font-size: 12px;
     font-weight: 400;
 }

[dir="rtl"] .file_link .link_icon {
    margin-left: 5px;
    margin-right: 0;
}

@media (min-width: 992px) {
    [dir="rtl"] .col-md-1, [dir="rtl"] .col-md-10, [dir="rtl"] .col-md-11,
    [dir="rtl"] .col-md-12, [dir="rtl"] .col-md-2, [dir="rtl"] .col-md-3,
    [dir="rtl"] .col-md-4, [dir="rtl"] .col-md-5, [dir="rtl"] .col-md-6,
    [dir="rtl"] .col-md-7, [dir="rtl"] .col-md-8, [dir="rtl"] .col-md-9 {
        float: right;
    }
}

[dir="rtl"] .app-container .content-container .navbar-top,
[dir="rtl"] .app-container .side-body,
[dir="rtl"] .app-container.expanded .content-container .navbar-top {
    height: 60px;
}

[dir="rtl"] .voyager .navbar .navbar-nav .dropdown-menu,
[dir="rtl"] .voyager .navbar.navbar-default .navbar-nav .dropdown-menu {
    background-color: #fff;
    display: block;
    position: absolute !important;
    left: 0;
    right: auto;
}

[dir="rtl"] .voyager .navbar.navbar-default>.container-fluid:after,
[dir="rtl"] .voyager .navbar>.container-fluid {
    border-bottom:0;
    width: 99.5%;
    height: 1px;
}

/******** New ********/
[dir="rtl"] .database-tables .name a {
 float:right;
}

[dir="rtl"] .app-container .side-body .container-fluid{
	padding-left:0;
	padding-right: 15px;

	}

[dir="rtl"] .table.dataTable tbody td,
table.dataTable tbody th {
 padding:8px 18px
}
[dir="rtl"] .btn-group-sm > .btn i, .btn-sm i {top:3px}

[dir="rtl"] .glyphicon-list::before{font-family: voyager !important;}

[dir="rtl"] .ps.ps--active-y > .ps__scrollbar-y-rail {
    right: auto !important;
    left: 0;
}

[dir="rtl"] .ps > .ps__scrollbar-y-rail > .ps__scrollbar-y {
    right:auto !important;
    left: 2px;
}

[dir="rtl"] .hamburger.is-active .hamburger-inner:before {
    transform: translate3d(5px,1px,0) rotate(45deg) scaleX(.5);
}

[dir="rtl"] .hamburger.is-active .hamburger-inner:after {
    transform: translate3d(5px,-1px,0) rotate(-45deg) scaleX(.5);
}

[dir="rtl"] .dd-list .dd-list {
    padding-left: unset;
    padding-right: 30px;
}


text:
package com.opengamma.web.analytics;

import com.opengamma.id.UniqueId;

/**
 * Contains the human-readable name and {@link UniqueId} of the target of a row in the analytics grid.
 */
/* package */  abstract class RowTarget {

  /** The row name. */
  private final String _name;
  /** ID of the row's target. */
  private final UniqueId _nodeId;

  /* package */  RowTarget(String name, UniqueId nodeId) {
    _name = name;
    _nodeId = nodeId;
  }

  /**
   * @return The name of the row's target
   */
  public String getName() {
    return _name;
  }

  /**
   * @return The ID of the row's target
   */
  public UniqueId getNodeId() {
    return _nodeId;
  }
}


text: Get the week start date and end date of any year, with today's date


text:
package com.njackson.pebble;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import com.getpebble.android.kit.PebbleKit;
import com.getpebble.android.kit.util.PebbleDictionary;
import com.njackson.Constants;
import com.njackson.adapters.AdvancedLocationToNewLocation;
import com.njackson.adapters.NewLocationToPebbleDictionary;
import com.njackson.analytics.IAnalytics;
import com.njackson.application.PebbleBikeApplication;
import com.njackson.events.GPSServiceCommand.NewLocation;
import com.njackson.gps.Navigator;
import com.njackson.utils.BatteryStatus;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.inject.Inject;

import fr.jayps.android.AdvancedLocation;

/**
 * Manages a thread-safe message queue using a Looper worker thread to complete blocking tasks.
 */
public class MessageManager implements IMessageManager, Runnable {

    private static String TAG = "PB-MessageManager";

    private int transID = 0;
    public Handler messageHandler;
    private final BlockingQueue<PebbleDictionary> messageQueue = new LinkedBlockingQueue<PebbleDictionary>();
    private Boolean isMessagePending = false;
    private PebbleKit.PebbleAckReceiver ackReceiver;
    private PebbleKit.PebbleNackReceiver nackReceiver;

    private Context _applicationContext;

    private Thread _thisThread;

    private boolean debug = true;
    private Boolean _hasStarted = Boolean.valueOf(false);
    private boolean _isConnected = false;
    private int _skipped = 0;

    @Inject SharedPreferences _sharedPreferences;
    @Inject IAnalytics _parseAnalytics;
    @Inject Navigator _navigator;

    public MessageManager(SharedPreferences preferences, Context context) {
        _sharedPreferences = preferences;
        debug = _sharedPreferences.getBoolean("PREF_DEBUG", false);
        _applicationContext = context;
        _thisThread = new Thread(this);
        _thisThread.start();

        setupPebbbleHandlers();
        ((PebbleBikeApplication) context).inject(this);
    }

    private void removeMessageASync() {
        synchronized (_hasStarted) {
            messageHandler.post(new Runnable() {
                @Override
                public void run() {
                    synchronized (isMessagePending) {
                        isMessagePending = Boolean.valueOf(false);
                        if (messageQueue.size() == 0) {
                            // if possible (?): bug
                            return;
                        }
                        messageQueue.remove();
                    }
                }
            });
        }
    }

    private void setupPebbbleHandlers() {
        ackReceiver = new PebbleKit.PebbleAckReceiver(Constants.WATCH_UUID) {
            @Override
            public void receiveAck(final Context context, final int transactionId) {
                notifyAckReceivedAsync(transactionId);
                _isConnected = true;
            }
        };
        PebbleKit.registerReceivedAckHandler(_applicationContext, ackReceiver);

        nackReceiver = new PebbleKit.PebbleNackReceiver(Constants.WATCH_UUID) {
            @Override
            public void receiveNack(final Context context, final int transactionId) {
                notifyNackReceivedAsync(transactionId);
                _isConnected = true;
            }
        };
        PebbleKit.registerReceivedNackHandler(_applicationContext, nackReceiver);

        PebbleKit.registerPebbleConnectedReceiver(_applicationContext, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                _isConnected = true;
                pebbleConnected();
            }
        });
        PebbleKit.registerPebbleDisconnectedReceiver(_applicationContext, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                _isConnected = false;
                if (debug) Log.i(TAG, "Pebble disconnected!");
            }
        });
    }

    private void notifyAckReceivedAsync(int transactionId) {
        if (debug) Log.i(TAG, "notifyAckReceivedAsync("+transactionId+") transID:" + transID);
        removeMessageASync();
        consumeAsync();
    }

    private void notifyNackReceivedAsync(int transactionId) {
        if (debug) Log.i(TAG, "notifyNackReceivedAsync("+transactionId+") transID:" + transID);
        removeMessageASync();
        consumeAsync();
    }
    private void pebbleConnected() {
        if (debug) Log.i(TAG, "pebbleConnected transID:" + transID);
        removeMessageASync();
        consumeAsync();
    }

    private void consumeAsync() {
        if (debug) Log.v(TAG, "consumeAsync");
        boolean needToWait = false;
        synchronized (_hasStarted) {
            if (_hasStarted.booleanValue() == false) {
                needToWait = true;
            }
        }
        if (needToWait) {
            Log.d(TAG, "Race condition, wait for run()");
            SystemClock.sleep(2000);
        }
        synchronized (_hasStarted) {
            messageHandler.post(new Runnable() {
                @Override
                public void run() {
                    synchronized (isMessagePending) {
                        if (isMessagePending.booleanValue()) {
                            return;
                        }

                        synchronized (messageQueue) {
                            if (messageQueue.size() == 0) {
                                return;
                            }
                            transID = (transID + 1) % 256;
                            PebbleDictionary data = messageQueue.peek();
                            if (debug) Log.i(TAG, "sendDataToPebble s:" + messageQueue.size() + " transID:" + transID + " " + data.toJsonString());
                            PebbleKit.sendDataToPebbleWithTransactionId(_applicationContext, Constants.WATCH_UUID, data, transID);
                        }

                        isMessagePending = Boolean.valueOf(true);
                    }
                }
            });
        }
    }

    @Override
    public void run() {
        //SystemClock.sleep(1000); // uncomment to simulate the race condition
        synchronized (_hasStarted) {
            Looper.prepare();
            messageHandler = new Handler();
        }
        _hasStarted = Boolean.valueOf(true);
        Looper.loop();
    }

    public boolean offer(final PebbleDictionary data) {
        final boolean success = messageQueue.offer(data);
        if (debug) {
            int s = messageQueue.size();
            if (s > 1) Log.i(TAG, "offer s:" + s);
        }

        if (success) {
            consumeAsync();
        }

        return success;
    }

    public boolean offerIfLow(final PebbleDictionary data, int sizeMax) {
        boolean success = false;
        synchronized (messageQueue) {
            int s = messageQueue.size();
            if (s > sizeMax) {
                if (debug) Log.i(TAG, "offerIfLow s:" + s + ">" + sizeMax);
                if (_isConnected) {
                    _skipped++;
                    if (_skipped == 50) {
                        // only track 50th message
                        _parseAnalytics.trackSkippedMessage();
                    }
                    if (_skipped % 20 == 19) {
                        // once every 20 messages, try to send next message in the queue
                        // avoid blocking situation if ack/nack are lost
                        removeMessageASync();
                        consumeAsync();
                    }
                }
                return false;
            }
            // reset counter if we can queue the message
            _skipped = 0;
            success = messageQueue.offer(data);
            if (debug) {
                if (s > 1) Log.i(TAG, "offerIfLow s:" + s + "<=" + sizeMax);
            }
        }

        if (success) {
            consumeAsync();
        }

        return success;
    }

    @Override
    public void showWatchFace() {
        PebbleKit.startAppOnPebble(_applicationContext,Constants.WATCH_UUID);
    }

    @Override
    public void hideWatchFace() {
        PebbleKit.closeAppOnPebble(_applicationContext,Constants.WATCH_UUID);
    }

    @Override
    public void sendAckToPebble(int transactionId) {
        if (debug) Log.i(TAG, "sendAckToPebble("+transactionId+")");
        PebbleKit.sendAckToPebble(_applicationContext,transactionId);
    }

    @Override
    public void showSimpleNotificationOnWatch(String title, String text) {
        final Intent i = new Intent("com.getpebble.action.SEND_NOTIFICATION");
        final Map<String, String> data = new HashMap<String, String>();
        data.put("title", title);
        data.put("body", text);
        final JSONObject jsonData = new JSONObject(data);
        final String notificationData = new JSONArray().put(jsonData).toString();

        i.putExtra("messageType", "PEBBLE_ALERT");
        i.putExtra("sender", "JayPS");
        i.putExtra("notificationData", notificationData);

        _applicationContext.sendBroadcast(i);
    }

    @Override
    public void sendMessageToPebble(String title, String message) {
        showSimpleNotificationOnWatch(title, message);
    }

    @Override
    public void sendSavedDataToPebble(boolean isLocationServicesRunning, int units, float distance, long elapsedTime, float ascent, float maxSpeed) {

        // use AdvancedLocation and than NewLocation to use units conversion in AdvancedLocationToNewLocation

        AdvancedLocation advancedLocation = new AdvancedLocation();
        advancedLocation.setDistance(distance);
        advancedLocation.setElapsedTime(elapsedTime);
        advancedLocation.setAscent(ascent);
        advancedLocation.setMaxSpeed(maxSpeed);

        NewLocation newLocation = new AdvancedLocationToNewLocation(advancedLocation, 0, 0, units);

        newLocation.setBatteryLevel(BatteryStatus.getBatteryLevel(_applicationContext));
        newLocation.setSendNavigation(_navigator.getNbPoints() > 0);

        // Get current version code
        int versionCode = 0;
        try {
            PackageInfo packageInfo = _applicationContext.getPackageManager().getPackageInfo(_applicationContext.getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            versionCode = 0;
        }

        PebbleDictionary dictionary = new NewLocationToPebbleDictionary(
                newLocation,
                _navigator,
                isLocationServicesRunning,
                _sharedPreferences.getBoolean("PREF_DEBUG", false),
                _sharedPreferences.getBoolean("LIVE_TRACKING", false),
                Integer.valueOf(_sharedPreferences.getString("REFRESH_INTERVAL", String.valueOf(Constants.REFRESH_INTERVAL_DEFAULT))),
                _sharedPreferences.getInt("WATCHFACE_VERSION", 0),
                _sharedPreferences.getBoolean("NAV_NOTIFICATION", false)
        );
        dictionary.addInt32(Constants.MSG_VERSION_ANDROID, versionCode);

        try {
            byte[] data_heartmax = new byte[2];
            data_heartmax[0] = (byte) (Integer.valueOf(_sharedPreferences.getString("PREF_BLE_HRM_HRMAX", "0")) % 256);
            data_heartmax[1] = (byte) (Integer.valueOf(_sharedPreferences.getString("PREF_BLE_HRM_ZONE_NOTIFICATION_MODE", "0")) % 256);
            dictionary.addBytes(Constants.MSG_HR_MAX, data_heartmax);
        } catch (NumberFormatException nfe) {}

        offer(dictionary);
    }
}


text:
package tests.cp;

import leap.lang.Threads;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;

public class AbandonTest extends PoolTestBase {

    @Test
    public void testAbandonIdleTimeout() throws SQLException {
        ds.setIdleTimeoutMs(100);

        try(Connection conn = ds.getConnection()) {}

        assertEquals(1, ms.getNrOfOpeningConnections());
        assertEquals(1, ms.getNrOfOpenedConnections());
        assertEquals(0, ms.getNrOfClosedConnections());

        Threads.sleep(1000);
        assertEquals(0, ms.getNrOfOpeningConnections());
        assertEquals(1, ms.getNrOfOpenedConnections());
        assertEquals(1, ms.getNrOfClosedConnections());
    }

    @Test
    public void testAbandonMaxIdle() throws SQLException {
        ds.setMaxIdle(0);

        try(Connection conn = ds.getConnection()) {}

        assertEquals(1, ms.getNrOfOpeningConnections());
        Threads.sleep(1000);
        assertEquals(0, ms.getNrOfOpeningConnections());
    }

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fung. Bavar. Palat. 4: 70 (1774)

#### Original name
Agaricus psittacinus Schaeff., 1774

### Remarks
null


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
define(["require", "exports", 'react', 'jquery'], function (require, exports, React, $) {
    var keywordData = undefined;
    var issuesData = undefined;
    $.getJSON('./keywords.json', function (data) {
        keywordData = data;
    });
    $.getJSON('./issues.json', function (data) {
        issuesData = data;
    });
    var ResultRow = (function (_super) {
        __extends(ResultRow, _super);
        function ResultRow() {
            _super.apply(this, arguments);
        }
        ResultRow.prototype.render = function () {
            return React.createElement("div", {"className": "result"}, React.createElement("div", {"className": "id"}, this.props.issue.number), React.createElement("div", {"className": "title"}, this.props.issue.title), React.createElement("div", {"className": "by"}, this.props.issue.loggedByName, "at ", this.props.issue.createdAt), React.createElement("div", {"className": "labels"}, this.props.issue.labels.map(function (lbl) { return lbl.name; }).join(', ')), React.createElement("div", {"className": "comments"}, this.props.issue.comments));
        };
        return ResultRow;
    })(React.Component);
    $(function () {
        $('#query').on('change', refreshQuery);
        var priorTimeout = undefined;
        $('#query').on('keyup', function () {
            if (priorTimeout !== undefined) {
                window.clearTimeout(priorTimeout);
            }
            priorTimeout = window.setTimeout(refreshQuery, 200);
        });
        window.setTimeout(refreshQuery, 200);
    });
    var lastQuery = undefined;
    function refreshQuery() {
        if (keywordData === undefined || issuesData === undefined) {
            console.log('Waiting...');
            window.setTimeout(refreshQuery, 250);
            return;
        }
        var noHits = [];
        var text = $('#query').val();
        if (text === lastQuery) {
            return;
        }
        lastQuery = text;
        var ids = undefined;
        var terms = text.split(' ');
        var result = undefined;
        terms.forEach(function (term) {
            if (term.indexOf(':') < 0) {
                term = 'term:' + term;
            }
            var match = keywordData[term];
            if (match) {
                if (ids === undefined) {
                    ids = match;
                }
                else {
                    ids = ids.filter(function (i) { return match.indexOf(i) >= 0; });
                }
            }
            else {
                noHits.push(term);
            }
        });
        ids = ids || [];
        var issues = ids.map(function (id) {
            var issue = issuesData.filter(function (iss) { return iss.number === id; })[0];
            return issue;
        });
        var warningsDiv = $('#warnings').get(0);
        if (noHits.length > 0) {
            React.render(React.createElement("div", {"className": "warnings"}, "No hits for ", noHits.join(', ')), warningsDiv);
        }
        else {
            React.render(React.createElement("div", {"className": "warnings"}), warningsDiv);
        }
        var resultsTarget = $('#results').get(0);
        React.render(React.createElement("div", {"id": "results"}, issues.map(function (issue, index) { return React.createElement(ResultRow, {"issue": issue, "key": index}); })), resultsTarget);
    }
});


text:
package fr.adrienbrault.idea.symfony2plugin.profiler;

import com.intellij.openapi.project.Project;
import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;
import org.jetbrains.annotations.Nullable;

import java.io.File;

public class ProfilerUtil {

    @Nullable
    public static File findProfilerCsv(Project project) {

        Symfony2ProjectComponent symfony2ProjectComponent = project.getComponent(Symfony2ProjectComponent.class);
        for(File file: symfony2ProjectComponent.getContainerFiles()) {
            if(file.exists()) {
                File translationRootPath = new File(file.getParentFile().getPath() + "/profiler/index.csv");
                if (translationRootPath.exists()) {
                    return translationRootPath;
                }
            }
        }

        return null;
    }

}


text:
<%= circled_title(2, "Log in") %>

Once VM with BOSH Director is running, point your CLI to it, saving the environment with the alias vbox:

$ bosh -e 192.168.50.6 alias-env vbox --ca-cert <(bosh int vbox/creds.yml --path /director_ssl/ca)

Using environment '192.168.50.6' as anonymous user

Name      Bosh Lite Director
UUID      ...
Version   261.4.0 (00000000)
CPI       warden_cpi
Features  compiled_package_cache: disabled
          config_server: disabled
          dns: disabled
          snapshots: disabled
User      (not logged in)

Succeeded

Obtain generated password to BOSH Director:

$ bosh int vbox/creds.yml --path /admin_password

Log in using admin username and generated password:

$ bosh -e vbox login

Now we are ready to deploy!


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.7
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package org.pjsip.pjsua2;

public class SendTypingIndicationParam {
  private transient long swigCPtr;
  protected transient boolean swigCMemOwn;

  protected SendTypingIndicationParam(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected static long getCPtr(SendTypingIndicationParam obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if (swigCPtr != 0) {
      if (swigCMemOwn) {
        swigCMemOwn = false;
        pjsua2JNI.delete_SendTypingIndicationParam(swigCPtr);
      }
      swigCPtr = 0;
    }
  }

  public void setIsTyping(boolean value) {
    pjsua2JNI.SendTypingIndicationParam_isTyping_set(swigCPtr, this, value);
  }

  public boolean getIsTyping() {
    return pjsua2JNI.SendTypingIndicationParam_isTyping_get(swigCPtr, this);
  }

  public void setTxOption(SipTxOption value) {
    pjsua2JNI.SendTypingIndicationParam_txOption_set(swigCPtr, this, SipTxOption.getCPtr(value), value);
  }

  public SipTxOption getTxOption() {
    long cPtr = pjsua2JNI.SendTypingIndicationParam_txOption_get(swigCPtr, this);
    return (cPtr == 0) ? null : new SipTxOption(cPtr, false);
  }

  public SendTypingIndicationParam() {
    this(pjsua2JNI.new_SendTypingIndicationParam(), true);
  }

}


text:
package edu.asu.ser.jsonrpc.lite.server;

import java.io.IOException;
import java.net.Socket;

import org.apache.logging.log4j.LogManager;

import edu.asu.ser.jsonrpc.exception.JsonRpcException;
import edu.asu.ser.jsonrpc.lite.jsonutils.JsonResponse;

public class TCPServer extends AbstractServer{

	private Socket sock;

	/**
	 * Constructor for the TCP Server
	 * @param ob : object of class with server methods
	 * @param socket: socket number at which server will accept requests
	 * @throws IOException: in case socket is not initialized
	 */
	public TCPServer(Object ob,int socket) throws IOException{
		super(ob,socket);
		logger = LogManager.getLogger("serverLog");
		logger.debug("Listening at port:"+socket);

	}
	/**
	 * Starts the TCP Server
	 * @throws JsonRpcException: in case of abnormal execution
	 */
	public void start()
	{
		try {
			while(true){
				sock = getServSock().accept();
				new Thread(new ServerExecutor(this,sock,getOb())).run();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Returns the TCP response on top of JSON response for transport
	 * @param response : JSONresponse object to be put inside the outer protocol format
	 * @return response :  packaged String response in format of the protocol for the server
	 */
	@Override
	public String getResponseInFormat(JsonResponse response) {
		return response.toString();
	}

}


text:
"""Tests for the Abode binary sensor device."""
from homeassistant.components.abode import ATTR_DEVICE_ID
from homeassistant.components.abode.const import ATTRIBUTION
from homeassistant.components.binary_sensor import (
    DEVICE_CLASS_WINDOW,
    DOMAIN as BINARY_SENSOR_DOMAIN,
)
from homeassistant.const import (
    ATTR_ATTRIBUTION,
    ATTR_DEVICE_CLASS,
    ATTR_FRIENDLY_NAME,
    STATE_OFF,
)
from homeassistant.helpers import entity_registry as er

from .common import setup_platform

async def test_entity_registry(hass):
    """Tests that the devices are registered in the entity registry."""
    await setup_platform(hass, BINARY_SENSOR_DOMAIN)
    entity_registry = er.async_get(hass)

    entry = entity_registry.async_get("binary_sensor.front_door")
    assert entry.unique_id == "2834013428b6035fba7d4054aa7b25a3"

async def test_attributes(hass):
    """Test the binary sensor attributes are correct."""
    await setup_platform(hass, BINARY_SENSOR_DOMAIN)

    state = hass.states.get("binary_sensor.front_door")
    assert state.state == STATE_OFF
    assert state.attributes.get(ATTR_ATTRIBUTION) == ATTRIBUTION
    assert state.attributes.get(ATTR_DEVICE_ID) == "RF:01430030"
    assert not state.attributes.get("battery_low")
    assert not state.attributes.get("no_response")
    assert state.attributes.get("device_type") == "Door Contact"
    assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Front Door"
    assert state.attributes.get(ATTR_DEVICE_CLASS) == DEVICE_CLASS_WINDOW


text:
package org.auraframework.impl.java.provider;

import java.util.Map;

import org.auraframework.def.TokenMapProvider;
import org.auraframework.system.Annotations.Provider;
import org.auraframework.throwable.quickfix.QuickFixException;

import com.google.common.collect.ImmutableMap;

@Provider
public class TestTokenMapProvider implements TokenMapProvider {
    public static final String REF = "java://org.auraframework.impl.java.provider.TestTokenMapProvider";

    public static final Map<String, String> MAP = ImmutableMap.of(
            "font", "Arial",
            "padding", "15px",
            "textColor", "red",
            "bgColor", "#434fef"
            );

    @Override
    public Map<String, String> provide() throws QuickFixException {
        return MAP;
    }
}


text:
package org.parosproxy.paros.network;

import java.io.IOException;

public class HttpMalformedHeaderException extends IOException {

	private static final long serialVersionUID = 2328568976708794693L;

	public HttpMalformedHeaderException() {
		super();
	}

	public HttpMalformedHeaderException(String msg) {
		super(msg);
	}
}


text:
CLASS({
  package: 'foam.ui',
  name: 'DetailView',

  extendsModel: 'foam.ui.View',

  requires: [
    'Property',
    'foam.ui.TextFieldView',
    'foam.ui.IntFieldView',
    'foam.ui.FloatFieldView',
    'foam.ui.DAOController'
  ],
  exports: [ 'propertyViewProperty' ],

  documentation: function() {/*
    When a default view based on $$DOC{ref:'Property'} values is desired, $$DOC{ref:'foam.ui.DetailView'}
    is the place to start. Either using $$DOC{ref:'foam.ui.DetailView'} directly, implementing
    a .toDetailHTML() $$DOC{ref:'Method'} in your model, or extending
    $$DOC{ref:'foam.ui.DetailView'} to add custom formatting.

Set the $$DOC{ref:'.data'} $$DOC{ref:'Property'} to the $$DOC{ref:'Model'} instance
    you want to display. $$DOC{ref:'foam.ui.DetailView'} will extract the $$DOC{ref:'Model'}
    definition, create editors for the $$DOC{ref:'Property',usePlural:true}, and
    display the current values of your instance. Set $$DOC{ref:'.mode',usePlural:true}
    to indicate read-only if desired.

$$DOC{ref:'Model',usePlural:true} may specify a .toDetailHTML() $$DOC{ref:'Method'} or
    $$DOC{ref:'Template'} to render their contents instead of
    $$DOC{ref:'foam.ui.DetailView.defaultToHTML'}.

For each $$DOC{ref:'Property'} in the $$DOC{ref:'.data'} instance specified,
    a $$DOC{ref:'PropertyView'} is created that selects the appropriate $$DOC{ref:'foam.ui.View'}
    to construct.
  */},

  properties: [
    {
      name: 'className',
      defaultValue: 'detailView',
      documentation: function() {/*
          The CSS class names to use for HTML $$DOC{ref:'foam.ui.View',usePlural:true}.
          Separate class names with spaces. Each instance of a $$DOC{ref:'foam.ui.DetailView'}
          may have different classes specified.
      */}
    },
    {
      name: 'data',
      preSet: function(old,nu) {
        if ( nu.model_ ) {
          this.model = nu.model_;
        }
        return nu;
      }
    },
    {
      name: 'model',
      // TODO: Add declarative runtime type checking
      postSet: function(_, model) {
        console.assert(Model.isInstance(model), 'Invalid model specified for ' + this.name_);
      }
    },
    {
      name: 'title',
      defaultValueFn: function() {
        return /*(this.data && this.data.id ? 'Edit ' : 'New ') +*/ this.model.label;
      },
      documentation: function() {/*

The display title for the $$DOC{ref:'foam.ui.View'}.

      */}
    },
    {
      model_: 'StringProperty',
      name: 'mode',
      defaultValue: 'read-write',
      documentation: function() {/*
        The editing mode. To disable editing set to 'read-only'.
      */}
    },
    {
      model_: 'BooleanProperty',
      name: 'showRelationships',
      defaultValue: false,
      documentation: function() {/*
        Set true to create sub-views to display $$DOC{ref:'Relationship',usePlural:true}
        for the $$DOC{ref:'.model'}.
      */}
    },
    {
      name: 'propertyViewProperty',
      type: 'Property',
      defaultValueFn: function() { return this.Property.DETAIL_VIEW; }
    }
  ],

  methods: {
    // Template Method

    shouldDestroy: function(old,nu) {
      if ( ! old || ! old.model_ || ! nu || ! nu.model_ ) return true;
      return old.model_ !== nu.model_;
    },

    generateContent: function() { /* rebuilds the children of the view */
      if ( ! this.$ ) return;
      this.$.outerHTML = this.toHTML();
      this.initHTML();
    },

    titleHTML: function() {
      /* Title text HTML formatter */
      var title = this.title;

      return title ?
        '
' + title + '
' :
        '';
    },

    startForm: function() { /* HTML formatter */ return '
'; },
    endForm: function() { /* HTML formatter */ return '
'; },

    startColumns: function() { /* HTML formatter */ return '

'; },
    nextColumn:   function() { /* HTML formatter */ return '

'; },
    endColumns:   function() { /* HTML formatter */ return '

'; },

    rowToHTML: function(prop, view) {
      /* HTML formatter for each $$DOC{ref:'Property'} row. */
      var str = '';

      if ( prop.detailViewPreRow ) str += prop.detailViewPreRow(this);

      str += '
';
      if ( this.DAOController.isInstance(view) ) {
        str += "
" + prop.label + "
";
        str += view.toHTML();
        str += '	';
      } else {
        str += "" + prop.label + "	";
        str += '';
        str += view.toHTML();
        str += '	';
      }
      str += '
';

      if ( prop.detailViewPostRow ) str += prop.detailViewPostRow(this);

      return str;
    },

    // If the Model supplies a toDetailHTML method, then use it instead.
    toHTML: function() {
      /* Overridden to create the complete HTML content for the $$DOC{ref:'foam.ui.View'}.

$$DOC{ref:'Model',usePlural:true} may specify a .toDetailHTML() $$DOC{ref:'Method'} or
         $$DOC{ref:'Template'} to render their contents instead of the
          $$DOC{ref:'foam.ui.DetailView.defaultToHTML'} we supply here.
      */

      if ( ! this.data ) return '';

      if ( ! this.model ) throw "DetailView: either 'data' or 'model' must be specified.";

      return (this.model.getPrototype().toDetailHTML || this.defaultToHTML).call(this);
    },

    getDefaultProperties: function() {
      return this.model.getRuntimeProperties();
    },

    defaultToHTML: function() {
      /* For $$DOC{ref:'Model',usePlural:true} that don't supply a .toDetailHTML()
        $$DOC{ref:'Method'} or $$DOC{ref:'Template'}, a default listing of
        $$DOC{ref:'Property'} editors is implemented here.
        */
      this.children = [];
      var model = this.model;
      var str  = "";

      str += '
';
      str += this.startForm();
      str += this.titleHTML();

      var properties = this.getDefaultProperties();
      for ( var i = 0 ; i < properties.length ; i++ ) {
        var prop = properties[i];

        if ( prop.hidden ) continue;

        var view = this.createView(prop);
        //view.data$ = this.data$;
        this.addDataChild(view);
        str += this.rowToHTML(prop, view);
      }

      str += this.endForm();

      if ( this.showRelationships ) {
        var view = this.X.lookup('foam.ui.RelationshipsView').create({
          data: this.data
        });
        //view.data$ = this.data$;
        this.addDataChild(view);
        str += view.toHTML();
      }

      str += '
';

      return str;
    }
  },

  templates: [
    {
      name: 'CSS',
      template: function CSS() {/*
          .detailView {
            border: solid 2px #dddddd;
            background: #fafafa;
            display: table;
          }

          .detailView .heading {
            color: black;
            float: left;
            font-size: 16px;
            margin-bottom: 8px;
            padding: 2px;
          }

          .detailView .propertyLabel {
            font-size: 14px;
            display: block;
            font-weight: bold;
            text-align: right;
            float: left;
          }

          .detailView input {
            font-size: 12px;
            padding: 4px 2px;
            border: solid 1px #aacfe4;
            margin: 2px 0 0px 10px;
          }

          .detailView textarea {
            float: left;
            font-size: 12px;
            padding: 4px 2px;
            border: solid 1px #aacfe4;
            margin: 2px 0 0px 10px;
            width: 98%;
            overflow: auto;
          }

          .detailView select {
            font-size: 12px;
            padding: 4px 2px;
            border: solid 1px #aacfe4;
            margin: 2px 0 0px 10px;
          }

          .detailView .label {
            color: #444;
            font-size: smaller;
            padding-left: 6px;
            padding-top: 8px;
            vertical-align: top;
          }

          .detailArrayLabel {
            font-size: medium;
          }

          .detailArrayLabel .foamTable {
            margin: 1px;
          }
      */}
    }
  ]
});


text:
package org.hisp.dhis.webapi.controller.indicator;

import static org.hisp.dhis.expression.ParseType.INDICATOR_EXPRESSION;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

import org.hisp.dhis.analytics.resolver.ExpressionResolver;
import org.hisp.dhis.analytics.resolver.ExpressionResolverCollection;
import org.hisp.dhis.dxf2.webmessage.DescriptiveWebMessage;
import org.hisp.dhis.dxf2.webmessage.WebMessage;
import org.hisp.dhis.expression.ExpressionService;
import org.hisp.dhis.expression.ExpressionValidationOutcome;
import org.hisp.dhis.feedback.Status;
import org.hisp.dhis.i18n.I18nManager;
import org.hisp.dhis.indicator.Indicator;
import org.hisp.dhis.schema.descriptors.IndicatorSchemaDescriptor;
import org.hisp.dhis.webapi.controller.AbstractCrudController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
@Controller
@RequestMapping( value = IndicatorSchemaDescriptor.API_ENDPOINT )
public class IndicatorController
    extends AbstractCrudController<Indicator>
{
    @Autowired
    private ExpressionService expressionService;

    @Autowired
    private ExpressionResolverCollection resolvers;

    @Autowired
    private I18nManager i18nManager;

    @PostMapping( value = "/expression/description", produces = APPLICATION_JSON_VALUE )
    @ResponseBody
    public WebMessage getExpressionDescription( @RequestBody String expression )
    {
        String resolvingExpression = expression;

        for ( ExpressionResolver resolver : resolvers.getExpressionResolvers() )
        {
            resolvingExpression = resolver.resolve( resolvingExpression );
        }

        String resolvedExpression = resolvingExpression;
        ExpressionValidationOutcome result = expressionService.expressionIsValid( resolvedExpression,
            INDICATOR_EXPRESSION );

        return new DescriptiveWebMessage( result.isValid() ? Status.OK : Status.ERROR, HttpStatus.OK )
            .setDescription( result::isValid,
                () -> expressionService.getExpressionDescription( resolvedExpression, INDICATOR_EXPRESSION ) )
            .setMessage( i18nManager.getI18n().getString( result.getKey() ) );
    }
}


text:
body {
}

#csdn_shield { position:absolute; z-index:101; left:0px; top:0px; display:block; background-color:#999; width:100%; }

#csdn_divh { position:absolute; z-index:10001; top:30%; left:45%; width:460px; margin-left:-200px; }
#csdn_divh img { border:none; }

.loading { padding:20px; height:60px; text-align:center;font-size:16px; background:url(images/wait.gif) no-repeat center bottom #ffffff;}
.h1title { font-size:20px; margin-top:0px; padding-top:6px; border-bottom:solid 4px #FFE2D2;}
.openbox { border:solid 10px #FFE2D2; border-radius:10px; padding:10px; background-color:#fff; font-size:14px;}
.boxbody {}

#vcfrm { width:150px; height:50px; overflow:hidden; border:none; }

#csdn_divh a.revc { position:relative; top:-20px; margin-left:10px;}

#sperr { color:Red; }

#tr_third {}
#tr_third a { margin-right:8px; }

.clearfix { display:block; *display:inline-block;}
.clearfix:after {content:"."; display:block; height:0; clear:both; visibility:hidden;}
.csdn_loginbox{ margin:0 auto; background-image:url(images/login_bg.png); padding:3px; margin-top:100px; border-radius: 4px;}
.login_content{ width:auto;max-width:406px;text-align:left; margin:0 auto; background-color:#fbfbfb; border: solid 1px #ccc; padding:40px 82px;box-shadow:0px 0px 1px #fff inset; border-radius: 4px; position:fixed;top:50%;margin-top:-180px;}
.login_content_inner{width: 240px;margin:0 auto;}
@media (max-width:768px){
	.login_content{
		padding:40px 30px;
		left:50%;
		margin-left: -150px;

	}
}

.csdn_loginbox .close{ border: none; background:url(images/icons.png) -10px 10px no-repeat; width:30px; height:30px; position:absolute; top:0; right:0;border-radius: 3px; cursor:pointer;}
.csdn_loginbox .close:hover{ background:url(images/icons.png) -10px -19px no-repeat;}
.csdn_loginbox .point{ font-size:12px; color:#ff6666; text-align:center; margin-bottom:5px;}

.csdn_loginbox .user_id{ width:210px; height:30px; border-radius: 3px;border:1px #e3e3e3 solid; margin-bottom:10px;background:url(images/icons.png) #fff -8px -155px no-repeat; padding-left:30px;}
.csdn_loginbox .password{  width:210px; height:30px; border-radius: 3px; border:1px #e3e3e3 solid; margin-bottom:10px;background:url(images/icons.png) #fff -8px -187px no-repeat; padding-left:30px;}
.csdn_loginbox .remember{ font-size:12px; text-align:left; color:#999; margin-bottom:20px; vertical-align:middle; line-height: 13px;}
.csdn_loginbox .remember input{ float:left; margin-right:10px; float:left; vertical-align:middle;}
.csdn_loginbox .login_bt{ text-align:left; padding:8px 22px; cursor:pointer; border: 1px solid #ef5f06; background-color:#ff6c1e; margin-top:1px; font-size:14px; font-weight:bold; color:#FFF;  border-radius: 3px; margin-bottom:35px;}
.csdn_loginbox .login_bt:hover{ background-color:#ff3300; border: 1px solid #cc3300; }

.csdn_loginbox .pw_lg{ float:right; font-size:12px; color:#999;margin-top:18px;}
.csdn_loginbox .pw_lg a{ color:#999; text-decoration:none; padding:0 5px;}
.csdn_loginbox a.pw_a{ padding-right:0;}
.csdn_loginbox .pw_lg a:hover{ color:#06c;}

.csdn_loginbox .lg_3{ font-size:12px; color:#666; line-height:22px; text-align:left;}
.csdn_loginbox .lg_3 a{ display:block; float:right; background-image:url(images/icons.png); background-repeat:no-repeat;width:20px; height:20px;margin-left: 8px; border-radius: 3px;}
.csdn_loginbox .lg_3 a:hover { background-color:#eee; }
.csdn_loginbox .weibo{ background-position:-13px -90px; margin-left:0; }
.csdn_loginbox .qq{ background-position:-13px -56px;}
.csdn_loginbox .google{ background-position:-13px -125px;}
.csdn_loginbox .github{ background-position:-14px -226px; }
.csdn_loginbox .LinkedIn{ background-position:-14px -262px;}
.csdn_loginbox .baidu{ background-position:-14px -289px;}
.csdn_loginbox .lg_3 a.wechat{ background-image:url("http://127.0.0.1:8080/images/login-third-party.png"); background-position:-228px -4;width:18px;height:18px;}

div#csdn_divh { width:auto; }


text:
/**
 * Shortest Palindrome
 *
 * Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it.
 * Find and return the shortest palindrome you can find by performing this transformation.
 *
 * For example:
 *
 * Given "aacecaaa", return "aaacecaaa".
 *
 * Given "abcd", return "dcbabcd".
 */

/**
 * KMP algorithm to get the longest prefix and suffix count
 *
 * @param {string} s
 * @return {number[]}
 */
const getLPS = s => {
  const lps = Array(s.length).fill(0);
  let i = 1;
  let len = 0;

  while (i < s.length) {
    if (s[i] === s[len]) {
      lps[i++] = ++len;
    } else if (len === 0) {
      lps[i++] = 0;
    } else {
      len = lps[len - 1];
    }
  }

  return lps;
};

/**
 * @param {string} s
 * @return {string}
 */
const shortestPalindrome = s => {
  const r = s
    .split('')
    .reverse()
    .join('');
  const lps = getLPS(s + '|' + r);
  return r.substring(0, r.length - lps[lps.length - 1]) + s;
};

export default shortestPalindrome;


text:
/// \class AliAnalysisTaskStrangenessRatios

#ifndef __AliAnalysisTaskStrangenessRatios__
#define __AliAnalysisTaskStrangenessRatios__

#include "AliAnalysisTaskSE.h"
#include <Rtypes.h>
#include <TString.h>
#include "AliEventCuts.h"
#include "AliExternalBDT.h"
#include "AliAODMCParticle.h"

class AliPIDResponse;
class TH2F;
class TList;
class TTree;

struct MiniLambda {
  Double32_t pt;
  Double32_t eta;
  Double32_t mass;
  Double32_t ct;
  Double32_t radius;      //[0,101.6,8]
  Double32_t dcaV0PV;     //[0,10.16,16]
  Double32_t dcaPiPV;     //[0,20.32,8]
  Double32_t dcaPrPV;     //[0,20.32,8]
  Double32_t dcaV0tracks; //[0,2.54,8]
  Double32_t cosPA;       //[0.95,1,16]
  Double32_t tpcNsigmaPi; //[-5,5,8]
  Double32_t tpcNsigmaPr; //[-5,5,8]
  Double32_t itsNsigmaPr; //[-5,5,8]
  unsigned char tpcClV0Pi;
  unsigned char tpcClV0Pr;
  unsigned char centrality;
  bool matter;
  bool hasTOFhit;
  bool hasITSrefit;
};

struct MiniK0s {
  Double32_t pt;
  Double32_t eta;
  Double32_t mass;
  Double32_t ct;
  Double32_t radius;      //[0,101.6,8]
  Double32_t dcaV0PV;     //[0,10.16,16]
  Double32_t dcaPosPV;    //[0,20.32,8]
  Double32_t dcaNegPV;    //[0,20.32,8]
  Double32_t dcaV0tracks; //[0,2.54,8]
  Double32_t cosPA;       //[0.95,1,16]
  Double32_t tpcNsigmaPos; //[-5,5,8]
  Double32_t tpcNsigmaNeg; //[-5,5,8]
  unsigned char tpcClV0Pos;
  unsigned char tpcClV0Neg;
  unsigned char centrality;
  bool hasTOFhit;
  bool hasITSrefit;
};

struct MiniLambdaMC : public MiniLambda {
  float ptMC;
  float etaMC;
  float ctMC;
  float yMC;
  float ptMotherMC;
  float ctMotherMC;
  int pdg;
  bool isPrimary;
  bool isReconstructed;
  unsigned char flag;
};

struct MiniK0sMC : public MiniK0s {
  float ptMC;
  float etaMC;
  float ctMC;
  float yMC;
  bool isPrimary;
  bool isReconstructed;
  unsigned char flag;
};

struct MiniCascade {
  Double32_t pt;
  Double32_t eta;
  Double32_t mass;
  Double32_t ct;
  Double32_t radius; //[0,25.4,8]
  Double32_t radiusV0; //[0,25.4,8]
  Double32_t dcaBachPV; //[0,2.54,8]
  Double32_t dcaV0PV; //[0,2.54,16]
  Double32_t dcaV0piPV; //[0,2.54,8]
  Double32_t dcaV0prPV; //[0,2.54,8]
  Double32_t dcaV0tracks; //[0,2.54,8]
  Double32_t dcaBachV0; //[0,2.54,8]
  Double32_t cosPA; //[0.95,1,16]
  Double32_t cosPAV0; //[0.95,1,16]
  Double32_t V0invMassDelta; //[-0.01,0.01,8]
  Double32_t tpcNsigmaBach; //[-5,5,8]
  Double32_t tpcNsigmaV0Pr; //[-5,5,8]
  Double32_t tpcNsigmaV0Pi; //[-5,5,8]
  Double32_t competingMass; //[0,0.254,8]
  Double32_t bachBarCosPA;  //[0.9999, 1., 8]
  unsigned char tpcClBach;
  unsigned char tpcClV0Pr;
  unsigned char tpcClV0Pi;
  unsigned char centrality;
  bool matter;
  bool hasTOFhit;
  bool hasITSrefit;
  bool isOmega;
};

struct MiniCascadeMC : public MiniCascade {
  float ptMC;
  float etaMC;
  float ctMC;
  float yMC;
  int pdg;
  bool isReconstructed;
  unsigned char flag;
};

struct MiniLambdaBDTOut {
  Double32_t pt;
  Double32_t ct;
  Double32_t mass;
  Double32_t bdtOutputPrompt;
  Double32_t bdtOutputNonPrompt;
  Double32_t bdtOutputBackground;
  bool matter;
  bool pileUpCheck;
};

class AliAnalysisTaskStrangenessRatios : public AliAnalysisTaskSE {
public:
  enum StatusFlag {
    kPrimary = BIT(0),
    kSecondaryFromWDXi = BIT(1),
    kSecondaryFromWDOmega = BIT(2),
    kSecondaryFromWD = BIT(3),
    kSecondaryFromMaterial = BIT(4)
  };

  AliAnalysisTaskStrangenessRatios(bool isMC = false, TString taskname = "StrangenessRatios");
  static AliAnalysisTaskStrangenessRatios* AddTask(bool isMC, TString tskname, TString suffix);
  virtual ~AliAnalysisTaskStrangenessRatios();

  virtual void   UserCreateOutputObjects();
  virtual void   UserExec(Option_t *);
  virtual Bool_t UserNotify();
  virtual void   Terminate(Option_t *) {}

  AliEventCuts  fEventCut; ///<

  void SetFillK0s(bool toogle = true) { fFillK0s = toogle; }
  void SetFillLambdas(bool toogle = true) { fFillLambdas = toogle; }
  void SetFillCascades(bool toogle = true) { fFillCascades = toogle; }
  void SetFillLambdasBDTOut(bool toogle = true) { fFillLambdasBDTOut = toogle; }
  void SetLambdaDownscaling(float scale = true) { fLambdaDownscaling = scale; }
  void SetK0sDownscaling(float scale = true) { fK0sDownscaling = scale; }

  //Setters for topological cuts
  void SetRadiusCut(float xi = 1.2, float omega = 1., float lambda = 0.5) {fCutRadius[0]=xi; fCutRadius[1]=omega; fCutRadius[2]=lambda;}
  void SetRadiusV0Cut(float cut = 3.0) {fCutRadiusV0=cut;}
  void SetDCABachToPVCut(float cut = 0.1) {fCutDCABachToPV=cut;}
  void SetDCAV0toPVCut(float cut = 0.1) {fCutDCAV0toPV=cut;}
  void SetDCAV0piToPVCut(float cut = 0.2) {fCutDCAV0piToPV=cut;}
  void SetDCAV0prToPVCut(float cut = 0.2) {fCutDCAV0prToPV=cut;}
  void SetDCAV0tracksCut(float cut = 1.0) {fCutDCAV0tracks=cut;}
  void SetCutDCABachToV0XiCut(float xi = 1.0, float omega = 0.6) {fCutDCABachToV0[0]=xi; fCutDCABachToV0[1]=omega;}
  void SetCosPACut(float cut = 0.95) {fCutCosPA=cut;}
  void SetCosPAV0Cut(float cut = 0.95) {fCutCosPAV0=cut;}
  void SetV0MassWindowCut(float cut = 0.005) {fCutV0MassWindow=cut;}
  void SetYCut(float cut = 0.5) {fCutY=cut;}
  void SetYDaughtCut(float cut = 0.8) {fCutYDaught=cut;}
  void SetNsigmaTPCCut(float cut = 4.0) {fCutNsigmaTPC=cut;}
  void SetCtCut(float cut = 4 /*cm*/) {fCutCt=cut;}
  void SetCtV0Cut(float cut = 30 /*cm*/) {fCutCtV0=cut;}
  void SetCompetingMassCut(float omega = 0.008 /*GeV/c^2*/, float xi = 0. /*GeV/c^2*/) {fCutCompetingMass[0]=xi; fCutCompetingMass[1]=omega;}
  void SetTPCcluCut(int cut = 70) {fCutTPCclu=cut;}
  void SetSaveOnlyTrueCandidates(bool cut = true) { fOnlyTrueCandidates = cut; }
  void SetSaveOnlyTrueLambdas(bool cut = true) { fOnlyTrueLambdas = cut; }
  void SetTPCRowsCut(float cut = 80.) {fCutTPCrows=cut;}
  void SetTPCRowOvFCut(float cut = 0.8) {fCutRowsOvF=cut;}
  void UseOnTheFly(bool toggle = true) { fUseOnTheFly = toggle; }
  void SetMinCentrality(int minCentrality = 0) { fMinCentrality = minCentrality; }
  void SetMaxCentrality(int maxCentrality = 90) { fMaxCentrality = maxCentrality; }
  void SetCtPreselection(double cut = 1.) { fCtPreselection = cut; }
  void SetMaxCt(double maxCt = 40.) { fMaxCt = maxCt; }
  void SetMinPt(double minPt = 0.5) { fMinPt = minPt; }
  void SetMaxPt(double maxPt = 3.5) { fMaxPt = maxPt; }
  void SetRadiusPreselection(double cut = 3.) { fRadiusPreselection = cut; }
  void SetRadiusOverflowCut(double cut = 100.) { fRadiusOverflowCut = cut; }
  void SetTpcClV0PiPreselection(int cut = 70) { fTpcClV0PiPreselection = cut; }
  void SetTpcClV0PrPreselection(int cut = 70) { fTpcClV0PrPreselection = cut; }
  void SetDCAV0piToPVOverflowCut(double cut = 20.) { fDCAV0piToPVOverflowCut = cut; }
  void SetDCAV0prToPVOverflowCut(double cut = 20.) { fDCAV0prToPVOverflowCut = cut; }
  void SetDCAV0toPVOverflowCut(double cut = 10.) { fDCAV0toPVOverflowCut = cut; }
  void SetBdtOutputBackgroundCut(double cut = 0.15) { fBdtOutputBackgroundCut = cut; }

  void SetBDTPath(const char *path = "") { fBDTPath = path; }
  void SetCtBinsBDT(int nBins, double *ctBins) { fCtBinsBDT.Set(nBins+1,ctBins); }

private:
  AliAnalysisTaskStrangenessRatios (const AliAnalysisTaskStrangenessRatios &source);
  AliAnalysisTaskStrangenessRatios &operator=(const AliAnalysisTaskStrangenessRatios &source);

  void PostAllData();

  TList*          fList = nullptr;             //!<! List of the output histograms
  TTree*          fTree = nullptr;             //!<! Tree for Xis and Omegas
  TTree*          fTreeLambda = nullptr;       //!<! Tree for Lambdas
  TTree*          fTreeK0s = nullptr;          //!<! Tree for K0s
  TTree*          fTreeLambdaBDTOut = nullptr; //!<! Tree for Lambdas

  MiniCascade* fRecCascade = nullptr;          //!<! Transient fRecCascade
  MiniCascadeMC fGenCascade;
  MiniLambda* fRecLambda = nullptr;          //!<! Transient fRecLambda
  MiniLambdaMC fGenLambda;
  MiniK0s* fRecK0s = nullptr;          //!<! Transient fRecK0s
  MiniK0sMC fGenK0s;
  MiniLambdaBDTOut *fRecLambdaBDTOut = nullptr;//!<! Transient fRecLambda with BDT output
  AliPIDResponse* fPID = nullptr;              //!<! ALICE PID framework
  std::vector<AliExternalBDT*> fBDT;           //!<! BDTs
  bool fMC;
  bool fOnlyTrueCandidates = false;  ///< Save only true Xi and Omegas in MC
  bool fFillK0s = false;
  bool fFillLambdas = false;
  bool fFillLambdasBDTOut = false;
  bool fFillCascades = false;
  bool fOnlyTrueK0s = true;          ///< Save only true K0s in MC
  bool fOnlyTrueLambdas = true;      ///< Save only true Lambdas in MC
  float fLambdaDownscaling = 1.;
  float fK0sDownscaling = 1.;

  //configurable cuts
  float fCutRadius[3] = {1.2, 1.0, 3.0};
  float fCutRadiusV0 = 3.0;
  float fCutDCABachToPV = 0.1;
  float fCutDCAV0toPV = 0.1;
  float fCutDCAV0piToPV = 0.2;
  float fCutDCAV0prToPV = 0.2;
  float fCutDCAV0tracks = 1.2;
  float fCutDCABachToV0[2]{1.0, 1.0};
  float fCutCosPA = 0.95;
  float fCutCosPAV0 = 0.95;
  float fCutV0MassWindow = 0.005;
  float fCutY = 0.5;
  float fCutYDaught = 0.8;
  float fCutNsigmaTPC = 4.0;
  float fCutCt = 4;
  float fCutCtV0 = 30;
  float fCutCompetingMass[2]{0.,0.};
  int fCutTPCclu = 70;
  float fCutTPCrows = 80.;
  float fCutRowsOvF = 0.8;
  double fCascLeastCRaws;
  double fCascLeastCRawsOvF;
  double fV0LeastCRaws;
  double fV0LeastCRawsOvF;
  double fMinCentrality = 0;
  double fMaxCentrality = 90;
  double fCtPreselection = 1.;
  double fMaxCt = 40.;
  double fMinPt = 0.5;
  double fMaxPt = 3.5;
  double fRadiusPreselection = 3;
  double fRadiusOverflowCut = 100;
  int fTpcClV0PiPreselection = 70;
  int fTpcClV0PrPreselection = 70;
  double fDCAV0piToPVOverflowCut = 20;
  double fDCAV0prToPVOverflowCut = 20;
  double fDCAV0toPVOverflowCut = 10;
  double fBdtOutputBackgroundCut = 0.15;

  float fCosPALambda = 0.97;
  float fCutDCALambdaPrToPV = 0.08;
  float fCutDCALambdaPiToPV = 0.12;
  float fCutLambdaMass[2] = {1.09f, 1.15f};

  float fCosPAK0s = 0.97;
  float fCutDCAK0sProngToPV = 0.08;
  float fCutK0sMass[2] = {1.09f, 1.15f};

  bool fUseOnTheFly = false;

  TArrayD fCtBinsBDT;
  std::string fBDTPath = "";

  bool IsTopolSelected(bool isXi = true);
  bool IsTopolSelectedLambda();
  bool IsTopolSelectedK0s();
  float Eta2y(float pt, float m, float eta) const;
  int WhichBDT(double ct);
  void FindWDLambdaMother(AliAODMCParticle *track);

  /// \cond CLASSDEF
  ClassDef(AliAnalysisTaskStrangenessRatios, 1);
  /// \endcond
};

#endif /* defined(__AliAnalysisTaskStrangenessRatios__) */


text:
**Please check if the PR fulfills these requirements**
- [ ] The commit message follows our guidelines: https://github.com/angular/angular/blob/master/CONTRIBUTING.md#commit-message-format
- [ ] Tests for the changes have been added (for bug fixes / features)
- [ ] Docs have been added / updated (for bug fixes / features)

**What kind of change does this PR introduce?** (Bug fix, feature, docs update, ...)
- [ ] Bugfix
- [ ] Feature
- [ ] Code style update (formatting, local variables)
- [ ] Refactoring (no functional changes, no api changes)
- [ ] Build related changes
- [ ] CI related changes
- [ ] Other... Please describe:

**What is the current behavior?** (You can also link to an open issue here)

**What is the new behavior?**

**Does this PR introduce a breaking change?**
- [ ] Yes
- [ ] No

If this PR contains a breaking change, please describe the impact and migration path for existing applications: ...

**Other information**: