# This app's data and plots are heavily inspired from the scikit-learn Classifier
# comparison tutorial. You can find it here:
# http://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html
# The app mimics the dash for python application that can be found here:
# https://github.com/plotly/dash-sample-apps/tree/master/apps/dash-svm
# The Confusion Matrix Pie Chart format was inspired by Nicolas's Dash ROC app.
# The data used in this app were meant to generally replicate the datasets
# built in to scikit-learn, and were obtained using the clusterSim package
# See data/getData.R to see how the data were obtained

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

appName <- Sys.getenv("DASH_APP_NAME")
if (appName != ""){
  pathPrefix <- sprintf("/%s/", appName)

  Sys.setenv(DASH_ROUTES_PATHNAME_PREFIX = pathPrefix,
             DASH_REQUESTS_PATHNAME_PREFIX = pathPrefix)
}

source("utils/helperFunctions.R")
source("utils/reusableComponents.R")

# Read in stored datasets (see data/getData.R to see how data was acquired)
dataList <- readRDS("data/data.rds")

app <- Dash$new(name = "DashR SVM Explorer")

app$layout(
  htmlDiv(
    list(
      htmlDiv(
        className = "banner",
        children = list(
          htmlDiv(
            className = "container scalable",
            children = list(
              htmlH2(
                htmlA(
                  "Support Vector Machine (SVM) Explorer",
                  href = "https://github.com/plotly/dash-sample-apps/tree/master/apps/dashr-svm",
                  style = list(
                    textDecoration = "none",
                    color = "inherit"
                  )
                )
              ),
              htmlA(
                htmlImg(src = "assets/dash-logo.png"),
                href = "https://plot.ly/products/dash/"
              )
            )
          )
        )
      ),
      htmlDiv(
        id = "body",
        className = "container scalable",
        children = list(
          htmlDiv(
            id = "app-container",
            className = "row",
            children = list(
              htmlDiv(
                id = "left-column",
                className = "three columns",
                style = list(
                  minWidth = "24.5%",
                  maxHeight = "calc(100vh - 85px)",
                  overflowY = "auto",
                  overflowX = "hidden"
                ),
                children = list(
                  # card() is defined in utils/reusableComponents.R
                  card(
                    id = "first-card",
                    children = list(
                      # namedDropdown is defined in utils/reusableComponents.R
                      namedDropdown(
                        name = "Select Dataset",
                        id = "dropdown-select-dataset",
                        options = list(
                          list(label = "Moons", value = "moons"),
                          list(
                            label = "Linearly Separable",
                            value = "linear"
                          ),
                          list(label = "Circles", value = "circles")
                        ),
                        clearable = FALSE,
                        searchable = FALSE,
                        value = "moons"
                      ),
                      # namedSlider is defined in utils/reusableComponents.R
                      namedSlider(
                        name = "Sample Size",
                        id = "slider-dataset-sample-size",
                        min = 100,
                        max = 500,
                        step = 100,
                        marks = as.list(
                          setNames(
                            seq(100, 500, 100),
                            seq(100, 500, 100)
                          )
                        ),
                        value = 300
                      ),
                      namedSlider(
                        name = "Noise Level",
                        id = "slider-dataset-noise-level",
                        min = 0,
                        max = 1,
                        step = 0.1,
                        marks = as.list(
                          setNames(
                            seq(0, 1, 0.2),
                            seq(0, 1, 0.2)
                          )
                        ),
                        value = 0.2
                      )
                    )
                  ),
                  card(
                    id = "button-card",
                    children = list(
                      namedSlider(
                        name = "Threshold",
                        id = "slider-threshold",
                        min = 0,
                        max = 1,
                        value = 0.5,
                        step = 0.1
                      ),
                      htmlButton(
                        "Reset Threshold",
                        id = "button-zero-threshold",
                        style = list(display = "table", margin = "0 auto")
                      )
                    )
                  ),
                  card(
                    id = "last-card",
                    children = list(
                      namedDropdown(
                        name = "Kernel",
                        id = "dropdown-svm-parameter-kernel",
                        options = list(
                          list(
                            label = "Radial basis function (RBF)",
                            value = "rbf"
                          ),
                          list(label = "Linear", value = "linear"),
                          list(label = "Polynomial", value = "poly"),
                          list(label = "Sigmoid", value = "sigmoid")
                        ),
                        value = "rbf",
                        clearable = FALSE,
                        searchable = FALSE
                      ),
                      namedSlider(
                        name = "Cost (C)",
                        id = "slider-svm-parameter-C-power",
                        min = -2,
                        max = 4,
                        marks = as.list(setNames(10 ** (-2:4), -2:4)),
                        value = 0
                      ),
                      formattedSlider(
                        id = "slider-svm-parameter-C-coef",
                        min = 1,
                        max = 9,
                        value = 1
                      ),
                      namedSlider(
                        name = "Degree",
                        id = "slider-svm-parameter-degree",
                        min = 2,
                        max = 10,
                        value = 3,
                        step = 1,
                        marks = as.list(
                          setNames(
                            seq(2, 10, 2),
                            seq(2, 10, 2)
                          )
                        )
                      ),
                      namedSlider(
                        name = "Gamma",
                        id = "slider-svm-parameter-gamma-power",
                        min = -5,
                        max = 0,
                        value = -1,
                        marks = as.list(setNames(10 ** (-5:0), -5:0))
                      ),
                      # formattedSlider is defined in utils/reusableComponents.R
                      formattedSlider(
                        id = "slider-svm-parameter-gamma-coef",
                        min = 1,
                        max = 9,
                        value = 5
                      ),
                      # namedRadioItems is defined in utils/reusableComponents.R
                      namedRadioItems(
                        name = "Shrinking",
                        id = "radio-svm-parameter-shrinking",
                        labelStyle = list(
                          marginRight = "7px",
                          display = "inline-block"
                        ),
                        options = list(
                          list(label = " Enabled", value = TRUE),
                          list(label = " Disabled", value = FALSE)
                        ),
                        value = TRUE
                      )
                    )
                  ),
                  htmlDiv(
                    dccMarkdown(
                      paste0(
                         "[Click here](https://github.com/plotly/dash-sample-apps/tree/master/apps/dashr-svm)",
                         " to visit the project repo, ",
                         "and learn about how to use the app"
                      )
                    ),
                    style = list(
                      margin = "20px 20px",
                      textAlign = "center",
                      color = "#a5b1cd"
                    )
                  )
                )
              ),
              htmlDiv(
                id = "div-graphs",
                children = list(
                  htmlDiv(
                    className = "six columns",
                    id = "svm-graph-container",
                    style = list(marginTop = "1rem"),
                    children = list(
                      dccGraph(
                        id = "main_figure",
                        figure = plot_ly(
                          type = "contour"
                        ) %>%
                          layout(
                            paper_bgcolor = "#272b38",
                            plot_bgcolor = "#272b38",
                            xaxis = list(
                              zeroline = FALSE,
                              showline = FALSE,
                              showticklabels = FALSE,
                              showgrid = FALSE
                            ),
                            yaxis = list(
                              zeroline = FALSE,
                              showline = FALSE,
                              showticklabels = FALSE,
                              showgrid = FALSE
                            )
                          ),
                        style = list(
                          height = "calc(100vh - 90px)",
                          margin = "0 1.66rem"
                        ),
                        config = list(displayModeBar = FALSE)
                      )
                    )
                  ),
                  htmlDiv(
                    className = "three columns",
                    id = "graphs-container",
                    style = list(
                      minWidth = "22%",
                      height = "calc(100vh - 90px)",
                      marginTop = "1rem",
                      "-moz-user-select" = "none",
                      "-webkit-user-select" = "none",
                      "-ms-user-select" = "none"
                    ),
                    children = list(
                      dccGraph(
                        id = "graph-line-roc-curve",
                        style = list(height = "40%"),
                        figure = plot_ly(
                            type = "scatter",
                            mode = "lines"
                          ) %>%
                          layout(
                            paper_bgcolor = "#272b38",
                            plot_bgcolor = "#272b38",
                            xaxis = list(
                              zeroline = FALSE,
                              showline = FALSE,
                              showticklabels = FALSE,
                              showgrid = FALSE
                            ),
                            yaxis = list(
                              zeroline = FALSE,
                              showline = FALSE,
                              showticklabels = FALSE,
                              showgrid = FALSE
                            )
                          ),
                        config = list(displayModeBar = FALSE)
                      ),
                      dccGraph(
                        id = "graph-pie-confusion-matrix",
                        style = list(height = "55%", marginTop = "5%"),
                        figure = plot_ly(
                          type = "pie"
                        ) %>%
                          layout(
                            paper_bgcolor = "#272b38",
                            plot_bgcolor = "#272b38",
                            xaxis = list(
                              zeroline = FALSE,
                              showline = FALSE,
                              showticklabels = FALSE,
                              showgrid = FALSE
                            ),
                            yaxis = list(
                              zeroline = FALSE,
                              showline = FALSE,
                              showticklabels = FALSE,
                              showgrid = FALSE
                            )
                          ),
                        config = list(displayModeBar = FALSE)
                      )
                    )
                  )
                )
              )
            )
          )
        )
      )
    )
  )
)

app$callback(
  output("slider-svm-parameter-gamma-coef", "marks"),
  list(input("slider-svm-parameter-gamma-power", "value")),
  function(power){
    s <- 10 ** power
    as.list(
      setNames(
        lapply(seq(1, 10, 2) * s, round, 8),
        seq(1, 10, 2)
      )
    )
  }
)

app$callback(
  output("slider-svm-parameter-C-coef", "marks"),
  list(input("slider-svm-parameter-C-power", "value")),
  function(power){
    s <- 10 ** power
    as.list(
      setNames(
        round(seq(1, 10, 2) * s, 8),
        seq(1, 10, 2)
      )
    )
  }
)

app$callback(
  output("slider-threshold", "value"),
  list(input("button-zero-threshold", "n_clicks"),
       state("main_figure", "figure")),
  function(n_clicks, figure){
    if (!identical(n_clicks, list(NULL))){
      Z <- unlist(figure$data[[1]]$z)
      value <- - (min(Z) / (max(Z) - min(Z)))
    } else {
        value <- 0.4959986285375595
    }
    return(value)
  }
)

app$callback(
  output("slider-svm-parameter-degree", "disabled"),
  list(input("dropdown-svm-parameter-kernel", "value")),
  function(kernel){
    kernel != "poly"
  }
)

app$callback(
  output("slider-svm-parameter-gamma-coef", "disabled"),
  list(input("dropdown-svm-parameter-kernel", "value")),
  function(kernel){
    !kernel %in% c("rbf", "poly", "sigmoid")
  }
)

app$callback(
  output("slider-svm-parameter-gamma-power", "disabled"),
  list(input("dropdown-svm-parameter-kernel", "value")),
  function(kernel){
    !kernel %in% c("rbf", "poly", "sigmoid")
  }
)

app$callback(
  output("div-graphs", "children"),
  list(
    input("slider-svm-parameter-degree", "value"),
    input("slider-svm-parameter-C-coef", "value"),
    input("slider-svm-parameter-C-power", "value"),
    input("slider-svm-parameter-gamma-coef", "value"),
    input("slider-svm-parameter-gamma-power", "value"),
    input("dropdown-select-dataset", "value"),
    input("slider-dataset-noise-level", "value"),
    input("dropdown-svm-parameter-kernel", "value"),
    input("slider-dataset-sample-size", "value"),
    input("slider-threshold", "value"),
    input("radio-svm-parameter-shrinking", "value")
  ),
  function(degree,
           C_coef,
           C_power,
           gamma_coef,
           gamma_power,
           dataset,
           noise,
           kernel,
           n_points,
           threshold,
           shrinking){
    set.seed(42)
    if (dataset == "moons"){
      noise <- matrix(rnorm( (n_points * 2), sd = noise), ncol = 2)
      dat <- dataList$moons[sample(500, n_points)]
      dat[, c("X1", "X2") := dat[, c("X1", "X2")] + noise]
    } else if (dataset == "circles"){
      noise <- matrix(rnorm( (n_points * 2), sd = noise), ncol = 2)
      dat <- dataList$circles[sample(500, n_points)]
      dat[, c("X1", "X2") := dat[, c("X1", "X2")] + noise]
    } else if (dataset == "linear"){
      noise <- matrix(rnorm( (n_points * 2), sd = noise + 0.05), ncol = 2)
      dat <- dataList$linear[sample(500, n_points)]
      dat[, c("X1", "X2") := dat[, c("X1", "X2")] + noise]
    }
    C <- C_coef * 10 ** C_power
    gamma <- gamma_coef * 10 ** gamma_power
    # functions to split data and run the svm defined in utils/helperFunctions.R
    splitData <- trainTestSplit(dat)
    svm <- runSVM(
      train_data = splitData[["train"]],
      kernel = kernel,
      degree = degree,
      sigma = gamma,
      C = C,
      shrinking = shrinking
    )
    # plotting functions used here defined in utils/helperFunctions.R
    f <- generate_main_plot(splitData, svm, threshold = threshold)
    pieConf <- pieConfusionMatrix(svm, splitData, threshold = threshold)
    ROC <- rocCurve(splitData, svm)
    list(
      htmlDiv(
        className = "six columns",
        id = "svm-graph-container",
        style = list(marginTop = "1rem"),
        children = list(
          dccGraph(
            id = "main_figure",
            figure = f,
            style = list(
              height = "calc(100vh - 90px)",
              margin = "0 1.66rem"
            ),
            config = list(displayModeBar = FALSE)
          )
        )
      ),
      htmlDiv(
        className = "three columns",
        id = "graphs-container",
        style = list(
          minWidth = "22%",
          height = "calc(100vh - 90px)",
          marginTop = "1rem",
          "-moz-user-select" = "none",
          "-webkit-user-select" = "none",
          "-ms-user-select" = "none"
        ),
        children = list(
          dccGraph(
            id = "graph-line-roc-curve",
            style = list(height = "40%"),
            figure = ROC,
            config = list(displayModeBar = FALSE)
          ),
          dccGraph(
            id = "graph-pie-confusion-matrix",
            style = list(height = "55%", marginTop = "5%"),
            figure = pieConf,
            config = list(displayModeBar = FALSE))
        )
      )
    )
  }
)

if (appName != "") {
  app$run_server(host = "0.0.0.0", port = Sys.getenv('PORT', 8050))
} else {
  app$run_server()
}


Copyright (c) 2010, Google Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.

  * Neither the name of Google nor the names of its contributors may
    be used to endorse or promote products derived from this software
    without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


forever-agent

HTTP Agent that keeps socket connections alive between keep-alive requests. Formerly part of mikeal/request, now a standalone module.


/* SystemJS module definition */
declare var module: NodeModule;
interface NodeModule {
  id: string;
}


// Copyright (C) 2016 by rr-
//
// This file is part of arc_unpacker.
//
// arc_unpacker is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at
// your option) any later version.
//
// arc_unpacker 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. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with arc_unpacker. If not, see <http://www.gnu.org/licenses/>.

#include "dec/whale/dat_archive_decoder.h"
#include "test_support/catch.h"
#include "test_support/decoder_support.h"
#include "test_support/file_support.h"

using namespace au;
using namespace au::dec::whale;

static const std::string dir = "tests/dec/whale/files/dat/";

static void do_test(
    DatArchiveDecoder &decoder,
    const std::string &input_path,
    const std::vector<std::shared_ptr<io::File>> &expected_files)
{
    const auto input_file = tests::file_from_path(dir + input_path);
    const auto actual_files = tests::unpack(decoder, *input_file);
    tests::compare_files(actual_files, expected_files, true);
}

TEST_CASE("Whale DAT archives", "[dec]")
{
    SECTION("Plain")
    {
        DatArchiveDecoder decoder;
        decoder.add_file_name("123.txt");
        decoder.add_file_name("abc.txt");
        do_test(
            decoder,
            "plain.dat",
            {
                tests::stub_file("123.txt", "1234567890"_b),
                tests::stub_file("abc.txt", "abcdefghijklmnopqrstuvwxyz"_b),
            });
    }

    SECTION("Compressed")
    {
        DatArchiveDecoder decoder;
        decoder.add_file_name("123.txt");
        decoder.add_file_name("abc.txt");
        decoder.set_game_title("A Dog Story");
        do_test(
            decoder,
            "compressed.dat",
            {
                tests::stub_file("123.txt", "1234567890"_b),
                tests::stub_file("abc.txt", "abcdefghijklmnopqrstuvwxyz"_b),
            });
    }

    SECTION("Compressed, unknown names")
    {
        DatArchiveDecoder decoder;
        decoder.set_game_title("A Dog Story");
        do_test(
            decoder,
            "compressed.dat",
            {
                tests::stub_file("0000.txt", "1234567890"_b),
                tests::stub_file("0001.txt", "abcdefghijklmnopqrstuvwxyz"_b),
            });
    }

    SECTION("Fully encrypted")
    {
        DatArchiveDecoder decoder;
        decoder.add_file_name("123.txt");
        decoder.add_file_name("abc.txt");
        do_test(
            decoder,
            "encrypted.dat",
            {
                tests::stub_file("123.txt", "1234567890"_b),
                tests::stub_file("abc.txt", "abcdefghijklmnopqrstuvwxyz"_b),
            });
    }
}


:107E000001C0B7C0112484B790E89093610010922C
:107E10006100882361F0982F9A70923041F081FFC1
:107E200002C097EF94BF282E80E0C6D0E9C085E05D
:107E30008093810082E08093D00088E18093D1001C
:107E40008FE88093D40086E08093D2008EE0B4D097
:107E5000209A84E02DE53DEF91E03093850020935A
:107E6000840096BBB09BFECF189AA8954091D00095
:107E700047FD02C0815089F793D0813479F490D0C6
:107E8000182FA0D0123811F480E004C088E0113817
:107E900009F083E07ED080E17CD0EECF823419F40B
:107EA00084E198D0F8CF853411F485E0FACF853598
:107EB00041F476D0C82F74D0D82FCC0FDD1F82D0DC
:107EC000EACF863519F484E085D0DECF843691F58B
:107ED00067D066D0F82E64D0D82E00E011E05801AB
:107EE0008FEFA81AB80A5CD0F80180838501FA10D8
:107EF000F6CF68D0F5E4DF1201C0FFCF50E040E0DC
:107F000063E0CE0136D08E01E0E0F1E06F0182E067
:107F1000C80ED11C4081518161E0C8012AD00E5F9A
:107F20001F4FF601FC10F2CF50E040E065E0CE01BB
:107F300020D0B1CF843771F433D032D0F82E30D086
:107F400041D08E01F80185918F0123D0FA94F11070
:107F5000F9CFA1CF853739F435D08EE11AD085E934
:107F600018D087E197CF813509F0A9CF88E024D0D8
:107F7000A6CFFC010A0167BFE895112407B600FCF3
:107F8000FDCF667029F0452B19F481E187BFE89594
:107F900008959091D00095FFFCCF8093D60008956E
:107FA0008091D00087FFFCCF8091D00084FD01C07C
:107FB000A8958091D6000895E0E6F0E098E19083DE
:107FC00080830895EDDF803219F088E0F5DFFFCF80
:107FD00084E1DFCFCF93C82FE3DFC150E9F7CF9122
:027FE000F1CFDF
:027FFE00000879
:0400000300007E007B
:00000001FF


import {LogManager} from 'aurelia-framework';
import {inject} from 'aurelia-framework';
import {IdentityService} from './services/identity-service';
import {AlertService} from './services/alert-service';

let log = LogManager.getLogger('Login');

@inject(IdentityService, AlertService)
export class Login {

  errorMessage = undefined;

  constructor(identityService, alertService) {
    this.identityService = identityService;
    this.alertService = alertService;
  }

  get org() {
    return this.identityService.org;
  }

  login() {
    this.identityService.enroll(this.username, this.password).then(() => {
      this.errorMessage = undefined;
      this.alertService.success(`${this.username} logged in`)
    }).catch(e => {
      this.errorMessage = e;
      this.alertService.error(`cannot enroll, caught ${e}`);
    });
  }

}


/**
 *
 * WARNING! This file was autogenerated by:
 *  _   _ _   _ __   __
 * | | | | | | |\ \ / /
 * | | | | |_| | \ V /
 * | | | |  _  | /   \
 * | |_| | | | |/ /^\ \
 *  \___/\_| |_/\/   \/
 *
 * This file was autogenerated by UnrealHxGenerator using UHT definitions.
 * It only includes UPROPERTYs and UFUNCTIONs. Do not modify it!
 * In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix
**/
package unreal;

@:glueCppIncludes("CoreUObject.h")
@:uextern @:uclass extern class UStrProperty extends unreal.UProperty {

}


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
</configuration>


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="ca_ES">
<defaultcodec>UTF-8</defaultcodec>
<context>
    <name>KMoreExtendGalleryTile</name>
    <message>
        <source>Browse others</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>More templates...</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Standard screen</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Wide screen</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>KSlideLibraryLogic</name>
    <message>
        <source>ContentSlideType_Cover</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>ContentSlideType_Catalog</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>ContentSlideType_Main</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>ContentSlideType_Trans</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>ContentSlideType_Ending</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>ContentSlideType_More</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>KTemplateDetailHeaderButton</name>
    <message>
        <source>Back</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>KTemplateDlgBottom</name>
    <message>
        <source>Blank document</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>From template</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>KTemplateDlgDetailHeader</name>
    <message>
        <source>New</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>KTemplateDlgHeader</name>
    <message>
        <source>New</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Standard</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Wide screen</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Classification</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>KTemplateDownloadFinishTip</name>
    <message>
        <source>apply</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>template download success</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>template download failed</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>KTemplateExtendGallery</name>
    <message>
        <source>Recently Used</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>More templates</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>KWppTemplateItem</name>
    <message>
        <source>Load failed.</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Apply to &All Slides</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Apply to &Selected Slides</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>KWpsAssistMagicOnTabbarCommand</name>
    <message>
        <source>Quick Slide Design</source>
        <translation type="unfinished"></translation>
    </message>
</context>
<context>
    <name>KxInsertPicturesToMultiSlide</name>
    <message>
        <source>Insert Picture To Multiple Slides</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Unidentifiable picture format.</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>The picture you inserted is too large. Please compress it to save the disk space.
Note that compressing pictures may reduce the quality of your pictures. Do you want to compress it(them)?</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>All Pictures(*.emf;*.wmf;*.jpg;*.jpeg;*.jpe;*.png;*.bmp;*.gif;*.tif;*.tiff)|*.emf;*.wmf;*.jpg;*.jpeg;*.jpe;*.png;*.bmp;*.gif;*.tif;*.tiff</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Windows Enhanced Metafile(*.emf)|*.emf</source>
        <comment>DgUil_EnhancedMetaFiles</comment>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Windows Metafile(*.wmf)|*.wmf</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>JPEG File InterChange Format(*.jpg;*.jpeg;*.jpe)|*.jpg;*.jpeg;*.jpe</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Portable Network Graphics(*.png)|*.png</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Windows Bitmap(*.bmp)|*.bmp</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Graphics Interchange Format(*.gif)|*.gif</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <source>Tag Image File Format(*.tif;*.tiff)|*.tif;*.tiff</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


yallist

Yet Another Linked List

git push origin --all; git push origin --tags


/**
 * @file
 *
 * @ingroup ClassicRTEMSWorkspace
 */

/* COPYRIGHT (c) 1989-2008.
 * On-Line Applications Research Corporation (OAR).
 *
 * The license and distribution terms for this file may be
 * found in the file LICENSE in this distribution or at
 * http://www.rtems.org/license/LICENSE.
 */

#ifndef _RTEMS_RTEMS_SUPPORT_H
#define _RTEMS_RTEMS_SUPPORT_H

#include <rtems/rtems/types.h>
#include <rtems/config.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @addtogroup ClassicTasks
 */
/**@{**/

/**
 * @brief Returns the number of micro seconds for the milli seconds value @a _ms.
 */
#define RTEMS_MILLISECONDS_TO_MICROSECONDS(_ms) ((_ms) * 1000UL)

/**
 * @brief Returns the number of ticks for the milli seconds value @a _ms.
 */
#define RTEMS_MILLISECONDS_TO_TICKS(_ms) \
       (RTEMS_MILLISECONDS_TO_MICROSECONDS(_ms) / \
          rtems_configuration_get_microseconds_per_tick())

/**
 * @brief Returns the number of ticks for the micro seconds value @a _us.
 */
#define RTEMS_MICROSECONDS_TO_TICKS(_us) \
       ((_us) / rtems_configuration_get_microseconds_per_tick())

/**
 * @brief Returns @c true if the name is valid, and @c false otherwise.
 */
RTEMS_INLINE_ROUTINE bool rtems_is_name_valid (
  rtems_name name
)
{
  return ( name != 0 );
}

/**
 * @brief Breaks the object name into the four component characters @a c1,
 * @a c2, @a c3, and @a c4.
 */
RTEMS_INLINE_ROUTINE void rtems_name_to_characters(
  rtems_name    name,
  char         *c1,
  char         *c2,
  char         *c3,
  char         *c4
)
{
  *c1 = (char) ((name >> 24) & 0xff);
  *c2 = (char) ((name >> 16) & 0xff);
  *c3 = (char) ((name >> 8) & 0xff);
  *c4 = (char) ( name & 0xff);
}

/** @} */

/**
 * @defgroup ClassicRTEMSWorkspace Workspace
 *
 * @ingroup RTEMSAPIClassic
 *
 * Workspace definitions.
 */
/**@{**/

/**
 * @brief Gets Workspace Information
 *
 * Returns information about the heap that is used as the RTEMS Executive
 * Workspace in @a the_info.
 *
 * Returns @c true if successful, and @a false otherwise.
 */
bool rtems_workspace_get_information(
  Heap_Information_block  *the_info
);

/**
 * @brief Allocates Memory from the Workspace
 *
 * A number of @a bytes bytes will be allocated from the RTEMS Executive
 * Workspace and returned in @a pointer.
 *
 * Returns @c true if successful, and @a false otherwise.
 */
bool rtems_workspace_allocate(
  size_t   bytes,
  void   **pointer
);

/**
 * @brief Frees Memory Allocated from the Workspace
 *
 * This frees the memory indicated by @a pointer that was allocated from the
 * RTEMS Executive Workspace.
 *
 * Returns @c true if successful, and @a false otherwise.
 */
bool rtems_workspace_free(
  void *pointer
);

/**
 * @brief Greedy allocate that empties the workspace.
 *
 * Afterwards the heap has at most @a block_count allocatable blocks of sizes
 * specified by @a block_sizes.  The @a block_sizes must point to an array with
 * @a block_count members.  All other blocks are used.
 *
 * @see rtems_workspace_greedy_free().
 */
void *rtems_workspace_greedy_allocate(
  const uintptr_t *block_sizes,
  size_t block_count
);

/**
 * @brief Greedy allocate all blocks except the largest free block.
 *
 * Afterwards the heap has at most one allocatable block.  This block is the
 * largest free block if it exists.  The allocatable size of this block is
 * stored in @a allocatable_size.  All other blocks are used.
 *
 * @see rtems_workspace_greedy_free().
 */
void *rtems_workspace_greedy_allocate_all_except_largest(
  uintptr_t *allocatable_size
);

/**
 * @brief Frees space of a greedy allocation.
 *
 * The @a opaque argument must be the return value of
 * rtems_workspace_greedy_allocate() or
 * rtems_workspace_greedy_allocate_all_except_largest().
 */
void rtems_workspace_greedy_free( void *opaque );

/** @} */

#ifdef __cplusplus
}
#endif

#endif
/* end of include file */


# CycleGAN

**Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networks**
website: https://junyanz.github.io/CycleGAN/

arXiv: https://arxiv.org/abs/1703.10593

## Setup

To begin, you'll need the [latest version of Swift for
TensorFlow](https://github.com/tensorflow/swift/blob/master/Installation.md)
installed. Make sure you've added the correct version of `swift` to your path.

To train the model, run:

```sh
swift run CycleGAN
```


import React from 'react';
import FontAwesomeIcon from 'react-fontawesome';
import {Row,
        Col,
        FormGroup,
        Input,
        Label,
        UncontrolledTooltip,
        Button,
        Card,
        CardHeader,
        CardTitle,
        CardBody} from 'reactstrap';
import PropTypes from "prop-types";
import Pagination from './Pagination';
import classNames from 'classnames';
import {DEPLOYMENT_PIPELINES} from '../constants';
import Description from './Description';
import ContractOverviewContainer from '../containers/ContractOverviewContainer';
import FontAwesome from 'react-fontawesome';

const orderClassName = (address) => {
  return classNames('mr-4', {
    badge: true,
    'badge-success': address,
    'badge-secondary': !address
  });
};

// TODO add an ABI parser
const findConstructor = (abiDefinition) => abiDefinition.find(method => method.type === 'constructor');

const NoWeb3 = () => (
  <Row>
    <Col>

You are not connected to web3 yet

    </Col>
  </Row>
);

const LayoutContract = ({contract, children, title = contract.className, isLoading = false, isDeployed = false, deployedTitleSuffix, notDeployedTitleSuffix}) => (
  <Card>
    <CardHeader>
      <CardTitle>
        {contract.deployIndex + 1}
        {title}
        {isLoading && <FontAwesome name="spinner" spin />}
        {!isLoading && {(isDeployed && deployedTitleSuffix) || notDeployedTitleSuffix}}
      </CardTitle>
    </CardHeader>
    <CardBody>
      {children}
    </CardBody>
  </Card>
);

LayoutContract.propTypes = {
  contract: PropTypes.object,
  children: PropTypes.any,
  isLoading: PropTypes.bool,
  isDeployed: PropTypes.bool,
  title: PropTypes.any,
  deployedTitleSuffix: PropTypes.string,
  notDeployedTitleSuffix: PropTypes.string
};

const DeploymentResult = ({deployment}) => {
  if (deployment.running) {
    return
Deployment is in progress <FontAwesomeIcon className="ml-1" name="spinner" spin/>
;
  }

  if (deployment.error) {
    return
Deployment failed: {deployment.error}
;
  }

  return (
    <React.Fragment>

Deployment succeed:

        <Description label="Transaction" value={deployment.transactionHash}/>
        <Description label="Gas used" value={deployment.gasUsed}/>
        <Description label="Address" value={deployment.contractAddress}/>

    </React.Fragment>
  );
};

DeploymentResult.propTypes = {
  deployment: PropTypes.object
};

const GasEstimateResult = ({gasEstimate}) => {
  if (gasEstimate.running) {
    return
Gas Estimation is in progresss <FontAwesomeIcon className="ml-1" name="spinner" spin/>
;
  }

  if (gasEstimate.error) {
    return
Gas Estimation failed: {gasEstimate.error}
;
  }

  return
Gas Estimation succeed: {gasEstimate.gas}
;
};

GasEstimateResult.propTypes = {
  gasEstimate: PropTypes.object
};

class Web3Contract extends React.Component {
  constructor(props) {
    super(props);
    this.state = {inputs: {}};
  }

  handleOnChange(event, name) {
    let newInputs = this.state.inputs;
    newInputs[name] = event.target.value;
    this.setState({inputs: newInputs});
  }

  inputsAsArray() {
    const constructor = findConstructor(this.props.contract.abiDefinition);
    if (!constructor) return [];

    return constructor.inputs
      .map(input => this.state.inputs[input.name])
      .filter(value => value);
  }

  actionDisabled() {
    const constructor = findConstructor(this.props.contract.abiDefinition);
    if (!constructor) return false;

    return this.inputsAsArray().length !== constructor.inputs.length;
  }

  isDeployed() {
    const contractInStore = this.props.web3ContractsDeployed[this.props.contract.className];
    return contractInStore && contractInStore.isDeployed;
  }
  isCheckingIfDeployed() {
    const contractInStore = this.props.web3ContractsDeployed[this.props.contract.className];
    return contractInStore && contractInStore.running;
  }

  render() {
    const abiConstructor = findConstructor(this.props.contract.abiDefinition);
    const argumentsRequired = abiConstructor && abiConstructor.inputs.length > 0;
    const isDeployed = this.isDeployed();
    const isCheckingIfDeployed = this.isCheckingIfDeployed();
    return (
      <LayoutContract contract={this.props.contract}
                      isLoading={isCheckingIfDeployed}
                      isDeployed={isDeployed}
                      deployedTitleSuffix={`deployed at ${this.props.contract.deployedAddress}`}
                      notDeployedTitleSuffix={`not deployed`}>
        <Row>
          <Col md={6}>
            {isDeployed &&
Contract deployed
}
            {argumentsRequired &&
            <React.Fragment>

Arguments:

              {abiConstructor.inputs.map(input => (
                <FormGroup key={input.name}>
                  {input.name}
                  <Input id={input.name} placeholder={input.name} onChange={e => this.handleOnChange(e, input.name)}/>
                </FormGroup>
              ))}
            </React.Fragment>
            }

            {!this.props.web3 && <NoWeb3/>}

            {this.props.web3 &&
            <React.Fragment>
              <Button className="mr-2"
                      color="primary"
                      disabled={this.actionDisabled()}
                      onClick={() => this.props.web3EstimateGas(this.props.contract, this.inputsAsArray())}>
                Estimate
              </Button>
              <Button color="primary" disabled={this.actionDisabled()}
                      onClick={() => this.props.web3Deploy(this.props.contract, this.inputsAsArray())}>Deploy</Button>
            </React.Fragment>
            }
          </Col>
          <Col md={5}>
            {this.props.gasEstimate && <GasEstimateResult gasEstimate={this.props.gasEstimate}/>}

            {this.props.deployment && <DeploymentResult deployment={this.props.deployment}/>}
          </Col>
        </Row>
      </LayoutContract>
    );
  }
}

Web3Contract.propTypes = {
  contract: PropTypes.object,
  web3: PropTypes.object,
  web3EstimateGas: PropTypes.func,
  web3Deploy: PropTypes.func,
  gasEstimate: PropTypes.object,
  deployment: PropTypes.object,
  web3ContractsDeployed: PropTypes.object
};

const EmbarkContract = ({contract, toggleContractOverview}) => (
  <LayoutContract contract={contract}
    isDeployed={!!contract.deployedAddress}
    deployedTitleSuffix={`deployed at ${contract.deployedAddress}`}
    notDeployedTitleSuffix={'not deployed'}
    title={ toggleContractOverview(contract)}>{contract.className}}>
    {contract.deployedAddress &&
Arguments: {JSON.stringify(contract.args)}
}
    {contract.transactionHash &&
    <React.Fragment>

Transaction Hash: {contract.transactionHash}

{contract.gas} gas at {contract.gasPrice} Wei, estimated
        cost: {contract.gas * contract.gasPrice} Wei

    </React.Fragment>
    }
    {contract.deployedAddress && !contract.transactionHash &&

Contract already deployed

    }
  </LayoutContract>
);

EmbarkContract.propTypes = {
  contract: PropTypes.object,
  toggleContractOverview: PropTypes.func
};

const ContractsHeader = ({deploymentPipeline, updateDeploymentPipeline}) => (
  <Row>

      <FormGroup row>
        Deploy using
        <FormGroup check inline>

            <Input className="form-check-input"
                   type="radio"
                   onChange={() => updateDeploymentPipeline(DEPLOYMENT_PIPELINES.embark)}
                   checked={deploymentPipeline === DEPLOYMENT_PIPELINES.embark}/>
            Embark
            <FontAwesomeIcon className="ml-1" name="question" id="embark-tooltip"/>
            <UncontrolledTooltip placement="bottom" target="embark-tooltip">
              Embark will deploy the contracts automatically for you each time there is a change in one of them.
            </UncontrolledTooltip>

        </FormGroup>
        <FormGroup check inline>

            <Input className="form-check-input"
                   type="radio"
                   onChange={() => updateDeploymentPipeline(DEPLOYMENT_PIPELINES.injectedWeb3)}
                   checked={deploymentPipeline === DEPLOYMENT_PIPELINES.injectedWeb3}/>
            Injected Web3
            <FontAwesomeIcon className="ml-1" name="question" id="web3-tooltip"/>
            <UncontrolledTooltip placement="bottom" target="web3-tooltip">
              You will have full control on your deployment
            </UncontrolledTooltip>

        </FormGroup>
      </FormGroup>

  </Row>
);

ContractsHeader.propTypes = {
  deploymentPipeline:  PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.string
  ]),
  updateDeploymentPipeline: PropTypes.func
};

const Contract = ({web3, contract, deploymentPipeline, web3Deploy, web3EstimateGas, web3Deployments, web3GasEstimates, web3ContractsDeployed, toggleContractOverview}) => {
  const deployment = web3Deployments[contract.className];
  const gasEstimate = web3GasEstimates[contract.className];
  switch (deploymentPipeline) {
    case DEPLOYMENT_PIPELINES.embark:
      return <EmbarkContract contract={contract} toggleContractOverview={toggleContractOverview}/>;
    case DEPLOYMENT_PIPELINES.injectedWeb3:
      return <Web3Contract web3={web3}
                           deployment={deployment}
                           gasEstimate={gasEstimate}
                           contract={contract}
                           web3Deploy={web3Deploy}
                           web3EstimateGas={web3EstimateGas}
                           web3ContractsDeployed={web3ContractsDeployed}/>;
    default:
      return <React.Fragment/>;
  }
};

Contract.propTypes = {
  contract: PropTypes.object,
  deploymentPipeline:  PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.string
  ]),
  toggleContractOverview: PropTypes.func,
  web3: PropTypes.object,
  web3Deploy: PropTypes.func,
  web3Deployments: PropTypes.object,
  web3EstimateGas: PropTypes.func,
  web3GasEstimates: PropTypes.object,
  web3ContractsDeployed: PropTypes.object
};

class ContractsDeployment extends React.Component {
  constructor(props) {
    super(props);
    this.state = { currentContractOverview: null }
  }

  toggleContractOverview(contract) {
    if (this.state.currentContractOverview && this.state.currentContractOverview.className === contract.className) {
      return this.setState({currentContractOverview: null});
    }
    this.setState({currentContractOverview: contract});
  }

  isContractOverviewOpen() {
    return this.state.currentContractOverview && this.props.deploymentPipeline === DEPLOYMENT_PIPELINES.embark;
  }

  render() {
    const props = this.props;
    const {changePage, currentPage, numberOfPages} = props;
    return (
      <React.Fragment>
        <Row>
          <Col>
            <ContractsHeader
              deploymentPipeline={props.deploymentPipeline}
              updateDeploymentPipeline={props.updateDeploymentPipeline} />
            {!props.contracts.length && "No contracts to display"}
            {props.contracts
              .map((contract, index) => {
                contract.deployIndex = index;
                return (
                  <Contract key={contract.deployIndex}
                            contract={contract}
                            toggleContractOverview={(contract) => this.toggleContractOverview(contract)}
                            {...props} />
                );
              })}
          </Col>
          {this.isContractOverviewOpen() &&
            <Col xs={6} md={3}>
              <Card>
                <CardBody>

{this.state.currentContractOverview.className} - Overview

                  <ContractOverviewContainer contract={this.state.currentContractOverview} />
                </CardBody>
              </Card>
            </Col>
          }
        </Row>
        {numberOfPages > 1 && <Pagination changePage={changePage} currentPage={currentPage} numberOfPages={numberOfPages}/>}
      </React.Fragment>
    )
  }
}

ContractsDeployment.propTypes = {
  contracts: PropTypes.array,
  changePage: PropTypes.func,
  currentPage: PropTypes.number,
  numberOfPages: PropTypes.number,
  deploymentPipeline: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.string
  ]),
  updateDeploymentPipeline: PropTypes.func,
  web3Deployments: PropTypes.object,
  web3GasEstimates: PropTypes.object,
  web3: PropTypes.object,
  web3Deploy: PropTypes.func,
  web3EstimateGas: PropTypes.func,
  web3ContractsDeployed: PropTypes.object
};

export default ContractsDeployment;


/tmp/singleary1	input.pp	/^file { "\/tmp\/singleary1":$/;"	resource	line:3	language:PuppetManifest	end:5
/tmp/singleary2	input.pp	/^file { "\/tmp\/singleary2":$/;"	resource	line:7	language:PuppetManifest	end:9
/tmp/singleary3	input.pp	/^file { "\/tmp\/singleary3":$/;"	resource	line:11	language:PuppetManifest	end:14
/tmp/singleary4	input.pp	/^file { "\/tmp\/singleary4":$/;"	resource	line:16	language:PuppetManifest	end:19


/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#define BOOST_TEST_MODULE TNonblockingServerTest
#include <boost/test/unit_test.hpp>

#include "thrift/concurrency/Monitor.h"
#include "thrift/concurrency/Thread.h"
#include "thrift/server/TNonblockingServer.h"
#include "thrift/transport/TNonblockingServerSocket.h"
#include "thrift/stdcxx.h"

#include "gen-cpp/ParentService.h"

#include <event.h>

using apache::thrift::concurrency::Guard;
using apache::thrift::concurrency::Monitor;
using apache::thrift::concurrency::Mutex;
using apache::thrift::concurrency::PlatformThreadFactory;
using apache::thrift::concurrency::Runnable;
using apache::thrift::concurrency::Thread;
using apache::thrift::concurrency::ThreadFactory;
using apache::thrift::server::TServerEventHandler;
using apache::thrift::stdcxx::make_shared;
using apache::thrift::stdcxx::shared_ptr;

using namespace apache::thrift;

struct Handler : public test::ParentServiceIf {
  void addString(const std::string& s) { strings_.push_back(s); }
  void getStrings(std::vector<std::string>& _return) { _return = strings_; }
  std::vector<std::string> strings_;

  // dummy overrides not used in this test
  int32_t incrementGeneration() { return 0; }
  int32_t getGeneration() { return 0; }
  void getDataWait(std::string&, const int32_t) {}
  void onewayWait() {}
  void exceptionWait(const std::string&) {}
  void unexpectedExceptionWait(const std::string&) {}
};

class Fixture {
private:
  struct ListenEventHandler : public TServerEventHandler {
    public:
      ListenEventHandler(Mutex* mutex) : listenMonitor_(mutex), ready_(false) {}

      void preServe() /* override */ {
        Guard g(listenMonitor_.mutex());
        ready_ = true;
        listenMonitor_.notify();
      }

      Monitor listenMonitor_;
      bool ready_;
  };

  struct Runner : public Runnable {
    int port;
    shared_ptr<event_base> userEventBase;
    shared_ptr<TProcessor> processor;
    shared_ptr<server::TNonblockingServer> server;
    shared_ptr<ListenEventHandler> listenHandler;
    shared_ptr<transport::TNonblockingServerSocket> socket;
    Mutex mutex_;

    Runner() {
      listenHandler.reset(new ListenEventHandler(&mutex_));
    }

    virtual void run() {
      // When binding to explicit port, allow retrying to workaround bind failures on ports in use
      int retryCount = port ? 10 : 0;
      startServer(retryCount);
    }

    void readyBarrier() {
      // block until server is listening and ready to accept connections
      Guard g(mutex_);
      while (!listenHandler->ready_) {
        listenHandler->listenMonitor_.wait();
      }
    }
  private:
    void startServer(int retry_count) {
      try {
        socket.reset(new transport::TNonblockingServerSocket(port));
        server.reset(new server::TNonblockingServer(processor, socket));
        server->setServerEventHandler(listenHandler);
        if (userEventBase) {
          server->registerEvents(userEventBase.get());
        }
        server->serve();
      } catch (const transport::TTransportException&) {
        if (retry_count > 0) {
          ++port;
          startServer(retry_count - 1);
        } else {
          throw;
        }
      }
    }
  };

  struct EventDeleter {
    void operator()(event_base* p) { event_base_free(p); }
  };

protected:
  Fixture() : processor(new test::ParentServiceProcessor(make_shared<Handler>())) {}

  ~Fixture() {
    if (server) {
      server->stop();
    }
    if (thread) {
      thread->join();
    }
  }

  void setEventBase(event_base* user_event_base) {
    userEventBase_.reset(user_event_base, EventDeleter());
  }

  int startServer(int port) {
    shared_ptr<Runner> runner(new Runner);
    runner->port = port;
    runner->processor = processor;
    runner->userEventBase = userEventBase_;

    shared_ptr<ThreadFactory> threadFactory(
        new PlatformThreadFactory(
#if !USE_BOOST_THREAD && !USE_STD_THREAD
            PlatformThreadFactory::OTHER, PlatformThreadFactory::NORMAL,
            1,
#endif
            false));
    thread = threadFactory->newThread(runner);
    thread->start();
    runner->readyBarrier();

    server = runner->server;
    return runner->port;
  }

  bool canCommunicate(int serverPort) {
    shared_ptr<transport::TSocket> socket(new transport::TSocket("localhost", serverPort));
    socket->open();
    test::ParentServiceClient client(make_shared<protocol::TBinaryProtocol>(
        make_shared<transport::TFramedTransport>(socket)));
    client.addString("foo");
    std::vector<std::string> strings;
    client.getStrings(strings);
    return strings.size() == 1 && !(strings[0].compare("foo"));
  }

private:
  shared_ptr<event_base> userEventBase_;
  shared_ptr<test::ParentServiceProcessor> processor;
protected:
  shared_ptr<server::TNonblockingServer> server;
private:
  shared_ptr<concurrency::Thread> thread;

};

BOOST_AUTO_TEST_SUITE(TNonblockingServerTest)

BOOST_FIXTURE_TEST_CASE(get_specified_port, Fixture) {
  int specified_port = startServer(12345);
  BOOST_REQUIRE_GE(specified_port, 12345);
  BOOST_REQUIRE_EQUAL(server->getListenPort(), specified_port);
  BOOST_CHECK(canCommunicate(specified_port));

  server->stop();
}

BOOST_FIXTURE_TEST_CASE(get_assigned_port, Fixture) {
  int specified_port = startServer(0);
  BOOST_REQUIRE_EQUAL(specified_port, 0);
  int assigned_port = server->getListenPort();
  BOOST_REQUIRE_NE(assigned_port, 0);
  BOOST_CHECK(canCommunicate(assigned_port));

  server->stop();
}

BOOST_FIXTURE_TEST_CASE(provide_event_base, Fixture) {
  event_base* eb = event_base_new();
  setEventBase(eb);
  startServer(0);

  // assert that the server works
  BOOST_CHECK(canCommunicate(server->getListenPort()));
#if LIBEVENT_VERSION_NUMBER > 0x02010400
  // also assert that the event_base is actually used when it's easy
  BOOST_CHECK_GT(event_base_get_num_events(eb, EVENT_BASE_COUNT_ADDED), 0);
#endif
}

BOOST_AUTO_TEST_SUITE_END()


object SynchControlsForm: TSynchControlsForm
  Left = 0
  Top = 0
  Caption = 'Synchonize Controls '
  ClientHeight = 693
  ClientWidth = 828
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [dkDesktop, dkiPhone, dkiPad]
  OnCreate = FormCreate
  DesignerMobile = False
  DesignerWidth = 0
  DesignerHeight = 0
  DesignerDeviceName = ''
  DesignerOrientation = 0
  object Root1: TLayout
    Align = alClient
    Height = 693.000000000000000000
    Width = 828.000000000000000000
    object ToolBar1: TToolBar
      Height = 73.000000000000000000
      HelpType = htKeyword
      TabOrder = 0
      Width = 828.000000000000000000
      object Label4: TLabel
        Align = alCenter
        Font.Size = 12.000000000000000000
        Height = 55.000000000000000000
        HelpType = htKeyword
        Text =
          'Unidirection and Bidirectional expressions are used to synchroni' +
          'ze controls'
        TextAlign = taCenter
        Width = 433.000000000000000000
      end
    end
    object Grid1: TGridLayout
      Align = alClient
      Height = 612.000000000000000000
      ItemHeight = 200.000000000000000000
      ItemWidth = 200.000000000000000000
      Orientation = orHorizontal
      Margins.Left = 4.000000000000000000
      Margins.Top = 4.000000000000000000
      Margins.Right = 4.000000000000000000
      Margins.Bottom = 4.000000000000000000
      Width = 820.000000000000000000
      object Panel1: TPanel
        Align = alLeft
        Height = 196.000000000000000000
        HelpType = htKeyword
        Padding.Left = 5.000000000000000000
        Padding.Top = 5.000000000000000000
        Padding.Right = 5.000000000000000000
        Padding.Bottom = 5.000000000000000000
        Margins.Left = 2.000000000000000000
        Margins.Top = 2.000000000000000000
        Margins.Right = 2.000000000000000000
        Margins.Bottom = 2.000000000000000000
        Position.X = 2.000000000000000000
        Position.Y = 2.000000000000000000
        Width = 196.000000000000000000
        TabOrder = 0
        object ValueLabel1: TLabel
          Align = alTop
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 5.000000000000000000
          Position.Y = 5.000000000000000000
          Text = 'TrackBar <-> Edit and Label'
          TextAlign = taCenter
          Width = 186.000000000000000000
        end
        object Panel1TrackBar1: TTrackBar
          Frequency = 1.000000000000000000
          Height = 20.000000000000000000
          HelpType = htKeyword
          Orientation = orHorizontal
          Position.X = 42.000000000000000000
          Position.Y = 45.000000000000000000
          TabOrder = 1
          Width = 109.000000000000000000
          OnChange = OnControlChange
        end
        object Panel1Edit1: TEdit
          Touch.InteractiveGestures = [igLongTap, igDoubleTap]
          TabOrder = 2
          Text = '0'
          Position.X = 13.000000000000000000
          Position.Y = 103.000000000000000000
          Width = 110.000000000000000000
          Height = 21.000000000000000000
          HelpType = htKeyword
          KillFocusByReturn = False
          OnChange = OnControlChange
        end
        object Panel1Label1: TLabel
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 127.000000000000000000
          Position.Y = 105.000000000000000000
          Text = '0'
          TextAlign = taCenter
          Width = 50.000000000000000000
        end
        object Panel1CheckBox1: TCheckBox
          Height = 19.000000000000000000
          Position.X = 16.000000000000000000
          Position.Y = 168.000000000000000000
          TabOrder = 4
          Text = 'Active'
          Width = 120.000000000000000000
          OnChange = Panel1CheckBox1Change
        end
      end
      object Panel2: TPanel
        Align = alLeft
        Height = 196.000000000000000000
        HelpType = htKeyword
        Padding.Left = 5.000000000000000000
        Padding.Top = 5.000000000000000000
        Padding.Right = 5.000000000000000000
        Padding.Bottom = 5.000000000000000000
        Margins.Left = 2.000000000000000000
        Margins.Top = 2.000000000000000000
        Margins.Right = 2.000000000000000000
        Margins.Bottom = 2.000000000000000000
        Position.X = 202.000000000000000000
        Position.Y = 2.000000000000000000
        Width = 196.000000000000000000
        TabOrder = 1
        object TLabel
          Align = alTop
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 5.000000000000000000
          Position.Y = 5.000000000000000000
          Text = 'Two TrackBar <-> sync'
          TextAlign = taCenter
          Width = 186.000000000000000000
        end
        object Panel2Tracker1: TTrackBar
          Frequency = 0.500000000000000000
          Height = 20.000000000000000000
          HelpType = htKeyword
          Orientation = orHorizontal
          Position.X = 30.000000000000000000
          Position.Y = 76.000000000000000000
          TabOrder = 1
          Value = 50.000000000000000000
          Width = 135.000000000000000000
          OnChange = OnControlChange
        end
        object Panel2Tracker2: TTrackBar
          Frequency = 0.500000000000000000
          Height = 20.000000000000000000
          HelpType = htKeyword
          Orientation = orHorizontal
          Position.X = 30.000000000000000000
          Position.Y = 110.000000000000000000
          TabOrder = 2
          Value = 33.000000000000000000
          Width = 135.000000000000000000
          OnChange = OnControlChange
        end
        object Panel2Label1: TLabel
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 56.000000000000000000
          Position.Y = 41.000000000000000000
          Text = 'Label'
          TextAlign = taCenter
          Width = 83.000000000000000000
        end
        object Panel2CheckBox: TCheckBox
          Height = 19.000000000000000000
          Position.X = 8.000000000000000000
          Position.Y = 168.000000000000000000
          TabOrder = 4
          Text = 'Active'
          Width = 120.000000000000000000
          OnChange = Panel1CheckBox1Change
        end
      end
      object Panel3: TPanel
        Align = alLeft
        Height = 196.000000000000000000
        HelpType = htKeyword
        Padding.Left = 5.000000000000000000
        Padding.Top = 5.000000000000000000
        Padding.Right = 5.000000000000000000
        Padding.Bottom = 5.000000000000000000
        Margins.Left = 2.000000000000000000
        Margins.Top = 2.000000000000000000
        Margins.Right = 2.000000000000000000
        Margins.Bottom = 2.000000000000000000
        Position.X = 402.000000000000000000
        Position.Y = 2.000000000000000000
        Width = 196.000000000000000000
        TabOrder = 2
        object TLabel
          Align = alTop
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 5.000000000000000000
          Position.Y = 5.000000000000000000
          Text = 'Edit -> Label'
          TextAlign = taCenter
          Width = 186.000000000000000000
        end
        object Panel3Edit1: TEdit
          Touch.InteractiveGestures = [igLongTap, igDoubleTap]
          TabOrder = 1
          Text = 'BindingText'
          Position.X = 27.000000000000000000
          Position.Y = 105.000000000000000000
          Width = 149.000000000000000000
          Height = 21.000000000000000000
          HelpType = htKeyword
          KillFocusByReturn = False
          OnChange = OnControlChange
        end
        object Panel3Label1: TLabel
          Height = 38.000000000000000000
          HelpType = htKeyword
          Position.X = 27.000000000000000000
          Position.Y = 46.000000000000000000
          Text = 'binding text'
          TextAlign = taCenter
          Width = 149.000000000000000000
        end
        object Panel3CheckBox1: TCheckBox
          Height = 19.000000000000000000
          Position.X = 8.000000000000000000
          Position.Y = 168.000000000000000000
          TabOrder = 3
          Text = 'Active'
          Width = 120.000000000000000000
          OnChange = Panel1CheckBox1Change
        end
      end
      object Panel4: TPanel
        Align = alLeft
        Height = 196.000000000000000000
        HelpType = htKeyword
        Padding.Left = 5.000000000000000000
        Padding.Top = 5.000000000000000000
        Padding.Right = 5.000000000000000000
        Padding.Bottom = 5.000000000000000000
        Margins.Left = 2.000000000000000000
        Margins.Top = 2.000000000000000000
        Margins.Right = 2.000000000000000000
        Margins.Bottom = 2.000000000000000000
        Position.X = 602.000000000000000000
        Position.Y = 2.000000000000000000
        Width = 196.000000000000000000
        TabOrder = 3
        object TLabel
          Align = alTop
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 5.000000000000000000
          Position.Y = 5.000000000000000000
          Text = 'NumberBox -> Label'
          TextAlign = taCenter
          Width = 186.000000000000000000
        end
        object Panel4NumberBox1: TNumberBox
          Touch.InteractiveGestures = [igLongTap, igDoubleTap]
          TabOrder = 1
          Cursor = crIBeam
          Position.X = 48.000000000000000000
          Position.Y = 104.000000000000000000
          Width = 100.000000000000000000
          Height = 21.000000000000000000
          HelpType = htKeyword
          VertIncrement = 5.000000000000000000
          OnChange = OnControlChange
        end
        object Panel4Label1: TLabel
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 73.000000000000000000
          Position.Y = 56.000000000000000000
          StyleLookup = 'valuelabelstyle'
          Text = '33'
          TextAlign = taCenter
          Width = 50.000000000000000000
        end
        object Panel4CheckBox1: TCheckBox
          Height = 19.000000000000000000
          Position.X = 8.000000000000000000
          Position.Y = 168.000000000000000000
          TabOrder = 3
          Text = 'Active'
          Width = 120.000000000000000000
          OnChange = Panel1CheckBox1Change
        end
      end
      object Panel5: TPanel
        Align = alLeft
        Height = 196.000000000000000000
        HelpType = htKeyword
        Padding.Left = 5.000000000000000000
        Padding.Top = 5.000000000000000000
        Padding.Right = 5.000000000000000000
        Padding.Bottom = 5.000000000000000000
        Margins.Left = 2.000000000000000000
        Margins.Top = 2.000000000000000000
        Margins.Right = 2.000000000000000000
        Margins.Bottom = 2.000000000000000000
        Position.X = 2.000000000000000000
        Position.Y = 202.000000000000000000
        Width = 196.000000000000000000
        TabOrder = 4
        object TLabel
          Align = alTop
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 5.000000000000000000
          Position.Y = 5.000000000000000000
          Text = 'Edit <-> Edit'
          TextAlign = taCenter
          Width = 186.000000000000000000
        end
        object Panel5Edit1: TEdit
          Touch.InteractiveGestures = [igLongTap, igDoubleTap]
          TabOrder = 1
          Text = 'Edit'
          Position.X = 35.000000000000000000
          Position.Y = 66.000000000000000000
          Width = 122.000000000000000000
          Height = 21.000000000000000000
          HelpType = htKeyword
          KillFocusByReturn = False
          OnChange = OnControlChange
        end
        object Panel5Edit2: TEdit
          Touch.InteractiveGestures = [igLongTap, igDoubleTap]
          TabOrder = 2
          Text = 'Edit'
          Position.X = 35.000000000000000000
          Position.Y = 111.000000000000000000
          Width = 122.000000000000000000
          Height = 21.000000000000000000
          HelpType = htKeyword
          KillFocusByReturn = False
          OnChange = OnControlChange
        end
      end
      object Panel6: TPanel
        Align = alLeft
        Height = 196.000000000000000000
        HelpType = htKeyword
        Padding.Left = 5.000000000000000000
        Padding.Top = 5.000000000000000000
        Padding.Right = 5.000000000000000000
        Padding.Bottom = 5.000000000000000000
        Margins.Left = 2.000000000000000000
        Margins.Top = 2.000000000000000000
        Margins.Right = 2.000000000000000000
        Margins.Bottom = 2.000000000000000000
        Position.X = 202.000000000000000000
        Position.Y = 202.000000000000000000
        Width = 196.000000000000000000
        TabOrder = 5
        object TLabel
          Align = alTop
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 5.000000000000000000
          Position.Y = 5.000000000000000000
          Text = 'ListBox <-> Edit'
          TextAlign = taCenter
          Width = 186.000000000000000000
        end
        object Panel6ListBox1: TListBox
          Height = 87.000000000000000000
          HelpType = htKeyword
          Position.X = 30.000000000000000000
          Position.Y = 74.000000000000000000
          TabOrder = 1
          Width = 130.000000000000000000
          ItemIndex = 0
          ItemHeight = 19.000000000000000000
          DefaultItemStyles.ItemStyle = ''
          DefaultItemStyles.GroupHeaderStyle = ''
          DefaultItemStyles.GroupFooterStyle = ''
          OnChange = Panel6ListBox1Change
          object TListBoxItem
            Height = 19.000000000000000000
            IsSelected = True
            Text = 'lb one'
            Width = 126.000000000000000000
          end
          object TListBoxItem
            Height = 19.000000000000000000
            Position.Y = 19.000000000000000000
            Text = 'lb two'
            Width = 126.000000000000000000
          end
          object TListBoxItem
            Height = 19.000000000000000000
            Position.Y = 38.000000000000000000
            Text = 'lb three'
            Width = 126.000000000000000000
          end
        end
        object Panel6Edit1: TEdit
          Touch.InteractiveGestures = [igLongTap, igDoubleTap]
          TabOrder = 2
          Text = 'text'
          Position.X = 45.000000000000000000
          Position.Y = 37.000000000000000000
          Width = 100.000000000000000000
          Height = 21.000000000000000000
          HelpType = htKeyword
          KillFocusByReturn = False
          OnChange = OnControlChange
        end
        object Panel6CheckBox1: TCheckBox
          Height = 19.000000000000000000
          Position.X = 8.000000000000000000
          Position.Y = 168.000000000000000000
          TabOrder = 3
          Text = 'Active'
          Width = 120.000000000000000000
          OnChange = Panel1CheckBox1Change
        end
      end
      object Panel7: TPanel
        Align = alLeft
        Height = 196.000000000000000000
        HelpType = htKeyword
        Padding.Left = 5.000000000000000000
        Padding.Top = 5.000000000000000000
        Padding.Right = 5.000000000000000000
        Padding.Bottom = 5.000000000000000000
        Margins.Left = 2.000000000000000000
        Margins.Top = 2.000000000000000000
        Margins.Right = 2.000000000000000000
        Margins.Bottom = 2.000000000000000000
        Position.X = 402.000000000000000000
        Position.Y = 202.000000000000000000
        Width = 196.000000000000000000
        TabOrder = 6
        object TLabel
          Align = alTop
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 5.000000000000000000
          Position.Y = 5.000000000000000000
          Text = 'ComboBox -> Label'
          TextAlign = taCenter
          Width = 186.000000000000000000
        end
        object Panel7ComboBox1: TComboBox
          DisableFocusEffect = False
          Height = 23.000000000000000000
          HelpType = htKeyword
          ItemIndex = 3
          ItemHeight = 19.000000000000000000
          Position.X = 24.000000000000000000
          Position.Y = 38.000000000000000000
          TabOrder = 1
          Width = 148.000000000000000000
          OnChange = Panel7ComboBox1Change
        end
        object Panel7Label1: TLabel
          Height = 18.000000000000000000
          HelpType = htKeyword
          Position.X = 40.000000000000000000
          Position.Y = 106.000000000000000000
          StyleLookup = 'valuelabelstyle'
          TextAlign = taCenter
          Width = 117.000000000000000000
        end
        object Panel7CheckBox1: TCheckBox
          Height = 17.000000000000000000
          Position.X = 16.000000000000000000
          Position.Y = 168.000000000000000000
          TabOrder = 3
          Text = 'Active'
          Width = 105.000000000000000000
          OnChange = Panel1CheckBox1Change
        end
      end
      object Panel8: TPanel
        Align = alLeft
        Height = 196.000000000000000000
        HelpType = htKeyword
        Padding.Left = 5.000000000000000000
        Padding.Top = 5.000000000000000000
        Padding.Right = 5.000000000000000000
        Padding.Bottom = 5.000000000000000000
        Margins.Left = 2.000000000000000000
        Margins.Top = 2.000000000000000000
        Margins.Right = 2.000000000000000000
        Margins.Bottom = 2.000000000000000000
        Position.X = 602.000000000000000000
        Position.Y = 202.000000000000000000
        Width = 196.000000000000000000
        TabOrder = 7
        object TLabel
          Align = alTop
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 5.000000000000000000
          Position.Y = 5.000000000000000000
          Text = 'TrackBar -> ProgressBar'
          TextAlign = taCenter
          Width = 186.000000000000000000
        end
        object Panel8TrackBar1: TTrackBar
          Height = 20.000000000000000000
          HelpType = htKeyword
          Orientation = orHorizontal
          Position.X = 40.000000000000000000
          Position.Y = 43.000000000000000000
          TabOrder = 1
          Width = 100.000000000000000000
          OnChange = OnControlChange
        end
        object Panel8ProgressBar1: TProgressBar
          Height = 17.000000000000000000
          HelpType = htKeyword
          Orientation = orHorizontal
          Position.X = 16.000000000000000000
          Position.Y = 104.000000000000000000
          Width = 164.000000000000000000
        end
        object Panel8CheckBox1: TCheckBox
          Height = 19.000000000000000000
          Position.X = 16.000000000000000000
          Position.Y = 168.000000000000000000
          TabOrder = 3
          Text = 'Active'
          Width = 120.000000000000000000
          OnChange = Panel1CheckBox1Change
        end
      end
      object Panel9: TPanel
        Align = alLeft
        Height = 196.000000000000000000
        HelpType = htKeyword
        Padding.Left = 5.000000000000000000
        Padding.Top = 5.000000000000000000
        Padding.Right = 5.000000000000000000
        Padding.Bottom = 5.000000000000000000
        Margins.Left = 2.000000000000000000
        Margins.Top = 2.000000000000000000
        Margins.Right = 2.000000000000000000
        Margins.Bottom = 2.000000000000000000
        Position.X = 2.000000000000000000
        Position.Y = 402.000000000000000000
        Width = 196.000000000000000000
        TabOrder = 8
        object ValueLabel3: TLabel
          Align = alTop
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 5.000000000000000000
          Position.Y = 5.000000000000000000
          Text = 'Calendar ->'
          TextAlign = taCenter
          Width = 186.000000000000000000
        end
        object Panel9Calendar1: TCalendar
          ClipChildren = False
          Date = 40478.000000000000000000
          Height = 164.000000000000000000
          HelpType = htKeyword
          Position.X = 8.000000000000000000
          Position.Y = 27.000000000000000000
          TabOrder = 1
          Width = 182.000000000000000000
          OnChange = OnControlChange
        end
      end
      object Panel10: TPanel
        Align = alLeft
        Height = 196.000000000000000000
        HelpType = htKeyword
        Padding.Left = 5.000000000000000000
        Padding.Top = 5.000000000000000000
        Padding.Right = 5.000000000000000000
        Padding.Bottom = 5.000000000000000000
        Margins.Left = 2.000000000000000000
        Margins.Top = 2.000000000000000000
        Margins.Right = 2.000000000000000000
        Margins.Bottom = 2.000000000000000000
        Position.X = 202.000000000000000000
        Position.Y = 402.000000000000000000
        Width = 196.000000000000000000
        TabOrder = 9
        object Panel10Edit1: TEdit
          Touch.InteractiveGestures = [igLongTap, igDoubleTap]
          TabOrder = 0
          Text = '10/27/2010'
          Position.X = 27.000000000000000000
          Position.Y = 105.000000000000000000
          Width = 149.000000000000000000
          Height = 21.000000000000000000
          HelpType = htKeyword
          KillFocusByReturn = False
          OnChange = OnControlChange
        end
        object Panel10Label1: TLabel
          Height = 38.000000000000000000
          HelpType = htKeyword
          Position.X = 27.000000000000000000
          Position.Y = 46.000000000000000000
          Text = 'Label'
          TextAlign = taCenter
          Width = 149.000000000000000000
        end
        object ValueLabel4: TLabel
          Align = alTop
          Height = 15.000000000000000000
          HelpType = htKeyword
          Position.X = 5.000000000000000000
          Position.Y = 5.000000000000000000
          Text = '<- Text Controls'
          TextAlign = taCenter
          Width = 186.000000000000000000
        end
        object Panel10CheckBox1: TCheckBox
          Height = 19.000000000000000000
          Position.X = 16.000000000000000000
          Position.Y = 160.000000000000000000
          TabOrder = 3
          Text = 'Active'
          Width = 120.000000000000000000
          OnChange = Panel1CheckBox1Change
        end
      end
    end
  end
  object Panel5CheckBox: TCheckBox
    Height = 19.000000000000000000
    Position.X = 16.000000000000000000
    Position.Y = 448.000000000000000000
    TabOrder = 1
    Text = 'Active'
    Width = 120.000000000000000000
    OnChange = Panel1CheckBox1Change
  end
  object BindingsList1: TBindingsList
    Methods = <>
    OutputConverters = <>
    Left = 32
    Top = 24
    object Panel1TrackerEditExpressions: TBindExprItems
      Category = 'Binding Expressions'
      ControlComponent = Panel1Edit1
      SourceComponent = Panel1TrackBar1
      FormatExpressions = <
        item
          ControlExpression = 'Text'
          SourceExpression = 'Value'
          Direction = dirBidirectional
        end
        item
          ControlExpression = 'Owner.Panel1Label1.Text'
          SourceExpression = 'Value'
        end>
      ClearExpressions = <
        item
          ControlExpression = '0'
          SourceExpression = 'Value'
          Direction = dirControlToSource
        end>
      NotifyOutputs = False
    end
    object Panel2TrackerExpressions: TBindExprItems
      Category = 'Binding Expressions'
      ControlComponent = Panel2Tracker2
      SourceComponent = Panel2Tracker1
      FormatExpressions = <
        item
          ControlExpression = 'Value'
          SourceExpression = 'Value'
          Direction = dirBidirectional
        end
        item
          ControlExpression = 'Owner.Panel2Label1.Text'
          SourceExpression = 'Value'
        end>
      ClearExpressions = <
        item
          ControlExpression = '0'
          SourceExpression = 'Value'
          Direction = dirControlToSource
        end>
      NotifyOutputs = False
    end
    object Panel3LabelEditExpressions: TBindExprItems
      Category = 'Binding Expressions'
      ControlComponent = Panel3Label1
      SourceComponent = Panel3Edit1
      FormatExpressions = <
        item
          ControlExpression = 'Text'
          SourceExpression = 'Text'
        end>
      ClearExpressions = <
        item
          ControlExpression = 'Text'
          SourceExpression = '""'
        end>
      NotifyOutputs = False
    end
    object Panel4NumberBoxLabelExpressions: TBindExprItems
      Category = 'Binding Expressions'
      ControlComponent = Panel4Label1
      SourceComponent = Panel4NumberBox1
      FormatExpressions = <
        item
          ControlExpression = 'Text'
          SourceExpression = 'Value'
        end>
      ClearExpressions = <
        item
          ControlExpression = 'Text'
          SourceExpression = #39#39
        end>
      NotifyOutputs = False
    end
    object Panel5EditExpressions: TBindExprItems
      Category = 'Binding Expressions'
      ControlComponent = Panel5Edit2
      SourceComponent = Panel5Edit1
      FormatExpressions = <
        item
          ControlExpression = 'Text'
          SourceExpression = 'Text'
          Direction = dirBidirectional
        end>
      ClearExpressions = <
        item
          ControlExpression = 'Text '
          SourceExpression = '""'
        end
        item
          ControlExpression = '""'
          SourceExpression = 'Text'
          Direction = dirControlToSource
        end>
      NotifyOutputs = False
    end
    object Panel6EditListBoxExpressions: TBindExprItems
      Category = 'Binding Expressions'
      ControlComponent = Panel6Edit1
      SourceComponent = Panel6ListBox1
      FormatExpressions = <
        item
          ControlExpression = 'Text'
          SourceExpression = 'Selected.Text'
          Direction = dirBidirectional
        end>
      ClearExpressions = <
        item
          ControlExpression = 'Text'
          SourceExpression = '""'
        end>
      NotifyOutputs = False
    end
    object Panel7ComboBoxLabelExpressions: TBindExprItems
      Category = 'Binding Expressions'
      ControlComponent = Panel7Label1
      SourceComponent = Panel7ComboBox1
      FormatExpressions = <
        item
          ControlExpression = 'Text'
          SourceExpression = 'SelectedText(Self)'
        end>
      ClearExpressions = <
        item
          ControlExpression = 'Text'
          SourceExpression = '""'
        end>
      NotifyOutputs = False
    end
    object Panel8TrackBarProgressBarExpressions: TBindExprItems
      Category = 'Binding Expressions'
      ControlComponent = Panel8ProgressBar1
      SourceComponent = Panel8TrackBar1
      FormatExpressions = <
        item
          ControlExpression = 'Value'
          SourceExpression = 'Value'
        end>
      ClearExpressions = <
        item
          ControlExpression = 'Value'
          SourceExpression = '0'
        end>
      NotifyOutputs = False
    end
    object Panel9CalendarTextControlExpressions: TBindExprItems
      Category = 'Binding Expressions'
      ControlComponent = Panel10Edit1
      SourceComponent = Panel9Calendar1
      FormatExpressions = <
        item
          ControlExpression = 'Text'
          SourceExpression = 'Date'
          Direction = dirBidirectional
        end
        item
          ControlExpression = 'Owner.Panel10Label1.Text'
          SourceExpression = 'Date'
        end>
      ClearExpressions = <
        item
          ControlExpression = 'Owner.Panel10Label1.Text'
          SourceExpression = '""'
        end>
      NotifyOutputs = False
    end
  end
end


package tofu
package config

import cats.instances.string._
import cats.instances.int._
import cats.{Order, Show}

sealed trait Key
object Key {
  final case class Index(i: Int)         extends Key
  final case class Prop(name: String)    extends Key
  final case class Variant(name: String) extends Key

  implicit val show: Show[Key] = {
    case Index(i)      => s"[$i]"
    case Prop(name)    => s"$name"
    case Variant(name) => s"#$name#"
  }

  implicit val order: Order[Key] = data.instances.order.derive

}


/*
 * Copyright (c) 2018-2019. data2viz sàrl.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package io.data2viz.shape

//import io.data2viz.math.Angle
import kotlin.math.PI

val epsilon = 1e-12
val pi = PI
val halfPi = pi / 2
val tau = 2 * pi

fun acos(x: Double) = if (x > 1.0)  0.0     else if (x < -1) pi         else kotlin.math.acos(x)
fun asin(x: Double) = if (x >= 1.0) halfPi  else if (x <= -1.0) -halfPi else kotlin.math.asin(x)

//fun acos(a: Angle) = if (a.rad > 1.0)  0.0     else if (a.rad < -1) pi         else a.acos
//fun asin(a: Angle) = if (a.rad >= 1.0) halfPi  else if (a.rad <= -1.0) -halfPi else a.asin


/*
 * SoC audio driver for EM-X270, eXeda and CM-X300
 *
 * Copyright 2007, 2009 CompuLab, Ltd.
 *
 * Author: Mike Rapoport <mike@compulab.co.il>
 *
 * Copied from tosa.c:
 * Copyright 2005 Wolfson Microelectronics PLC.
 * Copyright 2005 Openedhand Ltd.
 *
 * Authors: Liam Girdwood <lrg@slimlogic.co.uk>
 *          Richard Purdie <richard@openedhand.com>
 *
 *  This program is free software; you can redistribute  it and/or modify it
 *  under  the terms of  the GNU General  Public License as published by the
 *  Free Software Foundation;  either version 2 of the  License, or (at your
 *  option) any later version.
 *
 */

#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/device.h>

#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>

#include <asm/mach-types.h>
#include <mach/audio.h>

static struct snd_soc_dai_link em_x270_dai[] = {
	{
		.name = "AC97",
		.stream_name = "AC97 HiFi",
		.cpu_dai_name = "pxa2xx-ac97",
		.codec_dai_name = "wm9712-hifi",
		.platform_name = "pxa-pcm-audio",
		.codec_name = "wm9712-codec",
	},
	{
		.name = "AC97 Aux",
		.stream_name = "AC97 Aux",
		.cpu_dai_name = "pxa2xx-ac97-aux",
		.codec_dai_name = "wm9712-aux",
		.platform_name = "pxa-pcm-audio",
		.codec_name = "wm9712-codec",
	},
};

static struct snd_soc_card em_x270 = {
	.name = "EM-X270",
	.owner = THIS_MODULE,
	.dai_link = em_x270_dai,
	.num_links = ARRAY_SIZE(em_x270_dai),
};

static struct platform_device *em_x270_snd_device;

static int __init em_x270_init(void)
{
	int ret;

	if (!(machine_is_em_x270() || machine_is_exeda()
	      || machine_is_cm_x300()))
		return -ENODEV;

	em_x270_snd_device = platform_device_alloc("soc-audio", -1);
	if (!em_x270_snd_device)
		return -ENOMEM;

	platform_set_drvdata(em_x270_snd_device, &em_x270);
	ret = platform_device_add(em_x270_snd_device);

	if (ret)
		platform_device_put(em_x270_snd_device);

	return ret;
}

static void __exit em_x270_exit(void)
{
	platform_device_unregister(em_x270_snd_device);
}

module_init(em_x270_init);
module_exit(em_x270_exit);

/* Module information */
MODULE_AUTHOR("Mike Rapoport");
MODULE_DESCRIPTION("ALSA SoC EM-X270, eXeda and CM-X300");
MODULE_LICENSE("GPL");


/* (c) 2020 Open Source Geospatial Foundation - all rights reserved
 * This code is licensed under the GPL 2.0 license, available at the root
 * application directory.
 */

/* Copyright (c) 2013 - 2017 Boundless - http://boundlessgeo.com All rights reserved.
 * This code is licensed under the GPL 2.0 license, available at the root
 * application directory.
 */
package org.geoserver.gsr.translate.feature;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.json.JSONObject;
import org.geoserver.catalog.FeatureTypeInfo;
import org.geoserver.gsr.model.feature.*;
import org.geoserver.gsr.model.geometry.*;
import org.geoserver.gsr.translate.geometry.AbstractGeometryEncoder;
import org.geoserver.gsr.translate.geometry.GeometryEncoder;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.FeatureTypes;
import org.opengis.feature.GeometryAttribute;
import org.opengis.feature.Property;
import org.opengis.feature.type.FeatureType;
import org.opengis.feature.type.PropertyDescriptor;

public class FeatureEncoder {

    public static final String OBJECTID_FIELD_NAME = "objectid";

    private FeatureEncoder() {
        throw new RuntimeException(
                "Feature encoder has only static methods, no need to instantiate it.");
    }

    /**
     * Get an {@link AttributeList} from a {@link org.opengis.feature.Feature}
     *
     * @param feature
     * @param objectIdFieldName
     * @return the list of feature attributes
     */
    public static Map<String, Object> attributeList(
            org.opengis.feature.Feature feature, String objectIdFieldName) {
        GeometryAttribute geometryAttribute = feature.getDefaultGeometryProperty();
        Map<String, Object> attributes = new HashMap<>();
        for (Property prop : feature.getProperties()) {
            if (prop.getValue() != null
                    && (geometryAttribute == null
                            || !prop.getName().equals(geometryAttribute.getName()))) {
                final Object value;
                if (prop.getValue() instanceof java.util.Date) {
                    value = ((java.util.Date) prop.getValue()).getTime();
                } else if (prop.getValue() instanceof java.lang.Boolean) {
                    value = ((Boolean) prop.getValue()) ? Integer.valueOf(1) : Integer.valueOf(0);
                } else {
                    value = prop.getValue().toString();
                }
                attributes.put(prop.getName().getLocalPart(), value);
            }
        }

        if (objectIdFieldName != null) {
            attributes.put(objectIdFieldName, toGSRObjectId(feature.getIdentifier().getID()));
        }

        return attributes;
    }

    public static Feature fromJson(JSONObject json) {
        Geometry geometry = GeometryEncoder.jsonToGeometry(json.getJSONObject("geometry"));
        Map<String, Object> attributes = new HashMap<>();
        JSONObject jsonAttributes = json.getJSONObject("attributes");

        for (Object key : jsonAttributes.keySet()) {
            attributes.put((String) key, jsonAttributes.get(key));
        }

        return new Feature(geometry, attributes, json.get("id"));
    }

    public static Feature feature(
            org.opengis.feature.Feature feature,
            boolean returnGeometry,
            SpatialReference spatialReference) {
        return feature(
                feature, returnGeometry, spatialReference, FeatureEncoder.OBJECTID_FIELD_NAME);
    }

    public static Feature feature(
            org.opengis.feature.Feature feature,
            boolean returnGeometry,
            SpatialReference spatialReference,
            String objectIdFieldName) {
        return feature(
                feature,
                returnGeometry,
                spatialReference,
                objectIdFieldName,
                new GeometryEncoder());
    }

    public static Feature feature(
            org.opengis.feature.Feature feature,
            boolean returnGeometry,
            SpatialReference spatialReference,
            String objectIdFieldName,
            AbstractGeometryEncoder geometryEncoder) {
        GeometryAttribute geometryAttribute = feature.getDefaultGeometryProperty();
        Map<String, Object> attributes = FeatureEncoder.attributeList(feature, objectIdFieldName);
        if (returnGeometry) {
            return new Feature(
                    geometryEncoder.toRepresentation(
                            (org.locationtech.jts.geom.Geometry) geometryAttribute.getValue(),
                            spatialReference),
                    attributes,
                    feature.getIdentifier().getID());
        } else {
            return new Feature(null, attributes, feature.getIdentifier().getID());
        }
    }

    public static Field field(PropertyDescriptor field, Boolean featureIsEditable) {
        // Similar to LayerListResource encodeSchemaProperties
        // Similar to FeatureEncoder descriptorToJson.

        FieldTypeEnum fieldType = FieldTypeEnum.forClass(field.getType().getBinding());
        Integer fieldLength = FeatureTypes.getFieldLength(field);
        Boolean editable;

        // String, Date, GlobalID, GUID and XML
        switch (fieldType) {
            case STRING:
            case DATE:
            case GUID:
            case GLOBAL_ID:
            case XML:
                fieldLength = fieldLength == -1 ? 4000 : fieldLength;
                editable = featureIsEditable;
                break;
            case GEOMETRY:
                fieldLength = null;
                editable = featureIsEditable;
                break;
            default:
                // length and editable are optional
                fieldLength = null;
                editable = null;
        }
        return new Field(
                field.getName().getLocalPart(),
                fieldType,
                field.getName().toString(),
                fieldLength,
                editable,
                field.isNillable());
    }

    public static <T extends FeatureType, F extends org.opengis.feature.Feature>
            FeatureIdSet objectIds(FeatureCollection<T, F> features) {

        // TODO: Advertise "real" identifier property

        List<Long> objectIds = new ArrayList<>();
        try (FeatureIterator<F> iterator = features.features()) {
            while (iterator.hasNext()) {
                F feature = iterator.next();
                objectIds.add(toGSRObjectId(feature.getIdentifier().getID()));
            }
        }
        return new FeatureIdSet(
                OBJECTID_FIELD_NAME, objectIds.stream().mapToLong(i -> i).toArray());
    }

    public static final Pattern FEATURE_ID_PATTERN = Pattern.compile("(^(?:.*\\.)?)(\\p{Digit}+)$");

    /**
     * Converts a GeoTools FeatureId of the form $NAME.$ID to a ESRI-compatible long value by
     * removing the $NAME prefix using {@link FeatureEncoder#FEATURE_ID_PATTERN}
     *
     * @param featureId
     * @return
     */
    public static Long toGSRObjectId(String featureId) {
        Matcher matcher = FEATURE_ID_PATTERN.matcher(featureId);
        if (matcher.matches()) {
            return Long.parseLong(matcher.group(2));
        } else {
            return (long) featureId.hashCode();
        }
    }

    /**
     * Converts a long id generated using {@link #toGSRObjectId(String)} back to a GeoTools
     * FeatureId.
     *
     * @param objectId the generated id
     * @param idPrefix the prefix to prepend
     * @return
     */
    public static String toGeotoolsFeatureId(Long objectId, String idPrefix) {
        return idPrefix + objectId.toString();
    }

    /**
     * Converts a long id generated using {@link #toGSRObjectId(String)} back to a GeoTools
     * FeatureId.
     *
     * @param objectId the generated id
     * @param targetFeature The target featuretype of the id, used to calculate the prefix
     * @return
     * @throws IOException
     */
    public static String toGeotoolsFeatureId(Long objectId, FeatureTypeInfo targetFeature)
            throws IOException {
        return toGeotoolsFeatureId(objectId, calculateFeatureIdPrefix(targetFeature));
    }

    /**
     * Calculates the geotools id prefix,
     *
     * @param targetFeature
     * @return
     * @throws IOException
     */
    public static String calculateFeatureIdPrefix(FeatureTypeInfo targetFeature)
            throws IOException {
        org.opengis.feature.Feature sampleFeature = null;
        String featureIdPrefix = "";
        try (FeatureIterator i =
                targetFeature.getFeatureSource(null, null).getFeatures().features()) {
            if (i.hasNext()) {
                sampleFeature = i.next();
                String fid = sampleFeature.getIdentifier().getID();

                Matcher matcher = FeatureEncoder.FEATURE_ID_PATTERN.matcher(fid);
                if (matcher.matches()) {
                    featureIdPrefix = matcher.group(1);
                }
            }
        }
        return featureIdPrefix;
    }

    /**
     * ESRI JS relies heavily on the object ID field, whereas in GeoServer this concept is a little
     * vaguer.
     *
     * @param objectIdFieldName
     * @return
     */
    public static Field syntheticObjectIdField(String objectIdFieldName) {
        Field idField = new Field(objectIdFieldName, FieldTypeEnum.OID, objectIdFieldName);
        return idField;
    }
}