text:
package dk.dtu.student.programanalysis.implementation.analysis;

import dk.dtu.student.programanalysis.implementation.ArithmeticExpression;
import dk.dtu.student.programanalysis.implementation.BaseAnalysis;
import dk.dtu.student.programanalysis.implementation.GeneralAnalysis;
import dk.dtu.student.programanalysis.implementation.Label;
import dk.dtu.student.programanalysis.implementation.declaration.DeclarationArrayInteger;
import dk.dtu.student.programanalysis.implementation.declaration.DeclarationInteger;
import dk.dtu.student.programanalysis.implementation.graph.FlowGraph;
import dk.dtu.student.programanalysis.implementation.label.LabelDS;
import dk.dtu.student.programanalysis.implementation.set.Signs;
import dk.dtu.student.programanalysis.implementation.statement.*;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.TerminalNodeImpl;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import org.jgrapht.DirectedGraph;
import org.jgrapht.graph.DefaultEdge;

import javax.xml.soap.DetailEntry;
import java.util.*;

/**
 * Created by ruimartins on 23/11/2015.
 */
public class AnalysisDetectionSigns extends GeneralAnalysis {

    DetectionSignsLattice iota;
    DetectionSignsLattice zeroLattice;
    DetectionSignsLattice negativeLattice;
    DetectionSignsLattice positiveLattice;
    DetectionSignsAnalysisType extremalValue;

    DetectionSignsAnalysisType bottom;
    Map<LabelDS, DetectionSignsAnalysisType> DSEnter;
    Map<LabelDS, DetectionSignsAnalysisType> DSLeave;

    public AnalysisDetectionSigns() {

        zeroLattice = new DetectionSignsLattice();
        zeroLattice.add(Signs.ZERO);

        negativeLattice = new DetectionSignsLattice();
        negativeLattice.add(Signs.NEGATIVE);

        positiveLattice = new DetectionSignsLattice();
        positiveLattice.add(Signs.POSITIVE);

        iota = new DetectionSignsLattice();
        iota.add(Signs.ZERO);
        iota.add(Signs.POSITIVE);
        iota.add(Signs.NEGATIVE);
        extremalValue = new DetectionSignsAnalysisType();
        bottom = new DetectionSignsAnalysisType();
        DSLeave = new HashMap<>();
        DSEnter = new HashMap<>();

    }

    @Override
    public String getName() {
        return "DetectionSigns";
    }
    @Override
    public void parse(StatementAssign node, ParserRuleContext context) {
        ArithmeticExpression e = new ArithmeticExpression();
        e.setUserObject(context.getChild(2));
        e.parseTreeNode();
        // Get Symbol for line
        TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(0);
        Label label = new LabelDS(node.getClass(), firstTerminal.getSymbol().getText(),
                context.getStart().getLine(), e);

        node.setL(label);
    }

    @Override
    public void parse(StatementAssignArray node, ParserRuleContext context) {

        ArithmeticExpression e = new ArithmeticExpression();
        e.setUserObject(context.getChild(2));
        e.parseTreeNode();

        ArithmeticExpression e2 = new ArithmeticExpression();
        e2.setUserObject(context.getChild(5));
        e2.parseTreeNode();
        // Get Symbol for line
        TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(0);
        Label label = new LabelDS(node.getClass(), firstTerminal.getSymbol().getText(),
                context.getStart().getLine(), e, e2);

        node.setL(label);
    }

    @Override
    public void parse(StatementIf node, ParserRuleContext context) {
        super.parse(node, context);

        // Get Symbol for line
        TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(0);
        Label label = new LabelDS(node.getClass(), firstTerminal.getSymbol().getText(),
                context.getStart().getLine());

        node.setL(label);
    }

    @Override
    public void parse(StatementRead node, ParserRuleContext context) {
        // Get Symbol for line
        TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(1);
        Label label = new LabelDS(node.getClass(), firstTerminal.getSymbol().getText(),
                context.getStart().getLine());

        node.setL(label);
    }

    @Override
    public void parse(StatementReadArray node, ParserRuleContext context) {
        ArithmeticExpression e = new ArithmeticExpression();
        e.setUserObject(context.getChild(3));
        e.parseTreeNode();

        // Get Symbol for line
        TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(1);
        Label label = new LabelDS(node.getClass(), firstTerminal.getSymbol().getText(),
                context.getStart().getLine(), e);

        node.setL(label);
    }

    @Override
    public void parse(StatementSkip node, ParserRuleContext context) {
        // Get Symbol for line
        TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(0);
        Label label = new LabelDS(node.getClass(), firstTerminal.getSymbol().getText(),
                context.getStart().getLine());

        node.setL(label);
    }

    @Override
    public void parse(StatementWhile node, ParserRuleContext context) {
        super.parse(node, context);

        // Get Symbol for line
        TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(0);
        Label label = new LabelDS(node.getClass(), firstTerminal.getSymbol().getText(),
                context.getStart().getLine());

        node.setL(label);
    }

    @Override
    public void parse(StatementWrite node, ParserRuleContext context) {
        // Get Symbol for line
        TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(0);
        Label label = new LabelDS(node.getClass(), firstTerminal.getSymbol().getText(),
                context.getStart().getLine());

        node.setL(label);
    }

    @Override
    public void parse(DeclarationInteger node, ParserRuleContext context) {
        // Get Symbol for line
        TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(1);
        Label label = new LabelDS(node.getClass(), firstTerminal.getSymbol().getText(),
                context.getStart().getLine());

        node.setL(label);
    }

    @Override
    public void parse(DeclarationArrayInteger node, ParserRuleContext context) {
        // Initiating our ArithmeticExpression
        ArithmeticExpression e = new ArithmeticExpression();
        e.setUserObject(context.getChild(3));
        e.parseTreeNode();

        // Get Symbol for line
        TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(1);
        Label label = new LabelDS(node.getClass(), firstTerminal.getSymbol().getText(),
                context.getStart().getLine(), e);

        node.setL(label);
    }

    @Override
    public void doAnalysis(FlowGraph graph) {
        assignBottomAndProduceExtremes(graph);
        super.doAnalysis(graph);
        System.out.println();
    }

    private void assignBottomAndProduceExtremes(FlowGraph graph) {

        Set<LabelDS> labels =  (Set<LabelDS>) graph.getLabels();

        for(LabelDS label : labels) {
            bottom.addValue(label.getSymbol(), new DetectionSignsLattice());
            //produce extremes.
            extremalValue.addValue(label.getSymbol(), iota);
        }

    }

    private void populateFunctions(FlowGraph graph) {

        Set<LabelDS> labels = (Set<LabelDS>) graph.getLabels();
        for(LabelDS l : labels) {
            DetectionSignsLattice lat = calculateSignsOfLabel(l);
        }

    }

    private DetectionSignsLattice calculateSignsOfLabel(LabelDS l) {

        return new DetectionSignsLattice();
    }

    private void produceFunctions(FlowGraph graph, Label l) {

    }

    @Override
    protected DetectionSignsAnalysisType getExtremeValue(Set<? extends Label> labels) {
        return extremalValue;
    }

    @Override
    protected  DetectionSignsAnalysisType getBottomValue() {
        return bottom;

    }

    protected DetectionSignsLattice getZeroLattice() {
        return zeroLattice;
    }

    @Override
    protected DetectionSignsAnalysisType analyseComponent(Label l) {

        if(l.getStatementClass() == DeclarationInteger.class)
        {
            String symbol = ((LabelDS) l).getSymbol();
            DetectionSignsAnalysisType current = DSEnter.get(l);
            current.addValue(symbol, getZeroLattice());
            setAnalysisResult(l, current);
            DSLeave.put((LabelDS) l, current);
            return current;

        }
        if(l.getStatementClass() == DeclarationArrayInteger.class)
        {
            String symbol = ((LabelDS) l).getSymbol();
            DetectionSignsAnalysisType current = DSEnter.get(l);

            if(ExpressionGreaterThanZero(((LabelDS) l).getExpression())) {
                current.addValue(symbol, getZeroLattice());
                setAnalysisResult(l, current);
                DSLeave.put((LabelDS) l, current);
                return current;
            }
            else
            {
                throw new IllegalArgumentException("Array declarations can not start with non-positive numbers.");
            }
        }
        if(l.getStatementClass() == StatementAssign.class)
        {
            String symbol = ((LabelDS) l).getSymbol();
            DetectionSignsAnalysisType current = DSEnter.get(l);

            current.addValue(symbol, calculateLatticeFromExpression(((LabelDS) l).getExpression()));
            setAnalysisResult(l, current);
            DSLeave.put((LabelDS) l, current);
            return current;

        }

        if(l.getStatementClass() == StatementAssignArray.class)
        {
            String symbol = ((LabelDS) l).getSymbol();
            DetectionSignsAnalysisType current = DSEnter.get(l);

            if(ExpressionGreaterThanZero(((LabelDS) l).getExpression())) {

                DetectionSignsLattice newLattice = current.unionValue(symbol, calculateLatticeFromExpression(((LabelDS) l).getExpression2()));
                DetectionSignsAnalysisType newAnalysis = new DetectionSignsAnalysisType();

                for (Map.Entry<String, DetectionSignsLattice> entry : current.GetValue().entrySet()) {
                    newAnalysis.addValue(entry.getKey(), entry.getValue());
                }
                newAnalysis.addValue(symbol, newLattice);
                setAnalysisResult(l, newAnalysis);
                DSLeave.put((LabelDS) l, newAnalysis);
                return newAnalysis;
            }
            else
            {
                throw new IllegalArgumentException("Array declarations can not start with non-positive numbers.");
            }

        }

        if(l.getStatementClass() == StatementReadArray.class)
        {
            String symbol = ((LabelDS) l).getSymbol();
            DetectionSignsAnalysisType current = DSEnter.get(l);

            if(ExpressionGreaterThanOrEqualToZero(((LabelDS) l).getExpression())) {
                current.addValue(symbol, iota);
                setAnalysisResult(l, current);
                DSLeave.put((LabelDS) l, current);
                return current;
            }
            else
            {
                throw new IllegalArgumentException("Array declarations can not start with non-positive numbers.");
            }
        }
        if(l.getStatementClass() == StatementSkip.class)
        {
            DetectionSignsAnalysisType current = DSEnter.get(l);
            setAnalysisResult(l, current);
            DSLeave.put((LabelDS) l, current);
            return current;

        }
        if(l.getStatementClass() == StatementWhile.class)
        {
            DetectionSignsAnalysisType current = DSEnter.get(l);
            setAnalysisResult(l, current);
            DSLeave.put((LabelDS) l, current);
            return current;

        }
        if(l.getStatementClass() == StatementWrite.class)
        {
            DetectionSignsAnalysisType current = DSEnter.get(l);
            setAnalysisResult(l, current);
            DSLeave.put((LabelDS) l, current);
            return current;

        }
        if(l.getStatementClass() == StatementRead.class)
        {
            String symbol = ((LabelDS) l).getSymbol();
            DetectionSignsAnalysisType current = DSEnter.get(l);
            current.addValue(symbol, iota);
            setAnalysisResult(l, current);
            DSLeave.put((LabelDS) l, current);
            return current;
        }

        return new DetectionSignsAnalysisType();
    }

    private DetectionSignsLattice calculateLatticeFromExpression(ArithmeticExpression expression) {
        DetectionSignsLattice result = new DetectionSignsLattice();

        if(expression.getOperand() != null ) {
            switch (expression.getOperand()) {
                case ADDITION:
                    if(expression.getLeftValue() > 0 && expression.getRightValue() < 0) {
                        result.add(Signs.POSITIVE);
                        result.add(Signs.NEGATIVE);
                        result.add(Signs.ZERO);
                    }
                    else if(expression.getLeftValue() < 0 && expression.getRightValue() > 0) {
                        result.add(Signs.POSITIVE);
                        result.add(Signs.NEGATIVE);
                        result.add(Signs.ZERO);
                    }
                    else if(expression.getLeftValue() == 0 && expression.getRightValue() == 0) {
                        result.add(Signs.ZERO);
                    }
                    else if(expression.getLeftValue() < 0 || expression.getRightValue() < 0) {
                        result.add(Signs.NEGATIVE);
                    }
                    else {
                        result.add(Signs.POSITIVE);
                    }

                    break;
                case SUBTRACTION:
                    if(expression.getLeftValue() < 0 && expression.getRightValue() < 0) {
                        result.add(Signs.POSITIVE);
                        result.add(Signs.NEGATIVE);
                        result.add(Signs.ZERO);
                    }
                    else if(expression.getLeftValue() > 0 && expression.getRightValue() > 0) {
                        result.add(Signs.POSITIVE);
                        result.add(Signs.NEGATIVE);
                        result.add(Signs.ZERO);
                    }
                    else if(expression.getLeftValue() == 0 && expression.getRightValue() == 0) {
                        result.add(Signs.ZERO);
                    }
                    else if(expression.getLeftValue() > 0 || expression.getRightValue() < 0) {
                        result.add(Signs.POSITIVE);
                    }
                    else {
                        result.add(Signs.NEGATIVE);
                    }
                    break;
                case MULTIPLICATION:
                    if(expression.getLeftValue() == 0 || expression.getRightValue() == 0) {
                        result.add(Signs.ZERO);
                    }
                    else if(expression.getLeftValue() > 0 && expression.getRightValue() > 0) {
                        result.add(Signs.POSITIVE);
                    }
                    else if(expression.getLeftValue() < 0 && expression.getRightValue() < 0) {
                        result.add(Signs.POSITIVE);
                    }
                    else result.add(Signs.NEGATIVE);
                    break;
                case DIVISION:
                    if(expression.getRightValue() == 0) {
                        throw new IllegalArgumentException("Division by zero.");
                    }
                    else if(expression.getLeftValue() == 0 ) {
                        result.add(Signs.ZERO);
                    }
                    else if(expression.getLeftValue() < 0 && expression.getRightValue() < 0) {
                        result.add(Signs.POSITIVE);
                    }
                    else if(expression.getLeftValue() > 0 && expression.getRightValue() > 0) {
                        result.add(Signs.POSITIVE);
                    }
                    else result.add(Signs.NEGATIVE);
                    break;
            }
            return result;
        }
        else {
            if(expression.getLeftValue() >0 ) {
                return positiveLattice;
            }
            else if(expression.getLeftValue() < 0) {
                return negativeLattice;
            }
            else{
                return zeroLattice;
            }
        }
    }
    private boolean ExpressionGreaterThanOrEqualToZero(ArithmeticExpression expression) {
        float result = Integer.MIN_VALUE;

        if(expression.getOperand() != null ) {
            switch (expression.getOperand()) {
                case ADDITION:
                    result = expression.getLeftValue() + expression.getRightValue();
                    break;
                case SUBTRACTION:
                    result = expression.getLeftValue() - expression.getRightValue();
                    break;
                case MULTIPLICATION:
                    result = expression.getLeftValue() * expression.getRightValue();
                    break;
                case DIVISION:
                    result = expression.getLeftValue() / expression.getRightValue();
                    break;
            }
            return result >= 0;
        }
        else {
            return expression.getLeftValue() >= 0;
        }
    }

    private boolean ExpressionGreaterThanZero(ArithmeticExpression expression) {

        float result = Integer.MIN_VALUE;

        if(expression.getOperand() != null ) {
            switch (expression.getOperand()) {
                case ADDITION:
                    result = expression.getLeftValue() + expression.getRightValue();
                    break;
                case SUBTRACTION:
                    result = expression.getLeftValue() - expression.getRightValue();
                    break;
                case MULTIPLICATION:
                    result = expression.getLeftValue() * expression.getRightValue();
                    break;
                case DIVISION:
                    result = expression.getLeftValue() / expression.getRightValue();
                    break;
            }
            return result > 0;
        }
        else {
            return expression.getLeftValue() > 0;
        }
    }

    @Override
    protected DetectionSignsAnalysisType getAnalysisResult(Label l) {
        return DSEnter.get((LabelDS)l);
    }

    @Override
    protected void setAnalysisResult(Label l, AnalysisType newSet) {
        DSEnter.put((LabelDS)l, (DetectionSignsAnalysisType) newSet);
    }

    @Override
    public String printResult()
    {
        String result = "";
        Iterator it = this.DSLeave.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry)it.next();
            LabelDS key = (LabelDS) pair.getKey();
            DetectionSignsAnalysisType response = (DetectionSignsAnalysisType) pair.getValue();
            result += "DS after leaving line: " + key.getLineNumber() + "\n";
            for (Map.Entry<String, DetectionSignsLattice> entry : response.GetValue().entrySet())
            {
                result += entry.getKey() + "\n";
                for(Signs s : entry.getValue().getSigns()) {
                        result += "/" + s.name() + "\n";
                }
            }
        }
        return result;
    }
}


text:
.. highlight:: c++

.. default-domain:: cpp

.. _chapter-tutorial:

========
Tutorial
========

Ceres solves robustified non-linear bounds constrained least squares
problems of the form

.. math:: :label: ceresproblem

   \min_{\mathbf{x}} &\quad \frac{1}{2}\sum_{i} \rho_i\left(\left\|f_i\left(x_{i_1}, ... ,x_{i_k}\right)\right\|^2\right) \\
   \text{s.t.} &\quad l_j \le x_j \le u_j

Problems of this form comes up in a broad range of areas across
science and engineering - from `fitting curves`_ in statistics, to
constructing `3D models from photographs`_ in computer vision.

.. _fitting curves: http://en.wikipedia.org/wiki/Nonlinear_regression
.. _3D models from photographs: http://en.wikipedia.org/wiki/Bundle_adjustment

In this chapter we will learn how to solve :eq:`ceresproblem` using
Ceres Solver. Full working code for all the examples described in this
chapter and more can be found in the `examples
<https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/>`_
directory.

The expression
:math:`\rho_i\left(\left\|f_i\left(x_{i_1},...,x_{i_k}\right)\right\|^2\right)`
is known as a ``ResidualBlock``, where :math:`f_i(\cdot)` is a
:class:`CostFunction` that depends on the parameter blocks
:math:`\left[x_{i_1},... , x_{i_k}\right]`. In most optimization
problems small groups of scalars occur together. For example the three
components of a translation vector and the four components of the
quaternion that define the pose of a camera. We refer to such a group
of small scalars as a ``ParameterBlock``. Of course a
``ParameterBlock`` can just be a single parameter. :math:`l_j` and
:math:`u_j` are bounds on the parameter block :math:`x_j`.

:math:`\rho_i` is a :class:`LossFunction`. A :class:`LossFunction` is
a scalar function that is used to reduce the influence of outliers on
the solution of non-linear least squares problems.

As a special case, when :math:`\rho_i(x) = x`, i.e., the identity
function, and :math:`l_j = -\infty` and :math:`u_j = \infty` we get
the more familiar `non-linear least squares problem
<http://en.wikipedia.org/wiki/Non-linear_least_squares>`_.

.. math:: \frac{1}{2}\sum_{i} \left\|f_i\left(x_{i_1}, ... ,x_{i_k}\right)\right\|^2.
   :label: ceresproblem2

.. _section-hello-world:

Hello World!
============

To get started, consider the problem of finding the minimum of the
function

.. math:: \frac{1}{2}(10 -x)^2.

This is a trivial problem, whose minimum is located at :math:`x = 10`,
but it is a good place to start to illustrate the basics of solving a
problem with Ceres [#f1]_.

The first step is to write a functor that will evaluate this the
function :math:`f(x) = 10 - x`:

.. code-block:: c++

   struct CostFunctor {
      template <typename T>
      bool operator()(const T* const x, T* residual) const {
        residual[0] = T(10.0) - x[0];
        return true;
      }
   };

The important thing to note here is that ``operator()`` is a templated
method, which assumes that all its inputs and outputs are of some type
``T``. The use of templating here allows Ceres to call
``CostFunctor::operator<T>()``, with ``T=double`` when just the value
of the residual is needed, and with a special type ``T=Jet`` when the
Jacobians are needed. In :ref:`section-derivatives` we will discuss the
various ways of supplying derivatives to Ceres in more detail.

Once we have a way of computing the residual function, it is now time
to construct a non-linear least squares problem using it and have
Ceres solve it.

.. code-block:: c++

   int main(int argc, char** argv) {
     google::InitGoogleLogging(argv[0]);

     // The variable to solve for with its initial value.
     double initial_x = 5.0;
     double x = initial_x;

     // Build the problem.
     Problem problem;

     // Set up the only cost function (also known as residual). This uses
     // auto-differentiation to obtain the derivative (jacobian).
     CostFunction* cost_function =
         new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor);
     problem.AddResidualBlock(cost_function, NULL, &x);

     // Run the solver!
     Solver::Options options;
     options.linear_solver_type = ceres::DENSE_QR;
     options.minimizer_progress_to_stdout = true;
     Solver::Summary summary;
     Solve(options, &problem, &summary);

     std::cout << summary.BriefReport() << "\n";
     std::cout << "x : " << initial_x
               << " -> " << x << "\n";
     return 0;
   }

:class:`AutoDiffCostFunction` takes a ``CostFunctor`` as input,
automatically differentiates it and gives it a :class:`CostFunction`
interface.

Compiling and running `examples/helloworld.cc
<https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/helloworld.cc>`_
gives us

.. code-block:: bash

      0: f: 1.250000e+01 d: 0.00e+00 g: 5.00e+00 h: 0.00e+00 rho: 0.00e+00 mu: 1.00e+04 li:  0 it: 6.91e-06 tt: 1.91e-03
      1: f: 1.249750e-07 d: 1.25e+01 g: 5.00e-04 h: 5.00e+00 rho: 1.00e+00 mu: 3.00e+04 li:  1 it: 2.81e-05 tt: 1.99e-03
      2: f: 1.388518e-16 d: 1.25e-07 g: 1.67e-08 h: 5.00e-04 rho: 1.00e+00 mu: 9.00e+04 li:  1 it: 1.00e-05 tt: 2.01e-03
   Ceres Solver Report: Iterations: 2, Initial cost: 1.250000e+01, Final cost: 1.388518e-16, Termination: CONVERGENCE.
   x : 5 -> 10

Starting from a :math:`x=5`, the solver in two iterations goes to 10
[#f2]_. The careful reader will note that this is a linear problem and
one linear solve should be enough to get the optimal value.  The
default configuration of the solver is aimed at non-linear problems,
and for reasons of simplicity we did not change it in this example. It
is indeed possible to obtain the solution to this problem using Ceres
in one iteration. Also note that the solver did get very close to the
optimal function value of 0 in the very first iteration. We will
discuss these issues in greater detail when we talk about convergence
and parameter settings for Ceres.

.. rubric:: Footnotes

.. [#f1] `examples/helloworld.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/helloworld.cc>`_

.. [#f2] Actually the solver ran for three iterations, and it was
   by looking at the value returned by the linear solver in the third
   iteration, it observed that the update to the parameter block was too
   small and declared convergence. Ceres only prints out the display at
   the end of an iteration, and terminates as soon as it detects
   convergence, which is why you only see two iterations here and not
   three.

.. _section-derivatives:

Derivatives
===========

Ceres Solver like most optimization packages, depends on being able to
evaluate the value and the derivatives of each term in the objective
function at arbitrary parameter values. Doing so correctly and
efficiently is essential to getting good results.  Ceres Solver
provides a number of ways of doing so. You have already seen one of
them in action --
Automatic Differentiation in `examples/helloworld.cc
<https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/helloworld.cc>`_

We now consider the other two possibilities. Analytic and numeric
derivatives.

Numeric Derivatives
-------------------

In some cases, its not possible to define a templated cost functor,
for example when the evaluation of the residual involves a call to a
library function that you do not have control over.  In such a
situation, numerical differentiation can be used. The user defines a
functor which computes the residual value and construct a
:class:`NumericDiffCostFunction` using it. e.g., for :math:`f(x) = 10 - x`
the corresponding functor would be

.. code-block:: c++

  struct NumericDiffCostFunctor {
    bool operator()(const double* const x, double* residual) const {
      residual[0] = 10.0 - x[0];
      return true;
    }
  };

Which is added to the :class:`Problem` as:

.. code-block:: c++

  CostFunction* cost_function =
    new NumericDiffCostFunction<NumericDiffCostFunctor, ceres::CENTRAL, 1, 1, 1>(
        new NumericDiffCostFunctor)
  problem.AddResidualBlock(cost_function, NULL, &x);

Notice the parallel from when we were using automatic differentiation

.. code-block:: c++

  CostFunction* cost_function =
      new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor);
  problem.AddResidualBlock(cost_function, NULL, &x);

The construction looks almost identical to the one used for automatic
differentiation, except for an extra template parameter that indicates
the kind of finite differencing scheme to be used for computing the
numerical derivatives [#f3]_. For more details see the documentation
for :class:`NumericDiffCostFunction`.

**Generally speaking we recommend automatic differentiation instead of
numeric differentiation. The use of C++ templates makes automatic
differentiation efficient, whereas numeric differentiation is
expensive, prone to numeric errors, and leads to slower convergence.**

Analytic Derivatives
--------------------

In some cases, using automatic differentiation is not possible. For
example, it may be the case that it is more efficient to compute the
derivatives in closed form instead of relying on the chain rule used
by the automatic differentiation code.

In such cases, it is possible to supply your own residual and jacobian
computation code. To do this, define a subclass of
:class:`CostFunction` or :class:`SizedCostFunction` if you know the
sizes of the parameters and residuals at compile time. Here for
example is ``SimpleCostFunction`` that implements :math:`f(x) = 10 -
x`.

.. code-block:: c++

  class QuadraticCostFunction : public ceres::SizedCostFunction<1, 1> {
   public:
    virtual ~QuadraticCostFunction() {}
    virtual bool Evaluate(double const* const* parameters,
                          double* residuals,
                          double** jacobians) const {
      const double x = parameters[0][0];
      residuals[0] = 10 - x;

      // Compute the Jacobian if asked for.
      if (jacobians != NULL && jacobians[0] != NULL) {
        jacobians[0][0] = -1;
      }
      return true;
    }
  };

``SimpleCostFunction::Evaluate`` is provided with an input array of
``parameters``, an output array ``residuals`` for residuals and an
output array ``jacobians`` for Jacobians. The ``jacobians`` array is
optional, ``Evaluate`` is expected to check when it is non-null, and
if it is the case then fill it with the values of the derivative of
the residual function. In this case since the residual function is
linear, the Jacobian is constant [#f4]_ .

As can be seen from the above code fragments, implementing
:class:`CostFunction` objects is a bit tedious. We recommend that
unless you have a good reason to manage the jacobian computation
yourself, you use :class:`AutoDiffCostFunction` or
:class:`NumericDiffCostFunction` to construct your residual blocks.

More About Derivatives
----------------------

Computing derivatives is by far the most complicated part of using
Ceres, and depending on the circumstance the user may need more
sophisticated ways of computing derivatives. This section just
scratches the surface of how derivatives can be supplied to
Ceres. Once you are comfortable with using
:class:`NumericDiffCostFunction` and :class:`AutoDiffCostFunction` we
recommend taking a look at :class:`DynamicAutoDiffCostFunction`,
:class:`CostFunctionToFunctor`, :class:`NumericDiffFunctor` and
:class:`ConditionedCostFunction` for more advanced ways of
constructing and computing cost functions.

.. rubric:: Footnotes

.. [#f3] `examples/helloworld_numeric_diff.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/helloworld_numeric_diff.cc>`_.

.. [#f4] `examples/helloworld_analytic_diff.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/helloworld_analytic_diff.cc>`_.

.. _section-powell:

Powell's Function
=================

Consider now a slightly more complicated example -- the minimization
of Powell's function. Let :math:`x = \left[x_1, x_2, x_3, x_4 \right]`
and

.. math::

  \begin{align}
     f_1(x) &= x_1 + 10x_2 \\
     f_2(x) &= \sqrt{5}  (x_3 - x_4)\\
     f_3(x) &= (x_2 - 2x_3)^2\\
     f_4(x) &= \sqrt{10}  (x_1 - x_4)^2\\
       F(x) &= \left[f_1(x),\ f_2(x),\ f_3(x),\ f_4(x) \right]
  \end{align}

:math:`F(x)` is a function of four parameters, has four residuals
and we wish to find :math:`x` such that :math:`\frac{1}{2}\|F(x)\|^2`
is minimized.

Again, the first step is to define functors that evaluate of the terms
in the objective functor. Here is the code for evaluating
:math:`f_4(x_1, x_4)`:

.. code-block:: c++

 struct F4 {
   template <typename T>
   bool operator()(const T* const x1, const T* const x4, T* residual) const {
     residual[0] = T(sqrt(10.0)) * (x1[0] - x4[0]) * (x1[0] - x4[0]);
     return true;
   }
 };

Similarly, we can define classes ``F1``, ``F2`` and ``F4`` to evaluate
:math:`f_1(x_1, x_2)`, :math:`f_2(x_3, x_4)` and :math:`f_3(x_2, x_3)`
respectively. Using these, the problem can be constructed as follows:

.. code-block:: c++

  double x1 =  3.0; double x2 = -1.0; double x3 =  0.0; double x4 = 1.0;

  Problem problem;

  // Add residual terms to the problem using the using the autodiff
  // wrapper to get the derivatives automatically.
  problem.AddResidualBlock(
    new AutoDiffCostFunction<F1, 1, 1, 1>(new F1), NULL, &x1, &x2);
  problem.AddResidualBlock(
    new AutoDiffCostFunction<F2, 1, 1, 1>(new F2), NULL, &x3, &x4);
  problem.AddResidualBlock(
    new AutoDiffCostFunction<F3, 1, 1, 1>(new F3), NULL, &x2, &x3)
  problem.AddResidualBlock(
    new AutoDiffCostFunction<F4, 1, 1, 1>(new F4), NULL, &x1, &x4);

Note that each ``ResidualBlock`` only depends on the two parameters
that the corresponding residual object depends on and not on all four
parameters. Compiling and running `examples/powell.cc
<https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/powell.cc>`_
gives us:

.. code-block:: bash

 Initial x1 = 3, x2 = -1, x3 = 0, x4 = 1
    0: f: 1.075000e+02 d: 0.00e+00 g: 1.55e+02 h: 0.00e+00 rho: 0.00e+00 mu: 1.00e+04 li:  0 it: 0.00e+00 tt: 0.00e+00
    1: f: 5.036190e+00 d: 1.02e+02 g: 2.00e+01 h: 2.16e+00 rho: 9.53e-01 mu: 3.00e+04 li:  1 it: 0.00e+00 tt: 0.00e+00
    2: f: 3.148168e-01 d: 4.72e+00 g: 2.50e+00 h: 6.23e-01 rho: 9.37e-01 mu: 9.00e+04 li:  1 it: 0.00e+00 tt: 0.00e+00
    3: f: 1.967760e-02 d: 2.95e-01 g: 3.13e-01 h: 3.08e-01 rho: 9.37e-01 mu: 2.70e+05 li:  1 it: 0.00e+00 tt: 0.00e+00
    4: f: 1.229900e-03 d: 1.84e-02 g: 3.91e-02 h: 1.54e-01 rho: 9.37e-01 mu: 8.10e+05 li:  1 it: 0.00e+00 tt: 0.00e+00
    5: f: 7.687123e-05 d: 1.15e-03 g: 4.89e-03 h: 7.69e-02 rho: 9.37e-01 mu: 2.43e+06 li:  1 it: 0.00e+00 tt: 0.00e+00
    6: f: 4.804625e-06 d: 7.21e-05 g: 6.11e-04 h: 3.85e-02 rho: 9.37e-01 mu: 7.29e+06 li:  1 it: 0.00e+00 tt: 0.00e+00
    7: f: 3.003028e-07 d: 4.50e-06 g: 7.64e-05 h: 1.92e-02 rho: 9.37e-01 mu: 2.19e+07 li:  1 it: 0.00e+00 tt: 0.00e+00
    8: f: 1.877006e-08 d: 2.82e-07 g: 9.54e-06 h: 9.62e-03 rho: 9.37e-01 mu: 6.56e+07 li:  1 it: 0.00e+00 tt: 0.00e+00
    9: f: 1.173223e-09 d: 1.76e-08 g: 1.19e-06 h: 4.81e-03 rho: 9.37e-01 mu: 1.97e+08 li:  1 it: 0.00e+00 tt: 0.00e+00
   10: f: 7.333425e-11 d: 1.10e-09 g: 1.49e-07 h: 2.40e-03 rho: 9.37e-01 mu: 5.90e+08 li:  1 it: 0.00e+00 tt: 0.00e+00
   11: f: 4.584044e-12 d: 6.88e-11 g: 1.86e-08 h: 1.20e-03 rho: 9.37e-01 mu: 1.77e+09 li:  1 it: 0.00e+00 tt: 0.00e+00
 Ceres Solver Report: Iterations: 12, Initial cost: 1.075000e+02, Final cost: 4.584044e-12, Termination: CONVERGENCE.
 Final x1 = 0.00116741, x2 = -0.000116741, x3 = 0.000190535, x4 = 0.000190535

It is easy to see that the optimal solution to this problem is at
:math:`x_1=0, x_2=0, x_3=0, x_4=0` with an objective function value of
:math:`0`. In 10 iterations, Ceres finds a solution with an objective
function value of :math:`4\times 10^{-12}`.

.. rubric:: Footnotes

.. [#f5] `examples/powell.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/powell.cc>`_.

.. _section-fitting:

Curve Fitting
=============

The examples we have seen until now are simple optimization problems
with no data. The original purpose of least squares and non-linear
least squares analysis was fitting curves to data. It is only
appropriate that we now consider an example of such a problem
[#f6]_. It contains data generated by sampling the curve :math:`y =
e^{0.3x + 0.1}` and adding Gaussian noise with standard deviation
:math:`\sigma = 0.2`. Let us fit some data to the curve

.. math::  y = e^{mx + c}.

We begin by defining a templated object to evaluate the
residual. There will be a residual for each observation.

.. code-block:: c++

 struct ExponentialResidual {
   ExponentialResidual(double x, double y)
       : x_(x), y_(y) {}

   template <typename T>
   bool operator()(const T* const m, const T* const c, T* residual) const {
     residual[0] = T(y_) - exp(m[0] * T(x_) + c[0]);
     return true;
   }

  private:
   // Observations for a sample.
   const double x_;
   const double y_;
 };

Assuming the observations are in a :math:`2n` sized array called
``data`` the problem construction is a simple matter of creating a
:class:`CostFunction` for every observation.

.. code-block:: c++

 double m = 0.0;
 double c = 0.0;

 Problem problem;
 for (int i = 0; i < kNumObservations; ++i) {
   CostFunction* cost_function =
        new AutoDiffCostFunction<ExponentialResidual, 1, 1, 1>(
            new ExponentialResidual(data[2 * i], data[2 * i + 1]));
   problem.AddResidualBlock(cost_function, NULL, &m, &c);
 }

Compiling and running `examples/curve_fitting.cc
<https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/curve_fitting.cc>`_
gives us:

.. code-block:: bash

    0: f: 1.211734e+02 d: 0.00e+00 g: 3.61e+02 h: 0.00e+00 rho: 0.00e+00 mu: 1.00e+04 li:  0 it: 0.00e+00 tt: 0.00e+00
    1: f: 1.211734e+02 d:-2.21e+03 g: 3.61e+02 h: 7.52e-01 rho:-1.87e+01 mu: 5.00e+03 li:  1 it: 0.00e+00 tt: 0.00e+00
    2: f: 1.211734e+02 d:-2.21e+03 g: 3.61e+02 h: 7.51e-01 rho:-1.86e+01 mu: 1.25e+03 li:  1 it: 0.00e+00 tt: 0.00e+00
    3: f: 1.211734e+02 d:-2.19e+03 g: 3.61e+02 h: 7.48e-01 rho:-1.85e+01 mu: 1.56e+02 li:  1 it: 0.00e+00 tt: 0.00e+00
    4: f: 1.211734e+02 d:-2.02e+03 g: 3.61e+02 h: 7.22e-01 rho:-1.70e+01 mu: 9.77e+00 li:  1 it: 0.00e+00 tt: 0.00e+00
    5: f: 1.211734e+02 d:-7.34e+02 g: 3.61e+02 h: 5.78e-01 rho:-6.32e+00 mu: 3.05e-01 li:  1 it: 0.00e+00 tt: 0.00e+00
    6: f: 3.306595e+01 d: 8.81e+01 g: 4.10e+02 h: 3.18e-01 rho: 1.37e+00 mu: 9.16e-01 li:  1 it: 0.00e+00 tt: 0.00e+00
    7: f: 6.426770e+00 d: 2.66e+01 g: 1.81e+02 h: 1.29e-01 rho: 1.10e+00 mu: 2.75e+00 li:  1 it: 0.00e+00 tt: 0.00e+00
    8: f: 3.344546e+00 d: 3.08e+00 g: 5.51e+01 h: 3.05e-02 rho: 1.03e+00 mu: 8.24e+00 li:  1 it: 0.00e+00 tt: 0.00e+00
    9: f: 1.987485e+00 d: 1.36e+00 g: 2.33e+01 h: 8.87e-02 rho: 9.94e-01 mu: 2.47e+01 li:  1 it: 0.00e+00 tt: 0.00e+00
   10: f: 1.211585e+00 d: 7.76e-01 g: 8.22e+00 h: 1.05e-01 rho: 9.89e-01 mu: 7.42e+01 li:  1 it: 0.00e+00 tt: 0.00e+00
   11: f: 1.063265e+00 d: 1.48e-01 g: 1.44e+00 h: 6.06e-02 rho: 9.97e-01 mu: 2.22e+02 li:  1 it: 0.00e+00 tt: 0.00e+00
   12: f: 1.056795e+00 d: 6.47e-03 g: 1.18e-01 h: 1.47e-02 rho: 1.00e+00 mu: 6.67e+02 li:  1 it: 0.00e+00 tt: 0.00e+00
   13: f: 1.056751e+00 d: 4.39e-05 g: 3.79e-03 h: 1.28e-03 rho: 1.00e+00 mu: 2.00e+03 li:  1 it: 0.00e+00 tt: 0.00e+00
 Ceres Solver Report: Iterations: 13, Initial cost: 1.211734e+02, Final cost: 1.056751e+00, Termination: CONVERGENCE.
 Initial m: 0 c: 0
 Final   m: 0.291861 c: 0.131439

Starting from parameter values :math:`m = 0, c=0` with an initial
objective function value of :math:`121.173` Ceres finds a solution
:math:`m= 0.291861, c = 0.131439` with an objective function value of
:math:`1.05675`. These values are a a bit different than the
parameters of the original model :math:`m=0.3, c= 0.1`, but this is
expected. When reconstructing a curve from noisy data, we expect to
see such deviations. Indeed, if you were to evaluate the objective
function for :math:`m=0.3, c=0.1`, the fit is worse with an objective
function value of :math:`1.082425`.  The figure below illustrates the fit.

.. figure:: least_squares_fit.png
   :figwidth: 500px
   :height: 400px
   :align: center

   Least squares curve fitting.

.. rubric:: Footnotes

.. [#f6] `examples/curve_fitting.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/curve_fitting.cc>`_

Robust Curve Fitting
=====================

Now suppose the data we are given has some outliers, i.e., we have
some points that do not obey the noise model. If we were to use the
code above to fit such data, we would get a fit that looks as
below. Notice how the fitted curve deviates from the ground truth.

.. figure:: non_robust_least_squares_fit.png
   :figwidth: 500px
   :height: 400px
   :align: center

To deal with outliers, a standard technique is to use a
:class:`LossFunction`. Loss functions, reduce the influence of
residual blocks with high residuals, usually the ones corresponding to
outliers. To associate a loss function in a residual block, we change

.. code-block:: c++

   problem.AddResidualBlock(cost_function, NULL , &m, &c);

to

.. code-block:: c++

   problem.AddResidualBlock(cost_function, new CauchyLoss(0.5) , &m, &c);

:class:`CauchyLoss` is one of the loss functions that ships with Ceres
Solver. The argument :math:`0.5` specifies the scale of the loss
function. As a result, we get the fit below [#f7]_. Notice how the
fitted curve moves back closer to the ground truth curve.

.. figure:: robust_least_squares_fit.png
   :figwidth: 500px
   :height: 400px
   :align: center

   Using :class:`LossFunction` to reduce the effect of outliers on a
   least squares fit.

.. rubric:: Footnotes

.. [#f7] `examples/robust_curve_fitting.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/robust_curve_fitting.cc>`_

Bundle Adjustment
=================

One of the main reasons for writing Ceres was our need to solve large
scale bundle adjustment problems [HartleyZisserman]_, [Triggs]_.

Given a set of measured image feature locations and correspondences,
the goal of bundle adjustment is to find 3D point positions and camera
parameters that minimize the reprojection error. This optimization
problem is usually formulated as a non-linear least squares problem,
where the error is the squared :math:`L_2` norm of the difference between
the observed feature location and the projection of the corresponding
3D point on the image plane of the camera. Ceres has extensive support
for solving bundle adjustment problems.

Let us solve a problem from the `BAL
<http://grail.cs.washington.edu/projects/bal/>`_ dataset [#f8]_.

The first step as usual is to define a templated functor that computes
the reprojection error/residual. The structure of the functor is
similar to the ``ExponentialResidual``, in that there is an
instance of this object responsible for each image observation.

Each residual in a BAL problem depends on a three dimensional point
and a nine parameter camera. The nine parameters defining the camera
are: three for rotation as a Rodriques' axis-angle vector, three
for translation, one for focal length and two for radial distortion.
The details of this camera model can be found the `Bundler homepage
<http://phototour.cs.washington.edu/bundler/>`_ and the `BAL homepage
<http://grail.cs.washington.edu/projects/bal/>`_.

.. code-block:: c++

 struct SnavelyReprojectionError {
   SnavelyReprojectionError(double observed_x, double observed_y)
       : observed_x(observed_x), observed_y(observed_y) {}

   template <typename T>
   bool operator()(const T* const camera,
                   const T* const point,
                   T* residuals) const {
     // camera[0,1,2] are the angle-axis rotation.
     T p[3];
     ceres::AngleAxisRotatePoint(camera, point, p);
     // camera[3,4,5] are the translation.
     p[0] += camera[3]; p[1] += camera[4]; p[2] += camera[5];

     // Compute the center of distortion. The sign change comes from
     // the camera model that Noah Snavely's Bundler assumes, whereby
     // the camera coordinate system has a negative z axis.
     T xp = - p[0] / p[2];
     T yp = - p[1] / p[2];

     // Apply second and fourth order radial distortion.
     const T& l1 = camera[7];
     const T& l2 = camera[8];
     T r2 = xp*xp + yp*yp;
     T distortion = T(1.0) + r2  * (l1 + l2  * r2);

     // Compute final projected point position.
     const T& focal = camera[6];
     T predicted_x = focal * distortion * xp;
     T predicted_y = focal * distortion * yp;

     // The error is the difference between the predicted and observed position.
     residuals[0] = predicted_x - T(observed_x);
     residuals[1] = predicted_y - T(observed_y);
     return true;
   }

    // Factory to hide the construction of the CostFunction object from
    // the client code.
    static ceres::CostFunction* Create(const double observed_x,
                                       const double observed_y) {
      return (new ceres::AutoDiffCostFunction<SnavelyReprojectionError, 2, 9, 3>(
                  new SnavelyReprojectionError(observed_x, observed_y)));
    }

   double observed_x;
   double observed_y;
 };

Note that unlike the examples before, this is a non-trivial function
and computing its analytic Jacobian is a bit of a pain. Automatic
differentiation makes life much simpler. The function
:func:`AngleAxisRotatePoint` and other functions for manipulating
rotations can be found in ``include/ceres/rotation.h``.

Given this functor, the bundle adjustment problem can be constructed
as follows:

.. code-block:: c++

 ceres::Problem problem;
 for (int i = 0; i < bal_problem.num_observations(); ++i) {
   ceres::CostFunction* cost_function =
       SnavelyReprojectionError::Create(
            bal_problem.observations()[2 * i + 0],
            bal_problem.observations()[2 * i + 1]);
   problem.AddResidualBlock(cost_function,
                            NULL /* squared loss */,
                            bal_problem.mutable_camera_for_observation(i),
                            bal_problem.mutable_point_for_observation(i));
 }

Notice that the problem construction for bundle adjustment is very
similar to the curve fitting example -- one term is added to the
objective function per observation.

Since this large sparse problem (well large for ``DENSE_QR`` anyways),
one way to solve this problem is to set
:member:`Solver::Options::linear_solver_type` to
``SPARSE_NORMAL_CHOLESKY`` and call :member:`Solve`. And while this is
a reasonable thing to do, bundle adjustment problems have a special
sparsity structure that can be exploited to solve them much more
efficiently. Ceres provides three specialized solvers (collectively
known as Schur-based solvers) for this task. The example code uses the
simplest of them ``DENSE_SCHUR``.

.. code-block:: c++

 ceres::Solver::Options options;
 options.linear_solver_type = ceres::DENSE_SCHUR;
 options.minimizer_progress_to_stdout = true;
 ceres::Solver::Summary summary;
 ceres::Solve(options, &problem, &summary);
 std::cout << summary.FullReport() << "\n";

For a more sophisticated bundle adjustment example which demonstrates
the use of Ceres' more advanced features including its various linear
solvers, robust loss functions and local parameterizations see
`examples/bundle_adjuster.cc
<https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/bundle_adjuster.cc>`_

.. rubric:: Footnotes

.. [#f8] `examples/simple_bundle_adjuster.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/simple_bundle_adjuster.cc>`_

Other Examples
==============

Besides the examples in this chapter, the  `example
<https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/>`_
directory contains a number of other examples:

#. `bundle_adjuster.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/bundle_adjuster.cc>`_
   shows how to use the various features of Ceres to solve bundle
   adjustment problems.

#. `circle_fit.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/circle_fit.cc>`_
   shows how to fit data to a circle.

#. `denoising.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/denoising.cc>`_
   implements image denoising using the `Fields of Experts
   <http://www.gris.informatik.tu-darmstadt.de/~sroth/research/foe/index.html>`_
   model.

#. `nist.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/nist.cc>`_
   implements and attempts to solves the `NIST
   <http://www.itl.nist.gov/div898/strd/nls/nls_main.shtm>`_
   non-linear regression problems.

#. `libmv_bundle_adjuster.cc
   <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/libmv_bundle_adjuster.cc>`_
   is the bundle adjustment algorithm used by `Blender <www.blender.org>`_/libmv.

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Umulmrum\Holiday\Provider\Weekday;

use Umulmrum\Holiday\Constant\HolidayType;
use Umulmrum\Holiday\Constant\Weekday;

class Saturdays extends Weekdays
{
    public function __construct(int $additionalType = HolidayType::OTHER)
    {
        parent::__construct(Weekday::SATURDAY, $additionalType);
    }
}


text:
<video autobuffer autoplay loop>
	<source src="/video/patronsocialclub.m4v">
	<source src="/video/patronsocialclub.ogg">
	<object type="video/mp4" data="/video/patronsocialclub.m4v">
		<param name="src" value="/video/patronsocialclub.m4v">
		<param name="autoplay" value="true">
		<param name="autoStart" value="1">
		<param name="loop" value="true">

Download this video file.

	</object>
</video>


text:
import os
import sys
import time
import mock

def test_XmlRpcHandler():
    from rosgraph.xmlrpc import XmlRpcHandler
    # tripwire
    h = XmlRpcHandler()
    # noop
    h._ready('http://localhost:1234')

def test_XmlRpcNode():
    from rosgraph.xmlrpc import XmlRpcNode, XmlRpcHandler
    # not a very comprehensive test (yet)
    #port, handler
    tests = [
        (None, None, None),
        (8080, None, 8080),
        ('8080', None, 8080),
        (u'8080', None, 8080),
      ]

    for port, handler,true_port in tests:
        n = XmlRpcNode(port, handler)
        assert true_port == n.port
        assert handler == n.handler
        assert None == n.uri
        assert None == n.server
        n.set_uri('http://fake:1234')
        assert 'http://fake:1234' == n.uri

        n.start()
        start = time.time()
        while not n.uri and time.time() - start < 5.:
            time.sleep(0.00001) #poll for XMLRPC init

        assert n.uri
        n.shutdown('test case')

    # get coverage on run init
    n = XmlRpcNode(0, XmlRpcHandler())
    n._run_init()
    n.shutdown('test case')

    # mock in server in order to play with _run()
    n.server = mock.Mock()
    n.is_shutdown = False
    n._run_init = mock.Mock()
    n.server.serve_forever.side_effect = IOError(1, 'boom')
    n._run()


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black">

    <com.github.florent37.wearkit.view.Pager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <com.github.florent37.wearkit.view.StatusBarView
        android:id="@+id/statusBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:backEnabled="true" />

    <com.github.florent37.wearkit.view.ContextualMenu
        android:id="@+id/menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>


text:
const {shiphold} = require('../../dist/bundle');

export default ({test}) => {

    test('should create a service when a definition argument is passed', t => {
        const registry = shiphold({});

        const service = registry.service({table: 'users'});

        t.eq(typeof service.select, 'function', 'select method should be defined');
        t.eq(typeof service.insert, 'function', 'insert method should be defined');
        t.eq(typeof service.delete, 'function', 'delete method should be defined');
        t.eq(typeof service.update, 'function', 'update method should be defined');
        t.eq(typeof service.if, 'function', 'if method should be defined');
    });

    test('services should be singletons', t => {
        const registry = shiphold({});
        const service = registry.service({name: 'foo', table: 'users'});
        t.eq(service, registry.service('foo'), 'should refer to the same reference');
    });

    test('should pass default value', t => {
        const registry = shiphold({});
        const service = registry.service({table: 'users'});
        t.eq(service.definition.primaryKey, 'id', 'default primaryKey should be "id"');
        t.eq(service.definition.name, 'Users', 'default name should be a camel case version of the table name');
    });

    test('registry should be iterable', t => {
        const registry = shiphold({});

        const service = registry.service({
            table: 'users',
            name: 'foo'
        });

        t.eq(typeof registry[Symbol.iterator], 'function');
        const items = [...registry];
        t.eq(items, [['foo', service]]);
    });
}


text:
package hudson.tasks.junit;

import hudson.model.AbstractBuild;
import hudson.model.AbstractModelObject;
import hudson.model.Api;
import hudson.tasks.test.AbstractTestResultAction;
import org.kohsuke.stapler.export.ExportedBean;

import java.io.Serializable;
import java.util.List;

/**
 * Stub of base class for all test result objects. The real implementation of
 * the TestObject is in hudson.tasks.test.TestObject. This class simply defines
 * abstract methods so that legacy code will continue to compile.
 *
 * @deprecated Use {@link hudson.tasks.test.TestObject} instead.
 *
 * @author Kohsuke Kawaguchi
 */
@ExportedBean
public abstract class TestObject extends AbstractModelObject implements Serializable {

    public abstract AbstractBuild<?, ?> getOwner();

    public abstract TestObject getParent();

    public abstract String getId();

    /**
     * Returns url relative to TestResult
     */
    public abstract String getUrl();

    public abstract TestResult getTestResult();

    public abstract AbstractTestResultAction getTestResultAction();

    public abstract List<TestAction> getTestActions();

    public abstract <T> T getTestAction(Class<T> klazz);

    /**
     * Gets the counter part of this {@link TestObject} in the previous run.
     *
     * @return null if no such counter part exists.
     */
    public abstract TestObject getPreviousResult();

    public abstract TestObject getResultInBuild(AbstractBuild<?, ?> build);

    /**
     * Time took to run this test. In seconds.
     */
    public abstract float getDuration();

    /**
     * Returns the string representation of the {@link #getDuration()}, in a
     * human readable format.
     */
    public abstract String getDurationString();

    public abstract String getDescription();

    public abstract void setDescription(String description);

    /**
     * Exposes this object through the remote API.
     */
    public abstract Api getApi();

    /**
     * Gets the name of this object.
     */
    public abstract String getName();

    /**
     * Gets the version of {@link #getName()} that's URL-safe.
     */
    public abstract String getSafeName();

    public abstract String getSearchUrl();

    /**
     * Gets the total number of passed tests.
     */
    public abstract int getPassCount();

    /**
     * Gets the total number of failed tests.
     */
    public abstract int getFailCount();

    /**
     * Gets the total number of skipped tests.
     */
    public abstract int getSkipCount();

    /**
     * Gets the total number of tests.
     */
    public abstract int getTotalCount();

    public abstract History getHistory();
//    public abstract Object getDynamic(String token, StaplerRequest req,
//			StaplerResponse rsp);
//
//    public abstract  HttpResponse doSubmitDescription(
//			@QueryParameter String description) throws IOException,
//			ServletException;
}


text:
describe RuboCop::Cop::Style::NumericLiterals, :config do
  subject(:cop) { described_class.new(config) }
  let(:cop_config) { { 'MinDigits' => 5 } }

  it 'registers an offense for a long undelimited integer' do
    inspect_source(cop, 'a = 12345')
    expect(cop.offenses.size).to eq(1)
    expect(cop.config_to_allow_offenses).to eq('MinDigits' => 6)
  end

  it 'registers an offense for a float with a long undelimited integer part' do
    inspect_source(cop, 'a = 123456.789')
    expect(cop.offenses.size).to eq(1)
    expect(cop.config_to_allow_offenses).to eq('MinDigits' => 7)
  end

  it 'accepts integers with less than three places at the end' do
    inspect_source(cop, ['a = 123_456_789_00',
                         'b = 819_2'])
    expect(cop.offenses).to be_empty
  end

  it 'registers an offense for an integer with misplaced underscore' do
    inspect_source(cop, ['a = 123_456_78_90_00',
                         'b = 1_8192'])
    expect(cop.offenses.size).to eq(2)
    expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
  end

  it 'accepts long numbers with underscore' do
    inspect_source(cop, ['a = 123_456',
                         'b = 123_456.55'])
    expect(cop.messages).to be_empty
  end

  it 'accepts a short integer without underscore' do
    inspect_source(cop, 'a = 123')
    expect(cop.messages).to be_empty
  end

  it 'does not count a leading minus sign as a digit' do
    inspect_source(cop, 'a = -1230')
    expect(cop.messages).to be_empty
  end

  it 'accepts short numbers without underscore' do
    inspect_source(cop, ['a = 123',
                         'b = 123.456'])
    expect(cop.messages).to be_empty
  end

  it 'ignores non-decimal literals' do
    inspect_source(cop, ['a = 0b1010101010101',
                         'b = 01717171717171',
                         'c = 0xab11111111bb'])
    expect(cop.offenses).to be_empty
  end

  it 'autocorrects a long integer offense' do
    corrected = autocorrect_source(cop, ['a = 123456'])
    expect(corrected).to eq 'a = 123_456'
  end

  it 'autocorrects an integer with misplaced underscore' do
    corrected = autocorrect_source(cop, ['a = 123_456_78_90_00'])
    expect(corrected).to eq 'a = 123_456_789_000'
  end

  it 'autocorrects negative numbers' do
    corrected = autocorrect_source(cop, ['a = -123456'])
    expect(corrected).to eq 'a = -123_456'
  end

  it 'autocorrects floating-point numbers' do
    corrected = autocorrect_source(cop, ['a = 123456.78'])
    expect(corrected).to eq 'a = 123_456.78'
  end

  it 'autocorrects negative floating-point numbers' do
    corrected = autocorrect_source(cop, ['a = -123456.78'])
    expect(corrected).to eq 'a = -123_456.78'
  end

  context 'strict' do
    let(:cop_config) do
      {
        'MinDigits' => 5,
        'Strict' => true
      }
    end

    it 'registers an offense for an integer with misplaced underscore' do
      inspect_source(cop, ['a = 123_456_78_90_00',
                           'b = 81_92'])
      expect(cop.offenses.size).to eq(2)
      expect(cop.config_to_allow_offenses).to eq('Enabled' => false)
    end
  end
end


text:
package org.apache.camel.reifier;

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

import org.apache.camel.ExchangePattern;
import org.apache.camel.Expression;
import org.apache.camel.NoSuchLanguageException;
import org.apache.camel.Processor;
import org.apache.camel.Route;
import org.apache.camel.builder.ExpressionBuilder;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.model.ToDynamicDefinition;
import org.apache.camel.processor.SendDynamicProcessor;
import org.apache.camel.spi.Language;
import org.apache.camel.util.Pair;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.URISupport;

public class ToDynamicReifier<T extends ToDynamicDefinition> extends ProcessorReifier<T> {

    public ToDynamicReifier(Route route, ProcessorDefinition<?> definition) {
        super(route, (T) definition);
    }

    @Override
    public Processor createProcessor() throws Exception {
        String uri;
        Expression exp;
        if (definition.getEndpointProducerBuilder() != null) {
            uri = definition.getEndpointProducerBuilder().getUri();
            exp = definition.getEndpointProducerBuilder().expr(camelContext);
        } else {
            uri = StringHelper.notEmpty(definition.getUri(), "uri", this);
            exp = createExpression(uri);
        }

        SendDynamicProcessor processor = new SendDynamicProcessor(uri, exp);
        processor.setCamelContext(camelContext);
        processor.setPattern(parse(ExchangePattern.class, definition.getPattern()));
        if (definition.getCacheSize() != null) {
            processor.setCacheSize(parseInt(definition.getCacheSize()));
        }
        if (definition.getIgnoreInvalidEndpoint() != null) {
            processor.setIgnoreInvalidEndpoint(parseBoolean(definition.getIgnoreInvalidEndpoint(), false));
        }
        if (definition.getAllowOptimisedComponents() != null) {
            processor.setAllowOptimisedComponents(parseBoolean(definition.getAllowOptimisedComponents(), true));
        }
        if (definition.getAutoStartComponents() != null) {
            processor.setAutoStartupComponents(parseBoolean(definition.getAutoStartComponents(), true));
        }
        return processor;
    }

    protected Expression createExpression(String uri) {
        List<Expression> list = new ArrayList<>();

        // make sure to parse property placeholders
        uri = camelContext.resolvePropertyPlaceholders(uri);

        String[] parts = safeSplitRaw(uri);
        for (String part : parts) {
            // the part may have optional language to use, so you can mix
            // languages
            String value = StringHelper.after(part, "language:");
            if (value != null) {
                String before = StringHelper.before(value, ":");
                String after = StringHelper.after(value, ":");
                if (before != null && after != null) {
                    // maybe its a language, must have language: as prefix
                    try {
                        Language partLanguage = camelContext.resolveLanguage(before);
                        if (partLanguage != null) {
                            Expression exp = partLanguage.createExpression(after);
                            list.add(exp);
                            continue;
                        }
                    } catch (NoSuchLanguageException e) {
                        // ignore
                    }
                }
            }

            // fallback and use simple language
            Language lan = camelContext.resolveLanguage("simple");
            Expression exp = lan.createExpression(part);
            list.add(exp);
        }

        Expression exp;
        if (list.size() == 1) {
            exp = list.get(0);
        } else {
            exp = ExpressionBuilder.concatExpression(list);
        }

        return exp;
    }

    // Utilities
    // -------------------------------------------------------------------------

    /**
     * We need to split the string safely for each + sign, but avoid splitting within RAW(...).
     */
    private static String[] safeSplitRaw(String s) {
        List<String> list = new ArrayList<>();

        if (!s.contains("+")) {
            // no plus sign so there is only one part, so no need to split
            list.add(s);
        } else {
            // there is a plus sign so we need to split in a safe manner
            List<Pair<Integer>> rawPairs = URISupport.scanRaw(s);
            StringBuilder sb = new StringBuilder();
            char[] chars = s.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                char ch = chars[i];
                if (ch != '+' || URISupport.isRaw(i, rawPairs)) {
                    sb.append(ch);
                } else {
                    list.add(sb.toString());
                    sb.setLength(0);
                }
            }
            // any leftover?
            if (sb.length() > 0) {
                list.add(sb.toString());
                sb.setLength(0);
            }
        }

        return list.toArray(new String[list.size()]);
    }

}


text: luajit main.lua


text:
class ::Chef::Recipe
  include ::Opscode::ChefClient::Helpers
end

# libraries/helpers.rb method to DRY directory creation resources
client_bin = find_chef_client
log "Found chef-client in #{client_bin}"
node.set["chef_client"]["bin"] = client_bin
create_directories

log "You specified service style 'bsd'. You will need to set up your rc.local file."
log "Hint: chef-client -i #{node["chef_client"]["client_interval"]} -s #{node["chef_client"]["client_splay"]}"


text:
package io.pravega.connectors.flink.table.catalog.pravega.util;

import io.pravega.schemaregistry.contract.data.SchemaInfo;
import io.pravega.schemaregistry.contract.data.SerializationFormat;
import io.pravega.schemaregistry.serializer.avro.schemas.AvroSchema;
import io.pravega.schemaregistry.serializer.json.schemas.JSONSchema;
import org.apache.avro.Schema;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.flink.annotation.Internal;
import org.apache.flink.formats.avro.typeutils.AvroSchemaConverter;
import org.apache.flink.formats.json.JsonRowSchemaConverter;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
import org.apache.flink.table.api.TableSchema;
import org.apache.flink.table.catalog.ResolvedSchema;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.utils.DataTypeUtils;
import org.apache.flink.table.types.utils.TypeConversions;

import java.util.List;

@Internal
public class PravegaSchemaUtils {

    private PravegaSchemaUtils() {
        // private
    }

    public static ResolvedSchema schemaInfoToResolvedSchema(SchemaInfo schemaInfo) {

        SerializationFormat format = schemaInfo.getSerializationFormat();
        String schemaString;
        DataType dataType;

        switch (format) {
            case Json:
                JSONSchema jsonSchema = JSONSchema.from(schemaInfo);
                schemaString = jsonSchema.getSchemaString();
                dataType = TypeConversions.fromLegacyInfoToDataType(JsonRowSchemaConverter.convert(schemaString));
                break;
            case Avro:
                AvroSchema avroSchema = AvroSchema.from(schemaInfo);

                schemaString = avroSchema.getSchema().toString();
                dataType = TypeConversions.fromLegacyInfoToDataType(AvroSchemaConverter.convertToTypeInfo(schemaString));
                break;

            default:
                throw new NotImplementedException("Not supporting serialization format");
        }

        return DataTypeUtils.expandCompositeTypeToSchema(dataType);
    }

    public static SchemaInfo tableSchemaToSchemaInfo(TableSchema tableSchema, SerializationFormat serializationFormat) {
        switch (serializationFormat) {
            case Avro:
                Schema schema = AvroSchemaConverter.convertToSchema(tableSchema.toRowDataType().getLogicalType());
                AvroSchema avroSchema = AvroSchema.of(schema);
                return avroSchema.getSchemaInfo();
            case Json:
                LogicalType logicalType = tableSchema.toRowDataType().getLogicalType();
                String schemaString = convertToJsonSchemaString(logicalType);
                JSONSchema<JsonNode> jsonSchema = JSONSchema.of("", schemaString, JsonNode.class);
                return jsonSchema.getSchemaInfo();
            default:
                throw new NotImplementedException("Not supporting serialization format");
        }
    }

    /**
     * Converts Flink SQL {@link LogicalType} (can be nested) into a Json Schema String.
     * <p>
     * @param logicalType logical type
     * @return String matching this logical type.
     */
    public static String convertToJsonSchemaString(LogicalType logicalType) {
        StringBuilder sb = new StringBuilder();
        switch (logicalType.getTypeRoot()) {
            case NULL:
                sb.append("null");
                break;
            case BOOLEAN:
                sb.append("boolean");
                break;
            case CHAR:
            case VARCHAR:
                sb.append("string");
                break;
            case BINARY:
            case VARBINARY:
                sb.append("string").append("\", \"").append("contentEncoding")
                        .append("\": \"").append("base64");
                break;
            case DECIMAL:
            case TINYINT:
            case SMALLINT:
            case INTEGER:
            case BIGINT:
            case FLOAT:
            case DOUBLE:
            case INTERVAL_DAY_TIME:
            case INTERVAL_YEAR_MONTH:
                sb.append("number");
                break;
            case DATE:
                sb.append("string").append("\", \"").append("format")
                        .append("\": \"").append("date");
                break;
            case TIME_WITHOUT_TIME_ZONE:
                sb.append("string").append("\", \"").append("format")
                        .append("\": \"").append("time");
                break;
            case TIMESTAMP_WITHOUT_TIME_ZONE:
            case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
                sb.append("string").append("\", \"").append("format")
                        .append("\": \"").append("date-time");
                break;
            case ARRAY:
                sb.append("array");
                break;
            case MULTISET:
            case MAP:
                sb.append("object");
                break;
            case ROW:
                RowType rowType = (RowType) logicalType;
                List<String> fieldNames = rowType.getFieldNames();
                sb.append("{").append("\"title\": ").append("\"Json Schema\", ").
                        append("\"type\": ").append("\"object\", ").
                        append("\"properties\": { ");
                for (int i = 0; i < rowType.getFieldCount(); i++) {
                    String fieldName = fieldNames.get(i);
                    String fieldType = convertToJsonSchemaString(rowType.getTypeAt(i));
                    sb.append("\"").append(fieldName).append("\": {").
                            append("\"type\": \"").append(fieldType).append("\"},");
                }
                sb.deleteCharAt(sb.length() - 1).append("}}");
                break;
            case RAW:
            default:
                throw new UnsupportedOperationException("Unsupported type: " + logicalType);
        }
        return sb.toString();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lepista praevillosa Murrill

### Remarks
null


text:
package com.intellij.tasks.trello.model;

import com.intellij.openapi.util.NlsSafe;
import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.util.xmlb.annotations.Tag;
import com.intellij.util.xmlb.annotations.Transient;
import org.jetbrains.annotations.NotNull;

/**
 * This is a stub definition intended to be used with Google GSON. Its fields are initialized reflectively.
 */
@SuppressWarnings("UnusedDeclaration")
@Tag("TrelloList")
public class TrelloList extends TrelloModel {

  public static final String REQUIRED_FIELDS = "closed,name,idBoard";

  private boolean closed;
  private String idBoard;
  @NotNull
  private String name = "";
  /**
   * This field is not part of REST responses. It will be set explicitly to show in UI, that
   * selected list doesn't belong to specified board anymore.
   *
   * @see com.intellij.tasks.trello.TrelloRepositoryEditor
   */
  private boolean myMoved;

  /**
   * Serialization constructor
   */
  @SuppressWarnings("UnusedDeclaration")
  public TrelloList() {
  }

  @Override
  public String toString() {
    return String.format("TrelloList(id='%s' name='%s')", getId(), getName());
  }

  public boolean isClosed() {
    return closed;
  }

  @NotNull
  public String getIdBoard() {
    return idBoard;
  }

  @NotNull
  @Attribute("name")
  @Override
  public @NlsSafe String getName() {
    return name;
  }

  @Override
  public void setName(@NotNull String name) {
    this.name = name;
  }

  @Transient
  public boolean isMoved() {
    return myMoved;
  }

  public void setMoved(boolean moved) {
    this.myMoved = moved;
  }
}


text:
"""Elements for Figure 2B from the PySB publication"""

from __future__ import print_function
from pysb import *
from pysb.macros import *
from pysb.bng import generate_equations

Model()

Monomer('Bax', ['s1', 's2'])
Initial(Bax(s1=None, s2=None), Parameter('Bax_0', 1))

ktable = [[1, 1]] * 5

# This is the code shown for "Example Macro Call" (not printed here)
assemble_pore_sequential(Bax, 's1', 's2', 6, ktable)

generate_equations(model)

num_rules = len(model.rules)
num_odes = len(model.odes)

print("BNGL Rules")
print("==========")
print(num_rules, "rules")
print()
print("ODEs")
print("====")
print(num_odes, "ODEs")

def test_fig2c():
    assert num_rules == 5, "number of rules not as expected"
    assert num_odes == 6, "number of odes not as expected"


text:
package org.spanna.component.messaging;

/**
 * Represents the different directions a component channel may go.
 */
public enum ComponentChannelDirection {

    /**
     * The component channel is being sent to the server from a client.
     */
    INCOMING,

    /**
     * The component channel is being sent to a client from the server.
     */
    OUTGOING
}


text:
Discord: https://discord.gg/xP2s6EY8rd

🚧 WORK IN PROGRESS 🚧

Note: this project is still in quite early stages. Regardless, I've been using
this as a daily driver for over a year now. This is also my first "real" Rust
project, which brings with it the usual caveats. Luckily refactoring Rust code
is a fairly pleasant experience.

If you're not ready to get your hands dirty with Rust code, I would suggest
trying out other alternatives for now.

### Quick start

- Install the Rust toolchain using [`rustup`](https://rustup.rs/)
- Run `./start-backend.sh`
- In a separate terminal, run `./start-frontend.sh`
- Navigate to `http://localhost:8080`

You should now have a demo/dummy homectl environment running.

To control your home automation systems, you need to edit the generated
configuration file in `/Settings.toml`. See below sections for
configuration instructions and examples.

## Description

This project aims to unify home automation (HA) systems from different
brands, and does so by assuming complete control over the individual systems.
It brings some features that I felt are missing from consumer HA systems,
and also other similar solutions to homectl:

- A common interface for configuring everything in one place (plaintext config file for now).

  - (Hopefully) no more figuring out obscure schedule/rule/condition/action
    configuration that vary per HA supplier. (Instead you have homectl's
    obscure configuration file format for now, but this will be improved upon
    later! :-))

- Allow complete control of actions performed when sensors/buttons are triggered.

  - Because homectl only reads sensor values from HA systems, we are not
    limited by what actions can be programmed into the individual HA system
    controllers.

  - For example, you can put your computer to sleep/wake when you turn off/on
    the lights to your office.

  - Or you could start a robot vacuum when leaving your home between certain
    times of the day.

  - You can also control other manufacturers devices than the one that made the
    light switch you pressed

- Don't trust that the HA systems always do what you want

  - Some HA systems are not as reliable as you would hope, and may for example
    miss a command that you send them.

  - Or a device might simply forget its state due to an accidental power cycle.

  - Due to this, homectl will keep track of the expected state for each device,
    and actively poll devices for their current state, automatically correcting
    any incorrect state it might find.

- An advanced scenes system allow controlling a large amount of devices to preset states.

  - Because homectl keeps track of a device's active scene, we can perform
    certain actions only when a device is in a certain scene. For example, we
    can bind a light switch to multiple scenes and cycle between the scenes.

  - Scenes may "link" state from other devices: "go look up what the state of
    this device is and copy the state from there".

  - These devices can be "virtual" devices, such as a device that returns the
    approximate color of the sky.

  - Combine these facts and you can e.g. have your lights smoothly follow a
    circadian rhythm. These transitions will be so smooth that you won't
    notice them. Every time homectl polls your lights their expected state is
    calculated and compared against the actual state. If the difference is
    large enough (still imperceptibly small), then homectl will update the
    lights to match the expected state.

## Setup

### Environment variables (optional):

- `DATABASE_URL`: Used by the backend to connect to a PostgreSQL database. If
  not provided, functionalities requiring a database connection will be
  disabled.

  For example: `DATABASE_URL=postgres://user:password@localhost/homectl`

- `WS_ENDPOINT`: Read at compile time to decide what WebSocket endpoint the
  frontend attempts connecting to.

  Defaults to `ws://localhost:8080/ws`.

### Database setup (optional)

- Install PostgreSQL.
- Set `DATABASE_URL` according to above instructions.
- Run migrations:
  - `cargo install sqlx-cli`
  - `cd backend`
  - `sqlx database create`
  - `sqlx migrate run`

## Sample configs for supported integrations:

You can refer to the [sample config](/Settings.toml.example) for an
example on how to put these concepts together.

### Tuya

```
# Start by adding your devices to the Tuya Smart app.

[integrations.tuya]
plugin = "tuya"

[integrations.tuya.devices]
# Find the device_id and local_key of your devices via https://iot.tuya.com.
# Create an account, create a "Cloud Project" (Industry: Smart Home), link
# your Tuya Smart app under the project's Devices tab and you should find your
# device_id:s here. For each device, go to API Explorer call the Get Device
# Information API with your device_id to retreive the device's local_key.

# TODO: how to find out the field ID numbers? I had to fiddle around with
# https://github.com/codetheweb/tuyapi, and log the results of device.get()

20_character_device_id_here = { name = "Lower bathroom spot 1", ip = "<Local IP of Tuya device>", local_key = "0123456789abcdef", power_on_field = "20", brightness_field = "22", color_temp_field = "23" }
```

### Hue

```
# Start by adding your devices to the Hue app.

[integrations.hue]
plugin = "hue"
addr = "<Local IP of Hue bridge>"
poll_rate_lights = 10000
poll_rate_sensors = 100

# Generated by pressing link button on Hue bridge and calling
# $ curl -X POST <Local IP of hue bridge>/api -d '{"devicetype":"homectl#homectl"}'
username = "1028d66426293e821ecfd9ef1a0731df"
```

### Lifx

```
# Start by adding your devices to the Lifx app. The devices will be auto
# discovered via UDP broadcasts (make sure your router allows this).

[integrations.lifx]
plugin = "lifx"
network_interface = "enp0s31f6"
```

### Neato

```
[integrations.neato]
plugin = "neato"
email = "example@gmail.com"
password = "your-password-here"
cleaning_days = ["Mon", "Wed", "Fri"]
cleaning_time_start = "08:00"
cleaning_time_end = "19:00"

# Set to true for debugging
dummy = false

# Example routine that starts your Neato robot(s)
[routines.leave_home]
name = "Leave home"
rules = [
  { integration_id = "hue1", name = "Entryway switch", state = { off = true } }
]
actions = [
  { action = "IntegrationAction", integration_id = "neato", payload = "clean_house" },
]
```

### Wake on LAN

```
# Wake up your PC:s by MAC address, and optionally put them to sleep!
# Make sure you've set up Wake on LAN on your PC.
# (optional) Set up sleep on lan: https://github.com/SR-G/sleep-on-lan
[integrations.wol]
plugin = "wake_on_lan"
machines = [
  { id = "office_pc", mac = "DE:AD:BE:EF:12:34", sleep_on_lan = "http://192.168.1.123:8009/sleep" }
]

# Example of a scene that turns on PC via WOL
[scenes.office]
name = "Office devices"

  [scenes.office.devices.wol]
  office_pc = { power = true }
```

## Configuration tips / "recipes"

### Group lights to control multiple lights at once:

```
[groups.entryway]
name = "Entryway"
devices = [
  { integration_id = "hue", name = "Entryway spot 1" },
  { integration_id = "hue", name = "Entryway spot 2" },
  { integration_id = "lifx", name = "Entryway table lamp" },
]
```

### Combine groups into larger groups:

```
[groups.downstairs]
name = "Downstairs"
groups = [
  { group_id = "entryway" },
  { group_id = "kitchen" },
  { group_id = "office" },
]
```

I would suggest creating at least an "All" group containing all your devices.

### Create scenes for setting lights to preset states:

```
[scenes.normal_downstairs]
name = "Normal (downstairs only)"

  # Add as many groups as you want
  [scenes.normal_downstairs.groups]
  downstairs = { power = true, color = { hue = 42, saturation = 1.0, value = 1.0 }}
  outdoor = { power = true, color = { red = 255, green = 255, blue = 255 }, brightness = 0.75 }

  # You can add devices directly per integration and device name, too
  [scenes.normal_downstairs.devices.hue]
  "Hue lightstrip" = { power = true, color = { hue = 263.0, saturation = 1.0, value = 1.0 } }
```

### Combine scenes into larger scenes:

```
[scenes.normal]
name = "Normal"

  # You can make a scene group/device use the state that it would have in
  # another scene
  [scenes.normal.groups]
  downstairs = { scene_id = "normal_downstairs" }
  upstairs = { scene_id = "normal_upstairs" }
  outdoor_spots = { scene_id = "outdoor" }
```

This is a bit of a niche feature, but I use it to create a scene for the entire
house without needing to duplicate the config of contained scenes.

### Make lights follow a fake circadian rhythm:

```
[integrations.circadian]
plugin = "circadian"
device_name = "Circadian rhythm"
day_color = { hue = 25, saturation = 0.35, value = 1 }
day_fade_start = "04:00"
day_fade_duration_hours = 4
night_color = { hue = 20, saturation = 0.95, value = 0.75 }
night_fade_start = "18:00"
night_fade_duration_hours = 3

[scenes.normal]
name = "Normal"

  # You can make a scene group/device use the state of another device
  [scenes.normal.groups]
  all = { integration_id = "circadian", device_id = "color" }
```

### Make a light switch activate a scene:

```
[routines.arrive_home]
name = "Arrive home"
rules = [
  { integration_id = "hue", name = "Entryway switch", state = { on = true } }
]
actions = [
  { action = "ActivateScene", scene_id = "normal_downstairs" },
]
```

### Make a light switch cycle through a list of scenes:

```
[routines.favorite_scenes]
name = "Cycle through favorite scenes"
rules = [
  { integration_id = "hue1", name = "Living room switch", state = { on = true } }
]
actions = [
  { action = "CycleScenes", scenes = [ { scene_id = "normal" }, { scene_id = "wedding" } ] },
]
```

### Temporarily disable a motion detector when leaving the house:

```
[integrations.entryway_timer]
plugin = "timer"
device_name = "Entryway timer"

# This routine is triggered and turns on the lights when a motion sensor detects
# movement, and `entryway_timer` is not running.
[routines.entryway]
name = "Entryway"
rules = [
  { integration_id = "hue1", name = "Entryway motion sensor", state = { value = true } },
  { integration_id = "entryway_timer", name = "Entryway timer", state = { value = false } },
]
actions = [
  { action = "ActivateScene", scene_id = "normal_downstairs" },
  { action = "ActivateScene", scene_id = "outdoor" }
]

# This routine is triggered when switching off all lights via a switch located
# in the entryway. It activates a scene that turns off all lights, and starts
# `entryway_timer` with a timeout of 300 seconds.
[routines.leave_home]
name = "Leave home"
rules = [
  { integration_id = "hue1", name = "Entryway switch", state = { off = true } }
]
actions = [
  { action = "ActivateScene", scene_id = "leave" },
  { action = "IntegrationAction", integration_id = "entryway_timer", payload = "300000" }

  # Clean the house too!
  { action = "IntegrationAction", integration_id = "neato", payload = "clean_house" },
]
```

### Enable a motion sensor only when lights controlled by it are in a certain state:

```
# Activates `normal_upstairs` scene when motion is detected in staircase only if
# all upstairs lights are off
[routines.staircase_upstairs]
name = "Staircase (upstairs)"
rules = [
  { integration_id = "hue1", name = "Staircase motion sensor", state = { value = true } },
  { group_id = "upstairs", power = false }
]
actions = [
  { action = "ActivateScene", scene_id = "normal_upstairs" },
]

# Activates `normal_downstairs` scene when motion is detected in staircase only
# if all downstairs lights are off
[routines.staircase_downstairs]
name = "Staircase (downstairs)"
rules = [
  { integration_id = "hue1", name = "Staircase motion sensor", state = { value = true } },
  { group_id = "downstairs", power = false }
]
actions = [
  { action = "ActivateScene", scene_id = "normal_downstairs" }
]
```

My motivation for this setup is that the only task my motion sensor should
perform is turning on the lights if they were previously off.

For instance if I have manually enabled another scene, I don't want that scene
overwritten every time someone uses the stairs. Or if I'm setting the colors of
my lights through the homectl UI, I don't want the changes to be lost whenever I
walk past a motion detector.


text:
MyFirstAppAngular
=================

Primeiro app basico com CRUD(com arrays) utilizando o AngularJS;


text:
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>
#include <stdio.h>
#include <sys/stat.h>

#include "licenseplatecandidate.h"
#include "../statedetection/state_detector.h"
#include "utility.h"
#include "support/filesystem.h"

using namespace std;
using namespace cv;
using namespace alpr;

// Given a directory full of pre-cropped images, identify the state that each image belongs to.
// This is used to sort our own positive image database as a first step before grabbing characters to use to train the OCR.

bool detectPlate( StateDetector* identifier, Mat frame);

int main( int argc, const char** argv )
{
  string inDir;
  string outDir;
  Mat frame;

  //Check if user specify image to process
  if(argc == 3 )
  {
    inDir = argv[1];
    outDir =  argv[2];
    outDir = outDir + "/";
  }
  else
  {
    printf("Use:\n\t%s directory \n",argv[0]);
    printf("Ex: \n\t%s ./pics/   \n",argv[0]);
    return 0;
  }

  Config config("us");
  StateDetector identifier(config.country, config.config_file_path, config.runtimeBaseDir);

  if (DirectoryExists(outDir.c_str()) == false)
  {
    printf("Output dir does not exist\n");
    return 0;
  }

  if (DirectoryExists(inDir.c_str()))
  {
    vector<string> files = getFilesInDir(inDir.c_str());

    for (int i = 0; i< files.size(); i++)
    {
      if (hasEnding(files[i], ".png"))
      {
        string fullpath = inDir + "/" + files[i];
        cout << fullpath << endl;
        frame = imread( fullpath.c_str() );

        vector<StateCandidate> candidates = identifier.detect(frame.data, frame.elemSize(), frame.cols, frame.rows);

        if (candidates.size() > 0)
        {
          cout << candidates[0].confidence << " : " << candidates[0].state_code;

          ostringstream convert;   // stream used for the conversion
          convert << i;      // insert the textual representation of 'Number' in the characters in the stream

          string copyCommand = "cp \"" + fullpath + "\" " + outDir + candidates[0].state_code + convert.str() + ".png";
          system( copyCommand.c_str() );
          waitKey(50);
          //while ((char) waitKey(50) != 'c') { }
        }
      }
    }
  }
}

bool detectPlate( StateDetector* identifier, Mat frame);


text:
SYSTEMTESTTOP=../..
. $SYSTEMTESTTOP/conf.sh

../named-compilezone -D -F raw -o example.db.raw example \
        example.db > /dev/null 2>&1
../named-compilezone -D -F map -o ../ns3/example.db.map example \
        example.db > /dev/null 2>&1
../named-compilezone -D -F map -o ../ns3/dynamic.db.map dynamic \
        example.db > /dev/null 2>&1
../named-compilezone -D -F raw=1 -o example.db.raw1 example-explicit \
        example.db > /dev/null 2>&1
../named-compilezone -D -F raw=0 -o example.db.compat example-compat \
        example.db > /dev/null 2>&1
../named-compilezone -D -F raw -L 3333 -o example.db.serial.raw example \
        example.db > /dev/null 2>&1
../named-compilezone -D -F raw -o large.db.raw large large.db > /dev/null 2>&1
../named-compilezone -D -F map -o example.db.map example-map \
        example.db > /dev/null 2>&1

$KEYGEN -q -r $RANDFILE signed > /dev/null 2>&1
$KEYGEN -q -r $RANDFILE -fk signed > /dev/null 2>&1
$SIGNER -S -f signed.db.signed -o signed signed.db > /dev/null 2>&1
../named-compilezone -D -F map -o signed.db.map signed signed.db.signed > /dev/null 2>&1


text:
<?php

require '../src/autoload.php';

use \MysqlShard\Adapters\MysqlShard;
use MysqlShard\Tools\Config;
use \MysqlShard\Strategy\LinearStrategy;
use MysqlShard\Generator\LinesGenerator;

$shard = new MysqlShard();
$strategy = new LinearStrategy(null, 'lines', $shard->getConfig());

// create 10 tables for shards 0..9
for ($i=0; $i < 10; $i++) {
    $query = LinesGenerator::getCreateTableSQL($i);
    $strategy->setId( $i * LinearStrategy::MAX_RECORD_COUNT +1 );
    $shard->query( $query,  $strategy);
}


text:
var subcommand = require('subcommand')

var config = {
  root: require('./bin/root.js'),
  commands: [
    require('./bin/checkout.js'),
    require('./bin/clone.js'),
    require('./bin/datasets.js'),
    require('./bin/delete.js'),
    require('./bin/destroy.js'),
    require('./bin/diff.js'),
    require('./bin/export.js'),
    require('./bin/files.js'),
    require('./bin/forks.js'),
    require('./bin/get.js'),
    require('./bin/import.js'),
    require('./bin/init.js'),
    require('./bin/keys.js'),
    require('./bin/log.js'),
    require('./bin/merge.js'),
    require('./bin/pull.js'),
    require('./bin/push.js'),
    require('./bin/read.js'),
    require('./bin/replicate.js'),
    require('./bin/help.js'),
    require('./bin/serve.js'),
    require('./bin/status.js'),
    require('./bin/write.js')
  ],
  defaults: require('./bin/defaults.js'),
  none: noMatch
}

var route = subcommand(config)
route(process.argv.slice(2))

function noMatch (args) {
  console.error('dat:', args._[0], 'is not a valid command')
  process.exit(1)
}


text:
Synchronize the textarea
========================

When the textarea is transformed into a CKEditor widget, the textarea value is
no more populated except when the form is submitted. Then, it leads to issues
when you try to serialize the form or you try to rely on the textarea value in
JavaScript. To automatically synchronize the textarea value, you can do it
globally in your configuration:

.. code-block:: yaml

    # app/config/config.yml
    ivory_ck_editor:
        input_sync: true

Or you can do it in your widget:

.. code-block:: php

    $builder->add('field', 'ckeditor', array('input_sync' => true));


text:
class AddBlogIdIdToContenido < ActiveRecord::Migration
  def change
    add_column :contenidos, :blog_id, :integer
  end
end


text:
FROM ubuntu:bionic
MAINTAINER romeOz <serggalka@gmail.com>

ENV OS_LOCALE="en_US.UTF-8" \
    DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y locales && locale-gen ${OS_LOCALE}
ENV LANG=${OS_LOCALE} \
    LANGUAGE=${OS_LOCALE} \
    LC_ALL=${OS_LOCALE}

ENV PHP_RUN_DIR=/run/php \
    PHP_LOG_DIR=/var/log/php \
    PHP_CONF_DIR=/etc/php/7.3 \
    PHP_DATA_DIR=/var/lib/php

RUN \
    BUILD_DEPS='software-properties-common' \
    && dpkg-reconfigure locales \
    # Install common libraries
    && apt-get install --no-install-recommends -y $BUILD_DEPS \
    && add-apt-repository -y ppa:ondrej/php \
    && apt-get update \
    # Install PHP libraries
    # php7.3-mcrypt not support and move to PECL. Use extension Sodium: http://php.net/manual/book.sodium.php
    && apt-get install -y curl php7.3-fpm php7.3-cli php7.3-readline php7.3-mbstring php7.3-zip php7.3-intl php7.3-json php7.3-xml php7.3-curl php7.3-gd php7.3-pgsql php7.3-mysql php-pear \
    # Install composer
    && curl -sS https://getcomposer.org/installer | php -- --version=1.8.4 --install-dir=/usr/local/bin --filename=composer \
    && mkdir -p ${PHP_LOG_DIR} ${PHP_RUN_DIR} \
    # Cleaning
    && apt-get purge -y --auto-remove $BUILD_DEPS \
    && apt-get autoremove -y && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

COPY ./configs/php-fpm.conf ${PHP_CONF_DIR}/fpm/php-fpm.conf
COPY ./configs/www.conf ${PHP_CONF_DIR}/fpm/pool.d/www.conf
COPY ./configs/php.ini ${PHP_CONF_DIR}/fpm/conf.d/custom.ini

RUN sed -i "s~PHP_RUN_DIR~${PHP_RUN_DIR}~g" ${PHP_CONF_DIR}/fpm/php-fpm.conf \
    && sed -i "s~PHP_LOG_DIR~${PHP_LOG_DIR}~g" ${PHP_CONF_DIR}/fpm/php-fpm.conf \
    && chown www-data:www-data ${PHP_DATA_DIR} -Rf

WORKDIR /var/www

EXPOSE 9000

# PHP_DATA_DIR store sessions
VOLUME ["${PHP_RUN_DIR}", "${PHP_DATA_DIR}"]
CMD ["/usr/sbin/php-fpm7.3"]


text:
package com.tvd12.ezyfox.data;

import com.tvd12.ezyfox.collect.Sets;
import com.tvd12.ezyfox.data.annotation.EzyIndexedData;
import com.tvd12.ezyfox.data.annotation.IndexedData;
import com.tvd12.ezyfox.identifier.EzyIdFetchers;
import com.tvd12.ezyfox.identifier.EzySimpleIdFetchers;
import com.tvd12.ezyfox.message.annotation.EzyMessage;
import com.tvd12.ezyfox.message.annotation.Message;

import java.lang.annotation.Annotation;
import java.util.Set;

public class EzyIndexedDataIdFetchers extends EzySimpleIdFetchers {

    public EzyIndexedDataIdFetchers(Builder builder) {
        super(builder);
    }

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder extends EzySimpleIdFetchers.Builder {

        @SuppressWarnings("unchecked")
        @Override
        protected Set<Class<? extends Annotation>> getAnnotationClasses() {
            return Sets.newHashSet(
                Message.class, IndexedData.class,
                EzyMessage.class, EzyIndexedData.class
            );
        }

        @Override
        protected EzyIdFetchers newProduct() {
            return new EzyIndexedDataIdFetchers(this);
        }

    }
}


text:
gradle_options=()

while [ $# -gt 0 ]; do
    if [[ $1 == "--docker-image" ]]; then
        declare docker_image="$2"
        shift
    elif [[ $1 == "--docker-network" ]]; then
        declare docker_network="$2"
        shift
    elif [[ $1 == "--job-directory" ]]; then
        declare job_directory="$2"
        shift
    else
        gradle_options+=($1)
   fi
  shift
done

# Pass any environment variable starting with ORG_GRADLE_PROJECT_
# to the container. This makes it available as a variable in the Gradle script.
# Example: The value of ORG_GRADLE_PROJECT_dbUriPub can be accessed
# with the variable dbUriPub in the Gradle script.
for envvar in $(env | grep ORG_GRADLE_PROJECT_); do
    envvars_string+="--env ${envvar} "
done

# Build a string containing the --network ... option if the --docker-network option has been set
if [[ -v docker_network ]]; then
    declare network_string="--network ${docker_network}"
fi

# For accessing the "GRETL share", use the gretlShare variable.

declare gretl_cmd="gretl ${gradle_options[@]} -PgretlShare=/tmp/gretl-share"

echo "======================================================="
echo "Starts the GRETL image to execute the given GRETL job"
echo "Docker Image: $docker_image"
echo "Docker network: $docker_network"
echo "job directory: $job_directory"
echo "Gradle options: ${gradle_options[@]}"
echo "gretl_cmd: $gretl_cmd"
echo "======================================================="

# Create a directory that is going to be mounted as the "GRETL share"
mkdir -p /tmp/gretl-share

# special run configuration for jenkins-slave based image:
# 1. use a shell as entry point
# 2. mount job directory as volume
# 3. mount /tmp directory as GRETL share
# 4. Pass all environment variables starting with ORG_GRADLE_PROJECT_ to the container
# 5. run as current user to avoid permission problems on generated .gradle directory
# 6. connect container to a specific docker network if specified by the user
# 7. run gretl image passed by the user
# 8. executed commands seperated by semicolon:
#    a. jenkins jnlp client
#    b. change to project directory
#    c. run gradle with given task and parameter using init script from image

docker run -i --rm --name gretl \
    --entrypoint="//bin/sh" \
    -v "/${job_directory}":/home/gradle/project \
    -v //tmp/gretl-share:/tmp/gretl-share \
     ${envvars_string} \
    --user $UID \
    ${network_string} \
    "$docker_image" "-c" "$gretl_cmd"


text:
package com.libs.sample.showcaseview;

/**
 * Created by huibin on 2/10/14.
 */
public class AnimationSampleActivity {
}