text:
Managing large projects

Syberia comes bundled with director, an R6
package aimed at simplifying management of large R projects.

By default, most R projects are collections of loosely organized scripts. A
newcomer to the project would have to rely on very thorough documentation to understand
how the executable tasks fit together and how to replicate and expand on any analysis.
Using notebooks like Jupyter just makes the problem worse: hard to inspect in code
reviews and encouraging messy watch-and-see-what-you-get scripting, notebooks
suck the developer right out of our analyst bones.

If you just want to roll up your sleeves and get to work, feel free to skip this
section and move on to testing (a software developer wrote this guide;
we won't let you skip testing!). A high-level understanding of how Syberia projects
manage stuff under the hood is helpful for expanding your horizon to more than
just the functionality packaged with the modeling engine.

In Syberia, we rely on convention over configuration, a common design
pattern in software frameworks that removes some leeway in the organizational structure
in exchange for something incredibly powerful: all R developers working in Syberia projects
will share common knowledge about how work is organized.

The modeling engine conventions

In particular, the modeling engine that currently comes bundled as
the default engine for structured supervised learning projects such as regression and
classification sets up a few conventions which all modeling engine projects conform to:

The models directory holds all models for a given project. Each file is
  an R script that ends with a list object which hyper-parameterizes the
  data science process into a linear sequence of stages. All the conventions below are
  the recipe ingredients that turn model files from static lists to living, breathing
  objects defining a dynamic modeling pipeline.

In the current modeling engine incarnation, these are stagerunners,
  R6 objects that tie together all aspects of the modeling process—but in the future
  we may release support for distributed backends and engines such as Spark or Tensorflow.
  Let's humbly learn how to walk before we run.

The lib/adapters directory defines IO (input and output) mechanisms for data
  and serialized model objects. For example, data might be read in CSV format, from a
  database or data warehouse, or simply reside in-memory. Data and model objects may
  be written to a file, to a cloud storage service, or pushed via HTTP to an API.

The lib/mungebits directory holds mungebits, already familiar from an
  earlier lesson, which define feature engineering templates that transform dataframes
  to dataframes. In the future, we may extend the notion of mungebits to distributed
  settings such as Spark, Tensorflow or Hadoop and even explore graphical or other
  forms of data manipulation and computation—but development will stay nice and cozy within R.

The lib/stages directory is a collection of modeling stages, by default
  import, data, model, and export. The complex logic that
  defines how to process the parameters in the modeling file lives in these stages:
  each R file in this directory is a functional, a function that returns another function,
  namely, a function that takes in the parameters from the model file under the given stage key and spits out a
  transformation of an environment that performs the appropriate operations of the stage.

For example, import stage may read from a CSV file whereas model stage may construct
  a tundra container and then call its predict method.

The lib/classifiers directory is responsible for housing all the training and
  prediction functions for various statistical classifiers: linear regression, random forest,
  gradient boosting machines, support vector machines, et cetera. These are responsible for
  the construction of a  model object, a serializable R object that represents all
  meta-data required to replicate the scoring of outputs on new validation sets or real-time
  data.

Note that while in the current convention modeling remains in-memory and finitely bound,
this is not a given. If the syntax is sharp and compact, we may replace backends from
the current in-memory R approach to acting as a distributed command center for millions
of machines, but experimentation on local slices of the data can remain in one of the most
powerful interactive consoles we know: the R interpreter.

The base engine

The above conventions are not exhaustive. Several are inherited from the parent engine
of the modeling engine: the base engine. The conventions established in the list below are defined by the
base engine, which is more general than the modeling engine and serves as the
clay for almost all future Syberia engines. In case you are wondering, do not worry, at the
present moment the topology is simple and linear: your project makes use of the modeling engine, which makes
use of the base engine, which relies on the Syberia package.

Future larger projects may
have complex intertwined engines for a variety of machine learning and business tasks, but
for the moment, once again, let us walk before we run.

For example, unsupervised learning, natural language processing, scientific research,
dashboarding and business intelligence, trading and finance, may all require different
conventions which differ somewhat or drastically from the structured supervised learning problem.
Building on top of the base engine allows for some very powerful meta-conventions:

The config/routes resource (typically just a routes.R file) establishes the
  link between the lib/controllers directory and the rest of the project: it tethers
  together which directories are processed by which controllers.

The lib/controllers directory forms the heart of Syberia's expansive
  configurability. In an effort to strike the balance between establishing conventions
  over configurations, whilst suitably recognizing that the taxonomy of
  computing tasks may require different conventions to optimally iterate
  on its given set of problems, the notion of a controller allows us to
  generalize how R works. In the old way, we would use base::source
  to execute an R file and store the value of its last expression in a local variable.

Controllers allow us to define preprocessors and parsers. A preprocessor
  is a function that specifies everything before we execute an R file and a parser
  is a function that specifies everything after we execute an R file—in a
  given directory. In effect, controllers allow us to establish heterogeneous DSLs
  (domain-specific languages) in a hierarchical directory structure in a way that
  most optimally conforms to how we wish to solve a particular problem, whether it be
  production-ready machine learning or experimental business intelligence dashboarding.

The Syberia team looks forward to the creativity and imagination the R community
  will display when fully unlocking the power of controllers: let the domain-specific
  languages flood out the rigidity of CRAN and the constraints of packages, thus
  establishing R as a true player in the "general purpose programming language"
  sector. It is, after all, just a LISP—a rather powerful one at that.

Philosophical asides beside, let's examine how a director object helps us
generalize our thinking about R projects with some more concrete examples.

The most basic director object

Let us start from the beginning and open a vanilla R session from the terminal:
R --vanilla.

devtools::install_github("syberia/director") # Install director into the global library.
library(director)
dir <- tempdir()
project <- director(dir)
project # Director object monitoring 'temporary director'.

We have in our hands a director object! Note the class(project).
Under the hood, Syberia manages the creation of a director object when your R session
starts and syberia::syberia_project() is called: this last
expression returns a syberia_engine R6 object which inherits
from the director R6 class and expands on the vanilla functionalities
of a director object.

Let's see what our object can do: ls(project). The noteworthy
methods are exists, filename, find, root and
resource.

Let's create an R file in our temporary project and see what happens.

# Write "cat('Hello world!')" into hello.R at the root of the project.
# You can also do this using a text editor.
# Note: `project$root()` is equivalent to `dir` from earlier, if not a little clearer.
writeLines("cat('Hello world!')", file.path(project$root(), "hello.R"))
# Our project now recognizes hello.R as a "hello" resource.
project$find() # [1] "hello"
# Executing the resource gives us what we expect.
project$resource("hello") # Hello world!NULL
# We have a NULL at the end the return value of the cat function is NULL.

By default, the resource method acts as a slightly more
powerful source.

devtools::install_github("robertzk/Ramd") # Install the Ramd package for the 'define' helper.
# Create dir/world
dir.create(file.path(project$root(), "world"))
# Write to dir/world/world.R
writeLines("Ramd::define('hello', function(hello) { cat(hello, 'world!') })",
           file.path(project$root(), "world", "world.R"))
writeLines("'hello'", file.path(project$root(), "world", "hello.R"))
project$find() # [1] "world" "hello"

Note that find does not produce results in alphabetical
order. The resources are ordered by which ones were modified most recently.

In the above example, we illustrated one of the most powerful concepts in
director: idempotent resources. Many dynamic scripting languages like JavaScript
or R have found themselves at the forefront of popular usage without
the language designer anticipating their growth in complexity. In R projects,
we typically find it hard to organize our work sometimes because, like JavaScript,
R was simply not designed with large architectures in mind.

However, there is a neat solution. We take a page out of the books of
require.js and node.js and allow each director object a very
specific convention: if a file (ignoring extension) has the same name as its
parent directory, it gets treated as an idempotent resource, meaning that
the other files in that directory are helper files which become invisible
to the director object.

These helper files are implicitly understood to be available
to the main file for its final construction, but otherwise should not be
treated as Syberia resources, that is, should not be made available as modular
pieces for re-use within the rest of the project. If you find yourself
needing to make use of them, it is a good indication that they deserve
the title of their own distinct resource.

list.files(project$root(), recursive = TRUE)
# "hello.R"       "world/hello.R" "world/world.R"
project$filename("world")
# [1] "world/world.R"

The director object keeps track of the fact that the "world" resource
is in fact at "world/world.R". This is a virtual construction which maps
either to "world.R" or "world/world.R" depending on the name of the parent
directory of "world.R".

project$resource("world")
# hello world!NULL

Our resource has been pieced together from the world directory using
both "world/hello.R" and "world/world.R".

The usage of the Ramd package was for the Ramd::define
function, which allows a convenient syntax for sourcing adjacent files. Note
these files are truly sourced using base::source
and are pure helper R scripts—they do not benefit from the preprocessor
or parser magic in director that we are about to introduce! (This is a frequent
source of bizarre bugs and stack traces and merits explicit mention.)

Preprocessors and parsers

Continuing with the example from the previous section, let's add some flair
to our project.

john <- utils::person("John", "Doe")
john # "John Doe"
class(john) # "person"

We use the simplest illustrative structure we know of: the utils package's
definition of a person S3 class. Imagine we
want to define a convention that all files in the "people" directory
must return a c("first name", "last name")
character vector and create a person object. It would be annoying and
repetitive to write utils::person("first name", "last name")
in each file, and anyway we may wish to replace the base definition with another
class down the road. (See don't repeat yourself.)

dir.create(file.path(project$root(), "people"))
writeLines('c("Jane", "Smith")', file.path(project$root(), "people/jane.R"))
jane <- project$resource("people/jane")
jane # [1] "Jane" "Smith"
class(jane) # "character"

So far, we have not accomplished our objective: jane
is still a lowly character vector, not a person.
To animate her like Pinnocchio, we shall define a parser on the director object.

project$register_parser("people", function(output) {
  do.call(utils::person, as.list(unname(output)))
})

Now let's try again.

jane <- project$resource("people/jane")
jane # [1] "Jane Smith"
class(jane) # "person"

What a lovely lady jane now has become! By
calling register_parser on the project,
we have implicitly told our director to, going forward, treat all
files in the "people" directory with the convention: take the output
of the file and pass it as arguments to utils::person.

dir.create(file.path(project$root(), "people", "maryjane"))
writeLines("mary <- 'Mary'; jane <- 'Jane'; paste(mary, jane, sep = '-')",
           file.path(project$root(), "people", "maryjane", "mj.R"))
writeLines("Ramd::define('mj', function(mj) { c(mj, 'Jones') })",
           file.path(project$root(), "people", "maryjane", "maryjane.R"))
maryjane <- project$resource("people/maryjane")
maryjane # [1] "Mary-Jane Jones"
class(maryjane) # "person"

As you can see, maryjane is more complex than
mary, but she is still a great example of a
person.

So far, we have encountered an example of a parser. We can also do additional
work before sourcing the file, such as injecting helper functions (maybe even
recursively composed of other Syberia resources.)

project$register_preprocessor("people", function(source_env, source) {
  source_env$capitalize <- function(x) {
    x <- strsplit(x, "")[[1]]
    paste(c(toupper(x[1]), tolower(x[-1])), collapse = "")
  }
  source()
})

We can now use the capitalize helper in
files in the "people" directory.

writeLines("sapply(c('jimmy', 'JOHNSON'), capitalize)",
           file.path(project$root(), "people", "jimmy.R"))
jimmy <- project$resource("people/jimmy")
jimmy # [1] "Jimmy Johnson"
class(jimmy) # "person"

Before Hadley Wickham pops out of thin air to remind you never to use
sapply, note that we never defined
capitalize anywhere in the file: it got injected
by the preprocessor.

The full list of magic provided by the preprocessor and parser
definitions is listed in the appendix. The Syberia base engine (the
foundation for the modeling engine) provides conventions that bootstrap
a vanilla director object into providing
some very basic conventions: everything in "lib/controllers" allows
us some shortcuts for calling project$register_preprocessor
and project$register_parser under the hood.

In other words, Syberia uses director recursively to bootstrap the definition
of "controllers" into existence: even controllers are just another Syberia
resource and can be rewritten at will; and even director
objects can be replaced with more powerful tools for managing R projects.

cat("I know of these people:", paste(collapse = ", ", project$find("people")), "\n")
# I know of these people:  people/jimmy, people/maryjane, people/jane
vapply(project$find("people"), function(p) { as.character(project$resource(p)) }, "")
#      people/jimmy   people/maryjane       people/jane
#   "Jimmy Johnson" "Mary-Jane Jones"      "Jane Smith"

Additional director functionality

# By default, `find` matches using fuzzy wildcard and is equivalent to
# the regex: .*p.*.p.*l.*
project$find("ppl") # [1] "people/jimmy"    "people/maryjane" "people/jane"
# This is mostly because the author is lazy and likes convenience. Feel
# free to suggest a change in a pull request or issue in the director package.
# You can target just subdirectories:
project$find("ppl", method = "partial") # character(0)
project$find("people", method = "partial") # [1] "people/jimmy"    "people/maryjane" "people/jane"
# You can also target for an exact match, at most one result.
project$find("people", method = "exact") # character(0)
project$find("people/jimmy", method = "exact") # [1] "people/jimmy"

# You can use `filename` to discover the filename behind a resource.
unname(vapply(project$find("people"), project$filename, character(1)))
# [1] "people/jimmy.R" "people/maryjane/maryjane.R" "people/jane.R"

# You can use `exists` to check for resource existence.
project$exists("people/jimmy") # [1] TRUE
project$exists("people/jimmyjohns") # [1] FALSE

Some additional more advanced functionality is provided by the
syberia_engine object which extends the director
object but that is beyond the scope of this introduction. It involves handling
all communication and coordination between the root project and its
dependent engines, in addition to locating resources across the topology
of engines mounted to the root project. If all that sounds complicated,
that's because it is, so don't worry about it for now.

How director interacts with your project

Under the hood, you don't have to worry about most of the explicit
examples in this chapter. The Syberia modeling engine handles almost
all uses of director objects under the hood. The only real usage
you should remember is to call project$resource("foo")
when you want to call resource "foo" (e.g., "models/model1", "lib/mungebits/imputer", et cetera).

The project global helper is just a
shortcut for syberia::syberia_project(), which
builds your project from the current working directory into a syberia_engine
R6 object and then memoizes (caches) it in memory.

Next Steps

You are so close! You can skip straight to the summary, but any great
aspiring developer will read the section on testing.

Testing

Summary and review

Appendix: Available arguments for preprocessor and parser definitions

Preprocessors and parsers offer powerful capability for extending the
vanilla base::source function.


text:
import React, {Component} from 'react'
import {connect} from 'react-redux'
import NewGroup from './NewGroup';
import {createGroup, setGroup} from '../../../action/groupAction';

export class NewGroupContainer extends Component {

    render() {
        return (
            <NewGroup group={this.props.group}
                      fieldErrors={this.props.fieldErrors}
                      callbacks={{
                          setGroup: this.props.setGroup,
                          createGroup: this.props.createGroup,
                      }}/>
        )
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        setGroup: (group) => {
            dispatch(setGroup(group))
        },
        createGroup: (group) => {
            dispatch(createGroup(group))
        }
    }
};

const mapStateToProps = (state) => {
    return {
        group: state.groupData.group || {},
        fieldErrors: state.groupData.fieldErrors || {}
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(NewGroupContainer)

redpajama_set_name: RedPajamaGithub


text:
import { Component, OnInit, ViewChild, AfterViewInit, Output, EventEmitter } from '@angular/core';
import { jqxGridComponent } from 'jqwidgets-framework/jqwidgets-ts/angular_jqxgrid';

@Component({
  selector: 'app-grid',
  templateUrl: './grid.component.html',
  styleUrls: ['./grid.component.css']
})
export class GridComponent implements OnInit, AfterViewInit {
  settings: jqwidgets.GridOptions = {};
  source: any = {};
  cols: any[] = [];
  showFilterRow: boolean = false;
  filterable: boolean = false;
  private dataAdapter: any = {};

  @Output() onRowSelected: EventEmitter<Function> = new EventEmitter<Function>();
  @ViewChild('indusoftGrid') grid: jqxGridComponent;

  constructor() {

  }

  ngAfterViewInit(): void {
    this.dataAdapter = new jqx.dataAdapter(this.source);
    this.settings = {
      width: '100%',
      source: this.dataAdapter,
      pageable: true,
      autoheight: true,
      sortable: true,
      altrows: true,
      enabletooltips: true,
      editable: false,
      scrollmode: '"deferred"',
      columns: this.cols,
      filterable: this.filterable,
      showfilterrow: this.showFilterRow
    };
    this.grid.createWidget(this.settings);
  }

  ngOnInit() { }

  rowSelected(event): void {
    this.onRowSelected.emit(event);
  }

  updatebounddata(): void {
    this.grid.updatebounddata();
  }
}


text:
class ScopeTimer
{
public:
    ScopeTimer(const std::string &name, std::ostream &os) : m_name(name), m_os(os)
    {
        m_tic = cv::getTickCount();
    }
    ~ScopeTimer()
    {
        int64 toc = cv::getTickCount();
        double elapsed = double(toc - m_tic)/double(cv::getTickFrequency());
        m_os << m_name << " " << elapsed << std::endl;
    }
protected:
    int64 m_tic;
    std::string m_name;
    std::ostream &m_os;
};

#include <opencv2/photo.hpp>

// ############### homomorphic ###############

class HomomorphicFilter : public Filter
{
public:
    HomomorphicFilter(float cutoff = 0.49, int order = 2, float boost = 4.0)
    : kCutoff(cutoff)
    , kOrder(order)
    , kBoost(boost) {}

    virtual cv::Mat operator()(const cv::Mat &src, cv::Mat &dst)
    {
        const float kBeta = (1.0/kBoost);
        const float kAlpha = (1.0 - kBeta);
        homomorphic(src, dst, kCutoff, kOrder, kAlpha, kBeta, {0.00f, 0.94f}, dst.empty() ? cv::Mat() : dst);
        return dst;
    }

    virtual const char * getFilterName() const { return "HomomorphicFilter"; }

    int kOrder = 2;
    float kBoost = 4.0;
    float kCutoff = 0.49;
};

// ############### bilateral #################

static void bilateral(const cv::Mat &input, cv::Mat &output, int spatialRad, int colorRad, int iter)
{
    std::vector<cv::Mat> buffer { cv::Mat(), output };
    int j = 1;
    for(int i = 0; i < iter; i++, j = 1-j)
    {
        cv::bilateralFilter((i == 0) ? input : buffer[1-j], buffer[j], 0, spatialRad, colorRad);
    }
    output = buffer[1-j];
}

class BilateralFilter : public Filter
{
public:

    BilateralFilter(int spatialRad, int colorRad, int iter)
    : m_spatialRad(spatialRad)
    , m_colorRad(colorRad)
    , m_iter(iter)
    { }

    virtual cv::Mat operator()(const cv::Mat &src, cv::Mat &dest)
    {
        bilateral(src, dest, m_spatialRad, m_colorRad, m_iter);
        return dest;
    }

    virtual const char * getFilterName() const { return "BilateralFilter"; }

    int m_iter = 10;
    int m_spatialRad = 10;
    int m_colorRad = 10;
};

// ########### inpaint filter ################

class InpaintFilter : public Filter
{
public:
    InpaintFilter(int radius) : m_radius(radius) {}
    virtual cv::Mat operator()(const cv::Mat &src, cv::Mat &dst)
    {
        cv::Mat saturated = (src >= 254) | (src <= 2);
        cv::reduce(saturated.reshape(1, saturated.total()), saturated, 1, cv::REDUCE_MAX);
        saturated = saturated.reshape(1, src.rows);
        cv::inpaint(src, saturated, dst, m_radius, cv::INPAINT_TELEA);
        return dst;
    }
    virtual const char * getFilterName() const { return "InpaintFilter"; }
    float m_radius = 5;
};

// ########## Symmetry filter ##################

class SymmetryFilter : public Filter
{
public:
    SymmetryFilter() {}

    virtual cv::Mat operator()(const cv::Mat &src, cv::Mat &dst)
    {
        return src;
    }

    virtual const char * getFilterName() const { return "SymmetryFilter"; }
};

// ############# Cartoonize ##################

class CartoonizeFilter : public Filter
{
public:

    CartoonizeFilter(float sigmaSpace, float sigmaColor, int iter, int medianKernel)
    : m_sigmaSpace(sigmaSpace)
    , m_sigmaColor(sigmaColor)
    , m_iter(iter)
    {

    }

    bool m_doLines = false;
    void setDoLines(bool flag)
    {
        m_doLines = flag;
    }

    virtual cv::Mat operator()(const cv::Mat &src, cv::Mat &dst)
    {
        cv::Mat small, smooth;
        cv::resize(src, small, {src.cols/2, src.rows/2});
        bilateral(small, smooth, m_sigmaSpace, m_sigmaColor, m_iter * 2);
        cv::resize(smooth, smooth, src.size(), 0, 0, cv::INTER_LINEAR);

        if(m_doLines)
        {
            smooth.copyTo(dst, makeLines(src));
        }
        else
        {
            dst = smooth;
        }

        return dst;
    }

    cv::Mat makeLines(const cv::Mat &src)
    {
        cv::Mat gray, edges, mask;
        cv::cvtColor(src, gray, cv::COLOR_BGR2GRAY);
        for(int i = 0; i < 2; i++)
        {
            cv::medianBlur(gray, gray, m_medianKernel);
        }

        cv::Laplacian(gray, edges, CV_8UC1, 5);
        cv::threshold(edges, mask, 0, 255,  cv::THRESH_OTSU  | cv::THRESH_BINARY_INV);
        return mask;
    }

    virtual const char * getFilterName() const { return "CartoonizeFilter"; }

protected:

    int m_medianKernel = 7;

    float m_sigmaSpace = 7;
    float m_sigmaColor = 9;
    int m_d = 0;
    int m_iter = 7;
};

const char *keys =
{
    "{ input     |       | input filename                            }"
    "{ hair-mask |       | input mask file                           }"
    "{ output    |       | output filename                           }"

    "{ log       |       | log file                                  }"

    "{ width     | 512   | processing width                          }"
    "{ verbose   | false | verbose mode (w/ display)                 }"

    // Tracker file
    "{ regressor |       | face landmark regressor file              }"
    "{ detector  |       | face detector                             }"

    "{ model     |       | model file                                }"
    "{ mapping   |       | mapping file                              }"

    // Triangulation
    "{ triangles |       | input precomputed triangulation           }"
    "{ triangles-out |   | output triangulation file                 }"

    "{ threads   | false | use worker threads when possible          }"
    "{ build     | false | print the OpenCV build information        }"
    "{ help      | false | print help message                        }"
};

#define SHOW_HISTORY 0
#define DO_INPAINT 0

int main(int argc, char *argv[])
{
    const std::string PATTERN = "HOME";
    std::string home = getenv(PATTERN.c_str());

    cv::CommandLineParser parser(argc, argv, keys);
    if(argc < 2 || parser.get<bool>("help"))
    {
        std::cout << "ARGC: " << argc << std::endl;
        parser.printMessage();
        return 0;
    }
    else if(parser.get<bool>("build"))
    {
        std::cout << cv::getBuildInformation() << std::endl;
        return 0;
    }

    std::string sInput = parser.get<std::string>("input");
    if(sInput.empty())
    {
        std::cerr << "Must specify input filename" << std::endl;
        return 1;
    }

    std::string sOutput = parser.get<std::string>("output");
    if(sOutput.empty())
    {
        std::cerr << "Must specify output filename" << std::endl;
        return 1;
    }

    std::string sHairMask = parser.get<std::string>("hair-mask");
    std::string sLog = parser.get<std::string>("log");
    std::string sDetector = parser.get<std::string>("detector");
    std::string sRegressor = parser.get<std::string>("regressor");
    std::string sTriangles = parser.get<std::string>("triangles");
    std::vector<std::string*> args
    {
        &sInput,
        &sOutput,
        &sDetector,
        &sRegressor,
        &sTriangles,
        &sLog,
        &sHairMask
    };
    for(auto &arg : args)
    {
        size_t pos = arg->find(PATTERN);
        if(pos != std::string::npos)
        {
            arg->replace(pos, PATTERN.size(), home);
        }
    }

    // Create log stream:
    std::ostream *os;
    std::ofstream log;
    if(!sLog.empty())
    {
        log.open(sLog);
        os = &log;
    }
    else
    {
        os = &std::cout;
    }

    bool verbose =  parser.get<bool>("verbose");

    cv::Mat input = cv::imread(sInput, cv::IMREAD_COLOR);
    if(input.empty())
    {
        std::cerr << "Unable to read input file " << sInput << std::endl;
        return 1;
    }

    cv::Mat hairMask = cv::imread(sHairMask, cv::IMREAD_GRAYSCALE);
    if(hairMask.empty())
    {
        hairMask = cv::Mat1b::zeros(input.size()); // create empty hair mask
    }
    CV_Assert(hairMask.size() == input.size());

    std::vector<std::pair<std::string,cv::Mat>> drawings;

    float sigmaSpace = 7;
    float sigmaColor = 7;
    int iter = 7;
    int medianKernel = 7;
    CartoonizeFilter cartoonizeFilter(sigmaSpace, sigmaColor, iter, medianKernel);

    *os << sInput << ": " << input.size() << std::endl;

    int width = parser.get<int>("width");
    cv::Size size = input.size();
    cv::resize(input, input, {width, input.rows * width/input.cols}, cv::INTER_CUBIC);
    cv::resize(hairMask, hairMask, {width, input.rows * width/input.cols}, cv::INTER_NEAREST);
    hairMask = hairMask > 0;

    //cv:: q("hairMask", hairMask);

    *os << sInput << ": " << input.size() << std::endl;

    // ######### Homomorhpic filter ############
    HomomorphicFilter homomorphicFilter(0.4, 2, 2.0);

    // ######### LANDMARK ######################
    *os << "Create landmarker:" << sRegressor << "," << sDetector << std::endl;
    std::shared_ptr<FaceLandmarker> landmarker;
    if(!sRegressor.empty())
    {
        landmarker = std::make_shared<FaceLandmarker>(sRegressor, sDetector);
        landmarker->canvas = input.clone();
        if(!sTriangles.empty())
        { // optional
            landmarker->readTriangulation(sTriangles);
        }
    }

    *os << "Do landmarks" << std::endl;
    std::vector<cv::Point2f> landmarks;
    if(landmarker)
    {
        cv::Mat gray;
        cv::extractChannel(input, gray, 1);

        { // FaceLandmarker:
            ScopeTimer timer("FaceLandmarker+Detection", *os);
            landmarks = (*landmarker)(gray, {});

            *os << landmarker->getRoi() << " " << double(landmarker->getRoi().area())/double(gray.size().area()) << std::endl;
        }

        std::string sTrianglesOut = parser.get<std::string>("triangles-out");
        if(!sTrianglesOut.empty())
        {
            landmarker->writeTriangulation(sTrianglesOut);
        }

        // DEBUG
        cv::Mat canvas = input.clone();
        landmarker->draw(canvas);
        drawings.emplace_back("FaceLandmarker", canvas);
    }

    // ######### INPAINT ################
    InpaintFilter inpaintFilter(int(landmarker->iod() * 0.25 + 0.5f));

    // ######### BILATERAL ##############
    BilateralFilter bilateralFilter(int(landmarker->iod() * 0.1 + 0.5f), 5, 10);

    cv::Mat filled;

#if DO_INPAINT
    *os << "Do inpaint" << std::endl;
    {
        ScopeTimer timer("InpaintFilter", *os);
        inpaintFilter(input, filled);
    }
#if SHOW_HISTORY
    drawings.emplace_back( inpaintFilter.getNamedDrawing(filled) );
#endif // endif(SHOW_HISTORY)

#else // else(DO_INPAINT)
    filled = input.clone();
#endif // endif(DO_INPAINT)

    cv::Mat even;
    {
        *os << "Do homomorphic" << std::endl;
        ScopeTimer timer("HomomorphicFilter", *os);
        homomorphicFilter(filled, even);
    }
    drawings.emplace_back( homomorphicFilter.getNamedDrawing(even) );

    cv::Mat smoothFull;
    {
        ScopeTimer timer("BilateralFilter", *os);
        bilateralFilter(even, smoothFull);
    }

    cv::Mat symmetric;
    {
        ScopeTimer timer("SymmetryFilter", *os);
        landmarker->balance(smoothFull, symmetric);
    }
#if SHOW_HISTORY
    drawings.emplace_back("Symmetry", symmetric);
#endif

    cv::Mat smooth;
    {
        ScopeTimer timer("BilateralFilter", *os);
        bilateralFilter(symmetric, smooth);
    }
#if SHOW_HISTORY
    drawings.emplace_back( bilateralFilter.getNamedDrawing(smooth) );
#endif

    // Create a face mask
    cv::Mat faceMask = (symmetric > 0);
    cv::reduce( faceMask.reshape(1, faceMask.total()), faceMask, 1, cv::REDUCE_MAX);
    faceMask = faceMask.reshape(1, input.rows);

    CV_Assert(hairMask.size() == faceMask.size());
    cv::Mat mask = (faceMask | hairMask);

    //cv::imshow("both-masks", mask);

    //cv::imshow("even", even);
    //cv::imshow("mask", mask);
    //cv::imshow("mask", mask); cv::waitKey(0);

    { // Head segmentation:
        ScopeTimer timer("Grabcut", *os);
        auto info = landmarker->segmentHead(even, mask);
        auto head = info.first;

        cv::Mat labels = landmarker->getLabels() * 255/3;
        cv::cvtColor(labels, labels, cv::COLOR_GRAY2BGR);
        drawings.emplace_back("labels", labels);

        //cv::medianBlur(smoothFull, smoothFull, 3);
        smoothFull.setTo(cv::Scalar(255,0,0), ~head);

        // Paste symmetric face back into head:
        symmetric.copyTo(smoothFull, faceMask);
        drawings.emplace_back("comp", smoothFull);
    }

    //cv::Mat shiftedFull;
    //cv::pyrMeanShiftFiltering(smoothFull, shiftedFull, 10, 10, 5);
    //cv::Mat final = shiftedFull;
    //drawings.emplace_back("final", final.clone());

    cv::Mat final = smoothFull.clone();

    cv::resize(final, final, size, 0, 0, cv::INTER_LANCZOS4);
    cv::imwrite(sOutput, final);

    // Dump the output
    if(verbose)
    {
        cv::Mat canvas;
        std::vector<cv::Mat> images;
        for(auto &i : drawings)
        {
            images.push_back(i.second);
        }
        cv::hconcat(images, canvas);
        cv::imshow("canvas", canvas); cv::waitKey(0);
    }

    return 0;
}


text:
import React from "react";

import ActiveLink from "../../links/ActiveLink";
import CollapsibleGroup from "../../links/collapsible/CollapsibleGroup";
import PackageLinks from "../../links/collapsible/PackageLinks";
import GuideLinks from "../../links/collapsible/GuideLinks";
import ExampleLinks from "../../links/collapsible/ExampleLinks";
import TutorialLinks from "../../links/collapsible/TutorialLinks";

let MainContents = () => {
  return (

        <ActiveLink name="Home" className="home-link">
          Curi
        </ActiveLink>

        <CollapsibleGroup title="API" initial={true}>
          <PackageLinks />
        </CollapsibleGroup>

        <CollapsibleGroup title="Guides" initial={true}>
          <GuideLinks />
        </CollapsibleGroup>

        <CollapsibleGroup title="Tutorials" initial={true}>
          <TutorialLinks />
        </CollapsibleGroup>

        <CollapsibleGroup title="Examples" initial={true}>
          <ExampleLinks />
        </CollapsibleGroup>

        GitHub

  );
};

export default MainContents;


text:
<?php

namespace Wingu\OctopusCore\CodeGenerator\Tests\Integration\Fixtures {

    use Wingu\OctopusCore\CodeGenerator\Tests\Integration\Fixtures\Test\MyExtension;

	class ClassGeneratorReflectionExtendsNotSameNamespace extends MyExtension {

    }
}

namespace Wingu\OctopusCore\CodeGenerator\Tests\Integration\Fixtures\Test {
    class MyExtension {}
}


text:
package io.cattle.platform.iaas.api.volume;

import static io.cattle.platform.core.constants.CommonStatesConstants.*;
import static io.cattle.platform.core.constants.VolumeConstants.*;
import io.cattle.platform.core.constants.VolumeConstants;
import io.cattle.platform.core.model.Backup;
import io.cattle.platform.core.model.Snapshot;
import io.cattle.platform.core.model.Volume;
import io.cattle.platform.iaas.api.filter.common.AbstractDefaultResourceManagerFilter;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.util.type.CollectionUtils;
import io.github.ibuildthecloud.gdapi.exception.ClientVisibleException;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;
import io.github.ibuildthecloud.gdapi.request.resource.ResourceManager;
import io.github.ibuildthecloud.gdapi.util.ResponseCodes;
import io.github.ibuildthecloud.gdapi.validation.ValidationErrorCodes;

import java.util.Map;

import javax.inject.Inject;

public class VolumeRevertRestoreValidationFilter extends AbstractDefaultResourceManagerFilter {

    @Inject
    ObjectManager objectManager;

    @Override
    public Class<?>[] getTypeClasses() {
        return new Class<?>[] { Volume.class };
    }

    @Override
    public Object resourceAction(String type, ApiRequest request, ResourceManager next) {
        if (!request.getAction().equalsIgnoreCase(ACTION_REVERT) && !request.getAction().equalsIgnoreCase(ACTION_RESTORE)) {
            return super.resourceAction(type, request, next);
        }

        Long volumeId = Long.valueOf(request.getId());
        Map<String, Object> data = CollectionUtils.toMap(request.getRequestObject());
        Long snapshotId = null;
        String field = null;
        String resourceToCheck = null;
        String stateToCheck = null;

        if (request.getAction().equalsIgnoreCase(ACTION_REVERT)) {
            field = "snapshotId";
            snapshotId = (Long)data.get(field);
            resourceToCheck = "Snapshot";

            Snapshot snapshot = objectManager.loadResource(Snapshot.class, snapshotId);
            stateToCheck = snapshot.getState();

            // Ensure the snapshot was made from the volume this action is being performed on
            if (!snapshot.getVolumeId().equals(volumeId)) {
                throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, ValidationErrorCodes.INVALID_REFERENCE,
                        "Snapshot is not for the specified volume.", null);
            }
        } else if (request.getAction().equalsIgnoreCase(ACTION_RESTORE)) {
            field = "backupId";
            Long backupId = (Long)data.get(field);
            Backup backup = objectManager.loadResource(Backup.class, backupId);
            snapshotId = backup.getSnapshotId();
            stateToCheck = backup.getState();
            resourceToCheck = "Backup";

            // If the volume we're restoring isn't the same as the volume from which we created the backup, then make sure neither is a root volume.
            if (!backup.getVolumeId().equals(volumeId)) {
                Volume targetVolume = objectManager.loadResource(Volume.class, volumeId);
                Volume sourceVolume = objectManager.loadResource(Volume.class, backup.getVolumeId());
                if (isRootVolume(targetVolume) || isRootVolume(sourceVolume)) {
                    throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, ValidationErrorCodes.INVALID_REFERENCE,
                            "When restoring a root volume, the backup must have been created from the same volume.", null);
                }
            }
        }

        // Ensure the backup or snapshot is in the created state
        if (!CREATED.equalsIgnoreCase(stateToCheck)) {
            throw new ClientVisibleException(ResponseCodes.UNPROCESSABLE_ENTITY, ValidationErrorCodes.INVALID_REFERENCE, resourceToCheck
                    + " must be in created state.", null);
        }

        return super.resourceAction(type, request, next);
    }

    private boolean isRootVolume(Volume volume) {
        // While there is no "is a vm's root volume" flag on a volume, for all practical purposes, if the volume has a base-image
        // driver-opt, it is a vm's root volume and cannot be restored.
        Map<String, Object> opts = DataAccessor.fieldMap(volume, VolumeConstants.FIELD_VOLUME_DRIVER_OPTS);
        return opts.containsKey(VolumeConstants.DRIVER_OPT_BASE_IMAGE);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	  <meta name="author" content="Nitesh Mishra" />
    <meta name="description" content="Personal blog and resume">
    <link rel="favicon" href="/static/img/favicon.ico">

      <title>Nitesh Mishra</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ=="
    crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="/static/css/main.css" />
	<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:200,400,200bold,400old" />
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
  <link rel="stylesheet" type="text/css" href="/static/css/syntax.css" />

HOME

PROJECTS

ACADEMICS

RESEARCH

  Nitesh Mishra

 FullStack Engineer at HashTag Loyalty

About Me

I am a full stack developer mostly working on Ruby of rails since September 2015. I currently work at Hashtag Loyalty as full stack developer in Mumbai. I like building applications(backend), database design, a little bit of frontend and working with infrastructure.

In my free time I like to read blogs about different architecture, how to build better softwares. I am also a great fan of MOOC and keep doing courses in free time. I like to read about new technologies/tools/techniques which could help building great softwares.

I also like cycling, playing outdoor games, exploring new places.

Here is my resume in pdf format.


text:
- [x] Permite múltiplos seletores JQuery
- [x] Permite inicializar o Collapse aberto ou fechado

# Como usar?

Estrutura HTML

```html
<div class="wrapper">
  <div class="container" id="first-container">
    <button class="button">Collapse!</button>
    <div class="content">
    <h3>Lorem Ipsum:</h3>
      <ul>
        <li>Lorem</li>
        <li>Lorem</li>
        <li>Lorem</li>
        <li>Lorem</li>
      </ul>
    </div>
  </div>
  <div class="container" id="second-container">
    <button class="button">Collapse!</button>
    <div class="content">
      <h3>Lorem Ipsum:</h3>
      <ul>
        <li>Lorem</li>
        <li>Lorem</li>
        <li>Lorem</li>
        <li>Lorem</li>
      </ul>
    </div>
  </div>
</div>
```

chamada javascript

```javascript
$('#first-container button').collapser();
$('#second-container button').collapser({opened: true});
```

## Como contribuir?

1. Faça um **Fork** do projeto
2. Crie uma branch com a nova feature: `git checkout -b nome-da-feature`
3. Faça commit das suas mudanças: `git commit -m 'Add some feature'`
4. Faça **Push** remoto da sua branch: `git push origin nome-da-feature`
5. Envie um **pull request** :)

## Suporte

> Alguma pergunta? Adicione ela usando uma [issue](https://github.com/aletslima123/collapser/issues/new).

## License
Created by and copyright [Alexandre Lima](https://github.com/aletslima123). Released under the [MIT license](https://github.com/aletslima123/collapser/blob/master/LICENSE).


text:
title: Structure
page_title: Structure Overview - RadChat
description: Check our Web Forms article about Structure Overview.
slug: chat/structure
tags: structure
published: True
position: 2
---

# RadChat Structure Overview

This article shows the UI elements in the **RadChat** control and explains their purpose and functionality.

>caption **Figure 1**: A RadChat control structure.

![chat-structure](images/chat-structure.png)

The two main elements the **RadChat** control is built with are **Message List** and **Message Box**.

## The Message List can contain:

* **Message Bubble** - element containing a message string. Usually the current user's message bubbles are right aligned and other users/chatbots' message bubbles are left aligned.
* **Message Group** - a continuous series of message bubbles by the same user.
* **Message Timestamp** - date string near the message bubble showing the time when the message is sent. Clicking the message bubble toggles the timestamp visibility.
* **Avatar** - a user icon next to the message bubble indicating the sender of the message. If there are more than one continuous messages from the same user, the icon stands only next to the last message of the message group.
* **Author** - a text message indicating the author of the message, if such is available. Displayed over the first message bubble of a message group.
* **Suggested Action** - button that the user can tap/click to provide input. Unlike buttons that appear within rich cards (which remain visible and accessible to the user even after being tapped), buttons that appear within the suggested actions pane will disappear after the user makes a selection. This prevents the user from tapping stale buttons within a conversation and simplifies bot development (since you will not need to account for that scenario).
* **Suggested Actions Pane** - an element that contains one or more suggested action elements.
* **Rich Card Attachment** - complex messages that can contain more that just a message string. For example, every card can contain image, custom styling and suggested actions. The default card available in **RadChat** is a "heroCard". More on cards can be found in the [Custom Templates]({%slug chat/functionality/templates%}) article.
* **Deck of cards** - collection of rich cards that can be listed in two ways:
    * **Carousel** - displays multiple cards *horizontally*. Might be referred as **Card Deck**;
    * **List** - displays multiple cards *vertically*. Might be referred as **Card List**;

## The Message Box contains:

* **Message Input** - input where the user writes their message. When there is no message written, a placeholder message is visible.
* **Send Button** - button that when clicked sends the message in the message input. When the focus is on the message input, pressing the `Enter` key is the same as clicking the send button.

# See Also

 * [RadChat Overview]({%slug chat/overview%})

 * [RadChat Server-Side Programming]({%slug chat/server-side-programming/overview%})


text:
package eu.hansolo.enzo.sixteensegment;

import eu.hansolo.enzo.sixteensegment.skin.SixteenSegmentSkin;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.Control;
import javafx.scene.control.Skin;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SixteenSegment extends Control {
    public static final String           STYLE_CLASS_RED     = "red";
    public static final String           STYLE_CLASS_GREEN   = "green";
    public static final String           STYLE_CLASS_BLUE    = "blue";
    public static final String           STYLE_CLASS_YELLOW  = "yellow";
    public static final String           STYLE_CLASS_ORANGE  = "orange";
    public static final String           STYLE_CLASS_CYAN    = "cyan";
    public static final String           STYLE_CLASS_MAGENTA = "magenta";
    public static final String           STYLE_CLASS_WHITE   = "white";
    public static final String           STYLE_CLASS_BLACK   = "black";
    public static enum                   Segment { A1, A2, B, C, D2, D1, E, F, G, H, I, K, L, M, N, P, DOT }
    public static enum                   SegmentStyle {
        RED(STYLE_CLASS_RED),
        GREEN(STYLE_CLASS_GREEN),
        BLUE(STYLE_CLASS_BLUE),
        YELLOW(STYLE_CLASS_YELLOW),
        ORANGE(STYLE_CLASS_ORANGE),
        CYAN(STYLE_CLASS_CYAN),
        MAGENTA(STYLE_CLASS_MAGENTA),
        WHITE(STYLE_CLASS_WHITE),
        BLACK(STYLE_CLASS_BLACK);

        public final String ON_CLASS;
        public final String OFF_CLASS;

        private SegmentStyle(final String CLASS_NAME) {
            ON_CLASS  = CLASS_NAME;
            OFF_CLASS = CLASS_NAME + "-off";
        }
    }
    private boolean                      keepAspect;
    private String                       _character = " ";
    private StringProperty               character;
    private boolean                      _dotOn = false;
    private BooleanProperty              dotOn;
    private SegmentStyle                 _segmentStyle;
    private ObjectProperty<SegmentStyle> segmentStyle;
    private Map<Integer, List<Segment>>  mapping;

    // ******************** Constructors **************************************
    public SixteenSegment() {
        this(" ", SegmentStyle.RED);
    }
    public SixteenSegment(final String CHARACTER) {
        this(CHARACTER, SegmentStyle.RED);
    }
    public SixteenSegment(final Character CHARACTER) {
        this(CHARACTER, SegmentStyle.RED);
    }
    public SixteenSegment(final int CHARACTER) {
        this(Integer.toString(CHARACTER < 0 ? 0 : (CHARACTER > 9 ? 9 : CHARACTER)), SegmentStyle.RED);
    }
    public SixteenSegment(final Character CHARACTER, final SegmentStyle SEGMENT_STYLE) {
        this(String.valueOf(CHARACTER), SEGMENT_STYLE);
    }
    public SixteenSegment(final int CHARACTER, final SegmentStyle SEGMENT_STYLE) {
        this(Integer.toString(CHARACTER < 0 ? 0 : (CHARACTER > 9 ? 9 : CHARACTER)), SEGMENT_STYLE);
    }
    public SixteenSegment(final String CHARACTER, final SegmentStyle SEGMENT_STYLE) {
        getStyleClass().add("sixteen-segment");
        keepAspect    = true;
        _character    = CHARACTER.substring(0, 1);
        _segmentStyle = SEGMENT_STYLE;
        mapping       = new HashMap<>(48);
        initMapping();
    }

    // ******************** Initialization ************************************
    private void initMapping() {
        /*
         * Sixteen Segments
         *
         *         A1A1A1 A2A2A2
         *        F G    H    I B
         *        F  G   H   I  B
         *        F   G  H  I   B
         *        F    G H I    B
         *         PPPPPP KKKKKK
         *        E    N M L    C
         *        E   N  M  L   C
         *        E  N   M   L  C
         *        E N    M    L C
         *         D1D1D1 D2D2D2
         *
         */

        // Space
        mapping.put(20, Arrays.asList(new Segment[] {}));
        // * + , - . /
        mapping.put(42, Arrays.asList(new Segment[]{Segment.G, Segment.H, Segment.I, Segment.L, Segment.M, Segment.N}));
        mapping.put(43, Arrays.asList(new Segment[]{Segment.H, Segment.K, Segment.M, Segment.P}));
        mapping.put(44, Arrays.asList(new Segment[]{Segment.N}));
        mapping.put(45, Arrays.asList(new Segment[]{Segment.P, Segment.K}));
        mapping.put(46, Arrays.asList(new Segment[]{Segment.DOT}));
        mapping.put(47, Arrays.asList(new Segment[]{Segment.I, Segment.N}));
        // 0 - 9
        mapping.put(48, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.C, Segment.D2, Segment.D1, Segment.E, Segment.F, Segment.I, Segment.N}));
        mapping.put(49, Arrays.asList(new Segment[]{Segment.I, Segment.B, Segment.C}));
        mapping.put(50, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.D2, Segment.D1, Segment.E, Segment.P, Segment.K}));
        mapping.put(51, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.C, Segment.D2, Segment.D1, Segment.K}));
        mapping.put(52, Arrays.asList(new Segment[]{Segment.B, Segment.C, Segment.F, Segment.P, Segment.K}));
        mapping.put(53, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.C, Segment.D2, Segment.D1, Segment.F, Segment.P, Segment.K}));
        mapping.put(54, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.C, Segment.D2, Segment.D1, Segment.E, Segment.F, Segment.P, Segment.K}));
        mapping.put(55, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.I, Segment.M}));
        mapping.put(56, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.C, Segment.D2, Segment.D1, Segment.E, Segment.F, Segment.P, Segment.K}));
        mapping.put(57, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.C, Segment.F, Segment.P, Segment.K}));
        // A - Z
        mapping.put(65, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.C, Segment.E, Segment.F, Segment.P, Segment.K}));
        mapping.put(66, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.C, Segment.D2, Segment.D1, Segment.H, Segment.M, Segment.K}));
        mapping.put(67, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.D2, Segment.D1, Segment.E, Segment.F}));
        mapping.put(68, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.C, Segment.D2, Segment.D1, Segment.H, Segment.M}));
        mapping.put(69, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.D2, Segment.D1, Segment.E, Segment.F, Segment.P, Segment.K}));
        mapping.put(70, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.E, Segment.F, Segment.P, Segment.K}));
        mapping.put(71, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.C, Segment.D2, Segment.D1, Segment.E, Segment.F, Segment.K}));
        mapping.put(72, Arrays.asList(new Segment[]{Segment.B, Segment.C, Segment.E, Segment.F, Segment.P, Segment.K}));
        mapping.put(73, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.D2, Segment.D1, Segment.M, Segment.H}));
        mapping.put(74, Arrays.asList(new Segment[]{Segment.B, Segment.C, Segment.D2, Segment.D1, Segment.E}));
        mapping.put(75, Arrays.asList(new Segment[]{Segment.E, Segment.F, Segment.I, Segment.L, Segment.P}));
        mapping.put(76, Arrays.asList(new Segment[]{Segment.D2, Segment.D1, Segment.E, Segment.F}));
        mapping.put(77, Arrays.asList(new Segment[]{Segment.B, Segment.C, Segment.E, Segment.F, Segment.G, Segment.I}));
        mapping.put(78, Arrays.asList(new Segment[]{Segment.B, Segment.C, Segment.E, Segment.F, Segment.G, Segment.L}));
        mapping.put(79, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.C, Segment.D2, Segment.D1, Segment.E, Segment.F}));
        mapping.put(80, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.E, Segment.F, Segment.P, Segment.K}));
        mapping.put(81, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.C, Segment.D2, Segment.D1, Segment.E, Segment.F, Segment.L}));
        mapping.put(82, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.B, Segment.E, Segment.F, Segment.P, Segment.K, Segment.L}));
        mapping.put(83, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.C, Segment.D2, Segment.D1, Segment.G, Segment.K}));
        mapping.put(84, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.H, Segment.M}));
        mapping.put(85, Arrays.asList(new Segment[]{Segment.B, Segment.C, Segment.D2, Segment.D1, Segment.E, Segment.F}));
        mapping.put(86, Arrays.asList(new Segment[]{Segment.E, Segment.F, Segment.I, Segment.N}));
        mapping.put(87, Arrays.asList(new Segment[]{Segment.B, Segment.C, Segment.E, Segment.F, Segment.L, Segment.N}));
        mapping.put(88, Arrays.asList(new Segment[]{Segment.G, Segment.I, Segment.L, Segment.N}));
        mapping.put(89, Arrays.asList(new Segment[]{Segment.G, Segment.I, Segment.M}));
        mapping.put(90, Arrays.asList(new Segment[]{Segment.A1, Segment.A2, Segment.D2, Segment.D1, Segment.I, Segment.N}));

        mapping.put(186, Arrays.asList(new Segment[] {Segment.A1, Segment.F, Segment.H, Segment.P}));
    }

    // ******************** Methods *******************************************
    public final boolean isKeepAspect() {
        return keepAspect;
    }
    public final void setKeepAspect(final boolean KEEP_ASPECT) {
        keepAspect = KEEP_ASPECT;
    }

    public final String getCharacter() {
        return null == character ? _character : character.get();
    }
    public final void setCharacter(final String CHARACTER) {
        if (null == character) {
            _character = CHARACTER.substring(0, 1);
        } else {
            character.set(CHARACTER.substring(0, 1));
        }
    }
    public final void setCharacter(final Character CHARACTER) {
        if (null == character) {
            _character = String.valueOf(CHARACTER);
        } else {
            character.set(String.valueOf(CHARACTER));
        }
    }
    public final void setCharacter(final int CHARACTER) {
        if (null == character) {
            _character = Integer.toString(CHARACTER < 0 ? 0 : (CHARACTER > 9 ? 9 : CHARACTER));
        } else {
            character.set(Integer.toString(CHARACTER < 0 ? 0 : (CHARACTER > 9 ? 9 : CHARACTER)));
        }
    }
    public final ReadOnlyStringProperty characterProperty() {
        if (null == character) {
            character = new SimpleStringProperty(this, "character", _character);
        }
        return character;
    }

    public final boolean isDotOn() {
        return null == dotOn ? _dotOn : dotOn.get();
    }
    public final void setDotOn(final boolean DOT_ON) {
        if (null == dotOn) {
            _dotOn = DOT_ON;
        } else {
            dotOn.set(DOT_ON);
        }
    }
    public final BooleanProperty dotOnProperty() {
        if (null == dotOn) {
            dotOn = new SimpleBooleanProperty(this, "dotOn", _dotOn);
        }
        return dotOn;
    }

    public final SegmentStyle getSegmentStyle() {
        return null == segmentStyle ? _segmentStyle : segmentStyle.get();
    }
    public final void setSegmentStyle(final SegmentStyle SEGMENT_STYLE) {
        if (null == segmentStyle) {
            _segmentStyle = SEGMENT_STYLE;
        } else {
            segmentStyle.set(SEGMENT_STYLE);
        }
    }
    public final ObjectProperty<SegmentStyle> segmentStyleProperty() {
        if (null == segmentStyle) {
            segmentStyle = new SimpleObjectProperty<>(this, "segmentStyle", _segmentStyle);
        }
        return segmentStyle;
    }

    /**
     * Returns a Map that contains the default mapping from ascii integers to lcd segments.
     * The segments are defined as follows:
     *
     *         A1A1A1 A2A2A2
     *        F G    H    I B
     *        F  G   H   I  B
     *        F   G  H  I   B
     *        F    G H I    B
     *         PPPPPP KKKKKK
     *        E    N M L    C
     *        E   N  M  L   C
     *        E  N   M   L  C
     *        E N    M    L C
     *         D1D1D1 D2D2D2
     *
     * @return a Map that contains the default mapping from ascii integers to segments
     */
    public final Map<Integer, List<Segment>> getSegmentMapping() {
        Map<Integer, List<Segment>> segmentMapping = new HashMap<>(48);
        for (int key : mapping.keySet()) {
            segmentMapping.put(key, mapping.get(key));
        }
        return segmentMapping;
    }

    @Override public boolean isResizable() {
        return true;
    }

    // ******************** Style related *************************************
    @Override protected Skin createDefaultSkin() {
        return new SixteenSegmentSkin(this);
    }

    @Override protected String getUserAgentStylesheet() {
        return getClass().getResource(getClass().getSimpleName().toLowerCase() + ".css").toExternalForm();
    }
}


text:
package org.wildfly.security.password.impl;

import java.security.AlgorithmParametersSpi;

import org.wildfly.security.asn1.ASN1Decoder;
import org.wildfly.security.asn1.ASN1Encoder;
import org.wildfly.security.password.spec.IteratedPasswordAlgorithmSpec;
import org.wildfly.security.util.AbstractAlgorithmParametersSpiImpl;

/**
 * An implementation of the {@link AlgorithmParametersSpi} SPI, in order to support encoding and decoding of
 * password algorithm parameters.
 *
 * @author David M. Lloyd
 */
public final class IteratedPasswordAlgorithmParametersSpiImpl extends AbstractAlgorithmParametersSpiImpl<IteratedPasswordAlgorithmSpec> {

    /**
     * Construct a new instance.
     */
    public IteratedPasswordAlgorithmParametersSpiImpl() {
    }

    protected Class<IteratedPasswordAlgorithmSpec> getParameterType() {
        return IteratedPasswordAlgorithmSpec.class;
    }

    protected void engineEncode(final ASN1Encoder encoder, final IteratedPasswordAlgorithmSpec parameterSpec) {
        encoder.encodeInteger(parameterSpec.getIterationCount());
    }

    protected IteratedPasswordAlgorithmSpec engineDecode(final ASN1Decoder decoder) {
        return new IteratedPasswordAlgorithmSpec(decoder.decodeInteger().intValue());
    }
}


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
Quart. J. Micr. Soc. , (N. S. ) 10, 20.

#### Original name
null

### Remarks
null


text:
package ch.unige.idsi.cultweb;

import java.io.IOException;

import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import ch.unige.idsi.cultweb.api.DataAccessObject;
import ch.unige.idsi.cultweb.api.DataRequest;
import ch.unige.idsi.cultweb.model.Cinema;
import ch.unige.idsi.cultweb.model.Museum;
import ch.unige.idsi.cultweb.model.Place.Infrastructure;

@Controller
public class ApiController {

	private DataAccessObject dao;

	public ApiController() throws IOException  {
		dao = new DataAccessObject();
	}

	@RequestMapping("/api")
	public ModelAndView getRoot() {

		String msg = "
Welcome to the CultProject API
";
		msg += "
";
		msg += "[GET]	/museums/	=> get all the museums";
		msg += "\n";
		msg += "[GET]	/cinemas/	=> get all the cinemas";
		msg += "\n";
		msg += "[GET]	/museum/{ID}/	=> get all the information of a given museum ID";
		msg += "\n";
		msg += "[GET]	/cinema/{ID}/	=> get all the information of a given cinema ID";
		msg += "
";

		return new ModelAndView("api", "response", msg);
	}

	/**
	 * Fetches all the museums
	 *
	 * @return : Museums parsed in JSON format
	 * @throws IOException
	 */
	@RequestMapping("/api/museums")
	public ModelAndView getMuseums() throws IOException {
		DataRequest req = new DataRequest();
		String response = req.getMuseums().toString();
		return new ModelAndView("apijson", "response", response);
	}

	/**
	 * Fetches all the cinemas
	 *
	 * @return : Cinemas parsed in JSON format
	 * @throws IOException
	 */
	@RequestMapping("/api/cinemas")
	public ModelAndView getCinemas() throws IOException {
		DataRequest req = new DataRequest();
		String response = req.getCinemas().toString();
		return new ModelAndView("apijson", "response", response);
	}

	/**
	 * Fetches the museum informations
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/api/museum/{id:[\\d]+}")
	public ModelAndView getMuseumInfo(@PathVariable int id)
			throws IOException {

		Museum museum = (Museum) dao.getPlace(id, Infrastructure.MUSEUM);

		if(museum != null) {

			JSONObject res = museum.toJSON();
			res.put("status", "success");

			return new ModelAndView("apijson", "response", res);
		} else {
			return new ModelAndView("apijson", "response", this.generateError().toString());
		}
	}

	/**
	 * Fetches the cinema informations
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/api/cinema/{id:[\\d]+}")
	public ModelAndView getCinemaInfo(@PathVariable int id)
			throws IOException {

		Cinema cinema = (Cinema) dao.getPlace(id, Infrastructure.CINEMA);

		if(cinema != null) {

			JSONObject res = cinema.toJSON();
			res.put("status", "success");

			return new ModelAndView("apijson", "response", res);
		} else {
			return new ModelAndView("apijson", "response", this.generateError().toString());
		}
	}

	/**
	 * Generates an error
	 * @return: JSON error
	 */
	private JSONObject generateError() {
		JSONObject res = new JSONObject();
		res.put("message", "INVALID_OBJECT_ID");
		res.put("status", "error");

		return res;
	}
}


text:
package com.smartg.color;

import java.text.NumberFormat;
import java.util.logging.Logger;

/**
 * @author Andrey Kuznetsov
 */
public class WhitePoint {

    static final WhitePoint D65 = new WhitePoint("D65", .3127, .3290, .3582);
    static final WhitePoint D50 = new WhitePoint("D50", .3457, .3585, .2958);
    static final WhitePoint E = new WhitePoint("E", .3333, .3333, .3334);
    static final WhitePoint C = new WhitePoint("C", .3100, .3160, .3740);

    public final String name;

    public final double wx;
    public final double wy;
    public final double wz;

    public WhitePoint(float[] v) {
	this(v[0], v[1], v[2]);
    }

    public WhitePoint(double[] v) {
	this(v[0], v[1], v[2]);
    }

    public WhitePoint(double wx, double wy, double wz) {
	this("", wx, wy, wz);
    }

    public WhitePoint(String name, double wx, double wy, double wz) {
	this.name = name;
	this.wx = wx;
	this.wy = wy;
	this.wz = wz;
    }

    public boolean equals(Object obj) {
	if (obj == null || !(obj instanceof WhitePoint)) {
	    return false;
	}
	WhitePoint wp = (WhitePoint) obj;
	final int m = 100000;
	if (Math.round(wx * m) != Math.round(wp.wx * m)) {
	    return false;
	}
	if (Math.round(wy * m) != Math.round(wp.wy * m)) {
	    return false;
	}
	if (Math.round(wz * m) != Math.round(wp.wz * m)) {
	    return false;
	}
	return true;
    }

    public double[] getValues() {
	return new double[] { wx, wy, wz };
    }

    public int hashCode() {
	return (int) (Math.round(1 / wx) * 13 * Math.round(1 / wy) * 17 * Math.round(1 / wz) * 31);
    }

    void print(NumberFormat format) {
	Logger l = Logger.getLogger("com.imagero.color");

	l.info("White point: [" + name + "] ");
	l.info(format.format(wx));
	l.info(" ");
	l.info(format.format(wy));
	l.info(" \n");
	l.info(format.format(wz));
    }
}


text:
<!DOCTYPE html>

    <title>Browser tests</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../../node_modules/mocha/mocha.css" />


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
	    http://www.springframework.org/schema/beans
	    http://www.springframework.org/schema/beans/spring-beans.xsd"
       default-autowire="byName">

    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="${jdbc.initialSize}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
        <property name="minIdle" value="${jdbc.minIdle}"/>
        <property name="maxWait" value="${jdbc.maxWait}"/>

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"/>

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"/>

        <property name="validationQuery" value="SELECT 'x'"/>
        <property name="testWhileIdle" value="true"/>
        <property name="testOnBorrow" value="false"/>
        <property name="testOnReturn" value="false"/>

        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
        <property name="poolPreparedStatements" value="false"/>
        <property name="maxPoolPreparedStatementPerConnectionSize"
                  value="20"/>

        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="stat,wall,slf4j"/>

        <property name="proxyFilters">
            <list>
                <ref bean="stat-filter"/>
            </list>
        </property>
    </bean>

    <bean id="stat-filter"
          class="com.alibaba.druid.filter.stat.StatFilter">
        <property name="slowSqlMillis" value="1000"/>
        <property name="logSlowSql" value="true"/>
        <property name="mergeSql" value="true"/>
    </bean>

    <!-- 配置事物管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置mybatis的对象工厂 -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mapping/*.xml"/>
        <property name="typeAliasesPackage" value="com.bjtu.gits.domain.bean"/>
    </bean>

    <!-- 自动扫描 生成Mapper接口的代理注入到Spring 此时若只有一个dataSource则可以自动装配
		sqlSessionFactory,若有多个dataSource 则sqlSessionTemplateBeanName是必须的,
		所有此处value代替了ref-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
        <property name="basePackage" value="com.bjtu.gits.dao.interf" />
        <property name="annotationClass" value="com.bjtu.gits.dao.Mapper"/>
    </bean>
</beans>


text:
<!DOCTYPE html>

	<title>PreloadJS: Queue Example</title>

	<link href="../_assets/css/shared.css" rel="stylesheet" type="text/css"/>
	<link href="../_assets/css/examples.css" rel="stylesheet" type="text/css"/>

Preload Queue

Click "load another" to add another image the the overall queue. As
		images are added, the preload progress reflects
		the overall loaded progress. Click "load all" to queue everything at
		once.
		Note that when loading images and sounds locally, you need to ensure
		that PreloadJS uses tag loading to avoid
		cross-origin errors.

	<input type="button" id="loadAnotherBtn" value="Load Another"
		   disabled="disabled"/>
	<input type="button" id="loadAllBtn" value="Load All" disabled="disabled"/>
	<input type="button" id="reloadBtn" value="Reset"/>

		Overall Progress


text:
// Copyright (c) 2014-2020, Justin Crawford <Justin@stacksmash.net>
// 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.

// 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.

#pragma once
#include "Flux.h"
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#define SPDLOG_ENABLE_SYSLOG 1
#include <spdlog/spdlog.h>

namespace spd = spdlog;

// Forward declare because we dont need recursive includes.
class Command;
class User;

/**
 * @brief Basic logging class to make things MUCH nicer and easier to write.
 * @class Log
 */
class Log
{
	spd::level::level_enum				lvl;
	std::string							message;
	bool								alreadylogged;
	static std::shared_ptr<spd::logger> logsink;

  public:
	/// @brief Defined for user-defined literal.
	/// @param l The log level used for spdlog. Values can be spd::level::info,warn,err,critical.
	/// @param str the log string.
	/// @param len the length of log string.
	Log(spd::level::level_enum l, const char *str, size_t len) : lvl(l), message(str, len), alreadylogged(false) {}

	~Log()
	{
		if (!this->alreadylogged)
			Log::logsink->log(this->lvl, this->message.c_str());
	}

	// C++ likes us to have the call operator defined.
	template<typename... Args>
	Log &operator()(Args &&... args)
	{
		Log::logsink->log(this->lvl, this->message.c_str(), args...);
		this->alreadylogged = true;
		return *this;
	}

	// Used for spdlog.
	static inline void Initialize()
	{
		try
		{
			// Create an async console and syslog logger.
			spd::set_async_mode(8192);
			// Make a vector of sinks we want to use (currently console ansi color and syslog.)
			std::vector<spd::sink_ptr> sinks;
			sinks.push_back(std::make_shared<spd::sinks::ansicolor_stdout_sink_mt>());
			sinks.push_back(std::make_shared<spd::sinks::syslog_sink>("silicon"));

			// Initialize the sink pointer.
			Log::logsink = std::make_shared<spd::logger>("silicon", begin(sinks), end(sinks));
			// Register the sink with spdlog.
			spd::register_logger(Log::logsink);
		}
		catch (const spd::spdlog_ex &ex)
		{
			// Oops we blew up :(
			std::cerr << "Log initialization failed: " << ex.what() << std::endl;
		}
	}

	static inline void Terminate()
	{
		try
		{
			spd::drop_all();
		}
		catch (const spd::spdlog_ex &ex)
		{
			// Oops we blew up :(
			std::cerr << "Log termination failed: " << ex.what() << std::endl;
		}
	}
};

// Allow for "Here is the value: %s!"_l("the value!"); style logs.
inline Log operator"" _l(const char *str, size_t len) { return Log(spd::level::info, str, len); }
inline Log operator"" _lw(const char *str, size_t len) { return Log(spd::level::warn, str, len); }
inline Log operator"" _le(const char *str, size_t len) { return Log(spd::level::err, str, len); }
inline Log operator"" _lc(const char *str, size_t len) { return Log(spd::level::critical, str, len); }


text:
/**
 * \file balDynasty.h
 * \brief Definition of the class Dynasty
 */

#ifndef _BALDYNASTY_
#define _BALDYNASTY_

#include "balObject.h"
#include "balParameters.h"
#include "balDynamicalSystem.h"
#include <cstring>
#include <cvode/cvode.h>

#define EPS (1.0E-4)

namespace bal {

enum {MINIMA, MAXIMA, ANY};

/**
 * \class Dynasty
 * \brief Implementation of a dynamical system that describes a
 * model of Chinese dynasty.
 *
 * \sa DynamicalSystem
 */
class Dynasty : public DynamicalSystem {
 public:
  virtual const char * GetClassName () const;
  static Dynasty * Create ();
  static Dynasty * Copy(Dynasty *dynasty);
  virtual DynamicalSystem * Clone() const;
  virtual void Destroy ();

  int RHS (realtype t, N_Vector x, N_Vector xdot, void * data);
#ifdef CVODE25
  int Jacobian (long int N, DenseMat J, realtype t, N_Vector x, N_Vector fy,
		void *jac_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3);
#endif
#ifdef CVODE26
  int Jacobian (int N, realtype t, N_Vector x, N_Vector fy, DlsMat J,
		void *jac_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3);
#endif
  int Events (realtype t, N_Vector x, realtype * event, void * data);
  void EventsConstraints (realtype t, N_Vector x, int * constraints, void * data);

  bool HasJacobian() const;
  bool HasEvents() const;
  bool HasEventsConstraints() const;
  bool SpecialOptions(const void *opt);

 protected:
  Dynasty();
  Dynasty(const Dynasty& hr);
  virtual ~Dynasty();

 private:
  N_Vector xderiv;
  int constraint_type;
};

} // namespace bal

#ifdef __cplusplus
extern "C" {
#endif

bal::DynamicalSystem* DynastyFactory();

#ifdef __cplusplus
}
#endif

#endif


text:
// Define Paths
var src = 'source/'
var srcAssets = 'source/_assets/'
var build = 'build/'
var development = 'build/development/'
var developmentAssets = 'build/assets/'
var production = 'build/production/'
var productionAssets = 'build/production/assets/'

// Define Configuration
module.exports = {
  watch: {
    jekyll: [
      '_config.yml',
      '_config.production.yml',
      src + '_data/**/*',
      src + '_includes/**/*',
      src + '_layouts/**/*',
      src + '_plugins/**/*',
      src + '_posts/**/*',
      src + '/**/*.{html,markdown,md,yml,json,txt,xml}',
      src + '/*'
    ],
    styles: srcAssets + '/styles/**/*',
    scripts: srcAssets + '/scripts/**/*',
    images: srcAssets + '/images/**/*',
    icons: srcAssets + '/icons/**/*',
    favicons: srcAssets + '/favicons/**/*',
    fonts: srcAssets + '/fonts/**/*',
    audio: srcAssets + '/audio/**/*'
  },
  serve: {
    development: {
      server: {
        baseDir: [development, build, src]
      },
      files: [
        developmentAssets + '/audio/**',
        developmentAssets + '/styles/*.css',
        developmentAssets + '/scripts/*.js',
        developmentAssets + '/images/**',
        developmentAssets + '/icons/**',
        developmentAssets + '/favicons/*',
        developmentAssets + '/fonts/*',
        developmentAssets + '/audio/*'
      ],
      port: 9999,
      xip: false,
      notify: {
        styles: ['display: hidden; padding: 12px; font-family: sans-serif; position: fixed; font-size: 14px; z-index: 10000; left: 0; bottom: 0; width: 200px; margin: 0; border-top-left-radius: 0; border-top-right-radius: 3px; color: #fff; text-align: center; background-color: rgba(0, 0, 0, 0.75);']
      }
    },
    production: {
      server: {
        baseDir: [production]
      },
      port: 9998,
      xip: true
    }
  },
  build: {},
  clean: {
    src: developmentAssets
  },
  jekyll: {
    development: {
      src: src,
      dest: development,
      config: '_config.yml'
    },
    production: {
      src: src,
      dest: production,
      config: '_config.yml,_config.production.yml'
    }
  },
  styles: {
    src: srcAssets + 'styles/styles.css',
    dest: developmentAssets + 'styles/',
    processors: {
      cssnext: {
        browsers: [
          'last 2 versions'
        ]
      },
      mqpacker: {
        sort: true
      }
    }
  },
  scripts: {
    debug: true,
    extensions: ['.coffee', '.hbs'],
    bundleConfigs: [
      {
        entries: srcAssets + 'scripts/scripts.js',
        dest: developmentAssets + 'scripts/',
        outputName: 'scripts.js'
      },
      {
        entries: srcAssets + 'scripts/head.js',
        dest: developmentAssets + 'scripts/',
        outputName: 'head.js'
      }
    ]
  },
  images: {
    src: srcAssets + 'images/**/*',
    dest: developmentAssets + 'images/',
    processors: {
      imageResize: {
        src: srcAssets + '/images/site-section/**',
        dest: developmentAssets + '/images/site-section/',
        small: {
          width: 360,
          quality: 0.8,
          progressive: true
        },
        smallDest: '/small',
        medium: {
          width: 768,
          quality: 0.8,
          progressive: true
        },
        mediumDest: '/medium',
        large: {
          width: 1140,
          quality: 0.8,
          progressive: true
        },
        largeDest: '/large'
      }
    }
  },
  icons: {
    src: srcAssets + 'icons/**/*.svg',
    dest: developmentAssets + 'icons',
    processors: {
      sprite: {
        mode: {
          symbol: {
            dest: './',
            sprite: 'sprite.svg'
          }
        }
      }
    }
  },
  favicons: {
    src: srcAssets + 'favicons/**/*',
    dest: developmentAssets + 'favicons/'
  },
  fonts: {
    src: srcAssets + 'fonts/**/*',
    dest: developmentAssets + 'fonts/'
  },
  audio: {
    src: srcAssets + 'audio/**/*',
    dest: developmentAssets + 'audio/'
  },
  optimize: {
    styles: {
      src: developmentAssets + '/styles/*.css',
      dest: productionAssets + '/styles/',
      processors: {
        rename: {
          suffix: '.min'
        }
      }
    },
    scripts: {
      src: developmentAssets + '/scripts/*.js',
      dest: productionAssets + '/scripts/',
      processors: {
        rename: {
          suffix: '.min'
        },
        uglify: {}
      }
    },
    images: {
      src: developmentAssets + '/images/**/*.{jpg,jpeg,png,gif,svg}',
      dest: productionAssets + '/images/',
      processors: {
        imagemin: {
          optimizationLevel: 3,
          progessive: true,
          interlaced: true,
          svgoPlugins: [{
            removeViewBox: false
          }]
        }
      }
    },
    icons: {
      src: developmentAssets + '/icons/**/*',
      dest: productionAssets + '/icons/'
    },
    favicons: {
      src: developmentAssets + '/favicons/**/*',
      dest: productionAssets + '/favicons/'
    },
    fonts: {
      src: developmentAssets + '/fonts/**/*',
      dest: productionAssets + '/fonts/'
    },
    audio: {
      src: developmentAssets + '/audio/**/*',
      dest: productionAssets + '/audio/'
    },
    html: {
      src: production + '/**/*.html',
      dest: production,
      processors: {
        htmlmin: {
          collapseWhitespace: true
        },
        htmlreplace: {
          styles: {
            src: '/assets/styles/',
            tpl: '<link rel="stylesheet" href="%sstyles.min.css">'
          },
          head: {
            src: '/assets/scripts/',
            tpl: '<script src="%shead.min.js"></script>'
          },
          scripts: {
            src: '/assets/scripts/',
            tpl: '<script src="%sscripts.min.js"></script>'
          }
        }
      }
    }
  },
  copy: {
    cname: {
      src: 'CNAME',
      dest: production
    }
  },
  revision: {
    src: {
      assets: [
        productionAssets + '/styles/*.css',
        productionAssets + '/scripts/*.js',
        productionAssets + '/images/**/*'
      ],
      base: production
    },
    dest: {
      assets: production,
      manifest: {
        name: 'manifest.json',
        path: productionAssets
      }
    },
    collect: {
      src: [
        productionAssets + '/manifest.json',
        production + '/**/*.{html,xml,txt,json,css,js}',
        '!' + production + '/feed.xml'
      ],
      dest: production
    }
  },
  gzip: {
    src: production + '/**/*.{html,xml,json,css,js}',
    dest: production,
    options: {}
  },
  ghPages: {
    src: production + '/**',
    options: {}
  },
  rsync: {
    src: production + '/**',
    options: {
      destination: '/var/www/marlaandchris2016.com/public_html/www/',
      root: production,
      hostname: 'cbracco.me',
      username: 'chris',
      port: 415,
      incremental: true,
      progress: true,
      relative: true,
      emptyDirectories: true,
      recursive: true,
      clean: true,
      exclude: ['.DS_Store'],
      include: [],
      command: true
    }
  }
}


text:
package jodd.json.mock;

import java.util.Date;

public class Employee extends Person {

	String company;

	public Employee() {
	}

	public Employee(String firstname, String lastname, Date birthdate, Address home, Address work, String company) {
		super(firstname, lastname, birthdate, home, work);
		this.company = company;
	}

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public void setCompany(StringBuilder builder) {
		this.company = builder.toString();
	}
}


text:
import * as React from 'react';
import {properties, stylable} from 'wix-react-tools';
import styles from './loader.st.css';

export interface LoaderProps extends properties.Props {
    delay?: number;
    text?: string;
    children?: React.ReactNode;
}

export interface LoaderState {
    active: boolean;
}

@stylable(styles)
@properties
export class Loader extends React.Component<LoaderProps, LoaderState> {
    private timer: number;

    public constructor(props: LoaderProps) {
        super();
        this.state = {
            active: !props.delay
        };
    }

    public componentWillMount() {
        this.setTimer(this.props);
    }

    public componentWillReceiveProps(props: LoaderProps) {
        this.setTimer(props);
    }

    public componentWillUnmount() {
        clearTimeout(this.timer!);
    }

    public render() {
        const {text, children} = this.props;

        if (!this.state.active) {
            return null;
        }

        if (children) {
            return
;
        }

        return (

                {this.renderLoader()}
                {text &&

                }

        );
    }

    protected renderLoader(): JSX.Element | null {
        return null;
    }

    private setTimer(props: LoaderProps) {
        if (props.delay) {
            clearTimeout(this.timer!);
            this.timer = window.setTimeout(() => {
                this.setState({active: true});
            }, props.delay);
        } else if (!this.state.active) {
            this.setState({active: true});
        }
    }

}


text:
<?php if ($actions = $this->configuration->getValue('list.actions')): ?>
<div class="btn-group">
<?php foreach ($actions as $name => $params): ?>
<?php if ('_new' == $name): ?>
<?php echo $this->addCredentialCondition('[?php echo $helper->linkToNew('.$this->asPhp($params).') ?]', $params)."\n" ?>
<?php else: ?>
  <?php echo $this->addCredentialCondition($this->getLinkToAction($name, array_merge($params, array('params' => array('class' => 'btn btn-sm btn-default'))), false), $params)."\n" ?>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>


text:
#include "sky/engine/platform/graphics/ThreadSafeDataTransport.h"

#include "sky/engine/platform/SharedBuffer.h"

namespace blink {

ThreadSafeDataTransport::ThreadSafeDataTransport()
    : m_readBuffer(SharedBuffer::create())
    , m_allDataReceived(false)
    , m_readPosition(0)
{
}

ThreadSafeDataTransport::~ThreadSafeDataTransport()
{
}

void ThreadSafeDataTransport::setData(SharedBuffer* buffer, bool allDataReceived)
{
    ASSERT(buffer->size() >= m_readPosition);
    Vector<RefPtr<SharedBuffer> > newBufferQueue;

    const char* segment = 0;
    while (size_t length = buffer->getSomeData(segment, m_readPosition)) {
        m_readPosition += length;
        newBufferQueue.append(SharedBuffer::create(segment, length));
    }

    MutexLocker locker(m_mutex);
    m_newBufferQueue.appendVector(newBufferQueue);
    m_allDataReceived = allDataReceived;
}

void ThreadSafeDataTransport::data(SharedBuffer** buffer, bool* allDataReceived)
{
    Vector<RefPtr<SharedBuffer> > newBufferQueue;
    {
        MutexLocker lock(m_mutex);
        m_newBufferQueue.swap(newBufferQueue);
    }
    for (size_t i = 0; i < newBufferQueue.size(); ++i)
        m_readBuffer->append(newBufferQueue[i].get());
    ASSERT(buffer);
    ASSERT(allDataReceived);
    *buffer = m_readBuffer.get();
    *allDataReceived = m_allDataReceived;
}

bool ThreadSafeDataTransport::hasNewData()
{
    MutexLocker lock(m_mutex);
    return !m_newBufferQueue.isEmpty();
}

} // namespace blink


text:
@class Artist;

@interface BESongViewController : UITableViewController

@property (nonatomic, strong) Artist *artist;

-(id)initWithArtist:(Artist *)artist;

@end


text:
import Cycle from '@cycle/xstream-run';
import {div, input, p, makeDOMDriver} from '@cycle/dom';

function main(sources) {
  let sinks = {
    DOM: sources.DOM.select('input').events('change')
      .map(ev => ev.target.checked)
      .startWith(false)
      .map(toggled =>
        div([
          input({attrs: {type: 'checkbox'}}), 'Toggle me',
          p(toggled ? 'ON' : 'off')
        ])
      )
  };
  return sinks;
}

Cycle.run(main, {
  DOM: makeDOMDriver('#main-container')
});