text:
// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2013 - 2018)
//   René Fritze     (2014, 2016, 2018)
//   René Milk       (2017)
//   Tobias Leibner  (2014, 2017)

#ifndef DUNE_GDT_LOCAL_INTEGRANDS_PRODUCTS_HH
#define DUNE_GDT_LOCAL_INTEGRANDS_PRODUCTS_HH

#include <dune/xt/common/memory.hh>
#include <dune/xt/la/container/eye-matrix.hh>
#include <dune/xt/grid/print.hh>
#include <dune/xt/functions/constant.hh>
#include <dune/xt/functions/base/combined-functions.hh>
#include <dune/xt/functions/base/combined-grid-functions.hh>
#include <dune/xt/functions/grid-function.hh>
#include <dune/xt/functions/interfaces/grid-function.hh>

#include <dune/gdt/print.hh>

#include "interfaces.hh"

namespace Dune {
namespace GDT {

/**
 * Given an inducing function f (may be matrix-valued), computes `(f(x) * psi(x)) * phi(x)` for all combinations of phi
 * in the ansatz basis and psi in the test basis.
 *
 * \note Note that f can also be given as a scalar value or omitted.
 *
 * \note Applying f to the ansatz basis can be done by passing f^T (the transposed of f)
 *
 * \sa local_binary_to_unary_element_integrand
 */
template <class E, size_t r = 1, class TR = double, class F = double, class AR = TR>
class LocalElementProductIntegrand : public LocalBinaryElementIntegrandInterface<E, r, 1, TR, F, r, 1, AR>
{
  using ThisType = LocalElementProductIntegrand;
  using BaseType = LocalBinaryElementIntegrandInterface<E, r, 1, TR, F, r, 1, AR>;

public:
  using BaseType::d;
  using typename BaseType::DomainType;
  using typename BaseType::ElementType;
  using typename BaseType::LocalAnsatzBasisType;
  using typename BaseType::LocalTestBasisType;

  LocalElementProductIntegrand(XT::Functions::GridFunction<E, r, r, F> weight = {1.},
                               const std::string& logging_prefix = "")
    : BaseType({},
               logging_prefix.empty() ? "ElementProductIntegrand" : logging_prefix,
               /*logging_disabled=*/logging_prefix.empty())
    , weight_(weight.copy_as_grid_function())
    , local_weight_(weight_->local_function())
  {
    LOG_(info) << "LocalElementProductIntegrand(this=" << this << ", weight=" << &weight << ")" << std::endl;
  }

  LocalElementProductIntegrand(const ThisType& other)
    : BaseType(other)
    , weight_(other.weight_->copy_as_grid_function())
    , local_weight_(weight_->local_function())
  {}

  LocalElementProductIntegrand(ThisType&& source) = default;

  std::unique_ptr<BaseType> copy_as_binary_element_integrand() const override final
  {
    LOG_(debug) << "copy_as_binary_element_integrand()" << std::endl;
    return std::make_unique<ThisType>(*this);
  }

protected:
  void post_bind(const ElementType& ele) override final
  {
    LOG_(debug) << "post_bind(element=" << XT::Grid::print(ele) << ")" << std::endl;
    local_weight_->bind(ele);
  }

public:
  int order(const LocalTestBasisType& test_basis,
            const LocalAnsatzBasisType& ansatz_basis,
            const XT::Common::Parameter& param = {}) const override final
  {
    LOG_(debug) << "order(element=" << XT::Grid::print(this->element()) << ", {test|ansatz}_basis.size()={"
                << test_basis.size(param) << "|" << ansatz_basis.size(param) << "}, param=" << param
                << ")\n     local_weight.order() = " << local_weight_->order(param)
                << "\n     test_basis.order() = " << test_basis.order(param)
                << "\n     ansatz_basis.order() = " << ansatz_basis.order(param) << "\n     returning "
                << local_weight_->order(param) + test_basis.order(param) + ansatz_basis.order(param) << std::endl;
    return local_weight_->order(param) + test_basis.order(param) + ansatz_basis.order(param);
  }

  using BaseType::evaluate;

  void evaluate(const LocalTestBasisType& test_basis,
                const LocalAnsatzBasisType& ansatz_basis,
                const DomainType& point_in_reference_element,
                DynamicMatrix<F>& result,
                const XT::Common::Parameter& param = {}) const override final
  {
    LOG_(debug) << "evaluate({test|ansatz}_basis.size()={" << test_basis.size(param) << "|" << ansatz_basis.size(param)
                << "}, point_in_{reference_element|physical_space} = {" << print(point_in_reference_element) << "|"
                << print(this->element().geometry().global(point_in_reference_element)) << "}, param=" << param << ")"
                << std::endl;
    // prepare storage
    const size_t rows = test_basis.size(param);
    const size_t cols = ansatz_basis.size(param);
    if (result.rows() < rows || result.cols() < cols)
      result.resize(rows, cols);
    // evaluate
    test_basis.evaluate(point_in_reference_element, test_basis_values_, param);
    ansatz_basis.evaluate(point_in_reference_element, ansatz_basis_values_, param);
    const auto weight = local_weight_->evaluate(point_in_reference_element, param);
    LOG_(debug) << "  test_basis_values_ = " << test_basis_values_
                << "\n  ansatz_basis_values_ = " << ansatz_basis_values_ << "\n  weight = " << weight << std::endl;
    // compute product
    for (size_t ii = 0; ii < rows; ++ii)
      for (size_t jj = 0; jj < cols; ++jj)
        result[ii][jj] = (weight * test_basis_values_[ii]) * ansatz_basis_values_[jj];
    LOG_(debug) << "  result = " << print(result, {{"oneline", "true"}}) << std::endl;
  } // ... evaluate(...)

private:
  const std::unique_ptr<XT::Functions::GridFunctionInterface<E, r, r, F>> weight_;
  std::unique_ptr<typename XT::Functions::GridFunctionInterface<E, r, r, F>::LocalFunctionType> local_weight_;
  mutable std::vector<typename LocalTestBasisType::RangeType> test_basis_values_;
  mutable std::vector<typename LocalAnsatzBasisType::RangeType> ansatz_basis_values_;
}; // class LocalElementProductIntegrand

/**
 * Given an inducing function f, computes `<f> * phi * psi` for all combinations of phi and psi in the bases, where
 * `<f>` denotes the average of f evaluated on the inside and evaluated on the outside.
 *
 * \note Note that f can also be given as a scalar value or omitted.
 */
template <class I, size_t r = 1, class TR = double, class F = double, class AR = TR>
class LocalCouplingIntersectionProductIntegrand
  : public LocalQuaternaryIntersectionIntegrandInterface<I, r, 1, TR, F, r, 1, AR>
{
  using ThisType = LocalCouplingIntersectionProductIntegrand;
  using BaseType = LocalQuaternaryIntersectionIntegrandInterface<I, r, 1, TR, F, r, 1, AR>;

public:
  using BaseType::d;
  using typename BaseType::DomainType;
  using typename BaseType::E;
  using typename BaseType::IntersectionType;
  using typename BaseType::LocalAnsatzBasisType;
  using typename BaseType::LocalTestBasisType;

  using GridFunctionType = XT::Functions::GridFunctionInterface<E, r, r, F>;

  LocalCouplingIntersectionProductIntegrand(XT::Functions::GridFunction<E, r, r, F> weight = {1.},
                                            const std::string& logging_prefix = "")
    : BaseType({},
               logging_prefix.empty() ? "LocalCouplingIntersectionProductIntegrand" : logging_prefix,
               /*logging_disabled=*/logging_prefix.empty())
    , weight_(weight.copy_as_grid_function())
    , local_weight_in_(weight_->local_function())
    , local_weight_out_(weight_->local_function())
  {}

  LocalCouplingIntersectionProductIntegrand(const ThisType& other)
    : BaseType(other)
    , weight_(other.weight_->copy_as_grid_function())
    , local_weight_in_(weight_->local_function())
    , local_weight_out_(weight_->local_function())
  {}

  LocalCouplingIntersectionProductIntegrand(ThisType&& source) = default;

  std::unique_ptr<BaseType> copy_as_quaternary_intersection_integrand() const override final
  {
    return std::make_unique<ThisType>(*this);
  }

protected:
  void post_bind(const IntersectionType& intersct) override final
  {
    auto inside_element = intersct.inside();
    local_weight_in_->bind(inside_element);
    if (intersct.neighbor()) {
      local_weight_out_->bind(intersct.outside());
    } else
      local_weight_out_->bind(intersct.inside());
  } // ... post_bind(...)

public:
  int order(const LocalTestBasisType& test_basis_inside,
            const LocalAnsatzBasisType& ansatz_basis_inside,
            const LocalTestBasisType& test_basis_outside,
            const LocalAnsatzBasisType& ansatz_basis_outside,
            const XT::Common::Parameter& param = {}) const override final
  {
    return std::max(local_weight_in_->order(param), local_weight_out_->order(param))
           + std::max(test_basis_inside.order(param), test_basis_outside.order(param))
           + std::max(ansatz_basis_inside.order(param), ansatz_basis_outside.order(param));
  }

  using BaseType::evaluate;

  void evaluate(const LocalTestBasisType& test_basis_inside,
                const LocalAnsatzBasisType& ansatz_basis_inside,
                const LocalTestBasisType& test_basis_outside,
                const LocalAnsatzBasisType& ansatz_basis_outside,
                const DomainType& point_in_reference_intersection,
                DynamicMatrix<F>& result_in_in,
                DynamicMatrix<F>& result_in_out,
                DynamicMatrix<F>& result_out_in,
                DynamicMatrix<F>& result_out_out,
                const XT::Common::Parameter& param = {}) const override final
  {
    // prepare sotrage
    const size_t rows_in = test_basis_inside.size(param);
    const size_t rows_out = test_basis_outside.size(param);
    const size_t cols_in = ansatz_basis_inside.size(param);
    const size_t cols_out = ansatz_basis_outside.size(param);
    const auto ensure_size = [](auto& m, const auto& rws, const auto& cls) {
      if (m.rows() < rws || m.cols() < cls)
        m.resize(rws, cls);
    };
    ensure_size(result_in_in, rows_in, cols_in);
    ensure_size(result_in_out, rows_in, cols_out);
    ensure_size(result_out_in, rows_out, cols_in);
    ensure_size(result_out_out, rows_out, cols_out);
    // evaluate
    const auto point_in_inside_reference_element =
        this->intersection().geometryInInside().global(point_in_reference_intersection);
    test_basis_inside.evaluate(point_in_inside_reference_element, test_basis_in_values_, param);
    ansatz_basis_inside.evaluate(point_in_inside_reference_element, ansatz_basis_in_values_, param);
    const auto weight_in = local_weight_in_->evaluate(point_in_inside_reference_element, param);
    const auto point_in_outside_reference_element =
        this->intersection().geometryInOutside().global(point_in_reference_intersection);
    test_basis_outside.evaluate(point_in_outside_reference_element, test_basis_out_values_, param);
    ansatz_basis_outside.evaluate(point_in_outside_reference_element, ansatz_basis_out_values_, param);
    const auto weight_out = local_weight_out_->evaluate(point_in_outside_reference_element, param);
    // compute integrand
    const auto average_function_value = (weight_in + weight_out) * 0.5;
    for (size_t ii = 0; ii < rows_in; ++ii) {
      for (size_t jj = 0; jj < cols_in; ++jj)
        result_in_in[ii][jj] = (average_function_value * ansatz_basis_in_values_[jj]) * test_basis_in_values_[ii];
      for (size_t jj = 0; jj < cols_out; ++jj)
        result_in_out[ii][jj] = (average_function_value * ansatz_basis_out_values_[jj]) * test_basis_in_values_[ii];
    }
    for (size_t ii = 0; ii < rows_out; ++ii) {
      for (size_t jj = 0; jj < cols_in; ++jj)
        result_out_in[ii][jj] = (average_function_value * ansatz_basis_in_values_[jj]) * test_basis_out_values_[ii];
      for (size_t jj = 0; jj < cols_out; ++jj)
        result_out_out[ii][jj] = (average_function_value * ansatz_basis_out_values_[jj]) * test_basis_out_values_[ii];
    }
  } // ... evaluate(...)

private:
  const std::unique_ptr<XT::Functions::GridFunctionInterface<E, r, r, F>> weight_;
  std::unique_ptr<typename XT::Functions::GridFunctionInterface<E, r, r, F>::LocalFunctionType> local_weight_in_;
  std::unique_ptr<typename XT::Functions::GridFunctionInterface<E, r, r, F>::LocalFunctionType> local_weight_out_;
  mutable std::vector<typename LocalTestBasisType::RangeType> test_basis_in_values_;
  mutable std::vector<typename LocalTestBasisType::RangeType> test_basis_out_values_;
  mutable std::vector<typename LocalAnsatzBasisType::RangeType> ansatz_basis_in_values_;
  mutable std::vector<typename LocalAnsatzBasisType::RangeType> ansatz_basis_out_values_;
}; // class LocalCouplingIntersectionProductIntegrand

/**
 * Given an inducing function f, computes `f * phi * psi` for all combinations of phi and psi in the bases.
 *
 * \note Note that f can also be given as a scalar value or omitted.
 */
template <class I, size_t r = 1, class TR = double, class F = double, class AR = TR>
class LocalIntersectionProductIntegrand : public LocalBinaryIntersectionIntegrandInterface<I, r, 1, TR, F, r, 1, AR>
{
  using ThisType = LocalIntersectionProductIntegrand;
  using BaseType = LocalBinaryIntersectionIntegrandInterface<I, r, 1, TR, F, r, 1, AR>;

public:
  using BaseType::d;
  using typename BaseType::DomainType;
  using typename BaseType::E;
  using typename BaseType::IntersectionType;
  using typename BaseType::LocalAnsatzBasisType;
  using typename BaseType::LocalTestBasisType;

  using GridFunctionType = XT::Functions::GridFunctionInterface<E, r, r, F>;

  LocalIntersectionProductIntegrand(XT::Functions::GridFunction<E, r, r, F> weight = {1.},
                                    const bool use_inside_bases = true,
                                    const std::string& logging_prefix = "")
    : BaseType({},
               logging_prefix.empty() ? "LocalIntersectionProductIntegrand" : logging_prefix,
               /*logging_disabled=*/logging_prefix.empty())
    , weight_(weight.copy_as_grid_function())
    , local_weight_(weight_->local_function())
    , inside_(use_inside_bases)
  {}

  LocalIntersectionProductIntegrand(const ThisType& other)
    : BaseType(other)
    , weight_(other.weight_->copy_as_grid_function())
    , local_weight_(weight_->local_function())
    , inside_(other.inside_)
  {}

  LocalIntersectionProductIntegrand(ThisType&& source) = default;

  std::unique_ptr<BaseType> copy_as_binary_intersection_integrand() const override final
  {
    return std::make_unique<ThisType>(*this);
  }

protected:
  void post_bind(const IntersectionType& intersct) override final
  {
    if (inside_)
      local_weight_->bind(intersct.inside());
    else {
      DUNE_THROW_IF(!intersct.neighbor(), Exceptions::integrand_error, "");
      local_weight_->bind(intersct.outside());
    }
  } // ... post_bind(...)

public:
  bool inside() const override final
  {
    return inside_;
  }

  int order(const LocalTestBasisType& test_basis,
            const LocalAnsatzBasisType& ansatz_basis,
            const XT::Common::Parameter& param = {}) const override final
  {
    return local_weight_->order(param) + test_basis.order(param) + ansatz_basis.order(param);
  }

  using BaseType::evaluate;

  void evaluate(const LocalTestBasisType& test_basis,
                const LocalAnsatzBasisType& ansatz_basis,
                const DomainType& point_in_reference_intersection,
                DynamicMatrix<F>& result,
                const XT::Common::Parameter& param = {}) const override final
  {
    // prepare sotrage
    this->ensure_size_and_clear_results(test_basis, ansatz_basis, result, param);
    // evaluate
    typename XT::Functions::GridFunctionInterface<E, r, r, F>::LocalFunctionType::RangeReturnType weight;
    if (inside_) {
      const auto point_in_inside_reference_element =
          this->intersection().geometryInInside().global(point_in_reference_intersection);
      test_basis.evaluate(point_in_inside_reference_element, test_basis_values_, param);
      ansatz_basis.evaluate(point_in_inside_reference_element, ansatz_basis_values_, param);
      weight = local_weight_->evaluate(point_in_inside_reference_element, param);
    } else {
      const auto point_in_outside_reference_element =
          this->intersection().geometryInOutside().global(point_in_reference_intersection);
      test_basis.evaluate(point_in_outside_reference_element, test_basis_values_, param);
      ansatz_basis.evaluate(point_in_outside_reference_element, ansatz_basis_values_, param);
      weight = local_weight_->evaluate(point_in_outside_reference_element, param);
    }
    // compute integrand
    const size_t rows = test_basis.size(param);
    const size_t cols = ansatz_basis.size(param);
    for (size_t ii = 0; ii < rows; ++ii)
      for (size_t jj = 0; jj < cols; ++jj)
        result[ii][jj] = (weight * ansatz_basis_values_[jj]) * test_basis_values_[ii];
  } // ... evaluate(...)

private:
  const std::unique_ptr<XT::Functions::GridFunctionInterface<E, r, r, F>> weight_;
  std::unique_ptr<typename XT::Functions::GridFunctionInterface<E, r, r, F>::LocalFunctionType> local_weight_;
  const bool inside_;
  mutable std::vector<typename LocalTestBasisType::RangeType> test_basis_values_;
  mutable std::vector<typename LocalAnsatzBasisType::RangeType> ansatz_basis_values_;
}; // class LocalIntersectionProductIntegrand

template <class E_or_I, size_t r = 1, class TR = double, class F = double, class AR = TR>
class LocalProductIntegrand
  : public std::conditional_t<XT::Grid::is_entity<E_or_I>::value,
                              LocalElementProductIntegrand<E_or_I, r, TR, F, AR>,
                              LocalIntersectionProductIntegrand<E_or_I, r, TR, F, AR>>
{
  using BaseType = std::conditional_t<XT::Grid::is_entity<E_or_I>::value,
                                      LocalElementProductIntegrand<E_or_I, r, TR, F, AR>,
                                      LocalIntersectionProductIntegrand<E_or_I, r, TR, F, AR>>;

public:
  template <class... Args>
  explicit LocalProductIntegrand(Args&&... args)
    : BaseType(std::forward<Args>(args)...)
  {}
}; // class LocalProductIntegrand

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_LOCAL_INTEGRANDS_PRODUCTS_HH


text:
package com.ss.editor.ui.component.editor.impl.material;

import static com.ss.editor.Messages.MATERIAL_EDITOR_NAME;
import static com.ss.editor.config.DefaultSettingsProvider.Defaults.PREF_DEFAULT_FLIPPED_TEXTURES;
import static com.ss.editor.config.DefaultSettingsProvider.Preferences.PREF_FLIPPED_TEXTURES;
import static com.ss.editor.util.EditorUtil.getAssetFile;
import static com.ss.editor.util.EditorUtil.toAssetPath;
import static com.ss.editor.util.MaterialUtils.updateMaterialIdNeed;
import static com.ss.rlib.common.util.ObjectUtils.notNull;

import com.jme3.asset.AssetKey;
import com.jme3.asset.AssetManager;
import com.jme3.asset.MaterialKey;
import com.jme3.asset.TextureKey;
import com.jme3.material.MatParam;
import com.jme3.material.MatParamTexture;
import com.jme3.material.Material;
import com.jme3.material.MaterialDef;
import com.jme3.shader.VarType;
import com.jme3.texture.Texture;
import com.ss.editor.FileExtensions;
import com.ss.editor.Messages;
import com.ss.editor.annotation.BackgroundThread;
import com.ss.editor.annotation.FromAnyThread;
import com.ss.editor.annotation.FxThread;
import com.ss.editor.config.EditorConfig;
import com.ss.editor.manager.ResourceManager;
import com.ss.editor.model.node.material.RootMaterialSettings;
import com.ss.editor.model.undo.EditorOperationControl;
import com.ss.editor.model.undo.editor.ChangeConsumer;
import com.ss.editor.part3d.editor.impl.material.MaterialEditor3DPart;
import com.ss.editor.plugin.api.editor.material.BaseMaterialEditor3DPart.ModelType;
import com.ss.editor.plugin.api.editor.material.BaseMaterialFileEditor;
import com.ss.editor.ui.component.editor.EditorDescription;
import com.ss.editor.ui.component.editor.state.EditorState;
import com.ss.editor.ui.component.editor.state.impl.EditorMaterialEditorState;
import com.ss.editor.ui.control.property.operation.PropertyOperation;
import com.ss.editor.ui.css.CssClasses;
import com.ss.editor.ui.event.impl.FileChangedEvent;
import com.ss.editor.ui.util.UiUtils;
import com.ss.editor.util.EditorUtil;
import com.ss.editor.util.MaterialSerializer;
import com.ss.editor.util.MaterialUtils;
import com.ss.rlib.fx.util.FXUtils;
import javafx.collections.ObservableList;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.input.DragEvent;
import javafx.scene.layout.HBox;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * The implementation of the Editor to edit materials.
 *
 * @author JavaSaBr
 */
public class MaterialFileEditor extends
        BaseMaterialFileEditor<MaterialEditor3DPart, EditorMaterialEditorState, ChangeConsumer> {

    /**
     * The description.
     */
    @NotNull
    public static final EditorDescription DESCRIPTION = new EditorDescription();

    static {
        DESCRIPTION.setConstructor(MaterialFileEditor::new);
        DESCRIPTION.setEditorName(MATERIAL_EDITOR_NAME);
        DESCRIPTION.setEditorId(MaterialFileEditor.class.getSimpleName());
        DESCRIPTION.addExtension(FileExtensions.JME_MATERIAL);
    }

    @NotNull
    private static final ResourceManager RESOURCE_MANAGER = ResourceManager.getInstance();

    /**
     * The list of material definitions.
     */
    @Nullable
    private ComboBox<String> materialDefinitionBox;

    /**
     * The current editing material.
     */
    @Nullable
    private Material currentMaterial;

    private MaterialFileEditor() {
        super();
    }

    @Override
    @FxThread
    protected @NotNull MaterialEditor3DPart create3DEditorPart() {
        return new MaterialEditor3DPart(this);
    }

    @Override
    @FxThread
    protected void processChangedFile(@NotNull final FileChangedEvent event) {
        super.processChangedFile(event);

        final Material currentMaterial = getCurrentMaterial();
        final Path file = event.getFile();

        EXECUTOR_MANAGER.addJmeTask(() -> {
            final Material newMaterial = updateMaterialIdNeed(file, currentMaterial);
            if (newMaterial != null) {
                EXECUTOR_MANAGER.addFxTask(() -> reload(newMaterial));
            }
        });
    }

    @Override
    @BackgroundThread
    public void doSave(@NotNull final Path toStore) throws IOException {
        super.doSave(toStore);

        final Material currentMaterial = getCurrentMaterial();
        final String content = MaterialSerializer.serializeToString(currentMaterial);

        try (final PrintWriter out = new PrintWriter(Files.newOutputStream(toStore))) {
            out.print(content);
        }
    }

    @Override
    @FxThread
    protected void handleExternalChanges() {
        super.handleExternalChanges();

        final Path assetFile = notNull(getAssetFile(getEditFile()));
        final MaterialKey materialKey = new MaterialKey(toAssetPath(assetFile));

        final AssetManager assetManager = EditorUtil.getAssetManager();
        final Material material = assetManager.loadAsset(materialKey);

        reload(material);

        final EditorOperationControl operationControl = getOperationControl();
        operationControl.clear();
    }

    /**
     * Try to apply dropped texture.
     *
     * @param editor    the editor.
     * @param dragEvent the drag event.
     * @param path      the path to the texture.
     */
    private void applyTexture(@NotNull final MaterialFileEditor editor, @NotNull final DragEvent dragEvent,
                              @NotNull final Path path) {

        final String textureName = path.getFileName().toString();
        final int textureType = MaterialUtils.getPossibleTextureType(textureName);

        if (textureType == 0) {
            return;
        }

        final String[] paramNames = MaterialUtils.getPossibleParamNames(textureType);
        final Material currentMaterial = getCurrentMaterial();
        final MaterialDef materialDef = currentMaterial.getMaterialDef();

        final Optional<MatParam> param = Arrays.stream(paramNames)
                .map(materialDef::getMaterialParam)
                .filter(Objects::nonNull)
                .filter(p -> p.getVarType() == VarType.Texture2D)
                .findAny();

        if (!param.isPresent()) {
            return;
        }

        final MatParam matParam = param.get();

        EXECUTOR_MANAGER.addJmeTask(() -> {

            final EditorConfig config = EditorConfig.getInstance();
            final Path assetFile = notNull(getAssetFile(path));
            final TextureKey textureKey = new TextureKey(toAssetPath(assetFile));
            textureKey.setFlipY(config.getBoolean(PREF_FLIPPED_TEXTURES, PREF_DEFAULT_FLIPPED_TEXTURES));

            final AssetManager assetManager = EditorUtil.getAssetManager();
            final Texture texture = assetManager.loadTexture(textureKey);
            texture.setWrap(Texture.WrapMode.Repeat);

            final String paramName = matParam.getName();
            final MatParamTexture textureParam = currentMaterial.getTextureParam(paramName);
            final Texture currentTexture = textureParam == null? null : textureParam.getTextureValue();

            PropertyOperation<ChangeConsumer, Material, Texture> operation =
                    new PropertyOperation<>(currentMaterial, paramName, texture, currentTexture);
            operation.setApplyHandler((material, newTexture) -> material.setTexture(paramName, newTexture));

            execute(operation);
        });
    }

    @Override
    @FxThread
    protected void handleDragDroppedEvent(@NotNull final DragEvent dragEvent) {
        super.handleDragDroppedEvent(dragEvent);
        UiUtils.handleDroppedFile(dragEvent, FileExtensions.TEXTURE_EXTENSIONS, this,
                dragEvent, this::applyTexture);
    }

    @Override
    @FxThread
    protected void handleDragOverEvent(@NotNull final DragEvent dragEvent) {
        super.handleDragOverEvent(dragEvent);
        UiUtils.acceptIfHasFile(dragEvent, FileExtensions.TEXTURE_EXTENSIONS);
    }

    @Override
    @FxThread
    protected void doOpenFile(@NotNull final Path file) throws IOException {
        super.doOpenFile(file);

        final Path assetFile = notNull(getAssetFile(file));
        final MaterialKey materialKey = new MaterialKey(toAssetPath(assetFile));

        final AssetManager assetManager = EditorUtil.getAssetManager();
        final Material material = assetManager.loadAsset(materialKey);

        final MaterialEditor3DPart editor3DState = getEditor3DPart();
        editor3DState.changeMode(ModelType.BOX);

        reload(material);
    }

    @FxThread
    @Override
    protected @Nullable Supplier<EditorState> getEditorStateFactory() {
        return EditorMaterialEditorState::new;
    }

    /**
     * Reload the material.
     */
    @FxThread
    private void reload(@NotNull final Material material) {
        setCurrentMaterial(material);
        setIgnoreListeners(true);
        try {

            final MaterialEditor3DPart editor3DState = getEditor3DPart();
            editor3DState.updateMaterial(material);

            getSettingsTree().fill(new RootMaterialSettings(material));

            final ComboBox<String> materialDefinitionBox = getMaterialDefinitionBox();
            final ObservableList<String> items = materialDefinitionBox.getItems();
            items.clear();
            items.addAll(RESOURCE_MANAGER.getAvailableResources(FileExtensions.JME_MATERIAL_DEFINITION));

            final MaterialDef materialDef = material.getMaterialDef();
            materialDefinitionBox.getSelectionModel().select(materialDef.getAssetName());

        } finally {
            setIgnoreListeners(false);
        }
    }

    /**
     * @return the list of material definitions.
     */
    @FromAnyThread
    private @NotNull ComboBox<String> getMaterialDefinitionBox() {
        return notNull(materialDefinitionBox);
    }

    @Override
    @FxThread
    protected void createToolbar(@NotNull final HBox container) {
        super.createToolbar(container);

        final Label materialDefinitionLabel = new Label(Messages.MATERIAL_EDITOR_MATERIAL_TYPE_LABEL + ":");

        materialDefinitionBox = new ComboBox<>();
        materialDefinitionBox.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> changeType(newValue));

        FXUtils.addToPane(materialDefinitionLabel, container);
        FXUtils.addToPane(materialDefinitionBox, container);

        FXUtils.addClassTo(materialDefinitionLabel, CssClasses.FILE_EDITOR_TOOLBAR_LABEL);
        FXUtils.addClassTo(materialDefinitionBox, CssClasses.FILE_EDITOR_TOOLBAR_FIELD);
    }

    /**
     * Handle changing the type.
     */
    @FxThread
    private void changeType(@Nullable final String newType) {
        if (isIgnoreListeners()) return;
        processChangeTypeImpl(newType);
    }

    /**
     * Handle changing the type.
     */
    @FxThread
    private void processChangeTypeImpl(@Nullable final String newType) {
        if (newType == null) return;

        final AssetManager assetManager = EditorUtil.getAssetManager();
        final Material newMaterial = new Material(assetManager, newType);

        MaterialUtils.migrateTo(newMaterial, getCurrentMaterial());

        final EditorOperationControl operationControl = getOperationControl();
        operationControl.clear();

        incrementChange();
        reload(newMaterial);
    }

    @FromAnyThread
    private @NotNull Material getCurrentMaterial() {
        return notNull(currentMaterial);
    }

    /**
     * @param currentMaterial the current editing material.
     */
    @FxThread
    private void setCurrentMaterial(@NotNull final Material currentMaterial) {
        this.currentMaterial = currentMaterial;
    }

    @Override
    @FromAnyThread
    public @NotNull EditorDescription getDescription() {
        return DESCRIPTION;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php /** @noinspection ALL */

namespace Kernel;

use Exception;
use DirectoryIterator;
use Kernel\Security\Hash;
use Kernel\Security\Encryption;

/**
 * Class YamatoCLI
 * $command holds anything you type into YamatoCLI
 * then passes it to parseCommand($arg) to look for
 * specific method.
 *
 * @package Kernel
 * @property $command
 */
final class YamatoCLI
{
    private $command = null;

    /**
     * Get the arguments on instantiation
     * also prints yamato ascii art
     *
     * @param $arguments
     */
    public function __construct($arguments = null)
    {
        if (!isset($arguments[1])) {
            echo <<<EOF

           ..      ..   ..     ..    -#      ..
 ,#   x#  - ,#=  ##;;##+,+#   -..x# ++#++ .#+,-#X
  ##  #    ,.##  #.  =#   #+   ,,-#  ,#   #+    #.
   #-#+  #X  +#  #   =#   #+ -#.  #. -#   #=    #.
    ##   #X.,##  #.  +#   #x =#..x#. .#-. .#+,-#x
   ;#     ,,.    .    .   .    ;,      ;,   ,;;
  +X    11/10/2015 - 02/07/2020

 Yamato is a Command Line Interface(CLI) tool that is
 made to interact with the Strife Framework.

     COMMANDS                 ARGUMENTS                 DESCRIPTION
--------------------	--------------------    -----------------------------

{CLEANUP}
  clear:logs                                    clear logs directory
  clear:backups                                 clear backups directory
  clear:cache                                   clear cached pages
  clear:all                                     clear all backups,logs

{GENERATORS}
  create:model          [name] [table=null]     create a model class
  create:controller     [name] [empty=bool]     create a controller class
  create:migration      [name] [table]          create a migration class
  create:request        [name]                  create a request class
  create:seeder         [name] [model]          create a database seeder class
  create:key                                    create an application key

{DATABASE}
  db:migrate                                    install all migrations
  db:rollback                                   rollback all migrations
  db:table:up           [class]                 migrate a specific table using model class
  db:table:down         [class]                 rollback a specific table using model class
  db:table:dump         [class]                 view data types of a table
  db:backup                                     backup table data into JSON file
  db:restore                                    restore last made backup from JSON file
  db:seed                                       perform database seeding

{SECURITY}
  hash:encode           [string]                returns the hash of a given string
  hash:verify           [string] [hashed]       verify whether data matches the hashed value
  encryption:encode     [string] [level=1]      encrypt a string with levels specified
  encryption:decode     [string] [level=1]      decrypt with same level set to string

EOF;

        } else {
            $this->command = $arguments;
            return $this->parseCommand();
        }

        return (true);
    }

    /**
     * Command Parser
     *
     * @return mixed
     */
    private function parseCommand()
    {
        $cmd = $this->command;

        switch ($cmd[1]) {

            /****************************************************
             *                   Cleaning                       *
             ***************************************************/

            case 'clear:all':
                $this->clear('backups');
                $this->clear('logs');
                return die("backups,logs,cache were cleared.\n");
                break;

            case 'clear:logs':
                $this->clear('logs');
                return die("logs directory cleared.\n");
                break;

            case 'clear:cache':
                $this->clear('cache');
                return die("cached pages cleared.\n");
                break;

            case 'clear:backups':
                $this->clear('backups');
                return die("backup directory cleared.\n");
                break;

            /*********************************************
             *               Generators                  *
             *********************************************/

            case 'create:model':
                if (isset($cmd[2])) {
                    $option = isset($cmd[3]) ? $cmd[3] : strtolower($cmd[2]);
                    return $this->createModel($cmd[2], $option);
                } else {
                    die("too few arguments, create:model expects [name], [table] is optional.\n");
                }
                break;

            case 'create:controller':
                if (isset($cmd[2])) {
                    $option = isset($cmd[3]) ? $cmd[3] : "false";
                    $this->createController($cmd[2], $option);
                } else {
                    die("too few arguments, create:controller expects [name], [empty](bool) is optional.\n");
                }
                break;

            case 'create:migration':
                if (isset($cmd[2]) && isset($cmd[3])) {
                    $this->createMigration($cmd[2], $cmd[3]);
                } else {
                    die("too few arguments, create:migration expects [name] [table].\n");
                }
                break;

            case 'create:request':
                if (isset($cmd[2])) {
                    $this->createRequest($cmd[2]);
                } else {
                    die("create:request expects 1 parameter [name].\n");
                }
                break;

            case 'create:seeder':
                if (isset($cmd[2]) && isset($cmd[3])) {
                    $this->createSeeder($cmd[2], $cmd[3]);
                } else {
                    die("too few arguments, create:seeder expects [name] [model].\n");
                }
                break;

            case 'create:key':
                return die(Hash::generateSalt());
                break;

            /********************************************************
             *             Database and Migrations                  *
             ********************************************************/

            case 'db:migrate':
                return $this->migrate('up');
                break;

            case 'db:rollback':
                return $this->migrate('down');
                break;

            case 'db:table:up':
                return $this->tableMigration($cmd[2], 'up');
                break;

            case 'db:table:down':
                return $this->tableMigration($cmd[2], 'down');
                break;

            case 'db:table:dump':
                return $this->tableDump($cmd[2]);
                break;

            case 'db:backup':
                return $this->backup();
                break;

            case 'db:restore':
                return $this->restore();
                break;

            case 'db:seed':
                return $this->seed();
                break;

            /****************************************************
             *                    Security                      *
             ***************************************************/

            case 'hash:encode':
                if (!isset($cmd[2])) {
                    die("hash:verify expects 1 parameter [data].\n");
                }
                return die(Hash::encode(trim($cmd[2], ' ')));
                break;

            case 'hash:verify':
                if (!isset($cmd[2]) || !isset($cmd[3])) {
                    die("too few arguments, hash:verify expects [data] and [hashed] value.\n");
                }
                return (Hash::verify($cmd[2], $cmd[3])) ? die("true") : die("false");
                break;

            case 'encryption:encode':
                if (isset($cmd[2]) && !isset($cmd[3])) {
                    return die(Encryption::encode($cmd[2]));
                } elseif (isset($cmd[2]) && isset($cmd[3])) {
                    return die(Encryption::encode($cmd[2], $cmd[3]));
                } else {
                    die("hash:verify requires 1 parameter [data], [levels] optional.\n");
                }
                break;

            case 'encryption:decode':
                if (isset($cmd[2]) && !isset($cmd[3])) {
                    return die(Encryption::decode($cmd[2]));
                } elseif (isset($cmd[2]) && isset($cmd[3])) {
                    return die(Encryption::decode($cmd[2], $cmd[3]));
                } else {
                    die("hash:verify requires 1 parameter [data], [levels] optional.\n");
                }
                break;

            default:
                die("error: unknown command '{$cmd[1]}' read documentation for info.\n");
                break;
        }

        return (true);
    }

    /**
     * Clear garbage files inside storage.
     *
     * @param $folder
     * @return boolean
     * @var $filename
     */
    private function clear($folder)
    {
        $container = storage_path() . $folder;

        try {
            $handle = new DirectoryIterator($container);

            foreach ($handle as $file):
                if ($file->getFilename() == '.' || $file->getFilename() == '..'):
                    continue;
                endif;
                if (is_file("{$container}/{$file->getFilename()}")):
                    unlink("{$container}/{$file->getFilename()}");
                endif;
            endforeach;

            return true;
        }
        catch (Exception $e) {
            return die($e->getMessage());
        }
    }

    /**
     * Create new model class
     *
     * @param $name
     * @param $table
     * @return string
     * @var $name
     * @var $data
     * @var $file
     * @var $container
     */
    private function createModel($name, $table)
    {
        $container = models_path();
        $data = <<<EOF
<?php namespace App\Models;

use Kernel\Database\QueryBuilder as Model;

/**
 * Class $name
 *
 * @package App\Models
 */
class {$name} extends Model
{
    protected static \$table = "{$table}";
}
EOF;

        if (file_exists("{$container}/{$name}.php")):
            return die("model '{$name}' already exists.\n");
        endif;

        $file = fopen("{$container}/{$name}.php", 'x');
        fwrite($file, $data);
        exec('composer dump-autoload');

        return die("'{$name}' model class created.\n");
    }

    /**
     * Create a new controller class
     * By default, second parameter is false
     * means, it will generate a class along
     * with predefined methods. If you want
     * to specify an empty class, use yamato
     * like this:
     * php yamato create:controller MyController true
     * the code above returns an empty class.
     *
     * @param $name
     * @param $option
     * @var $container
     * @var $name
     * @var $append
     * @var $methods
     * @var $data
     * @var $file
     */
    private function createController($name, $option = "false")
    {
        $container = controllers_path();
        $name = preg_replace('/controller/i', 'Controller', ucfirst($name));
        $append = <<<EOF

    /**
     * Controller Index
     *
     * @return mixed
     **/
    public function index()
    {

    }

    /**
     * Fetch resource
     *
     * @return mixed
     **/
    public function fetch()
    {

    }

    /**
     * Show all/a resource(s)
     *
     * @param \$id
     * @return mixed
     **/
    public function show(\$id)
	{

	}

    /**
     * Create a resource
     *
     * @return mixed
     * */
    public function create()
    {

    }

    /**
     * Store the resource
     *
     * @return mixed
     * */
    public function store()
    {

    }

    /**
     * Edit a resource
     *
     * @param \$id
     * @return mixed
     */
    public function edit(\$id)
    {

    }

    /**
     * update the resource
     *
     * @return mixed
     */
    public function update()
    {

    }

    /**
     * Destroy a resource
     *
     * @param \$id
     */
    public function destroy(\$id)
    {

    }

EOF;

        /**
         * if $option is 'empty', return an empty class
         */
        $methods = ($option == "true") ? '' : $append;

        $sub = preg_replace('/(.*)\/(.*)/', '$2', $name);
        $data = <<<EOF
<?php

class {$sub}
{
    {$methods}
}

EOF;

        if (file_exists("{$container}/{$name}.php")):
            return die("controller '{$name}' already exists.\n");
        endif;

        $file = fopen("{$container}/{$name}.php", 'x');
        fwrite($file, $data);

        return die("'{$sub}' class created.\n");
    }

    /**
     * Create a migration class
     *
     * @param $name
     * @param $table
     * @var $container
     * @var $name
     * @var $append
     * @var $methods
     * @var $data
     * @var $file
     */
    private function createMigration($name, $table)
    {
        $container = migrations_path();
        $name = preg_replace('/migration/i', 'Migration', ucfirst($name));
        $data = <<<EOF
<?php namespace App\Migrations;

use Kernel\Database\Migration;

class {$name} extends Migration
{

    /**
     * name of the table to migrate
     **/
    protected \$table = "{$table}";

    /**
     * field names and data types for this table
     */
    public function __construct()
    {
        \$this->increments('id');
    }

    /**
     * Install the migration
     *
     * @return boolean
     */
    public function up()
    {
        return \$this->install();
    }

    /**
     * Drop the table
     *
     * @return boolean
     */
    public function down()
    {
        return \$this->uninstall();
    }

}
EOF;

        if (file_exists("{$container}/{$name}.php")):
            return die("migration '{$name}' already exists.\n");
        endif;

        $file = fopen("{$container}/{$name}.php", 'x');
        fwrite($file, $data);
        exec('composer dump-autoload');

        return die("'{$name}' class created.\n");
    }

    /**
     * Create a request class
     *
     * @param $name
     * @var $container
     * @var $name
     * @var $append
     * @var $methods
     * @var $data
     * @var $file
     */
    private function createRequest($name)
    {
        $container = requests_path();
        $name = preg_replace('/request/i', 'Request', ucfirst($name));
        $data = <<<EOF
<?php namespace App\Requests;

use Kernel\Requests\HTTPRequest;

/**
 * Class $name
 *
 * @package App\Requests
 */
class {$name} extends HTTPRequest
{
    /**
     * Rules to be followed by request
     */
    protected \$rules = [];
}
EOF;

        if (file_exists("{$container}/{$name}.php")):
            return die("request '{$name}' already exists.\n");
        endif;

        $file = fopen("{$container}/{$name}.php", 'x');
        fwrite($file, $data);
        exec('composer dump-autoload');

        return die("'{$name}' class created.\n");
    }

    /**
     * @param $name
     * @param $model
     */
    private function createSeeder($name, $model)
    {
        if (!file_exists(models_path() . "$model.php")):
            return die("Model '$model' does not exist\n");
        endif;
        $container = seeders_path();
        $name = preg_replace('/seeder/i', 'Seeder', ucfirst($name));
        $model = ucfirst($model);
        $data = <<<EOF
<?php namespace App\Seeders;

use App\Models\\{$model};

/**
 * Class {$name}
 *
 * @package App\Seeders
 */
class {$name}
{
    /**
     * Seed the database table
     */
    public function __construct()
    {
        $model::insert([

        ]);
    }
}
EOF;

        if (file_exists("{$container}/{$name}.php")):
            return die("seeder '{$name}' already exists");
        endif;

        $file = fopen("{$container}/{$name}.php", 'x');
        fwrite($file, $data);
        exec('composer dump-autoload');

        return die("'{$name}' class created.\n");
    }

    /**
     * Install/Uninstall all migrations
     *
     * @param $action
     * @return mixed
     * @var $migration
     * @var $container
     */
    private function migrate($action)
    {
        $directory = migrations_path();

        try {
            $container = new DirectoryIterator($directory);
            $message = ($action == 'down') ? "database rolled back.\n" : "database successfully migrated.\n";

            foreach ($container as $handle) {
                if (is_file("{$directory}/{$handle->getFilename()}") && $handle->getFilename() !== '.htaccess') {
                    $migration = self::FixNamespace(MIGRATIONS_PATH, $handle->getBasename('.php'));
                    $migration = new $migration();
                    $migration->$action();
                }
            }

            return die($message);
        }
        catch (Exception $e) {
            return die($e->getMessage());
        }
    }

    /**
     * Backup database's current state
     *
     * @return string
     */
    private function backup()
    {
        $container = models_path();

        try {
            $iterator = new DirectoryIterator($container);

            foreach ($iterator as $handle):
                if (!is_file($container . $handle->getFilename())):
                    continue;
                endif;

                $model = self::FixNamespace(MODELS_PATH, $handle->getBasename('.php'));
                $model = new $model();
                $model->backup();
            endforeach;

            return die("Database tables backed up.\n");
        }
        catch (Exception $e) {
            return die($e->getMessage());
        }
    }

    /**
     * Restore last backed up table state
     *
     * @return string
     */
    private function restore()
    {
        $container = models_path();

        try {
            $iterator = new DirectoryIterator($container);

            foreach ($iterator as $handle):
                if (!is_file($container . $handle->getFilename())):
                    continue;
                endif;
                $model = self::FixNamespace(MODELS_PATH, $handle->getBasename('.php'));
                $model = new $model();
                $model->restore();
            endforeach;

            return die("Database restored.\n");
        }
        catch (Exception $e) {
            return die ($e->getMessage());
        }
    }

    /**
     * Perform database seeding
     *
     * @return string
     */
    private function seed()
    {
        $container = seeders_path();

        try {
            $iterator = new DirectoryIterator($container);

            foreach ($iterator as $handle):
                if (!is_file($container . $handle->getFilename())):
                    continue;
                endif;

                $seeder = self::FixNamespace(SEEDERS_PATH, $handle->getBasename('.php'));
                new $seeder();
            endforeach;

            return die("Seeding completed.\n");
        }
        catch (Exception $e) {
            return die($e->getMessage());
        }
    }

    /**
     * Install/Uninstall a migration table
     *
     * @param $className
     * @param $action
     * @return mixed
     */
    private function tableMigration($className, $action)
    {
        $filePath = migrations_path() . $className;

        if (file_exists($filePath . ".php")):
            $class = self::FixNamespace(MIGRATIONS_PATH, $className);
            if (class_exists($class)):
                $migration = new $class();
                $migration->$action();
                $message = ($action == 'down') ? "table rolled back.\n" : "table successfully migrated.\n";
            else:
                return die("'{$className}' class does not exist.\n");
            endif;
        else:
            return die("'{$className}' file does not exist.\n");
        endif;

        return die($message);
    }

    /**
     * Dumps data types of a migration class.
     * e.g. php yamato db:table:dump MigrationClassName
     *
     * @param $className
     * @return string
     */
    private function tableDump($className)
    {
        $filePath = migrations_path() . $className;

        if (file_exists($filePath . ".php")):
            $class = self::FixNamespace(MIGRATIONS_PATH, $className);
            if (class_exists($class)):
                $migration = new $class();
                return $migration->dump();
            else:
                return die("'{$className}' class does not exist.\n");
            endif;
        else:
            return die("'{$className}' file does not exist.\n");
        endif;
    }

    /**
     * This will fix any Namespacing coming from
     * a forward slash path as well as fixes any
     * non uppercase first letter.
     *
     *
     * @param $path
     * @param $class
     * @return string
     */
    private static function FixNamespace($path, $class)
    {
        $namespace = explode('/', trim($path, '/'));
        $container = null;

        foreach ($namespace as $dir):
            $container .= ucfirst($dir) . '\\';
        endforeach;

        return ($container . $class);
    }
}


text:
package org.apache.jena.tdb.setup;

import org.apache.jena.tdb.base.file.FileFactory ;
import org.apache.jena.tdb.base.file.FileSet ;
import org.apache.jena.tdb.base.objectfile.ObjectFile ;
import org.apache.jena.tdb.base.record.RecordFactory ;
import org.apache.jena.tdb.index.RangeIndex ;
import org.apache.jena.tdb.index.RangeIndexBuilder ;
import org.apache.jena.tdb.lib.ColumnMap ;
import org.apache.jena.tdb.store.tupletable.TupleIndex ;
import org.apache.jena.tdb.store.tupletable.TupleIndexRecord ;
import org.apache.jena.tdb.sys.SystemTDB ;

public class BuilderStdDB {

    public static class TupleIndexBuilderStd implements TupleIndexBuilder
    {
        private final RangeIndexBuilder rangeIndexBuilder ;

        public TupleIndexBuilderStd(RangeIndexBuilder rangeIndexBuilder) {
            this.rangeIndexBuilder = rangeIndexBuilder ;
        }

        @Override
        public TupleIndex buildTupleIndex(FileSet fileSet, ColumnMap colMap, String name, StoreParams params) {
            RecordFactory recordFactory = new RecordFactory(SystemTDB.SizeOfNodeId * colMap.length(), 0) ;

            RangeIndex rIdx = rangeIndexBuilder.buildRangeIndex(fileSet, recordFactory, params) ;
            TupleIndex tIdx = new TupleIndexRecord(colMap.length(), colMap, name, recordFactory, rIdx) ;
            return tIdx ;
        }
    }

    public static class ObjectFileBuilderStd implements ObjectFileBuilder
    {
        public ObjectFileBuilderStd() { }

        @Override
        public ObjectFile buildObjectFile(FileSet fileSet, String ext)
        {
            String filename = fileSet.filename(ext) ;
            if ( fileSet.isMem() )
                return FileFactory.createObjectFileMem(filename) ;
            return FileFactory.createObjectFileDisk(filename) ;
        }
    }

}


text:
package com.wepay.model.data;
import java.math.BigDecimal;

public class AccountBalancesObjectData {

	public String currency;
	public BigDecimal balance;
	public BigDecimal incomingPendingAmount;
	public BigDecimal outgoingPendingAmount;
	public BigDecimal reservedAmount;
	public BigDecimal disputedAmount;
	public String withdrawalPeriod;
	public Long withdrawalNextTime;
	public String withdrawalBankName;
	public String withdrawalType;
}


text:
layout: post
date: '2015-12-07'
title: "COCKTAIL DRESSES Short Layer Chiffon Sweetheart Neck Prom Dress"
category: COCKTAIL DRESSES
tags: [COCKTAIL DRESSES]
---
### COCKTAIL DRESSES Short Layer Chiffon Sweetheart Neck Prom Dress
Just **$419.99**
###

Buy it: [https://www.eudances.com/en/cocktail-dresses/1299-short-layer-chiffon-sweetheart-neck-prom-dress.html](https://www.eudances.com/en/cocktail-dresses/1299-short-layer-chiffon-sweetheart-neck-prom-dress.html)


text:
layout: post
title: Microsoft MVP Award for Windows Platform Development
excerpt:
tags:
comments: true
---

I am thankful to Microsoft for renewing my MVP in the Windows Platform Development expertise. You may be asking yourself "What is the Windows Platform Development expertise?" Basically the Client Development and Windows Phone Development expertise merged into Windows Platform Development. So this means that I get to talk about everything that I'm already passionate about and it fits nicely in this new category!     I'd like to thank my family my employer (Telerik) and my MVP Lead (Dora Chan) who all believed in me and helped me pursue my dreams.     I look forward to doing even more in the upcoming future!


text:
package com.facebook.buck.shell;

import com.facebook.buck.android.toolchain.AndroidTools;
import com.facebook.buck.core.cell.CellPathResolver;
import com.facebook.buck.core.description.arg.BuildRuleArg;
import com.facebook.buck.core.description.arg.HasTests;
import com.facebook.buck.core.description.attr.ImplicitDepsInferringDescription;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.TargetConfiguration;
import com.facebook.buck.core.model.targetgraph.TargetGraph;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleCreationContextWithTargetGraph;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.BuildRuleResolver;
import com.facebook.buck.core.rules.DescriptionWithTargetGraph;
import com.facebook.buck.core.rules.common.BuildableSupport;
import com.facebook.buck.core.toolchain.ToolchainProvider;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.coercer.SourceSet;
import com.facebook.buck.rules.macros.ClasspathAbiMacroExpander;
import com.facebook.buck.rules.macros.ClasspathMacroExpander;
import com.facebook.buck.rules.macros.ExecutableMacro;
import com.facebook.buck.rules.macros.ExecutableMacroExpander;
import com.facebook.buck.rules.macros.ExecutableTargetMacro;
import com.facebook.buck.rules.macros.LocationMacroExpander;
import com.facebook.buck.rules.macros.Macro;
import com.facebook.buck.rules.macros.MacroContainer;
import com.facebook.buck.rules.macros.MacroExpander;
import com.facebook.buck.rules.macros.MavenCoordinatesMacroExpander;
import com.facebook.buck.rules.macros.QueryOutputsMacroExpander;
import com.facebook.buck.rules.macros.QueryPathsMacroExpander;
import com.facebook.buck.rules.macros.QueryTargetsAndOutputsMacroExpander;
import com.facebook.buck.rules.macros.QueryTargetsMacroExpander;
import com.facebook.buck.rules.macros.StringWithMacros;
import com.facebook.buck.rules.macros.StringWithMacrosConverter;
import com.facebook.buck.rules.macros.WorkerMacro;
import com.facebook.buck.rules.macros.WorkerMacroArg;
import com.facebook.buck.rules.macros.WorkerMacroExpander;
import com.facebook.buck.sandbox.SandboxExecutionStrategy;
import com.facebook.buck.util.stream.RichStream;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import java.util.Comparator;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;
import org.immutables.value.Value;

public abstract class AbstractGenruleDescription<T extends AbstractGenruleDescription.CommonArg>
    implements DescriptionWithTargetGraph<T>, ImplicitDepsInferringDescription<T> {

  protected final ToolchainProvider toolchainProvider;
  protected final SandboxExecutionStrategy sandboxExecutionStrategy;
  protected final boolean enableSandbox;

  protected AbstractGenruleDescription(
      ToolchainProvider toolchainProvider,
      SandboxExecutionStrategy sandboxExecutionStrategy,
      boolean enableSandbox) {
    this.toolchainProvider = toolchainProvider;
    this.sandboxExecutionStrategy = sandboxExecutionStrategy;
    this.enableSandbox = enableSandbox;
  }

  protected abstract BuildRule createBuildRule(
      BuildTarget buildTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleParams params,
      ActionGraphBuilder graphBuilder,
      T args,
      Optional<Arg> cmd,
      Optional<Arg> bash,
      Optional<Arg> cmdExe);

  protected BuildRule createBuildRule(
      BuildTarget buildTarget,
      ProjectFilesystem projectFilesystem,
      BuildRuleResolver resolver,
      T args,
      Optional<Arg> cmd,
      Optional<Arg> bash,
      Optional<Arg> cmdExe,
      Optional<String> outputFileName,
      Optional<ImmutableMap<String, ImmutableList<String>>> outputFileNames) {
    return new Genrule(
        buildTarget,
        projectFilesystem,
        resolver,
        sandboxExecutionStrategy,
        args.getSrcs(),
        cmd,
        bash,
        cmdExe,
        args.getType(),
        outputFileName,
        outputFileNames,
        args.getEnableSandbox().orElse(enableSandbox),
        args.getCacheable().orElse(true),
        args.getEnvironmentExpansionSeparator(),
        getAndroidToolsOptional(args, buildTarget.getTargetConfiguration()),
        false);
  }

  /**
   * Returns android tools if {@code args} has need_android_tools option set or empty optional
   * otherwise.
   */
  protected Optional<AndroidTools> getAndroidToolsOptional(
      T args, TargetConfiguration toolchainTargetConfiguration) {
    return args.isNeedAndroidTools()
        ? Optional.of(AndroidTools.getAndroidTools(toolchainProvider, toolchainTargetConfiguration))
        : Optional.empty();
  }

  /**
   * @return the {@link com.facebook.buck.rules.macros.MacroExpander}s which apply to the macros in
   *     this description.
   */
  protected Optional<ImmutableList<MacroExpander<? extends Macro, ?>>> getMacroHandler(
      @SuppressWarnings("unused") BuildTarget buildTarget,
      @SuppressWarnings("unused") ProjectFilesystem filesystem,
      @SuppressWarnings("unused") BuildRuleResolver resolver,
      TargetGraph targetGraph,
      @SuppressWarnings("unused") T args) {
    return Optional.of(
        ImmutableList.of(
            new ClasspathMacroExpander(),
            new ClasspathAbiMacroExpander(),
            new ExecutableMacroExpander<>(ExecutableMacro.class),
            new ExecutableMacroExpander<>(ExecutableTargetMacro.class),
            new WorkerMacroExpander(),
            new LocationMacroExpander(),
            new MavenCoordinatesMacroExpander(),
            new QueryTargetsMacroExpander(Optional.of(targetGraph)),
            new QueryOutputsMacroExpander(Optional.of(targetGraph)),
            new QueryPathsMacroExpander(Optional.of(targetGraph)),
            new QueryTargetsAndOutputsMacroExpander(Optional.of(targetGraph))));
  }

  @Override
  public BuildRule createBuildRule(
      BuildRuleCreationContextWithTargetGraph context,
      BuildTarget buildTarget,
      BuildRuleParams params,
      T args) {
    ActionGraphBuilder graphBuilder = context.getActionGraphBuilder();
    Optional<ImmutableList<MacroExpander<? extends Macro, ?>>> maybeExpanders =
        getMacroHandler(
            buildTarget,
            context.getProjectFilesystem(),
            graphBuilder,
            context.getTargetGraph(),
            args);
    if (maybeExpanders.isPresent()) {
      ImmutableList<MacroExpander<? extends Macro, ?>> expanders = maybeExpanders.get();
      StringWithMacrosConverter converter =
          StringWithMacrosConverter.of(
              buildTarget, context.getCellPathResolver(), graphBuilder, expanders);
      Function<StringWithMacros, Arg> toArg =
          str -> {
            Arg arg = converter.convert(str);
            if (RichStream.from(str.getMacros())
                .map(MacroContainer::getMacro)
                .anyMatch(WorkerMacro.class::isInstance)) {
              arg = WorkerMacroArg.fromStringWithMacros(arg, buildTarget, graphBuilder, str);
            }
            return arg;
          };
      Optional<Arg> cmd = args.getCmd().map(toArg);
      Optional<Arg> bash = args.getBash().map(toArg);
      Optional<Arg> cmdExe = args.getCmdExe().map(toArg);
      return createBuildRule(
          buildTarget,
          context.getProjectFilesystem(),
          params.withExtraDeps(
              Stream.concat(
                      graphBuilder.filterBuildRuleInputs(args.getSrcs().getPaths()).stream(),
                      Stream.of(cmd, bash, cmdExe)
                          .flatMap(RichStream::from)
                          .flatMap(input -> BuildableSupport.getDeps(input, graphBuilder)))
                  .collect(ImmutableSortedSet.toImmutableSortedSet(Comparator.naturalOrder()))),
          graphBuilder,
          args,
          cmd,
          bash,
          cmdExe);
    }
    return createBuildRule(
        buildTarget,
        context.getProjectFilesystem(),
        params,
        graphBuilder,
        args,
        Optional.empty(),
        Optional.empty(),
        Optional.empty());
  }

  @Override
  public void findDepsForTargetFromConstructorArgs(
      BuildTarget buildTarget,
      CellPathResolver cellRoots,
      T constructorArg,
      ImmutableCollection.Builder<BuildTarget> extraDepsBuilder,
      ImmutableCollection.Builder<BuildTarget> targetGraphOnlyDepsBuilder) {
    if (constructorArg.isNeedAndroidTools()) {
      AndroidTools.addParseTimeDepsToAndroidTools(
          toolchainProvider, buildTarget, targetGraphOnlyDepsBuilder);
    }
  }

  @SuppressFieldNotInitialized
  public interface CommonArg extends BuildRuleArg, HasTests {
    Optional<StringWithMacros> getBash();

    Optional<StringWithMacros> getCmd();

    Optional<StringWithMacros> getCmdExe();

    Optional<String> getType();

    @Value.Default
    default SourceSet getSrcs() {
      return SourceSet.EMPTY;
    }

    Optional<Boolean> getEnableSandbox();

    Optional<String> getEnvironmentExpansionSeparator();

    /**
     * If present and true, requests that Buck run this genrule remotely if possible. Defaults to
     * false for now.
     */
    Optional<Boolean> getRemote();

    /**
     * This functionality only exists to get around the lack of extensibility in our current build
     * rule / build file apis. It may go away at some point. Also, make sure that you understand
     * what {@link BuildRule#isCacheable} does with respect to caching if you decide to use this
     * attribute
     */
    Optional<Boolean> getCacheable();

    /**
     * This argument allows genrule to specify if it needs android tools (like dex, aapt, ndk, sdk).
     */
    @Value.Default
    default boolean isNeedAndroidTools() {
      return false;
    }
  }
}


text:
import urllib.request
import chardet
import sys
import codecs
from html.parser import HTMLParser

lentaUrl = 'http://lenta.ru/'
starTag = 'b-yellow-box__header bordered-title'
endTag = 'b-sidebar-sticky'
newsTag = 'a'
classTag = 'class'
separator = '---------------------------------------------------------------------------------------'
news = []

class MyHTMLParser(HTMLParser):

    def __init__(self):
        HTMLParser.__init__(self)
        self.readData = False
        self.weAreIn = False

    def handle_starttag(self, tag, attrs):
        for attr in attrs:
            if attr[0] == classTag:
                if attr[1] == starTag:
                    self.weAreIn = True
                if attr[1] == endTag:
                    self.weAreIn = False
        if tag == newsTag and self.weAreIn == True:
            news.append(separator)
            self.readData = True
        else:
            self.readData = False

    def handle_data(self, data):
        if self.readData:
            news.append(data)

def proceed():
    request = urllib.request.urlopen(lentaUrl)
    content = request.read()

    encoding = chardet.detect(content)['encoding']
    print('Encoding of the website: ' + str(encoding))
    print('Encoding of the console: ' + str(sys.stdout.encoding))

    html = content.decode('utf-8', errors='replace')
    parser = MyHTMLParser()
    parser.feed(html)

def show():
    finalOutput = []
    tempword = ' '
    for word in news:
        if word == separator:
           finalOutput.append(tempword)
           finalOutput.append(separator)
           tempword = ' '
        else:
            tempword = tempword + ' '  + word
    for f in finalOutput:
        bytes = str.encode(f)
        toPrint = bytes.decode('utf-8', errors='replace')
        print (toPrint)

print ("LENTA NEWS:")

try:
    proceed()
    show()
except Exception as e:
    print ("Error " + str(e.errno) + ' ' + str(e.strerror))

print ("")
input("Press Enter To Exit")


text:
If you don't yet know what BSON actually is, read [the spec](http://bsonspec.org).

This package can be used to serialize JSON documents into the BSON format or the other way around. If you want to use it within the browser, give [browserify](https://github.com/substack/node-browserify) a try (it will help you add this package to your bundle). The current build is located in the `browser_build/bson.js` file.

A simple example of how to use BSON in the browser:

```html
<script src="./browser_build/bson.js"></script>

<script>
  function start() {
    var BSON = bson().BSON
    var Long = bson().Long

    var doc = { long: Long.fromNumber(100) }

    // Serialize a document
    var data = BSON.serialize(doc, false, true, false)
    // De serialize it again
    var doc_2 = BSON.deserialize(data)
  }
</script>
```

A simple example of how to use BSON in `node.js`:

```js
var bson = require('bson')
var BSON = new bson.BSONPure.BSON()
var Long = bson.BSONPure.Long

var doc = { long: Long.fromNumber(100) }

// Serialize a document
var data = BSON.serialize(doc, false, true, false)
console.log('data:', data)

// Deserialize the resulting Buffer
var doc_2 = BSON.deserialize(data)
console.log('doc_2:', doc_2)
```

## API

The API consists of two simple methods to serialize/deserialize objects to/from BSON format:
=======
## Installation

`npm install bson`

## API

### BSON serialization and deserialiation

**`new bson.BSONPure.BSON()`** - Creates a new BSON seralizer/deserializer you can use to serialize and deserialize BSON.

  * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions)
     * @param {Object} object the Javascript object to serialize.
     * @param {Boolean} checkKeys the serializer will check if keys are valid.
     * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**.
     * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**
     * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports

  * BSON.deserialize(buffer, options, isArray)
     * Options
       * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized.
       * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse.
       * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function.
       * **promoteBuffers** {Boolean, default:false}, deserialize Binary data directly into node.js Buffer object.
     * @param {TypedArray/Array} a TypedArray/Array containing the BSON data
     * @param {Object} [options] additional options used for the deserialization.
     * @param {Boolean} [isArray] ignore used for recursive parsing.
     * @return {Object} returns the deserialized Javascript Object.

### ObjectId

**`bson.ObjectId.isValid(id)`** - Returns true if `id` is a valid number or hexadecimal string representing an ObjectId.
**`bson.ObjectId.createFromHexString(hexString)`** - Returns the ObjectId the `hexString` represents.
**`bson.ObjectId.createFromTime(time)`** - Returns an ObjectId containing the passed time.
* `time` - A Unix timestamp (number of seconds since the epoch).

**`var objectId = new bson.ObjectId(id)`** - Creates a new `ObjectId`.
* `id` - Must either be a 24-character hex string or a 12 byte binary string.

**`objectId.toJSON()`**
**`objectId.toString()`**
**`objectId.toHexString()`** - Returns a hexadecimal string representation of the ObjectId.

**`objectId.equals(otherObjectId)`** - Returns true if the ObjectIds are the same, false otherwise.

**`objectId.getTimestamp()`** - Returns a `Date` object containing the time the objectId was created for.

**`objectId.getTimestamp()`** - Returns a `Date` object containing the time the objectId contains.


text:
module Arel
  module Visitors
    class OrderClauses < Arel::Visitors::ToSql
      private

      def visit_Arel_Nodes_SelectStatement o, a
        o.orders.map { |x| visit x, a }
      end
    end
  end
end


text:
//-----------------------------------------------------------------------
// <copyright file="ProductItem.cs" company="Sitecore Corporation">
//     Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
//-----------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------

namespace Sitecore.Commerce.Storefront.Models
{
    using Sitecore.Data.Items;

    /// <summary>
    /// Used to represent a product item
    /// </summary>
    public class ProductItem : IImageEntity
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ProductItem" /> class
        /// </summary>
        /// <param name="sitecoreItem">The sitecore item to initialize the product item with</param>
        public ProductItem(Item sitecoreItem)
        {
            _item = sitecoreItem;
        }

        /// <summary>
        /// Gets the item the product is based on
        /// </summary>
        public Item Item
        {
            get { return _item; }
        }

        /// <summary>
        /// Gets or sets the Product ImageFileName.
        /// </summary>
        public string ImageFilename
        {
            get
            {
                return Item["Image_filename"];
            }

            set
            {
                Item["Image_filename"] = value;
            }
        }

        private Item _item { get; set; }
    }
}


text:
package batch.model.domain;

import static org.apache.commons.lang.time.DateUtils.addMonths;
import static org.apache.commons.lang.time.DateUtils.addWeeks;
import static org.apache.commons.lang.time.DateUtils.addYears;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import batch.util.DateUtils;

public class DateRange extends ValueRange<Date> {

	private Date min;

	private Date max;

	protected DateRange() {
	}

	public static DateRange createWeek(Date start) {
		Date end = addWeeks(start, 1);
		return new DateRange(start, end);
	}

	public static DateRange createMonthMinusThree(Date start) {
        Date end = addMonths(start, 1);
        // set startdate 3 months in past
        start = addMonths(start, -3);
        return new DateRange(start, end);
    }

	public static DateRange createMonth(Date start) {
		Date end = addMonths(start, 1);
		return new DateRange(start, end);
	}

	public static DateRange createYear(Date start) {
		Date end = addYears(start, 1);
		return new DateRange(start, end);
	}

	public DateRange(Date min, Date max) {
		validateNotNull(min);
		validateMaxLargerThanMin(min, max);
		this.min = DateUtils.truncateTimeStamp(min);
		this.max = DateUtils.truncateTimeStamp(max);
	}

	@Override
	public Date getMin() {
		return (Date) min.clone();
	}

	public void setMin(Date min) {
		validateNotNull(min);
		validateMaxLargerThanMin(min, getMax());
		this.min = DateUtils.truncateTimeStamp(min);
		;
	}

	@Override
	public Date getMax() {
		return max;
	}

	public void setMax(Date max) {
		validateMaxLargerThanMin(getMin(), max);
		this.max = DateUtils.truncateTimeStamp(max);
	}

	@Override
	public int compareTo(ValueRange<Date> other) {
		int result = DateUtils.compareDates(min, other.getMin());
		if (result == 0) {
			result = DateUtils.compareDates(max, other.getMax());
		}
		return result;
	}

	public boolean isOverlapping(DateRange other) {
		if (DateUtils.compareDates(min, other.getMin()) < 0) {
			return DateUtils.compareDates(max, other.getMin()) > 0;
		} else if (DateUtils.compareDates(min, other.getMin()) > 0) {
			return DateUtils.compareDates(other.getMax(), min) > 0;
		} else {
			return true;
		}
	}

	private void validateNotNull(Date date) {
		if (date == null) {
			throw new IllegalArgumentException("Date must not be null");
		}
	}

	private void validateMaxLargerThanMin(Date min, Date max) {
		if (!(DateUtils.compareDatesWithoutTime(min, max) < 0)) {
			throw new IllegalArgumentException(max + " must be null or larger than " + min);
		}
	}

	@Override
	public String getFormattedRange() {
		return DateUtils.format(getMin()) + " - " + DateUtils.format(getMax());
	}

	@Override
	public boolean contains(Date day) {
		return DateUtils.compareDates(getMin(), day) <= 0 && DateUtils.compareDates(getMax(), day) > 0;
	}

	public List<Date> getCoveredDays() {
		List<Date> result = new ArrayList<Date>();
		if (getMax() != null) {
			for (Date date = getMin(); date.before(getMax()); date = org.apache.commons.lang.time.DateUtils.addDays(date, 1)) {
				result.add(date);
			}
		}
		return result;
	}
}


text:
define([
    'Utils/CheckType',
    'backbone',
    'Utils/PromiseChain',
    'Domain/Collection'
], function(
    checkType,
    Backbone,
    PromiseChain,
    Collection
){
    var Playset = Backbone.Model.extend({
        defaults: {
            mix: 'default'
        },
        _collection: new Collection(),

        getCollection: function() {
            return this._collection;
        },

        set: function(domain) {
            this.reset();
            this.add(domain);
        },

        add: function(domain) {
            if (!checkType.obj(domain)) {
                throw new Error('Attempt to add non-object to Playset.');
            }

            this._collection.addDomainUnique(domain);

            return this;
        },

        reset: function() {
            this._collection.reset();
            this.trigger('reset');

            return this;
        },

        getNextTrack: function() {
            //TODO: get artist's track, etc.
            var domain = this._collection.getDomains()[Math.floor(Math.random() * this._collection.length)];

            if (!domain) {
                return Promise.reject();
            }

            switch (domain['domain']) {
                case 'artist':
                    return new PromiseChain()
                        .then(function() {
                            console.log('........Playset.getTopTracks');
                            return domain.getTopTracks();
                        })
                        .then(returnOneFromCollection)
                    ;
                case 'album':
                    return domain.getTracks().then(returnOneFromCollection);
                case 'track':
                    return Promise.resolve(domain);
                default:
                    return Promise.reject();
            }
        }
    });

    function returnOneFromCollection(collection) {
        console.log('........Playset.returnOneFromCollection');

        if (!collection.length) {
            return Promise.reject();
        }

        var track = collection.at([Math.floor(Math.random() * collection.length)]).get('domain');

        return Promise.resolve(track);
    }

    return Playset;
});


text:
package jp.fieldnotes.hatunatu.dao.annotation.tiger;

import java.lang.annotation.*;

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.METHOD, ElementType.FIELD })
public @interface ProcedureParameter {

    /** パラメータのタイプ */
    ParameterType value() default ParameterType.IN;
}


text:
package com.opengamma.strata.pricer.index;

import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.market.sensitivity.PointSensitivities;
import com.opengamma.strata.market.sensitivity.PointSensitivityBuilder;
import com.opengamma.strata.pricer.rate.RateComputationFn;
import com.opengamma.strata.pricer.rate.RatesProvider;
import com.opengamma.strata.product.index.ResolvedOvernightFuture;
import com.opengamma.strata.product.rate.RateComputation;

/**
 * Pricer for for Overnight rate future products.
 *

 * This function provides the ability to price a {@link ResolvedOvernightFuture}.
 *
 *
Price

 * The price of an Overnight rate future is based on the interest rate of the underlying index.
 * It is defined as {@code (100 - percentRate)}.
 *

 * Strata uses decimal prices for Overnight rate futures in the trade model, pricers and market data.
 * The decimal price is based on the decimal rate equivalent to the percentage.
 * For example, a price of 99.32 implies an interest rate of 0.68% which is represented in Strata by 0.9932.
 */
public class DiscountingOvernightFutureProductPricer {

  /**
   * Default implementation.
   */
  public static final DiscountingOvernightFutureProductPricer DEFAULT =
      new DiscountingOvernightFutureProductPricer(RateComputationFn.standard());

  /**
   * Rate computation.
   */
  private final RateComputationFn<RateComputation> rateComputationFn;

  /**
   * Creates an instance.
   *
   * @param rateComputationFn  the rate computation function
   */
  public DiscountingOvernightFutureProductPricer(RateComputationFn<RateComputation> rateComputationFn) {
    this.rateComputationFn = ArgChecker.notNull(rateComputationFn, "rateComputationFn");
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the number related to Overnight rate futures product on which the daily margin is computed.
   *

   * For two consecutive settlement prices C1 and C2, the daily margin is computed as
   *    {@code (marginIndex(future, C2) - marginIndex(future, C1))}.
   *
   * @param future  the future
   * @param price  the price of the product, in decimal form
   * @return the index
   */
  double marginIndex(ResolvedOvernightFuture future, double price) {
    return price * future.getNotional() * future.getAccrualFactor();
  }

  /**
   * Calculates the margin index sensitivity of the Overnight rate future product.
   *

   * The margin index sensitivity is the sensitivity of the margin index to the underlying curves.
   * For two consecutive settlement prices C1 and C2, the daily margin is computed as
   *    {@code (marginIndex(future, C2) - marginIndex(future, C1))}.
   *
   * @param future  the future
   * @param priceSensitivity  the price sensitivity of the product
   * @return the index sensitivity
   */
  PointSensitivities marginIndexSensitivity(ResolvedOvernightFuture future, PointSensitivities priceSensitivity) {
    return priceSensitivity.multipliedBy(future.getNotional() * future.getAccrualFactor());
  }

  //-------------------------------------------------------------------------
  /**
   * Calculates the price of the Overnight rate future product.
   *

   * The price of the product is the price on the valuation date.
   *
   * @param future  the future
   * @param ratesProvider  the rates provider
   * @return the price of the product, in decimal form
   */
  public double price(ResolvedOvernightFuture future, RatesProvider ratesProvider) {
    double forwardRate = rateComputationFn.rate(
        future.getOvernightRate(),
        future.getOvernightRate().getStartDate(),
        future.getOvernightRate().getEndDate(),
        ratesProvider);
    return 1d - forwardRate;
  }

  /**
   * Calculates the price sensitivity of the Overnight rate future product.
   *

   * The price sensitivity of the product is the sensitivity of the price to the underlying curves.
   *
   * @param future  the future
   * @param ratesProvider  the rates provider
   * @return the price curve sensitivity of the product
   */
  public PointSensitivities priceSensitivity(ResolvedOvernightFuture future, RatesProvider ratesProvider) {

    PointSensitivityBuilder forwardRateSensitivity = rateComputationFn.rateSensitivity(
        future.getOvernightRate(),
        future.getOvernightRate().getStartDate(),
        future.getOvernightRate().getEndDate(),
        ratesProvider);
    // The sensitivity should be to no currency or currency XXX. To avoid useless conversion, the dimension-less
    // price sensitivity is reported in the future currency.
    return forwardRateSensitivity.build().multipliedBy(-1d);
  }

}


text:
import classnames from "../classnames"
import annotationMapper from "./Type"
import ConnectorLine from "../Connector/ConnectorLine"

export default function AnnotationCallout(props) {
  const className = classnames("callout", props.className)
  return annotationMapper({ ...props, className }, ConnectorLine, {
    lineType: "horizontal"
  })
}