text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<language alias="es" intName="Spanish" localName="español" lcid="10" culture="es-ES">
  <creator>
    <name>The Umbraco community</name>
    <link>http://our.umbraco.org/documentation/Extending-Umbraco/Language-Files</link>
  </creator>
  <area alias="labels">
    <key alias="version">Versión</key>
  </area>
</language>

redpajama_set_name: RedPajamaGithub


text:
#include "ABI44_0_0BaseTextShadowNode.h"

#include <ABI44_0_0React/ABI44_0_0renderer/components/text/RawTextProps.h>
#include <ABI44_0_0React/ABI44_0_0renderer/components/text/RawTextShadowNode.h>
#include <ABI44_0_0React/ABI44_0_0renderer/components/text/TextProps.h>
#include <ABI44_0_0React/ABI44_0_0renderer/components/text/TextShadowNode.h>
#include <ABI44_0_0React/ABI44_0_0renderer/mounting/ShadowView.h>

namespace ABI44_0_0facebook {
namespace ABI44_0_0React {

inline ShadowView shadowViewFromShadowNode(ShadowNode const &shadowNode) {
  auto shadowView = ShadowView{shadowNode};
  // Clearing `props` and `state` (which we don't use) allows avoiding retain
  // cycles.
  shadowView.props = nullptr;
  shadowView.state = nullptr;
  return shadowView;
}

void BaseTextShadowNode::buildAttributedString(
    TextAttributes const &baseTextAttributes,
    ShadowNode const &parentNode,
    AttributedString &outAttributedString,
    Attachments &outAttachments) {
  for (auto const &childNode : parentNode.getChildren()) {
    // RawShadowNode
    auto rawTextShadowNode =
        std::dynamic_pointer_cast<RawTextShadowNode const>(childNode);
    if (rawTextShadowNode) {
      auto fragment = AttributedString::Fragment{};
      fragment.string = rawTextShadowNode->getConcreteProps().text;
      fragment.textAttributes = baseTextAttributes;

      // Storing a retaining pointer to `ParagraphShadowNode` inside
      // `attributedString` causes a retain cycle (besides that fact that we
      // don't need it at all). Storing a `ShadowView` instance instead of
      // `ShadowNode` should properly fix this problem.
      fragment.parentShadowView = shadowViewFromShadowNode(parentNode);
      outAttributedString.appendFragment(fragment);
      continue;
    }

    // TextShadowNode
    auto textShadowNode =
        std::dynamic_pointer_cast<TextShadowNode const>(childNode);
    if (textShadowNode) {
      auto localTextAttributes = baseTextAttributes;
      localTextAttributes.apply(
          textShadowNode->getConcreteProps().textAttributes);
      buildAttributedString(
          localTextAttributes,
          *textShadowNode,
          outAttributedString,
          outAttachments);
      continue;
    }

    // Any *other* kind of ShadowNode
    auto fragment = AttributedString::Fragment{};
    fragment.string = AttributedString::Fragment::AttachmentCharacter();
    fragment.parentShadowView = shadowViewFromShadowNode(*childNode);
    fragment.textAttributes = baseTextAttributes;
    outAttributedString.appendFragment(fragment);
    outAttachments.push_back(Attachment{
        childNode.get(), outAttributedString.getFragments().size() - 1});
  }
}

} // namespace ABI44_0_0React
} // namespace ABI44_0_0facebook


text:
package org.elasticsearch.action.admin.indices.settings.put;

import org.elasticsearch.ElasticsearchGenerationException;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.AcknowledgedRequest;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.action.ValidateActions.addValidationError;
import static org.elasticsearch.common.settings.Settings.readSettingsFromStream;
import static org.elasticsearch.common.settings.Settings.writeSettingsToStream;
import static org.elasticsearch.common.settings.Settings.Builder.EMPTY_SETTINGS;

/**
 * Request for an update index settings action
 */
public class UpdateSettingsRequest extends AcknowledgedRequest<UpdateSettingsRequest>
        implements IndicesRequest.Replaceable, ToXContentObject {

    private String[] indices;
    private IndicesOptions indicesOptions = IndicesOptions.fromOptions(false, false, true, true);
    private Settings settings = EMPTY_SETTINGS;
    private boolean preserveExisting = false;

    public UpdateSettingsRequest(StreamInput in) throws IOException {
        super(in);
        indices = in.readStringArray();
        indicesOptions = IndicesOptions.readIndicesOptions(in);
        settings = readSettingsFromStream(in);
        preserveExisting = in.readBoolean();
    }

    public UpdateSettingsRequest() {
    }

    /**
     * Constructs a new request to update settings for one or more indices
     */
    public UpdateSettingsRequest(String... indices) {
        this.indices = indices;
    }

    /**
     * Constructs a new request to update settings for one or more indices
     */
    public UpdateSettingsRequest(Settings settings, String... indices) {
        this.indices = indices;
        this.settings = settings;
    }

    @Override
    public ActionRequestValidationException validate() {
        ActionRequestValidationException validationException = null;
        if (settings.isEmpty()) {
            validationException = addValidationError("no settings to update", validationException);
        }
        return validationException;
    }

    @Override
    public String[] indices() {
        return indices;
    }

    public Settings settings() {
        return settings;
    }

    /**
     * Sets the indices to apply to settings update to
     */
    @Override
    public UpdateSettingsRequest indices(String... indices) {
        this.indices = indices;
        return this;
    }

    @Override
    public IndicesOptions indicesOptions() {
        return indicesOptions;
    }

    public UpdateSettingsRequest indicesOptions(IndicesOptions indicesOptions) {
        this.indicesOptions = indicesOptions;
        return this;
    }

    /**
     * Sets the settings to be updated
     */
    public UpdateSettingsRequest settings(Settings settings) {
        this.settings = settings;
        return this;
    }

    /**
     * Sets the settings to be updated
     */
    public UpdateSettingsRequest settings(Settings.Builder settings) {
        this.settings = settings.build();
        return this;
    }

    /**
     * Sets the settings to be updated (either json or yaml format)
     */
    public UpdateSettingsRequest settings(String source, XContentType xContentType) {
        this.settings = Settings.builder().loadFromSource(source, xContentType).build();
        return this;
    }

    /**
     * Returns true iff the settings update should only add but not update settings. If the setting already exists
     * it should not be overwritten by this update. The default is false
     */
    public boolean isPreserveExisting() {
        return preserveExisting;
    }

    /**
     * Iff set to true this settings update will only add settings not already set on an index. Existing settings remain
     * unchanged.
     */
    public UpdateSettingsRequest setPreserveExisting(boolean preserveExisting) {
        this.preserveExisting = preserveExisting;
        return this;
    }

    /**
     * Sets the settings to be updated (either json or yaml format)
     */
    public UpdateSettingsRequest settings(Map<String, ?> source) {
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
            builder.map(source);
            settings(Strings.toString(builder), builder.contentType());
        } catch (IOException e) {
            throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
        }
        return this;
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeStringArrayNullable(indices);
        indicesOptions.writeIndicesOptions(out);
        writeSettingsToStream(settings, out);
        out.writeBoolean(preserveExisting);
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        settings.toXContent(builder, params);
        builder.endObject();
        return builder;
    }

    public UpdateSettingsRequest fromXContent(XContentParser parser) throws IOException {
        Map<String, Object> settings = new HashMap<>();
        Map<String, Object> bodySettings = parser.map();
        Object innerBodySettings = bodySettings.get("settings");
        // clean up in case the body is wrapped with "settings" : { ... }
        if (innerBodySettings instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> innerBodySettingsMap = (Map<String, Object>) innerBodySettings;
            settings.putAll(innerBodySettingsMap);
        } else {
            settings.putAll(bodySettings);
        }
        return this.settings(settings);
    }

    @Override
    public String toString() {
        return "indices : " + Arrays.toString(indices) + "," + Strings.toString(this);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        UpdateSettingsRequest that = (UpdateSettingsRequest) o;
        return masterNodeTimeout.equals(that.masterNodeTimeout)
                && timeout.equals(that.timeout)
                && Objects.equals(settings, that.settings)
                && Objects.equals(indicesOptions, that.indicesOptions)
                && Objects.equals(preserveExisting, that.preserveExisting)
                && Arrays.equals(indices, that.indices);
    }

    @Override
    public int hashCode() {
        return Objects.hash(masterNodeTimeout, timeout, settings, indicesOptions, preserveExisting, Arrays.hashCode(indices));
    }

}


text:
<PackageItem xmlns:tcm="http://www.tridion.com/ContentManager/5.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.sdltridion.com/ContentManager/ImportExport/Package/2013">
  <Data>
    <tcm:Data xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <tcm:Title>Fishing Reel</tcm:Title>
      <tcm:Description>Describes properties of the fishing reel</tcm:Description>
      <tcm:Purpose>Component</tcm:Purpose>
      <tcm:NamespaceURI>uuid:44ad0262-ac47-49f1-b93c-93942cf735ae</tcm:NamespaceURI>
      <tcm:RootElementName>Content</tcm:RootElementName>
      <tcm:IsTridionWebSchema>true</tcm:IsTridionWebSchema>
      <tcm:XSD>
        <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="uuid:44ad0262-ac47-49f1-b93c-93942cf735ae" xmlns:tcmi="http://www.tridion.com/ContentManager/5.0/Instance" xmlns:category="tcm:0-6-1/Categories.xsd" elementFormDefault="qualified" targetNamespace="uuid:44ad0262-ac47-49f1-b93c-93942cf735ae">
  <xsd:import namespace="http://www.tridion.com/ContentManager/5.0/Instance" schemaLocation="/webdav/cm_xml_inst.xsd" />
  <xsd:import namespace="tcm:0-6-1/Categories.xsd" schemaLocation="/webdav/401%20Automated%20Test%20Parent/Categories.xsd" />
  <xsd:annotation>
    <xsd:appinfo>
      <tcm:Labels xmlns:tcm="http://www.tridion.com/ContentManager/5.0">
        <tcm:Label ElementName="name" Metadata="false">Title of the reel according to brand book</tcm:Label>
        <tcm:Label ElementName="brand" Metadata="false">Name of the brand</tcm:Label>
        <tcm:Label ElementName="size" Metadata="false">Size of the spool</tcm:Label>
        <tcm:Label ElementName="keyword" Metadata="false">info for SEO</tcm:Label>
      </tcm:Labels>
    </xsd:appinfo>
  </xsd:annotation>
  <xsd:element name="Content">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="name" minOccurs="1" maxOccurs="1" type="xsd:normalizedString">
          <xsd:annotation>
            <xsd:appinfo>
              <ExtensionXml xmlns="http://www.tridion.com/ContentManager/5.0" />
            </xsd:appinfo>
          </xsd:annotation>
        </xsd:element>
        <xsd:element name="brand" minOccurs="1" maxOccurs="1" type="xsd:normalizedString">
          <xsd:annotation>
            <xsd:appinfo>
              <ExtensionXml xmlns="http://www.tridion.com/ContentManager/5.0" />
            </xsd:appinfo>
          </xsd:annotation>
        </xsd:element>
        <xsd:element name="size" minOccurs="1" maxOccurs="1">
          <xsd:annotation>
            <xsd:appinfo>
              <ExtensionXml xmlns="http://www.tridion.com/ContentManager/5.0" />
              <tcm:Size xmlns:tcm="http://www.tridion.com/ContentManager/5.0">1</tcm:Size>
              <tcm:listtype xmlns:tcm="http://www.tridion.com/ContentManager/5.0">select</tcm:listtype>
            </xsd:appinfo>
          </xsd:annotation>
          <xsd:simpleType>
            <xsd:restriction base="xsd:decimal">
              <xsd:enumeration value="2500" />
              <xsd:enumeration value="3000" />
              <xsd:enumeration value="4000" />
            </xsd:restriction>
          </xsd:simpleType>
        </xsd:element>
        <xsd:element name="keyword" minOccurs="1" maxOccurs="unbounded" type="category:FishingType">
          <xsd:annotation>
            <xsd:appinfo>
              <ExtensionXml xmlns="http://www.tridion.com/ContentManager/5.0" />
              <tcm:Size xmlns:tcm="http://www.tridion.com/ContentManager/5.0">1</tcm:Size>
              <tcm:listtype xmlns:tcm="http://www.tridion.com/ContentManager/5.0">checkbox</tcm:listtype>
            </xsd:appinfo>
          </xsd:annotation>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>
      </tcm:XSD>
      <tcm:AllowedMultimediaTypes />
      <tcm:ComponentProcess xlink:type="simple" xlink:title="" xlink:href="tcm:0-0-0" />
      <tcm:BundleProcess xlink:type="simple" xlink:title="" xlink:href="tcm:0-0-0" />
      <tcm:DeleteBundleOnProcessFinished>false</tcm:DeleteBundleOnProcessFinished>
    </tcm:Data>
  </Data>
  <Dependencies>
    <Dependency dependencyType="Publication" itemUrl="/webdav/401%20Automated%20Test%20Parent" linkName="LocationInfo/ContextRepository" />
    <Dependency dependencyType="OrganizationalItemFolder" itemUrl="/webdav/401%20Automated%20Test%20Parent/Building%20Blocks/Content/SRQ9128/schemas" linkName="LocationInfo/OrganizationalItem" />
    <Dependency dependencyType="Category" itemUrl="/webdav/401%20Automated%20Test%20Parent/Fishing%20Type" linkName="Xsd" />
  </Dependencies>
</PackageItem>


text:
.class public Lcom/android/server/NetworkManagementSocketTagger$SocketTags;
.super Ljava/lang/Object;
.source "NetworkManagementSocketTagger.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/NetworkManagementSocketTagger;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "SocketTags"
.end annotation

# instance fields
.field public statsTag:I

.field public statsUid:I

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    const/4 v0, -0x1

    .line 109
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 110
    iput v0, p0, Lcom/android/server/NetworkManagementSocketTagger$SocketTags;->statsTag:I

    .line 111
    iput v0, p0, Lcom/android/server/NetworkManagementSocketTagger$SocketTags;->statsUid:I

    return-void
.end method


text:
FROM alpine:3.5
RUN apk update \
    && apk add tzdata \
    && cp /usr/share/zoneinfo/Asia/Chongqing /etc/localtime \
    && echo "Asia/Chongqing" > /etc/timezone \
    && apk del tzdata \
    && rm -rf /var/cache/apk/*

COPY /html/index.html /html/index.html
ADD forum /forum

ENTRYPOINT [ "/forum" ]


text:
<?php

namespace skeeks\cms\shop\controllers;

use skeeks\cms\backend\actions\BackendModelAction;
use skeeks\cms\backend\controllers\BackendModelStandartController;
use skeeks\cms\grid\DateTimeColumnData;
use skeeks\cms\grid\UserColumnData;
use skeeks\cms\models\CmsAgent;
use skeeks\cms\models\CmsUser;
use skeeks\cms\shop\models\ShopCashebox;
use skeeks\cms\shop\models\ShopCheck;
use skeeks\cms\shop\models\ShopOrder;
use skeeks\cms\shop\models\ShopOrderChange;
use skeeks\cms\shop\models\ShopPayment;
use skeeks\cms\shop\models\ShopPaySystem;
use skeeks\cms\shop\models\ShopStore;
use skeeks\cms\widgets\AjaxSelectModel;
use skeeks\yii2\form\fields\FieldSet;
use skeeks\yii2\form\fields\NumberField;
use skeeks\yii2\form\fields\SelectField;
use skeeks\yii2\form\fields\TextareaField;
use skeeks\yii2\form\fields\WidgetField;
use yii\base\Event;
use yii\helpers\ArrayHelper;

/**
 * @author Semenov Alexander <semenov@skeeks.com>
 */
class AdminPaymentController extends BackendModelStandartController
{
    public function init()
    {
        $this->name = \Yii::t('skeeks/shop/app', 'Платежи по заказам');
        $this->modelShowAttribute = "name";
        $this->modelClassName = ShopPayment::class;

        $this->permissionName = "shop/admin-order";

        $this->generateAccessActions = false;

        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        $result = ArrayHelper::merge(parent::actions(), [

            "view" => [
                'class'    => BackendModelAction::class,
                'priority' => 80,
                'name'     => 'Просмотр',
                'icon'     => 'fas fa-info-circle',
            ],

            "index" => [
                "filters" => [
                    "visibleFilters" => [
                        //'id',
                        'shop_order_id',
                    ],
                ],

                'grid' => [
                    'defaultOrder' => [
                        'created_at' => SORT_DESC,
                    ],

                    'on init' => function (Event $e) {
                        /**
                         * @var $dataProvider ActiveDataProvider
                         * @var $query ActiveQuery
                         */
                        $query = $e->sender->dataProvider->query;

                        $query->cmsSite();
                    },

                    'visibleColumns' => [
                        //'checkbox',
                        'actions',

                        'created_at',

                        'id',

                        'amount',
                        'shop_order_id',

                        'cms_user_id',

                        'shop_pay_system_id',
                        'shop_check_id',

                        'comment',

                    ],
                    'columns'        => [

                        'id'             => [
                            'value' => function(ShopPayment $model) {
                                return \yii\helpers\Html::a( ($model->is_debit ? "Поступление " : "Оплата") . " #{$model->id}", "#", [
                                    'class' => "sx-trigger-action",
                                ]);
                            }
                        ],

                        'created_at' => [
                            'class' => DateTimeColumnData::class,
                            'view_type' => DateTimeColumnData::VIEW_DATE,
                        ],
                        'cms_user_id' => [
                            'class' => UserColumnData::class,
                        ],
                        'amount' => [
                            'value' => function(ShopPayment $shopPayment) {
                                if ($shopPayment->is_debit) {
                                    return "+{$shopPayment->money}";
                                } else {
                                    return "-{$shopPayment->money}";
                                }
                            }
                        ],
                        'comment' => [
                            'value' => function(ShopPayment $shopPayment) {
                                return "{$shopPayment->comment}";
                            }
                        ],

                        'shop_order_id' => [
                            'value'         => function(ShopPayment $shopPayment) {
                                if ($shopPayment->shopOrder) {
                                    return \skeeks\cms\backend\widgets\AjaxControllerActionsWidget::widget([
                                        'controllerId'            => '/shop/admin-order',
                                        'modelId'                 => $shopPayment->shopOrder->id,
                                        'content'                 => $shopPayment->shopOrder->asText,
                                        'isRunFirstActionOnClick' => true,
                                        'options'                 => [
                                            'class' => 'btn btn-xs btn-default',
                                            //'style' => 'cursor: pointer; border-bottom: 1px dashed;',
                                        ],
                                    ]);
                                } else {
                                    return '';
                                }
                            },
                        ],

                        'shop_check_id' => [
                            'value'         => function(ShopPayment $shopPayment) {
                                if ($shopPayment->shopCheck) {
                                    return \skeeks\cms\backend\widgets\AjaxControllerActionsWidget::widget([
                                        'controllerId'            => '/shop/admin-shop-check',
                                        'modelId'                 => $shopPayment->shopCheck->id,
                                        'content'                 => $shopPayment->shopCheck->asText,
                                        'isRunFirstActionOnClick' => true,
                                        'options'                 => [
                                            'class' => 'btn btn-xs btn-default',
                                            //'style' => 'cursor: pointer; border-bottom: 1px dashed;',
                                        ],
                                    ]);
                                } else {
                                    return '';
                                }
                            },
                        ],

                        'shop_pay_system_id' => [
                            'value' => function(ShopPayment $shopPayment) {
                                $data = [];
                                if ($shopPayment->shop_store_id) {
                                    $data[] = 'Оплата в магазине (' . $shopPayment->shopStore->name . ')';
                                    $data[] = "{$shopPayment->shopStorePaymentTypeAsText}";
                                    if ($shopPayment->shopCashebox) {
                                        $data[] = "Касса: {$shopPayment->shopCashebox->name}";
                                    }
                                    if ($shopPayment->shopCasheboxShift) {
                                        $data[] = "{$shopPayment->shopCasheboxShift->asText}";
                                    }

                                } else {
                                    $data[] = 'Оплата через сайт';
                                    if ($shopPayment->shopPaySystem) {
                                        $data[] = "{$shopPayment->shopPaySystem->name}";
                                    }
                                }

                                return implode("
", $data);
                            }
                        ],
                    ],
                ],
            ],

            'create' => [
                'fields'        => [$this, 'updateFields'],
                'buttons'         => ["save"],
            ]
        ]);

       /// ArrayHelper::remove($result, "create");
        ArrayHelper::remove($result, "update");
        ArrayHelper::remove($result, "delete");
        ArrayHelper::remove($result, "delete-multi");

        return $result;
    }

    public function updateFields($action)
    {
        $model = $action->model;

        $result = [
            'main'         => [
                'class'  => FieldSet::class,
                'name'   => \Yii::t('skeeks/shop/app', 'Main'),
                'fields' => [

                    'is_debit' => [
                        'class'       => SelectField::class,
                        'label' => 'Тип операции',
                        'items' => [
                            '1' => 'Нам поступили деньги/Внесли деньги в кассу',
                            '0' => 'Мы заплатили/выплатили/выдали из кассы',
                        ],
                    ],

                    'cms_user_id' => [
                        'class'        => WidgetField::class,
                        'label' => 'Контрагент',
                        'widgetClass'  => AjaxSelectModel::class,
                        'widgetConfig' => [
                            'modelClass' => CmsUser::class,
                            'searchQuery' => function($word = '') {
                                $query = CmsUser::find()->cmsSite();
                                if ($word) {
                                    $query->search($word);
                                }
                                return $query;
                            },
                        ],
                    ],

                    'amount' => [
                        'class'        => NumberField::class,
                    ],

                    'comment' => [
                        'class'        => TextareaField::class,
                    ],
                ],
            ],

            'shop'         => [
                'class'  => FieldSet::class,
                'name'   => "Связь с магазном",
                'fields' => [

                    'shop_store_id' => [
                        'class'        => WidgetField::class,
                        'widgetClass'  => AjaxSelectModel::class,
                        'widgetConfig' => [
                            'modelClass' => ShopStore::class,
                            'searchQuery' => function($word = '') {
                                $query = ShopStore::find()->isSupplier(false)->cmsSite();
                                if ($word) {
                                    $query->search($word);
                                }
                                return $query;
                            },
                        ],
                    ],

                    'shop_cashebox_id' => [
                        'class'        => WidgetField::class,
                        'widgetClass'  => AjaxSelectModel::class,
                        'widgetConfig' => [
                            'modelClass' => ShopCashebox::class,
                            'searchQuery' => function($word = '') {
                                $query = ShopCashebox::find()->cmsSite();
                                if ($word) {
                                    $query->search($word);
                                }
                                return $query;
                            },
                        ],
                    ],

                    'shop_store_payment_type' => [
                        'class'       => SelectField::class,
                        'label' => 'Тип оплаты в магазине',
                        'items' => ShopPayment::getShopStorePaymentTypes(),
                    ],

                ],
            ],

            'relations'         => [
                'class'  => FieldSet::class,
                'name'   => "Дополнительны связи",
                'fields' => [

                    'shop_order_id' => [
                        'class'        => WidgetField::class,
                        'label' => 'Заказ/Продажа/Возврат',
                        'widgetClass'  => AjaxSelectModel::class,
                        'widgetConfig' => [
                            'modelClass' => ShopOrder::class,
                            'searchQuery' => function($word = '') {
                                $query = ShopOrder::find()->cmsSite();
                                if ($word) {
                                    $query->search($word);
                                }
                                return $query;
                            },
                        ],
                    ],

                    'shop_check_id' => [
                        'class'        => WidgetField::class,
                        'label' => 'Чек',
                        'widgetClass'  => AjaxSelectModel::class,
                        'widgetConfig' => [
                            'modelClass' => ShopCheck::class,
                            'searchQuery' => function($word = '') {
                                $query = ShopCheck::find()->cmsSite();
                                if ($word) {
                                    $query->search($word);
                                }
                                return $query;
                            },
                        ],
                    ],

                    'shop_pay_system_id' => [
                        'class'        => WidgetField::class,
                        'label' => 'Способ олплаты на сайте',
                        'widgetClass'  => AjaxSelectModel::class,
                        'widgetConfig' => [
                            'modelClass' => ShopPaySystem::class,
                            'searchQuery' => function($word = '') {
                                $query = ShopPaySystem::find()->cmsSite();
                                if ($word) {
                                    $query->search($word);
                                }
                                return $query;
                            },
                        ],
                    ],
                ],
            ],

        ];

        return $result;
    }

}


text:
var download = require('./')

download({
  version: '0.26.1',
  platform: 'darwin',
  symbols: 'true'
}, function (err, zipPath) {
  if (err) throw err
  console.log('OK! zip:', zipPath)
  process.exit(0)
})


text:
package es.logongas.ix3.web.json.impl;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import es.logongas.ix3.dao.DataSession;
import es.logongas.ix3.web.json.beanmapper.BeanMapper;
import es.logongas.ix3.web.json.JsonReader;

/**
 *
 * @author Lorenzo González
 */
public class JsonReaderImplJackson implements JsonReader {
    private final Class clazz;
    private final ObjectMapper objectMapper;

    public JsonReaderImplJackson(Class clazz) {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        SimpleModule module = new SimpleModule();
        module.addDeserializer(java.util.Date.class, new DateDeserializer());
        objectMapper.registerModule(module);
        this.clazz = clazz;
    }

    @Override
    public Object fromJson(String json, DataSession dataSession) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public Object fromJson(String json, BeanMapper beanMapper, DataSession dataSession) {
        throw new UnsupportedOperationException("No se permite el uso de BeanMapper en esta implementacion");
    }
}


text:
///////////////////////////////////////////////////////////////////////////////
//FILE:          MetadataPanel.java
//PROJECT:       Micro-Manager
//SUBSYSTEM:     mmstudio
//-----------------------------------------------------------------------------
//
// AUTHOR:       Henry Pinkard, henry.pinkard@gmail.com, & Arthur Edelstein, 2010
//
// COPYRIGHT:    University of California, San Francisco, 2012
//
// LICENSE:      This file is distributed under the BSD license.
//               License text is included with the source distribution.
//
//               This file is distributed in the hope that it will be useful,
//               but WITHOUT ANY WARRANTY; without even the implied warranty
//               of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//               IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//               CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//               INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
package org.micromanager.graph;

import com.swtdesigner.SwingResourceManager;
import ij.CompositeImage;
import ij.process.ImageProcessor;
import ij.process.LUT;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.prefs.Preferences;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import mmcorej.CMMCore;
import org.json.JSONArray;
import org.json.JSONObject;
import org.micromanager.dialogs.AcqControlDlg;
import org.micromanager.MMStudio;
import org.micromanager.imagedisplay.VirtualAcquisitionDisplay;
import org.micromanager.imagedisplay.MMCompositeImage;
import org.micromanager.api.ImageCache;
import org.micromanager.graph.HistogramPanel.CursorListener;
import org.micromanager.utils.HistogramUtils;
import org.micromanager.utils.ImageUtils;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.ReportingUtils;

/**
 * Draws one histogram of the Multi-Channel control panel
 *
 *
 */

public class ChannelControlPanel extends JPanel implements CursorListener {

   private static final Dimension CONTROLS_SIZE = new Dimension(130, 150);
   public static final Dimension MINIMUM_SIZE = new Dimension(400,CONTROLS_SIZE.height);

   private static final int NUM_BINS = 256;
   private final int channelIndex_;
   private HistogramPanel hp_;
   private final MultiChannelHistograms mcHistograms_;
   private final VirtualAcquisitionDisplay display_;
   private final ImageCache cache_;
   private final CompositeImage img_;
   private JButton autoButton_;
   private JButton zoomInButton_;
   private JButton zoomOutButton_;
   private JCheckBox channelNameCheckbox_;
   private JLabel colorPickerLabel_;
   private JButton fullButton_;
   private JPanel histogramPanelHolder_;
   private JLabel minMaxLabel_;
   private JComboBox histRangeComboBox_;
   private double binSize_;
   private int height_;
   private String histMaxLabel_;
   private int histMax_;
   private JPanel controls_;
   private JPanel controlsHolderPanel_;
   private int contrastMin_;
   private int contrastMax_;
   private double gamma_ = 1;
   private int minAfterRejectingOutliers_;
   private int maxAfterRejectingOutliers_;
   private int pixelMin_ = 0;
   private int pixelMax_ = 255;
   final private int maxIntensity_;
   final private int bitDepth_;
   private Color color_;
   private final String name_;

   public ChannelControlPanel(int channelIndex, MultiChannelHistograms mcHistograms, VirtualAcquisitionDisplay disp) {
      display_ = disp;
      img_ = (CompositeImage) disp.getHyperImage();
      cache_ = disp.getImageCache();
      color_ = cache_.getChannelColor(channelIndex);
      name_ = cache_.getChannelName(channelIndex);
      bitDepth_ = cache_.getBitDepth();
      maxIntensity_ = (int) Math.pow(2, bitDepth_) - 1;
      histMax_ = maxIntensity_ + 1;
      binSize_ = histMax_ / NUM_BINS;
      histMaxLabel_ = "" + histMax_;
      mcHistograms_ = mcHistograms;
      channelIndex_ = channelIndex;
      initComponents();
      loadDisplaySettings(cache_);
      updateHistogram();
   }

   private void initComponents() {

      fullButton_ = new javax.swing.JButton();
      autoButton_ = new javax.swing.JButton();
      colorPickerLabel_ = new javax.swing.JLabel();
      channelNameCheckbox_ = new javax.swing.JCheckBox();
      histogramPanelHolder_ = new javax.swing.JPanel();
      minMaxLabel_ = new javax.swing.JLabel();

      setOpaque(false);
      setPreferredSize(new java.awt.Dimension(250, height_));

      fullButton_.setFont(fullButton_.getFont().deriveFont((float) 9));
      fullButton_.setName("Full channel histogram width");
      fullButton_.setText("Full");
      fullButton_.setToolTipText("Stretch the display gamma curve over the full pixel range");
      fullButton_.setMargin(new java.awt.Insets(2, 4, 2, 4));
      fullButton_.setPreferredSize(new java.awt.Dimension(75, 30));
      fullButton_.addActionListener(new java.awt.event.ActionListener() {

         @Override
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            fullButtonAction();
         }
      });

      autoButton_.setFont(autoButton_.getFont().deriveFont((float) 9));
      autoButton_.setName("Auto channel histogram width");
      autoButton_.setText("Auto");
      autoButton_.setToolTipText("Align the display gamma curve with minimum and maximum measured intensity values");
      autoButton_.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
      autoButton_.setIconTextGap(0);
      autoButton_.setMargin(new java.awt.Insets(2, 4, 2, 4));
      autoButton_.setMaximumSize(new java.awt.Dimension(75, 30));
      autoButton_.setMinimumSize(new java.awt.Dimension(75, 30));
      autoButton_.setPreferredSize(new java.awt.Dimension(75, 30));
      autoButton_.addActionListener(new java.awt.event.ActionListener() {

         @Override
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            autoButtonAction();
         }
      });

      colorPickerLabel_.setBackground(color_);
      colorPickerLabel_.setToolTipText("Change the color for displaying this channel");
      colorPickerLabel_.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
      colorPickerLabel_.setOpaque(true);
      colorPickerLabel_.addMouseListener(new java.awt.event.MouseAdapter() {

         @Override
         public void mouseClicked(java.awt.event.MouseEvent evt) {
            colorPickerLabelMouseClicked();
         }
      });

      channelNameCheckbox_.setText(name_);
      channelNameCheckbox_.setToolTipText("Show/hide this channel in the multi-dimensional viewer");
      channelNameCheckbox_.addActionListener(new java.awt.event.ActionListener() {

         @Override
         public void actionPerformed(java.awt.event.ActionEvent evt) {
            channelNameCheckboxAction();
         }
      });

      histogramPanelHolder_.setToolTipText("Adjust the brightness and contrast by dragging triangles at top and bottom. Change the gamma by dragging the curve. (These controls only change display, and do not edit the image data.)");
      histogramPanelHolder_.setAlignmentX(0.3F);
      histogramPanelHolder_.setPreferredSize(new java.awt.Dimension(0, 100));
      histogramPanelHolder_.setLayout(new BorderLayout());

      minMaxLabel_.setFont(new java.awt.Font("Lucida Grande", 0, 10));
      minMaxLabel_.setText("Min:   Max:");

      histRangeComboBox_ = new JComboBox();
      histRangeComboBox_.setFont(new Font("", Font.PLAIN, 10));
      histRangeComboBox_.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(final ActionEvent e) {
            if (display_.getHistogramControlsState().syncChannels) {
               mcHistograms_.updateOtherDisplayCombos(histRangeComboBox_.getSelectedIndex());
            }
            displayComboAction();
         }
      });
      histRangeComboBox_.setModel(new DefaultComboBoxModel(new String[]{
                 "Camera Depth", "4bit (0-15)", "5bit (0-31)", "6bit (0-63)", "7bit (0-127)",
                 "8bit (0-255)", "9bit (0-511)", "10bit (0-1023)", "11bit (0-2047)",
                 "12bit (0-4095)", "13bit (0-8191)", "14bit (0-16383)", "15bit (0-32767)", "16bit (0-65535)"}));

      zoomInButton_ = new JButton();
      zoomInButton_.setIcon(SwingResourceManager.getIcon(MMStudio.class,
            "/org/micromanager/icons/zoom_in.png"));
      zoomOutButton_ = new JButton();
      zoomOutButton_.setIcon(SwingResourceManager.getIcon(MMStudio.class,
            "/org/micromanager/icons/zoom_out.png"));
      zoomInButton_.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            zoomInAction();
         }
      });
      zoomOutButton_.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            zoomOutAction();
         }
      });

      this.setMinimumSize(MINIMUM_SIZE);
      this.setPreferredSize(MINIMUM_SIZE);

      hp_ = addHistogramPanel();

      this.setLayout(new BorderLayout());
      controlsHolderPanel_ = new JPanel(new BorderLayout());
      controlsHolderPanel_.setPreferredSize(CONTROLS_SIZE);

      controls_ = new JPanel();
      this.add(controlsHolderPanel_, BorderLayout.LINE_START);
      this.add(histogramPanelHolder_, BorderLayout.CENTER);

      controlsHolderPanel_.add(controls_, BorderLayout.PAGE_START);
      GridBagLayout gbl = new GridBagLayout();
      controls_.setLayout(gbl);

      JLabel histRangeLabel = new JLabel("Hist. range:");
      histRangeLabel.setFont(new Font("Lucida Grande", 0, 11));

      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = 0;
      gbc.gridwidth = 5;
      gbc.weightx = 1;
      gbc.weighty = 1;
      gbc.anchor = GridBagConstraints.LINE_START;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      controls_.add(channelNameCheckbox_, gbc);

      fullButton_.setPreferredSize(new Dimension(45, 20));
      autoButton_.setPreferredSize(new Dimension(45, 20));
      colorPickerLabel_.setPreferredSize(new Dimension(18,18));
      FlowLayout flow = new FlowLayout();
      flow.setHgap(4);
      flow.setVgap(0);
      JPanel line2 = new JPanel(flow);
      line2.setPreferredSize(CONTROLS_SIZE);
      line2.add(fullButton_);
      line2.add(autoButton_);
      line2.add(colorPickerLabel_);
      line2.setPreferredSize(new Dimension(CONTROLS_SIZE.width,20));

      gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = 1;
      gbc.weightx = 1;
      gbc.weighty = 1;
      gbc.gridwidth = 5;
      gbc.anchor = GridBagConstraints.LINE_START;
      controls_.add(line2,gbc);

      gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = 2;
      gbc.weightx = 1;
      gbc.weighty = 1;
      gbc.gridwidth = 3;
      gbc.anchor = GridBagConstraints.LINE_START;
      controls_.add(histRangeLabel, gbc);

      zoomInButton_.setPreferredSize(new Dimension(22, 22));
      zoomOutButton_.setPreferredSize(new Dimension(22, 22));
      gbc = new GridBagConstraints();
      gbc.gridx = 4;
      gbc.gridy = 2;
      gbc.weightx = 0;
      gbc.weighty = 1;
      gbc.gridwidth = 1;
      controls_.add(zoomInButton_, gbc);

      gbc = new GridBagConstraints();
      gbc.gridx = 3;
      gbc.gridy = 2;
      gbc.weightx = 0;
      gbc.weighty = 1;
      gbc.gridwidth = 1;
      controls_.add(zoomOutButton_, gbc);

      gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = 3;
      gbc.weightx = 1;
      gbc.weighty = 1;
      gbc.gridwidth = 5;
      gbc.anchor = GridBagConstraints.LINE_START;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      controls_.add(histRangeComboBox_, gbc);

      gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = 4;
      gbc.weightx = 1;
      gbc.weighty = 1;
      gbc.gridwidth = 5;
      gbc.anchor = GridBagConstraints.LINE_START;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      controls_.add(minMaxLabel_, gbc);

      controls_.setPreferredSize(controls_.getMinimumSize());
   }

   public void setDisplayComboIndex(int index) {
      histRangeComboBox_.setSelectedIndex(index);
   }

   public int getDisplayComboIndex() {
      return histRangeComboBox_.getSelectedIndex();
   }

   private void zoomInAction() {
      int selected = histRangeComboBox_.getSelectedIndex();
      if (selected == 0) {
         selected = bitDepth_ - 3;
      }
      if (selected != 1) {
         selected--;
      }
      histRangeComboBox_.setSelectedIndex(selected);
   }

   private void zoomOutAction() {
      int selected = histRangeComboBox_.getSelectedIndex();
      if (selected == 0) {
         selected = bitDepth_ - 3;
      }
      if (selected < histRangeComboBox_.getModel().getSize() - 1) {
         selected++;
      }
      histRangeComboBox_.setSelectedIndex(selected);
   }

   public void displayComboAction() {
      int bits = histRangeComboBox_.getSelectedIndex() + 3;
      if (bits == 3) {
         histMax_ = maxIntensity_;
      } else {
         histMax_ = (int) (Math.pow(2, bits) - 1);
      }
      binSize_ = ((double) (histMax_ + 1)) / ((double) NUM_BINS);
      histMaxLabel_ = histMax_ + "";
      updateHistogram();
      calcAndDisplayHistAndStats(true);
      storeDisplaySettings();

   }

   private void updateHistogram() {
      hp_.setCursorText(contrastMin_ +"", contrastMax_ + "");
      hp_.setCursors(contrastMin_ / binSize_, (contrastMax_+1) / binSize_, gamma_);
      hp_.repaint();
   }

   private void fullButtonAction() {
      if (display_.getHistogramControlsState().syncChannels) {
         mcHistograms_.fullScaleChannels();
      } else {
         setFullScale();
         mcHistograms_.applyLUTToImage();
         display_.drawWithoutUpdate();
      }
   }

   public void autoButtonAction() {
      autostretch();
      applyLUT();
   }

   private void colorPickerLabelMouseClicked() {
      //Can only edit color in this way if there is an active window
      //so it is ok to get image cache in this way
      String name = "selected";
      if (cache_.getChannelName(channelIndex_) != null) {
         name = cache_.getChannelName(channelIndex_);
      }
      Color newColor = JColorChooser.showDialog(this, "Choose a color for the "
              + name + " channel", cache_.getChannelColor(channelIndex_));
      if (newColor != null) {
         cache_.setChannelColor(channelIndex_, newColor.getRGB());
      }
      updateChannelNameAndColorFromCache();

      //if multicamera, save color
      if (newColor != null) {
         saveColorPreference(cache_, newColor.getRGB());
      }
   }

   /*
    * save color to preferences, but only if this is multicamera.  Since
    * we cannot check for this directly from metadata,this performs a series of
    * checks to error on the side of not saving the preference
    */
   private void saveColorPreference(ImageCache cache, int color) {
      CMMCore core = MMStudio.getInstance().getCore();
      JSONObject summary = cache.getSummaryMetadata();
      if (core == null || summary == null) {
         return;
      }
      try {
         JSONArray dataNames = summary.getJSONArray("ChNames");

         Preferences root = Preferences.userNodeForPackage(AcqControlDlg.class);
         Preferences colorPrefs = root.node(root.absolutePath() + "/" +
               AcqControlDlg.COLOR_SETTINGS_NODE);
         colorPrefs.putInt("Color_Camera_" + dataNames.getString(channelIndex_),
               color);
      } catch (Exception ex) {
         ReportingUtils.logError(ex, "Error storing color preferences");
      }
   }

   private void channelNameCheckboxAction() {
      boolean[] active = img_.getActiveChannels();
      if (img_.getMode() != CompositeImage.COMPOSITE) {
         if (active[channelIndex_]) {
            channelNameCheckbox_.setSelected(true);
            return;
         } else {
            display_.setChannel(channelIndex_);
         }
      } else {
         img_.getActiveChannels()[channelIndex_] = channelNameCheckbox_.isSelected();
      }

      img_.getActiveChannels()[channelIndex_] = channelNameCheckbox_.isSelected();
      img_.updateAndDraw();
   }

   public void setFullScale() {
      display_.disableAutoStretchCheckBox();
      contrastMin_ = 0;
      contrastMax_ = histMax_;
   }

   public void autostretch() {
      contrastMin_ = pixelMin_;
      contrastMax_ = pixelMax_;
      if (pixelMin_ == pixelMax_) {
          if (pixelMax_ > 0) {
              contrastMin_--;
          } else {
              contrastMax_++;
          }
      }
      if (display_.getHistogramControlsState().ignoreOutliers) {
         if (contrastMin_ < minAfterRejectingOutliers_) {
            if (0 < minAfterRejectingOutliers_) {
               contrastMin_ = minAfterRejectingOutliers_;
            }
         }
         if (maxAfterRejectingOutliers_ < contrastMax_) {
            contrastMax_ = maxAfterRejectingOutliers_;
         }
         if (contrastMax_ <= contrastMin_) {
             if (contrastMax_ > 0) {
                 contrastMin_ = contrastMax_ - 1;
             } else {
                 contrastMax_ = contrastMin_ + 1;
             }
         }
      }
   }

   private void loadDisplaySettings(ImageCache cache) {
      contrastMax_ =  cache.getChannelMax(channelIndex_);
      if (contrastMax_ < 0 || contrastMax_ > maxIntensity_) {
         contrastMax_ = maxIntensity_;
      }
      contrastMin_ = cache.getChannelMin(channelIndex_);
      gamma_ = cache.getChannelGamma(channelIndex_);
      int histMax = cache.getChannelHistogramMax(channelIndex_);
      if (histMax != -1) {
         int index = (int) (Math.ceil(Math.log(histMax)/Math.log(2)) - 3);
         histRangeComboBox_.setSelectedIndex(index);
      }
//      mcHistograms_.setDisplayMode(cache.getDisplayMode());
   }

   private HistogramPanel addHistogramPanel() {
      HistogramPanel hp = new HistogramPanel() {

         @Override
         public void paint(Graphics g) {
            super.paint(g);
            //For drawing max label
            g.setColor(Color.black);
            g.setFont(new Font("Lucida Grande", 0, 10));
            g.drawString(histMaxLabel_, this.getSize().width - 8 * histMaxLabel_.length(), this.getSize().height);
         }
      };
      hp.setMargins(12, 12);
      hp.setTraceStyle(true, color_);
      hp.setToolTipText("Click and drag curve to adjust gamma");
      histogramPanelHolder_.add(hp, BorderLayout.CENTER);
      hp.addCursorListener(this);
      return hp;
   }

   public void updateChannelNameAndColorFromCache() {
      color_ = cache_.getChannelColor(channelIndex_);
      colorPickerLabel_.setBackground(color_);
      hp_.setTraceStyle(true, color_);
      String name = cache_.getChannelName(channelIndex_);
      if (name.length() > 11) {
         name = name.substring(0, 9) + "...";
      }
      channelNameCheckbox_.setText(name);
      calcAndDisplayHistAndStats(true);
      mcHistograms_.applyLUTToImage();
      display_.drawWithoutUpdate();
      this.repaint();
   }

   public int getContrastMin() {
      return contrastMin_;
   }

   public int getContrastMax() {
      return contrastMax_;
   }

   public double getContrastGamma() {
      return gamma_;
   }

   public void setContrast(int min, int max, double gamma) {
      contrastMin_ = min;
      contrastMax_ = Math.min(maxIntensity_, max);
      gamma_ = gamma;
   }

   //Need to put this on EDT to avoid index out of bounds because of setting currentChannel to -1
   public void applyChannelLUTToImage() {
      Runnable run = new Runnable() {

         @Override
         public void run() {
            if (!cache_.getIsOpen()) {
               // Cache has been closed; give up.
               return;
            }
            Color color = cache_.getChannelColor(channelIndex_);

            LUT lut = ImageUtils.makeLUT(color, gamma_);
            lut.min = contrastMin_;
            lut.max = contrastMax_;
            //uses lut.min and lut.max to set min and max of precessor
            img_.setChannelLut(lut, channelIndex_ + 1);

            // ImageJ workaround: do this so the appropriate color model and
            // min/max get applied in color or grayscale mode
            try {
               if (img_.getMode() == CompositeImage.COLOR
                       || img_.getMode() == CompositeImage.GRAYSCALE) {
                  JavaUtils.setRestrictedFieldValue(img_, CompositeImage.class,
                          "currentChannel", -1);
               }
            } catch (NoSuchFieldException ex) {
               ReportingUtils.logError(ex);
            }

            if (img_.getChannel() == channelIndex_ + 1) {
               LUT grayLut = ImageUtils.makeLUT(Color.white, gamma_);
               ImageProcessor processor = img_.getProcessor();
               if (processor != null) {
                  processor.setColorModel(grayLut);
                  processor.setMinAndMax(contrastMin_, contrastMax_);
               }
               if (img_.getMode() == CompositeImage.GRAYSCALE) {
                  img_.updateImage();
               }
            }
            storeDisplaySettings();

            updateHistogram();

         }
      };
      if (SwingUtilities.isEventDispatchThread()) {
         run.run();
      } else {
         SwingUtilities.invokeLater(run);
      }
   }

   private void storeDisplaySettings() {
      int histMax = histRangeComboBox_.getSelectedIndex() == 0 ? -1 : histMax_;
      display_.storeChannelHistogramSettings(channelIndex_, contrastMin_, contrastMax_,
              gamma_, histMax,((MMCompositeImage) img_).getMode());
   }

   public int getChannelIndex() {
      return channelIndex_;
   }

   /**
    * @param drawHist - set true if hist and stats calculated successfully
    *
    */
   public void calcAndDisplayHistAndStats(boolean drawHist) {
      if (img_ == null || img_.getProcessor() == null) {
         return;
      }
      ImageProcessor ip;
      if (img_.getMode() == CompositeImage.COMPOSITE) {
         ip = img_.getProcessor(channelIndex_ + 1);
         if (ip != null) {
            ip.setRoi(img_.getRoi());
         }
      } else {
         MMCompositeImage ci = (MMCompositeImage) img_;
         int flatIndex = 1 + channelIndex_ + (img_.getSlice() - 1) * ci.getNChannelsUnverified()
                 + (img_.getFrame() - 1) * ci.getNSlicesUnverified() * ci.getNChannelsUnverified();
         ip = img_.getStack().getProcessor(flatIndex);

      }

      if (((MMCompositeImage) img_).getNChannelsUnverified() <= 7) {
         boolean active = img_.getActiveChannels()[channelIndex_];
         channelNameCheckbox_.setSelected(active);
         if (!active) {
            drawHist = false;
         }
      }
      if (((MMCompositeImage) img_).getMode() != CompositeImage.COMPOSITE) {
         if (img_.getChannel() - 1 != channelIndex_) {
            drawHist = false;
         }
      }

      if (ip == null ) {
         return;
      }

      int[] rawHistogram = ip.getHistogram();
      int imgWidth = img_.getWidth();
      int imgHeight = img_.getHeight();

      if (rawHistogram[0] == imgWidth * imgHeight) {
         return;  //Blank pixels
      }
      if (display_.getHistogramControlsState().ignoreOutliers) {
         // todo handle negative values
         maxAfterRejectingOutliers_ = rawHistogram.length;
         // specified percent of pixels are ignored in the automatic contrast setting
         int totalPoints = imgHeight * imgWidth;
         HistogramUtils hu = new HistogramUtils(rawHistogram, totalPoints, 0.01*display_.getHistogramControlsState().percentToIgnore);
         minAfterRejectingOutliers_ = hu.getMinAfterRejectingOutliers();
         maxAfterRejectingOutliers_ = hu.getMaxAfterRejectingOutliers();
      }
      GraphData histogramData = new GraphData();

      pixelMin_ = -1;
      pixelMax_ = 0;

      int numBins = (int) Math.min(rawHistogram.length / binSize_, NUM_BINS);
      int[] histogram = new int[NUM_BINS];
      int total = 0;
      for (int i = 0; i < numBins; i++) {
         histogram[i] = 0;
         for (int j = 0; j < binSize_; j++) {
            int rawHistIndex = (int) (i * binSize_ + j);
            int rawHistVal = rawHistogram[rawHistIndex];
            histogram[i] += rawHistVal;
            if (rawHistVal > 0) {
               pixelMax_ = rawHistIndex;
               if (pixelMin_ == -1) {
                  pixelMin_ = rawHistIndex;
               }
            }
         }
         total += histogram[i];
         if (display_.getHistogramControlsState().logHist) {
            histogram[i] = histogram[i] > 0 ? (int) (1000 * Math.log(histogram[i])) : 0;
         }
      }
      //Make sure max has correct value is hist display mode isnt auto
      if (histRangeComboBox_.getSelectedIndex() != -1) {
         pixelMin_ = rawHistogram.length-1;
         for (int i = rawHistogram.length-1; i > 0; i--) {
            if (rawHistogram[i] > 0 && i > pixelMax_ ) {
               pixelMax_ = i;
            }
            if (rawHistogram[i] > 0 && i < pixelMin_ ) {
               pixelMin_ = i;
            }
         }
      }

      // work around what is apparently a bug in ImageJ
      if (total == 0) {
         if (img_.getProcessor().getMin() == 0) {
            histogram[0] = imgWidth * imgHeight;
         } else {
            histogram[numBins - 1] = imgWidth * imgHeight;
         }
      }

      if (drawHist) {
         hp_.setVisible(true);
         //Draw histogram and stats
         histogramData.setData(histogram);
         hp_.setData(histogramData);
         hp_.setAutoScale();
         hp_.repaint();

         minMaxLabel_.setText("Min: " + NumberUtils.intToDisplayString( pixelMin_) + "   "
                 + "Max: " + NumberUtils.intToDisplayString( pixelMax_));
      } else {
          hp_.setVisible(false);
      }

   }

   @Override
   public void contrastMaxInput(int max) {
      display_.disableAutoStretchCheckBox();
      contrastMax_ = max;
      if (contrastMax_ > maxIntensity_ ) {
         contrastMax_ = maxIntensity_;
      }
      if (contrastMax_ < 0) {
         contrastMax_ = 0;
      }
      if (contrastMin_ > contrastMax_) {
         contrastMin_ = contrastMax_;
      }
      applyLUT();
   }

   @Override
   public void contrastMinInput(int min) {
      display_.disableAutoStretchCheckBox();
      contrastMin_ = min;
      if (contrastMin_ >= maxIntensity_)
          contrastMin_ = maxIntensity_ - 1;
      if(contrastMin_ < 0 ) {
         contrastMin_ = 0;
      }
      if (contrastMax_ < contrastMin_) {
         contrastMax_ = contrastMin_ + 1;
      }
      applyLUT();
   }

   @Override
   public void onLeftCursor(double pos) {
      display_.disableAutoStretchCheckBox();
      contrastMin_ = (int) (Math.max(0, pos) * binSize_);
      if (contrastMin_ >= maxIntensity_)
          contrastMin_ = maxIntensity_ - 1;
      if (contrastMax_ < contrastMin_) {
         contrastMax_ = contrastMin_ + 1;
      }
      applyLUT();
   }

   @Override
   public void onRightCursor(double pos) {
      display_.disableAutoStretchCheckBox();
      contrastMax_ = (int) (Math.min(NUM_BINS - 1, pos) * binSize_);
      if (contrastMax_ < 1) {
         contrastMax_ = 1;
      }
      if (contrastMin_ > contrastMax_) {
         contrastMin_ = contrastMax_;
      }
      applyLUT();
   }

   @Override
   public void onGammaCurve(double gamma) {
      if (gamma != 0) {
         if (gamma > 0.9 & gamma < 1.1) {
            gamma_ = 1;
         } else {
            gamma_ = gamma;
         }
         applyLUT();
      }
   }

   private void applyLUT() {
      if (display_.getHistogramControlsState().syncChannels) {
         mcHistograms_.applyContrastToAllChannels(contrastMin_, contrastMax_, gamma_);
      } else {
         mcHistograms_.applyLUTToImage();
         display_.drawWithoutUpdate();
      }
   }
}


text:
<?php

/**
 *
 *
 * @package    Gems
 * @subpackage Default
 * @copyright  Copyright (c) 2013 Erasmus MC
 * @license    New BSD License
 * @since      Class available since version 1.6.2
 */
class Gems_Default_AgendaActivityAction extends \Gems_Controller_ModelSnippetActionAbstract
{
    /**
     * The snippets used for the autofilter action.
     *
     * @var mixed String or array of snippets name
     */
    protected $autofilterParameters = array(
        'columns'      => 'getBrowseColumns',
        'extraSort'    => array('gaa_name' => SORT_ASC),
        'searchFields' => 'getSearchFields',
        );

    /**
     * Variable to set tags for cache cleanup after changes
     *
     * @var array
     */
    public $cacheTags = array('activity', 'activities');

    /**
     * The snippets used for the index action, before those in autofilter
     *
     * @var mixed String or array of snippets name
     */
    protected $indexStartSnippets = array('Generic\\ContentTitleSnippet', 'Agenda\\AutosearchFormSnippet');

    /**
     * The snippets used for the show action
     *
     * @var mixed String or array of snippets name
     */
    protected $showParameters = array(
        'calSearchFilter' => 'getShowFilter',
        'caption'         => 'getShowCaption',
        'onEmpty'         => 'getShowOnEmpty',
        );

    /**
     * The snippets used for the show action
     *
     * @var mixed String or array of snippets name
     */
    protected $showSnippets = array(
        'Generic\\ContentTitleSnippet',
        'ModelItemTableSnippetGeneric',
        'Agenda_CalendarTableSnippet',
        );

    /**
     *
     * @var \Gems_Util
     */
    public $util;

    /**
     * Cleanup appointments
     */
    public function cleanupAction()
    {
        $params = $this->_processParameters($this->showParameters);
        $params['contentTitle'] = $this->_('Clean up existing appointments?');
        $params['filterOn']     = 'gap_id_activity';
        $params['filterWhen']   = 'gaa_filter';

        $snippets = array(
            'Generic\\ContentTitleSnippet',
            'Agenda\\AppointmentCleanupSnippet',
            'Agenda_CalendarTableSnippet',
            );

        $this->addSnippets($snippets, $params);
    }

    /**
     * Creates a model for getModel(). Called only for each new $action.
     *
     * The parameters allow you to easily adapt the model to the current action. The $detailed
     * parameter was added, because the most common use of action is a split between detailed
     * and summarized actions.
     *
     * @param boolean $detailed True when the current action is not in $summarizedActions.
     * @param string $action The current action.
     * @return \MUtil_Model_ModelAbstract
     */
    protected function createModel($detailed, $action)
    {
        $translated = $this->util->getTranslated();
        $model      = new \MUtil_Model_TableModel('gems__agenda_activities');

        \Gems_Model::setChangeFieldsByPrefix($model, 'gaa');

        $model->setDeleteValues('gaa_active', 0);

        $model->set('gaa_name',                    'label', $this->_('Activity'),
                'description', $this->_('An activity is a high level description about an appointment:
e.g. consult, check-up, diet, operation, physiotherapy or other.'),
                'required', true
                );

        $model->setIfExists('gaa_id_organization', 'label', $this->_('Organization'),
                'description', $this->_('Optional, an import match with an organization has priority over those without.'),
                'multiOptions', $translated->getEmptyDropdownArray() + $this->util->getDbLookup()->getOrganizations()
                );

        $model->setIfExists('gaa_name_for_resp',   'label', $this->_('Respondent explanation'),
                'description', $this->_('Alternative description to use with respondents.')
                );
        $model->setIfExists('gaa_match_to',        'label', $this->_('Import matches'),
                'description', $this->_("Split multiple import matches using '|'.")
                );

        $model->setIfExists('gaa_code',        'label', $this->_('Activity code'),
                'size', 10,
                'description', $this->_('Optional code name to link the activity to program code.'));

        $model->setIfExists('gaa_active',      'label', $this->_('Active'),
                'description', $this->_('Inactive means assignable only through automatich processes.'),
                'elementClass', 'Checkbox',
                'multiOptions', $translated->getYesNo()
                );
        $model->setIfExists('gaa_filter',      'label', $this->_('Filter'),
                'description', $this->_('When checked appointments with these activities are not imported.'),
                'elementClass', 'Checkbox',
                'multiOptions', $translated->getYesNo()
                );

        $model->addColumn("CASE WHEN gaa_active = 1 THEN '' ELSE 'deleted' END", 'row_class');

        return $model;
    }

    /**
     * Helper function to get the title for the index action.
     *
     * @return $string
     */
    public function getIndexTitle()
    {
        return $this->_('Agenda activities');
    }

    /**
     * Returns the fields for autosearch with
     *
     * @return array
     */
    public function getSearchFields()
    {
        return [
            'gaa_filter' => $this->_('(all filters)')
        ];
    }

    /**
     *
     * @return type
     */
    public function getShowCaption()
    {
        return $this->_('Example appointments');
    }

    /**
     *
     * @return type
     */
    public function getShowOnEmpty()
    {
        return $this->_('No example appointments found');

    }
    /**
     * Get an agenda filter for the current shown item
     *
     * @return array
     */
    public function getShowFilter()
    {
        return array(
            \MUtil_Model::SORT_DESC_PARAM => 'gap_admission_time',
            'gap_id_activity' => $this->_getIdParam(),
            'limit' => 10,
            );
    }

    /**
     * Helper function to allow generalized statements about the items in the model.
     *
     * @param int $count
     * @return $string
     */
    public function getTopic($count = 1)
    {
        return $this->plural('activity', 'activities', $count);
    }

    /**
     * Action for showing a browse page
     */
    public function indexAction()
    {
        parent::indexAction();

        $this->html->pInfo($this->getModel()->get('gaa_name', 'description'));
    }
}


text:
package us.feliscat.ir.web.google

import java.net.URL

import us.feliscat.ir.Query
import us.feliscat.ir.web

/**
 * <pre>
 * Created on 6/2/15.
 * </pre>
 * @param searchedPages searched pages
 * @param query query
 * @param startIndex starting index
 * @param currentUrl current URL
 * @param nextUrl next URL
 * @author K.Sakamoto
 */
class GoogleSearchedPageList(override val searchedPages: Array[web.SearchedPage],
                             override val query: Query,
                             override val startIndex: Int,
                             override val currentUrl: URL,
                             override val nextUrl: URL) extends web.SearchedPageList(searchedPages, query, startIndex, currentUrl, nextUrl)


text:
var link = document.createElement('link');
link.href =  chrome.extension.getURL('css/dinamohub.min.css');
link.rel = 'stylesheet';
head = document.getElementsByTagName ("head")[0] || document.documentElement;
head.insertBefore(link, head.firstChild);


text:
<?php

/** @file
* @brief
* @since version 0.85
*/

include ('../inc/includes.php');

Session::checkRight("queuedmail", READ);

Html::header(QueuedMail::getTypeName(), $_SERVER['PHP_SELF'], "admin", "queuedmail");

Search::show('QueuedMail');

Html::footer();
?>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Camera Example</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_select_photo">Select Picture</string>
    <string name="action_select_video">Select Video</string>
    <string name="action_take_photo">Take Picture</string>
    <string name="action_take_video_hd">Take HD Video</string>
    <string name="action_take_video">Take Video</string>
    <string name="about_text">About</string>
    <string name="title_activity_about_message">About Camera Example</string>
    <string name="about_html_file">file:///android_asset/about.html</string>

</resources>


text:
ALTER TABLE `addon_upsell` DROP FOREIGN KEY `free_id_refs_id_upsell`;
ALTER TABLE `addon_upsell` ADD CONSTRAINT `free_id_refs_id_upsell`
    FOREIGN KEY (`free_id`) REFERENCES `addons` (`id`) ON DELETE CASCADE;
ALTER TABLE `addon_upsell` DROP FOREIGN KEY `premium_id_refs_id_upsell`;
ALTER TABLE `addon_upsell` ADD CONSTRAINT `premium_id_refs_id_upsell`
    FOREIGN KEY (`premium_id`) REFERENCES `addons` (`id`) ON DELETE CASCADE;
ALTER TABLE `addon_upsell` DROP FOREIGN KEY `text_translated`;
ALTER TABLE `addon_upsell` ADD CONSTRAINT `text_translated`
    FOREIGN KEY (`text`) REFERENCES `translations` (`id`) ON DELETE CASCADE;

ALTER TABLE `addon_payment_data` DROP FOREIGN KEY `addon_id_refs_id_addon`;
ALTER TABLE `addon_payment_data` ADD CONSTRAINT `addon_id_refs_id_addon`
    FOREIGN KEY (`addon_id`) REFERENCES `addons` (`id`) ON DELETE CASCADE;


text:
Security updates are released for following Sniffy versions

| Version | Supported          |
| ------- | ------------------ |
| 3.1.x   | :white_check_mark: |
| 3.0.x   | :x:                |

## Reporting a Vulnerability

If you find a security vulnerability in Sniffy please report it using GitHub issues: https://github.com/sniffy/sniffy/issues/new


text:
<?xml version="1.0" encoding="UTF-8"?>
<positions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="group3.xsd" >
    <SetPosition>
        <XYPosition x="0.0" y="0.0"/>
        <Depth value="0.0"/>
    </SetPosition>
</positions>


text:
/**
  * Generators for different signals (currently only sine waves)
  */

// for now we use dsp.js
var dsp = require("../dsp.js");
var _ = require("lodash");
var Signal = require("./signal.js");

/** A generator can generate a periodic function
 *  using a given function
 */
var generator = function(genFunction, cfg){

  var data = []
  return {
    /** creates a signal
     *  call
     *   - create() [uses default: sampling=44100, length=1000]
     *   - create({sampling: 44100, length: 1000})
     */
    create: function(options){
      options = _.defaults(options || {}, {sampling:44100, length:1000});
//      var generator = new dsp.Oscillator(cfg.__dspGenerator,
//        cfg.frequency, cfg.amplitude, options.length, options.sampling);
//      generator.generate();
      var signalData = _.map(_.range(options.length), function(idx){
        return cfg.amplitude * genFunction(cfg.functionPeriod * cfg.frequency * idx / options.sampling);
      });
//      var signalData = generator.signal;
      var s = Signal(signalData, options);
      s.amplitude = cfg.amplitude;
      s.frequency = cfg.frequency;
      return s;
    }
  }
}

var mergeTwoSignals = function(s1,s2){
  var sigData = _(s1)
    .zip(s2)
    .map(function(p){
      return p[0].value + p[1].value;
    })
    .value();
  return Signal(sigData,{sampling:s1.sampling});
}

var mergeSignals = function(sigs){
  if(_.isArray(sigs)){
    return _.reduce(sigs,mergeTwoSignals);
  } else {
    return _.reduce(arguments,mergeTwoSignals);
  }
}

var combinator = function(generators){
  return {
    create: function(options){
      options = _.defaults(options || {}, {sampling:44100, length:1000});
      return _(generators)
        .invoke("create",options)
        .reduce(mergeTwoSignals);
    }
  }
}

var Signals = require("./utils/signals.js");

var Generators = {
  /** sine wave generator.
   *  call
   *   - sine() [uses default: frequency=440, phase = 0, amplitude: 1]
   *   - sine({frequency:440, phase:0, amplitude: 1})
   *  returns a generator for the sine wave
   */
  sine: function(options){
    options = _.defaults(options || {}, {frequency: 440, phase: 0, amplitude: 1});
    options.functionPeriod = 2*Math.PI;
    return generator(Math.sin, options);
  },
  sines: function(signals){
    var gens = _.map(signals, function(s){
      return Generators.sine(s); });
    return combinator(gens);
  },
  triangle: function(options){
    options = _.defaults(options || {}, {frequency: 440, phase: 0, amplitude: 1});
    options.functionPeriod = 1;
    return generator(Signals.triangle(1), options);
  },
  rectangle: function(options){
    options = _.defaults(options || {}, {frequency: 440, phase: 0, amplitude: 1});
    options.functionPeriod = 1;
    return generator(Signals.rectangle(1), options);
  }
}

module.exports = Generators;


text:
Returns the value of the specified `header` field in this request (`req`).  Note that header names are case-_insensitive_.

### Usage

```js
req.get(header);
```

### Example
Assuming `req` contains a header named 'myField' with value 'cat':

```javascript
req.get('myField');
// -> cat
```

### Notes
>+ The `header` argument is case-insensitive.
>+ The `header` argument treats both "referrer" and "referer" as synonyms, because sp3ll1n6.

<docmeta name="uniqueID" value="reqget839626">
<docmeta name="displayName" value="req.get()">


text:
var zmq = require('../build/default/index');

var context = new zmq.Context();

var socket = context.socket(zmq.REQ);

socket.on("recv", function(messages) {
	for (var i = 0, len = messages.length ; i < len ; i++) {
		console.log(messages[i]);
	}
	setTimeout(function() {
		socket.close();
	}, 0);
});

socket.connect("tcp://localhost:5555");

var rc = socket.send("From Client02:", zmq.SNDMORE);

var rc = socket.send("Hello");


text:
from django import forms
from django.utils.translation import ugettext_lazy as _
import re

class AddNetPool(forms.Form):
    name = forms.CharField(error_messages={'required': _('No pool name has been entered')},
                           max_length=20)
    subnet = forms.CharField(error_messages={'required': _('No subnet has been entered')},
                             max_length=20)
    forward = forms.CharField(max_length=100)
    dhcp = forms.BooleanField(required=False)
    bridge_name = forms.CharField(max_length=20, required=False)

    def clean_name(self):
        name = self.cleaned_data['name']
        have_symbol = re.match('[^a-zA-Z0-9._-]+', name)
        if have_symbol:
            raise forms.ValidationError(_('The pool name must not contain any special characters'))
        elif len(name) > 20:
            raise forms.ValidationError(_('The pool name must not exceed 20 characters'))
        return name

    def clean_subnet(self):
        subnet = self.cleaned_data['subnet']
        have_symbol = re.match('[^0-9./]+', subnet)
        if have_symbol:
            raise forms.ValidationError(_('The pool subnet must not contain any special characters'))
        elif len(subnet) > 20:
            raise forms.ValidationError(_('The pool subnet must not exceed 20 characters'))
        return subnet

    def clean_bridge_name(self):
        bridge_name = self.cleaned_data['bridge_name']
        have_symbol = re.match('[^a-zA-Z0-9._-]+', bridge_name)
        if have_symbol:
            raise forms.ValidationError(_('The pool bridge name must not contain any special characters'))
        elif len(bridge_name) > 20:
            raise forms.ValidationError(_('The pool bridge name must not exceed 20 characters'))
        return bridge_name


text:
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;

namespace Lucene.Net.Analysis.Miscellaneous
{

    /// <summary>
    /// Marks terms as keywords via the <see cref="KeywordAttribute"/>. Each token
    /// contained in the provided set is marked as a keyword by setting
    /// <see cref="KeywordAttribute.IsKeyword"/> to <c>true</c>.
    /// </summary>
    public sealed class SetKeywordMarkerFilter : KeywordMarkerFilter
    {
        private readonly ICharTermAttribute termAtt;
        private readonly CharArraySet keywordSet;

        /// <summary>
        /// Create a new <see cref="SetKeywordMarkerFilter"/>, that marks the current token as a
        /// keyword if the tokens term buffer is contained in the given set via the
        /// <see cref="KeywordAttribute"/>.
        /// </summary>
        /// <param name="in">
        ///          <see cref="TokenStream"/> to filter </param>
        /// <param name="keywordSet">
        ///          the keywords set to lookup the current termbuffer </param>
        public SetKeywordMarkerFilter(TokenStream @in, CharArraySet keywordSet)
            : base(@in)
        {
            this.keywordSet = keywordSet;
            termAtt = AddAttribute<ICharTermAttribute>();
        }

        protected override bool IsKeyword()
        {
            return keywordSet.Contains(termAtt.Buffer, 0, termAtt.Length);
        }
    }
}


text:
/** @file Capsule.h
	@author Jukka Jylänki
	@brief The Capsule geometry object. */
#pragma once

#include "../MathGeoLibFwd.h"
#include "LineSegment.h"

MATH_BEGIN_NAMESPACE

/// A 3D cylinder with spherical ends.
class Capsule
{
public:
	/// Specifies the two inner points of this capsule.
	LineSegment l;

	/// Specifies the radius of this capsule. [similarOverload: l]
	float r;

	/// The default constructor does not initialize any members of this class.
	/** This means that the values of the members l and r are both undefined after creating a new capsule using
		this default constructor. Remember to assign to them before use.
		@see l, r. */
	Capsule() {}

	/// Constructs a new capsule by explicitly specifying the member variables.
	/** @param endPoints Specifies the line segment of the capsule.
		@param radius Specifies the size of this capsule.
		@see l, r. */
	Capsule(const LineSegment &endPoints, float radius);

	/// Constructs a new capsule by explicitly specifying the member variables.
	/** This constructor is equivalent to calling Capsule(LineSegment(bottomPoint, topPoint), radius), but provided
		here for conveniency.
		@see l, r. */
	Capsule(const float3 &bottomPoint, const float3 &topPoint, float radius);

	/// Constructs a new capsule from a sphere.
	/** This conversion results in a capsule which has its both endpoints at the exact same coordinates, and hence the
		length of the inner line segment is set to 0. */
	void SetFrom(const Sphere &s);

	/// Computes the distance of the two inner points of this capsule.
	/**
		@see Height(). */
	float LineLength() const;

	/// Computes the total height of this capsule, i.e. LineLength() + Diameter().
	/**
		@see LineLength(). */
	float Height() const;

	/// Computes the diameter of this capsule.
	/**
		@return 2*r.
		@see r. */
	float Diameter() const;

	/// Returns the bottom-most point of this Capsule.
	/**
		@note The bottom-most point is only a naming convention, and does not correspond to the bottom-most point along any world axis. The returned
			point is simply the point at the far end of this Capsule where the point l.a resides.
		@note The bottom-most point of the capsule is different than the point l.a. The returned point is the point at the very far
			edge of this capsule, and does not lie on the internal line. See the attached diagram.
		@see Top(), l. */
	float3 Bottom() const;

	/// Returns the center point of this Capsule.
	/**
		@return The point (l.a + l.b) / 2. This point is the center of mass for this capsule.
		@see l, Bottom(), Top(). */
	float3 Center() const;
	float3 Centroid() const { return l.CenterPoint(); } ///< [similarOverload: Center]

	/// Computes the extreme point of this Capsule in the given direction.
	/** An extreme point is a farthest point of this Capsule in the given direction. Given a direction,
		this point is not necessarily unique.
		@param direction The direction vector of the direction to find the extreme point. This vector may
			be unnormalized, but may not be null.
		@return The extreme point of this Capsule in the given direction. */
	float3 ExtremePoint(const float3 &direction) const;

	/// Projects this Capsule onto the given 1D axis direction vector.
	/** This function collapses this Capsule onto an 1D axis for the purposes of e.g. separate axis test computations.
		The function returns a 1D range [outMin, outMax] denoting the interval of the projection.
		@param direction The 1D axis to project to. This vector may be unnormalized, in which case the output
			of this function gets scaled by the length of this vector.
		@param outMin [out] Returns the minimum extent of this object along the projection axis.
		@param outMax [out] Returns the maximum extent of this object along the projection axis. */
	void ProjectToAxis(const float3 &direction, float &outMin, float &outMax) const;

	/// Returns the topmost point of this Capsule.
	/**
		@note The topmost point is only a naming convention, and does not correspond to the topmost point along any world axis. The returned
			point is simply the point at the far end of this Capsule where the point l.b resides.
		@note The topmost point of the capsule is different than the point l.b. The returned point is the point at the very far
			edge of this capsule, and does not lie on the internal line. See the attached diagram.
		@see Bottom(), l. */
	float3 Top() const;

	/// Returns the direction from the bottommost point towards the topmost point of this Capsule.
	/**
		@return The normalized direction vector from l.a to l.b.
		@see l. */
	float3 UpDirection() const;

	/// Computes the volume of this Capsule.
	/** @return pi * r^2 * |b-a| + 4 * pi * r^2 / 3.
		@see SurfaceArea(). */
	float Volume() const;

	/// Computes the surface area of this Capsule.
	/** @return 2 * pi * r * |b-a| + 4 * pi * r^2.
		@see Volume(). */
	float SurfaceArea() const;

	/// Returns the cross-section circle at the given height of this Capsule.
	/**
		@param l A normalized parameter between [0,1]. l == 0 returns a degenerate circle of radius 0 at the bottom of this Capsule, and l == 1
				will return a degenerate circle of radius 0 at the top of this Capsule. */
	Circle CrossSection(float l) const;

	/// Returns a line segment that spans the far axis of this capsule from bottom to tip.
	/**
		@see Height(), LineLength(), l. */
	LineSegment HeightLineSegment() const;

	/// Tests if this Capsule is finite.
	/** A Capsule is finite if none of its member variables contain floating-point NaNs or +/-infs
		in them.
		@return True if each member variable has a finite floating-point value.
		@see l, r.
		@todo Implement IsDegenerate(). */
	bool IsFinite() const;

	/// Generates a point inside this capsule.
	/** @param l A normalized value between [0,1]. This specifies the point position along the height line of this capsule.
		@param a A normalized value between [0,1]. This specifies the normalized directed angle of the point position around the capsule line segment.
		@param d A normalized value between [0,1]. This specifies the normalized distance of the point position from the capsule line segment.
		@note This function does not generate points inside this capsule uniformly, as (l,a,d) ranges uniformly over [0,1]^3.
		@see UniformPointPerhapsInside(), RandomPointInside(). */
	float3 PointInside(float l, float a, float d) const;

	/// Generates a point that perhaps lies inside this capsule.
	/** @param l A normalized value between [0,1]. This specifies the point position along the height line of this capsule.
		@param x A normalized value between [0,1]. This specifies the x coordinate on the plane of the circle cross-section specified by l.
		@param y A normalized value between [0,1]. This specifies the y coordinate on the plane of the circle cross-section specified by l.
		@note This function will generate points uniformly, but they do not necessarily lie inside the capsule.
		@see PointInside(). */
	float3 UniformPointPerhapsInside(float l, float x, float y) const;

	/// Returns the smallest AABB that encloses this capsule.
	/** @see MinimalEnclosingOBB(). */
	AABB MinimalEnclosingAABB() const;

	/// Returns the smallest OBB that encloses this capsule.
	/** @see MinimalEnclosingAABB(). */
	OBB MinimalEnclosingOBB() const;

	/// Generates a random point inside this capsule.
	/** The points are distributed uniformly.
		@see RandomPointOnSurface(). */
	float3 RandomPointInside(LCG &rng) const;

	/// Generates a random point on the surface of this Capsule.
	/** @todo The points are NOT distributed uniformly. Convert this to using the rejection method and RandomPointInside()
			to produce a uniform distribution.
		@see RandomPointInside(). */
	float3 RandomPointOnSurface(LCG &rng) const;

	/// Moves this capsule by the given offset vector.
	/** @note This function operates in-place.
		@param offset The world space offset to apply to the position of this capsule.
		@see Transform(), Scale(). */
	void Translate(const float3 &offset);

	/// Applies a uniform scale to this Capsule.
	/** This function scales this capsule structure in-place, using the given center point as the origin
		for the scaling operation.
		@param centerPoint Specifies the center of the scaling operation, in world space.
		@param scaleFactor The uniform scale factor to apply to each world space axis.
		@see Translate(), Transform(). */
	void Scale(const float3 &centerPoint, float scaleFactor);

	/// Applies a transformation to this capsule.
	/** @param transform The transformation to apply to this capsule. This transformation must be
		affine, and must contain an orthogonal set of column vectors (may not contain shear or projection).
		The transformation can only contain uniform scale, and may not contain mirroring.
		@see Translate(), Scale(), classes float3x3, float3x4, float4x4, Quat. */
	void Transform(const float3x3 &transform);
	void Transform(const float3x4 &transform);
	void Transform(const float4x4 &transform);
	void Transform(const Quat &transform);

	/// Computes the closest point inside this capsule to the given point.
	/** If the target point lies inside this capsule, then that point is returned.
		@see Distance(), Contains(), Intersects().
		@todo Add ClosestPoint(Line/Ray/LineSegment/Plane/Triangle/Polygon/Circle/Disc/AABB/OBB/Sphere/Capsule/Frustum/Polyhedron). */
	float3 ClosestPoint(const float3 &targetPoint) const;

	/// Computes the distance between this capsule and the given object.
	/** This function finds the nearest pair of points on this and the given object, and computes their distance.
		If the two objects intersect, or one object is contained inside the other, the returned distance is zero.
		@todo Add Distance(Triangle/Polygon/Circle/Disc/Capsule).
		@see Contains(), Intersects(), ClosestPoint(). */
	float Distance(const float3 &point) const;
	float Distance(const Plane &plane) const;
	float Distance(const Sphere &sphere) const;
	float Distance(const Ray &ray) const;
	float Distance(const Line &line) const;
	float Distance(const LineSegment &lineSegment) const;
	float Distance(const Capsule &capsule) const;

	/// Tests if the given object is fully contained inside this capsule.
	/** This function returns true if the given object lies inside this capsule, and false otherwise.
		@note The comparison is performed using less-or-equal, so the surface of this capsule count as being inside, but
			due to float inaccuracies, this cannot generally be relied upon.
		@todo Add Contains(Circle/Disc/Sphere/Capsule).
		@see Distance(), Intersects(), ClosestPoint(). */
	bool Contains(const float3 &point) const;
	bool Contains(const LineSegment &lineSegment) const;
	bool Contains(const Triangle &triangle) const;
	bool Contains(const Polygon &polygon) const;
	bool Contains(const AABB &aabb) const;
	bool Contains(const OBB &obb) const;
	bool Contains(const Frustum &frustum) const;
	bool Contains(const Polyhedron &polyhedron) const;

	/// Tests whether this capsule and the given object intersect.
	/** Both objects are treated as "solid", meaning that if one of the objects is fully contained inside
		another, this function still returns true. (e.g. in case a line segment is contained inside this capsule,
		or this capsule is contained inside a Sphere, etc.)
		The first parameter of this function specifies the other object to test against.
		@see Contains(), Distance(), ClosestPoint().
		@todo Add Intersects(Circle/Disc). */
	bool Intersects(const Ray &ray) const;
	bool Intersects(const Line &line) const;
	bool Intersects(const LineSegment &lineSegment) const;
	bool Intersects(const Plane &plane) const;
	bool Intersects(const Sphere &sphere) const;
	bool Intersects(const Capsule &capsule) const;
	bool Intersects(const AABB &aabb) const;
	bool Intersects(const OBB &obb) const;
	bool Intersects(const Triangle &triangle) const;
	bool Intersects(const Polygon &polygon) const;
	bool Intersects(const Frustum &frustum) const;
	bool Intersects(const Polyhedron &polyhedron) const;

#ifdef MATH_ENABLE_STL_SUPPORT
	/// Returns a human-readable representation of this Capsule. Most useful for debugging purposes.
	/** The returned string specifies the line segment and the radius of this Capsule. */
	std::string ToString() const;
#endif
#ifdef MATH_QT_INTEROP
	operator QString() const { return toString(); }
	QString toString() const { return QString::fromStdString(ToString()); }
#endif
};

Capsule operator *(const float3x3 &transform, const Capsule &capsule);
Capsule operator *(const float3x4 &transform, const Capsule &capsule);
Capsule operator *(const float4x4 &transform, const Capsule &capsule);
Capsule operator *(const Quat &transform, const Capsule &capsule);

#ifdef MATH_QT_INTEROP
Q_DECLARE_METATYPE(Capsule)
Q_DECLARE_METATYPE(Capsule*)
#endif

#ifdef MATH_ENABLE_STL_SUPPORT
std::ostream &operator <<(std::ostream &o, const Capsule &capsule);
#endif

MATH_END_NAMESPACE


text:
import { EntityBase } from "./entity-base";

export class UserElementCell extends EntityBase {

    // Server-side
    UserId: number = 0;
    ElementCellId: number = 0;
    DecimalValue: number = null;

    static initializer(entity: UserElementCell) {
        super.initializer(entity);
    }
}


text:
'use strict'

/**
 * Inner shim:
 * Expected to launched by outer shim.
 * Monitors it's parent so it isn't left orphaned
 */

let loaded = false

let lastPulse = Date.now()

// expiry timer incase parent leaves us behind as an orphan
let pulseCheckInterval = setInterval(check, 1000)
pulseCheckInterval.unref()

process.on('message', function (msg) {
  if (msg.type && msg.type === 'heartbeat') {
    lastPulse = Date.now()
  }

  // Actually load the application up!
  if (msg.module && loaded === false) {
    loaded = true
    console.log(`[inner shim] loading ${msg.module}`)
    return require(msg.module)
  }
})

function check () {
  const now = Date.now()
  if (now - lastPulse > 5000) {
    console.log('[inner shim] no heartbeat recieved for 5 seconds - exiting')
    process.exit(1)
  }
}

/**
 * Phone home
 */
console.log(`[inner shim] phoning home`)
process.send('started')

/**
 * Tell parent about our view of the world
 */
process.send({
  type: 'process-state',
  state: {
    version: process.version
  }
})


text:
#include <sdl/SDL.h>
#include <nodeKitten/core/platform/platform.h>
#include <nodeKitten/core/gl/gl.h>

static char *data_path = NULL;
static float renderScaleX = 1.0;
static float renderScaleY = 1.0;
static SDL_Window *displayWindow = nullptr;
static SDL_Renderer *displayRenderer = nullptr;

void InitializeDataPath() {
    char *base_path = SDL_GetBasePath();
    if (base_path) {
        data_path = base_path;
    } else {
        data_path = SDL_strdup("./");
    }
}

namespace Platform {
    namespace Screen {
        F1t scale() {
            return 1.0;
        }
    }

    std::string appDirectory() {
        return std::string(data_path);
    }
}

class NKSDLView : public SceneController {

public:
    NKSDLView(F1t width = 800, F1t height = 600) : SceneController(V2t{width, height}) {
        sdl_width = width;
        sdl_height = height;
    }

    ~NKSDLView() {
        _running = false;
        cleanup();
    }

    bool setup() {

        InitializeDataPath();

        //First we need to start up SDL, and make sure it went ok
        if (SDL_Init(SDL_INIT_VIDEO) != 0) {
            std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
            return 0;
        }

        //to do: SDL_WINDOW_ALLOW_HIGHDPI
        SDL_RendererInfo displayRendererInfo;
        auto flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
        SDL_CreateWindowAndRenderer(sdl_width, sdl_height, flags, &displayWindow, &displayRenderer);
        SDL_GetRendererInfo(displayRenderer, &displayRendererInfo);
        /*TODO: Check that we have OpenGL */

        if ((displayRendererInfo.flags & SDL_RENDERER_ACCELERATED) == 0 ||
            (displayRendererInfo.flags & SDL_RENDERER_TARGETTEXTURE) == 0) {
            /*TODO: Handle this. We have no render surface and not accelerated. */
        }

        nkLog("SDL_Init Correctly: %d x %d", sdl_width, sdl_height);
        nkLog("%1.2f pixel density", Platform::Screen::scale());
        return 1;
    }

    bool loop() {

        SDL_Event event;

        while (_running) {
            while (SDL_PollEvent(&event)) {
                if (event.type == SDL_QUIT)_running = false;
                else if (event.type == SDL_KEYDOWN)
                    onKeyboardDown(event.key);
                else if (event.type == SDL_KEYUP)onKeyboardUp(event.key);
                else if (event.type == SDL_MOUSEMOTION) {
                    SDL_MouseMotionEvent mmevent = event.motion;
                    mmevent.y = sdl_height - mmevent.y;
                    mmevent.yrel = -mmevent.yrel;
                    onMouseMotion(mmevent);
                } else if (event.type == SDL_MOUSEBUTTONDOWN) {
                    SDL_MouseButtonEvent mbevent = event.button;
                    mbevent.y = sdl_height - mbevent.y;
                    onMouseButtonDown(mbevent);
                }

                if (event.type == SDL_WINDOWEVENT) {
                    switch (event.window.event) {
                        case SDL_WINDOWEVENT_SIZE_CHANGED:
                            sdl_width = event.window.data1;
                            sdl_height = event.window.data2;

//                            glClearColor(0.f, 0.f, 0.f, 1.f);
//                            glViewport(0, 0, sdl_width, sdl_height);
//                            glClear(GL_COLOR_BUFFER_BIT);

                            scene()->size.set(V2Make(sdl_width, sdl_height));
                            break;

                        default:
                            onEvent(&event);

                    }
                } else
                    onEvent(&event);
            }

            // DRAW CYCLE
            SDL_RenderClear(displayRenderer);
            SceneController::draw();
            SDL_RenderPresent(displayRenderer);
            //

            SDL_Delay(_cycle_ms);
            _time += _cycle_ms * 0.001;
            //test
            //_view_y+=1.1;
        }

        cleanup();

        return 0;
    }

    int _cycle_ms = 10;
    double _time = 0;

private:
    int sdl_width;
    int sdl_height;

    bool _running = true;

    virtual void onKeyboardDown(SDL_KeyboardEvent event) {};

    virtual void onKeyboardUp(SDL_KeyboardEvent event) {};

    virtual void onMouseMotion(SDL_MouseMotionEvent event) {};

    virtual void onMouseButtonDown(SDL_MouseButtonEvent event) {};

    virtual void onEvent(SDL_Event *event) {

        if (event->type == SDL_WINDOWEVENT) {
            switch (event->window.event) {
                case SDL_WINDOWEVENT_SHOWN:
                    SDL_Log("Window %d shown", event->window.windowID);
                    break;
                case SDL_WINDOWEVENT_HIDDEN:
                    SDL_Log("Window %d hidden", event->window.windowID);
                    break;
                case SDL_WINDOWEVENT_EXPOSED:
//                    SDL_Log("Window %d exposed", event->window.windowID);
                    break;
                case SDL_WINDOWEVENT_MOVED:
                    SDL_Log("Window %d moved to %d,%d",
                            event->window.windowID, event->window.data1,
                            event->window.data2);
                    break;
                case SDL_WINDOWEVENT_RESIZED:
                    SDL_Log("Window %d resized to %dx%d",
                            event->window.windowID, event->window.data1,
                            event->window.data2);
                    break;
                case SDL_WINDOWEVENT_SIZE_CHANGED:
                    SDL_Log("Window %d size changed to %dx%d",
                            event->window.windowID, event->window.data1,
                            event->window.data2);
                    break;
                case SDL_WINDOWEVENT_MINIMIZED:
                    SDL_Log("Window %d minimized", event->window.windowID);
                    break;
                case SDL_WINDOWEVENT_MAXIMIZED:
                    SDL_Log("Window %d maximized", event->window.windowID);
                    break;
                case SDL_WINDOWEVENT_RESTORED:
                    SDL_Log("Window %d restored", event->window.windowID);
                    break;
                case SDL_WINDOWEVENT_ENTER:
                    SDL_Log("Mouse entered window %d",
                            event->window.windowID);
                    break;
                case SDL_WINDOWEVENT_LEAVE:
                    SDL_Log("Mouse left window %d", event->window.windowID);
                    break;
                case SDL_WINDOWEVENT_FOCUS_GAINED:
                    SDL_Log("Window %d gained keyboard focus",
                            event->window.windowID);
                    break;
                case SDL_WINDOWEVENT_FOCUS_LOST:
                    SDL_Log("Window %d lost keyboard focus",
                            event->window.windowID);
                    break;
                case SDL_WINDOWEVENT_CLOSE:
                    SDL_Log("Window %d closed", event->window.windowID);
                    break;
                default:
                    SDL_Log("Window %d got unknown event %d",
                            event->window.windowID, event->window.event);
                    break;
            }
        }

    };

    virtual void cleanup() {
        //if(font)TTF_CloseFont(font);
        SDL_DestroyWindow(displayWindow);
        SDL_Quit();
    };

};