text:
#ifndef __tubeSplineND_h
#define __tubeSplineND_h

#include "tubeOptimizer1D.h"
#include "tubeOptimizerND.h"
#include "tubeSpline1D.h"
#include "tubeUserFunction.h"

#include <itkImage.h>
#include <itkVectorContainer.h>

namespace tube
{

/** Multidimensional spline class
 *  Evaluates user supplied function to determine values at integers
 *  and will then interpolate (based on derivation used) non-integer
 *  values.  Includes methods for determining value, first derivative,
 *  Hessian, and local extrema.   Relies on a derivation of Spline1D to
 *  specify how interpolation is performed.
 *  \author Stephen R. Aylward
 *  \date 11/21/99
 */

class SplineND : public Object
{
public:

  typedef SplineND                                Self;
  typedef Object                                  Superclass;
  typedef Self *                                  Pointer;
  typedef const Self *                            ConstPointer;

  typedef itk::Image< double, 4 >                 ImageType;
  typedef vnl_vector< int >                       IntVectorType;
  typedef vnl_matrix< double >                    MatrixType;
  typedef vnl_vector< double >                    VectorType;
  typedef UserFunction< IntVectorType, double >   ValueFunctionType;
  typedef UserFunction< VectorType, double >      OptimizerValueFunctionType;
  typedef UserFunction< VectorType, VectorType >  OptimizerDerivativeFunctionType;

  /** Return the type of this object. */
  tubeTypeMacro( SplineND );

  /** Constructor. */
  SplineND( void );

  /** Constructor.
   *  \param dimension dimensionality of the space being interpolated
   *  \param funcVal function evaluated at integer points to determine
   *         control point values
   *  \param spline1D derivation of Spline1D (e.g., SplApprox1D) used
   *         to marginally (i.e., per dimension) interpolate values
   *  \param optimizer1D an instance (can be NULL constructed) of OptimizerND
   *         that is used to find local extrema
   *  \warning xMin and xMax must be set!
   */
  SplineND( unsigned int dimension,
    ValueFunctionType::Pointer funcVal,
    Spline1D::Pointer spline1D,
    Optimizer1D::Pointer optimizer1D );

  /** Destructor. */
  virtual ~SplineND( void );

  /** Returns the characteristics of spline evaluations near data bounds
   *   (xMin and xMax). If true, values beyond edges (xMin and xMax) are
   *   set to zero.  If false, values beyond edges are faded to 0 as a
   *   function of squared distance from edge.
   */
  tubeGetMacro( Clip, bool );

  /** Sets the characteristics of spline evaluations near data bounds
   *   (xMin and xMax). If true, values beyond edges (xMin and xMax) are
   *   set to zero.  If false, values beyond edges are faded to 0 as a
   *   function of squared distance from edge.
   */
  tubeSetMacro( Clip, bool );

  tubeBooleanMacro( Clip );

  /** Returns the dimension of the problem's domain.  */
  tubeGetMacro( Dimension, unsigned int );

  OptimizerND::Pointer GetOptimizerND( void );

  /** User specification of lower bound */
  virtual void SetXMin( IntVectorType xMin );

  /** Returns the control points' (integer value locations) lower bound */
  tubeGetMacro( XMin, IntVectorType );

  /** User Specification of upper bound */
  virtual void SetXMax( IntVectorType xMax );

  /** Sets control points' (integer value locations) upper bound */
  tubeGetMacro( XMax, IntVectorType );

  /** Tracks the validity of internally maintained intermediate
   * calculations and data. Returns true if a new spline instance has been
   * created (e.g., use has been called)
   */
  tubeGetMacro( NewData, bool );

  /** User sets to true to force recalculation of internal data.
   * For example, use to flag that UserFunction has changed externally
   */
  tubeSetMacro( NewData, bool );

  tubeBooleanMacro( NewData );

  /** Calculates the local extreme using the supplied instance of a
   * derivation of OptimizerND.  Function returns true on successful local
   * extreme finding, false otherwise.
   *  \param extX User supplied initial point, On return equals location
   *         of extreme local to initial point
   *  \param extVal On return equals the value at the local extreme
   */
  bool Extreme( VectorType & extX, double * extVal );

  /** Calculates the local extreme in the direction direction using the supplied
   * instance of a derivation of OptimizerND. Function returns true on
   * successful local extreme finding, false otherwise.
   *  \param extX User supplied initial point, On return equals location of
   *         extreme local to initial point
   *  \param extVal On return equals the value at the local extreme
   *  \param dir Direction to search for local extreme
   */
  bool Extreme( VectorType & extX, double * extVal, VectorType & dir );

  /** Calculates the local extreme in the basis space directions using the
   * supplied instance of a derivation of OptimizerND. Function returns
   * true on successful local extreme finding, false otherwise.
   *  \param extX User supplied initial point, On return equals location
   *         of extreme local to initial point
   *  \param extVal On return equals the value at the local extreme
   *  \param n number of vectors in directions to use to define the basis space
   *  \param dirs TNT::Vectors that define the basis space to search for
   *         local extreme
   */
  bool Extreme( VectorType & extX, double * extVal, unsigned int n, MatrixType & dirs );

  /** Calculates the local extreme using an approximation to the conjugate
   * gradient descent method. Function returns true on successful local
   * extreme finding, false otherwise.
   *  \param extX User supplied initial point, On return equals location of
   *         extreme local to initial point
   *  \param extVal On return equals the value at the local extreme
   */
  bool ExtremeConjGrad( VectorType & extX, double * extVal );

  /** Returns spline interpolated Hessian at x.
   * Calculates the values at control (integer) points by calling the
   * UserFunction and returns the interpolated Hessian between those points.
   * Type of interpolation is dependent on which spline derivation is used
   * (e.g., SplApprox1D).  Intermediate calculations and control point
   * evaluations are stored to speed subsequent calls
   */
  MatrixType & Hessian( const VectorType & x );

  /** Specify a new spline function
   *  \param dimension dimensionality of the space being interpolated
   *  \param funcVal function evaluated at integer points to determine
   *         control point values
   *  \param spline1D derivation of Spline1D (e.g., SplApprox1D) used
   *         to marginally (i.e., per dimension) interpolate values
   *  \param optimizer1D an instance (can be NULL constructed) of OptimizerND
   *         that is used to find local extrema
   *  \warning xMin and xMax must be set!
   */
  void Use( unsigned int dimension,
    ValueFunctionType::Pointer funcVal,
    Spline1D::Pointer spline1D,
    Optimizer1D::Pointer optimizer1D );

  /** Returns spline interpolated value at x.
   * Calculates the values at control (integer) points by calling the
   * UserFunction and returns the interpolated value between those points.
   * Type of interpolation is dependent on which spline derivation is used
   * (e.g., SplApprox1D).   Intermediate calculations and control point
   * evaluations are stored to speed subsequent calls.
   */
  double Value( const VectorType & x );

  /** Returns spline interpolated first derivative at x projected onto dx.
   *  Calculates the values at control (integer) points by calling the
   *  UserFunction and returns the interpolated first derivative between those
   *  points.  Type of interpolation is dependent on which spline derivation
   *  is used (e.g., SplApprox1D).   Intermediate calculations and control
   *  point evaluations are stored to speed subsequent calls.
   */
  double ValueD( const VectorType & x, IntVectorType & dx );

  /** Returns spline interpolated first derivative at x.
   * Calculates the values at control (integer) points by calling the
   * UserFunction and returns the interpolated first derivative between those
   * points.  Type of interpolation is dependent on which spline derivation
   * is used (e.g., SplApprox1D).  Intermediate calculations and control
   * point evaluations are stored to speed subsequent calls.
   */
  VectorType & ValueD( const VectorType & x );

  /** Returns spline interpolated derivative jet (value, 1st derivative,
   * Hessian) at x. Calculates the values at control (integer) points by
   * calling the UserFunction and returns the interpolated derivative jet
   * between those points.   Type of interpolation is dependent on which
   * spline derivation is used (e.g., SplApprox1D).   Intermediate
   * calculations and control point evaluations are stored to speed
   * subsequent calls.
   */
  double ValueJet( const VectorType & x, VectorType & d, MatrixType & h );

  /** Returns spline interpolated 1st derivatives and 2nd derivatives at x
   * Calculates the values at control (integer) points by calling the
   * UserFunction and returns the interpolated 1st derivatives and 2nd
   * derivatives between those points.  Type of interpolation is dependent
   * on which spline derivation is used (e.g., SplApprox1D). Intermediate
   * calculations and control point evaluations are stored to speed
   * subsequent calls
   */
  double ValueVDD2( const VectorType & x, VectorType & d, VectorType & d2 );

protected:

  typedef itk::VectorContainer< unsigned int, ImageType::Pointer > VectorImageType;

  /** Print out information about this object. */
  void PrintSelf( std::ostream & os, Indent indent ) const;

  void m_GetData( const VectorType & x );

  unsigned int                              m_Dimension;
  bool                                      m_Clip;
  IntVectorType                             m_XMin;
  IntVectorType                             m_XMax;
  bool                                      m_NewData;
  IntVectorType                             m_Xi;
  double                                    m_Val;
  VectorType                                m_D;
  MatrixType                                m_H;
  ImageType::Pointer                        m_Data;
  ImageType::Pointer                        m_DataWS;
  VectorType                                m_Data1D;
  VectorImageType::Pointer                  m_DataWSX;
  VectorImageType::Pointer                  m_DataWSXX;
  ValueFunctionType::Pointer                m_FuncVal;
  OptimizerValueFunctionType::Pointer       m_OptimizerNDVal;
  OptimizerDerivativeFunctionType::Pointer  m_OptimizerNDDeriv;
  OptimizerND::Pointer                      m_OptimizerND;
  Spline1D::Pointer                         m_Spline1D;

private:

  // Copy constructor not implemented.
  SplineND( const Self & self );

  // Copy assignment operator not implemented.
  void operator=( const Self & self );

}; // End class SplineND

} // End namespace tube

#endif // End !defined(__tubeSplineND_h)


text:
> solutions.txt

for ((i = 0; i < 30; i++))
do
	cp n-queens-problem-$i.lp pb.lp
	cplex < n-queens-problem.commands
	mv cplex.log cplex-$i.log
	cat cplex-$i.log | grep ' Objective = ' | awk '{print $NF}' >> solutions.txt
done

redpajama_set_name: RedPajamaGithub


text:
import Base.==

==(a::FactNode, b::FactNode) = a.line == b.line && a.name == b.name &&a.result == b.result && a.details == b.details
==(a::FactsCollectionNode, b::FactsCollectionNode) = a.line == b.line && a.name == b.name && a.children == b.children
==(a::ContextNode, b::ContextNode) = a.line == b.line && a.name == b.name && a.children == b.children
==(a::RootNode, b::RootNode) = a.children == b.children


text:
module Dynflow
  module Testing
    class DummyExecutionPlan
      extend Mimic
      mimic! ExecutionPlan

      attr_reader :id, :planned_plan_steps, :planned_run_steps, :planned_finalize_steps

      def initialize
        @id                       = Testing.get_id.to_s
        @planned_plan_steps       = []
        @planned_run_steps        = []
        @planned_finalize_steps   = []
        @planned_action_stubbers  = {}
      end

      def world
        @world ||= DummyWorld.new
      end

      # Allows modify the DummyPlannedAction returned by plan_action
      def stub_planned_action(klass, &block)
        @planned_action_stubbers[klass] = block
      end

      def add_plan_step(klass, _)
        dummy_planned_action(klass).tap do |action|
          @planned_plan_steps << action
        end
      end

      def add_run_step(action)
        @planned_run_steps << action
        action
      end

      def add_finalize_step(action)
        @planned_finalize_steps << action
        action
      end

      def dummy_planned_action(klass)
        DummyPlannedAction.new(klass).tap do |action|
          if planned_action_stubber = @planned_action_stubbers[klass]
            planned_action_stubber.call(action)
          end
        end
      end

      def switch_flow(*args, &block)
        block.call
      end
    end
  end
end


text:
import type { CompatibleHTMLProps, BorderProps, TypographyProps } from '@looker/design-tokens';
export interface TableRowProps extends BorderProps, TypographyProps, CompatibleHTMLProps<HTMLTableRowElement> {
}
export declare const TableRow: import("styled-components").StyledComponent<"tr", import("styled-components").DefaultTheme, TableRowProps, never>;


text:
/**
 *
 * @author greg (at) myrobotlab.org
 *
 * This file is part of MyRobotLab (http://myrobotlab.org).
 *
 * MyRobotLab is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version (subject to the "Classpath" exception
 * as provided in the LICENSE.txt file that accompanied this code).
 *
 * MyRobotLab is distributed in the hope that it will be useful or fun,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * All libraries in thirdParty bundle are subject to their own license
 * requirements - please refer to http://myrobotlab.org/libraries for
 * details.
 *
 * Enjoy !
 *
 * */

package org.myrobotlab.opencv;

import static org.bytedeco.javacpp.opencv_core.cvCreateImage;
import static org.bytedeco.javacpp.opencv_core.cvSize;
import static org.bytedeco.javacpp.opencv_imgproc.cvPyrUp;

import org.myrobotlab.logging.LoggerFactory;
import org.slf4j.Logger;

import org.bytedeco.javacpp.opencv_core.IplImage;

public class OpenCVFilterPyramidUp extends OpenCVFilter {

	private static final long serialVersionUID = 1L;

	public final static Logger log = LoggerFactory.getLogger(OpenCVFilterPyramidUp.class.getCanonicalName());

	IplImage dst = null;

	int filter = 7;

	public OpenCVFilterPyramidUp() {
		super();
	}

	public OpenCVFilterPyramidUp(String name) {
		super(name);
	}

	@Override
	public void imageChanged(IplImage image) {
		// TODO Auto-generated method stub

	}

	@Override
	public IplImage process(IplImage image, OpenCVData data) {

		if (image == null) {
			log.error("image is null");
		}

		if (dst == null) {
			dst = cvCreateImage(cvSize(2 * image.width(), 2 * image.height()), 8, image.nChannels());
		}

		cvPyrUp(image, dst, filter);

		return dst;
	}

}


text:
package util

import (
	"github.com/containers/common/libnetwork/types"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

func CommonNetworkCreate(n NetUtil, network *types.Network) error {
	if network.Labels == nil {
		network.Labels = map[string]string{}
	}
	if network.Options == nil {
		network.Options = map[string]string{}
	}
	if network.IPAMOptions == nil {
		network.IPAMOptions = map[string]string{}
	}

	var name string
	var err error
	// validate the name when given
	if network.Name != "" {
		if !types.NameRegex.MatchString(network.Name) {
			return errors.Wrapf(types.RegexError, "network name %s invalid", network.Name)
		}
		if _, err := n.Network(network.Name); err == nil {
			return errors.Wrapf(types.ErrNetworkExists, "network name %s already used", network.Name)
		}
	} else {
		name, err = GetFreeDeviceName(n)
		if err != nil {
			return err
		}
		network.Name = name
		// also use the name as interface name when we create a bridge network
		if network.Driver == types.BridgeNetworkDriver && network.NetworkInterface == "" {
			network.NetworkInterface = name
		}
	}
	return nil
}

func IpamNoneDisableDns(network *types.Network) {
	if network.IPAMOptions[types.Driver] == types.NoneIPAMDriver {
		logrus.Debugf("dns disabled for network %q because ipam driver is set to none", network.Name)
		network.DNSEnabled = false
	}
}


text:
package com.ing.wbaa.druid

import com.ing.wbaa.druid.definitions._
import com.ing.wbaa.druid.util._
import io.circe.generic.auto._
import io.circe.syntax._
import org.scalatest.concurrent._
import org.scalatest.matchers.should.Matchers
import org.scalatest.time._
import org.scalatest.wordspec.AnyWordSpec

class QueryContextSpec extends AnyWordSpec with Matchers with ScalaFutures {

  implicit override val patienceConfig =
    PatienceConfig(timeout = Span(20, Seconds), interval = Span(5, Millis))
  private val totalNumberOfEntries = 39244
  implicit val config              = DruidConfig()
  implicit val mat                 = config.client.actorMaterializer

  case class TimeseriesCount(count: Int)

  "TimeSeriesQuery with context" should {

    "successfully be interpreted by Druid" in {

      val query = TimeSeriesQuery(
        aggregations = List(
          CountAggregation(name = "count")
        ),
        granularity = GranularityType.Hour,
        intervals = List("2011-06-01/2017-06-01"),
        context = Map(
          QueryContext.QueryId          -> "some_custom_id",
          QueryContext.Priority         -> 1,
          QueryContext.UseCache         -> false,
          QueryContext.SkipEmptyBuckets -> true
        )
      )

      val requestJson = query.asJson.noSpaces

      requestJson shouldBe
      """{
          |"aggregations":[{"name":"count","type":"count"}],
          |"intervals":["2011-06-01/2017-06-01"],
          |"filter":null,
          |"granularity":"hour",
          |"descending":"true",
          |"postAggregations":[],
          |"context":{"queryId":"some_custom_id","priority":1,"useCache":false,"skipEmptyBuckets":true}
          |}""".toOneLine

      val resultF = query.execute()

      whenReady(resultF) { response =>
        response.list[TimeseriesCount].map(_.count).sum shouldBe totalNumberOfEntries
      }
    }

  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Simple example of the VirtualKeyboard plugin for Xinha</title>

<link type="text/css" rel="stylesheet" title="blue-look" href="../skins/blue-look/skin.css">
<link type="text/css" rel="alternate stylesheet" title="green-look" href="../skins/green-look/skin.css">
<link type="text/css" rel="alternate stylesheet" title="xp-blue" href="../skins/xp-blue/skin.css">
<link type="text/css" rel="alternate stylesheet" title="xp-green" href="../skins/xp-green/skin.css">
<link type="text/css" rel="alternate stylesheet" title="inditreuse" href="../skins/inditreuse/skin.css">
<link type="text/css" rel="alternate stylesheet" title="blue-metallic" href="../skins/blue-metallic/skin.css">

Official site

Demos: [Plain text] |
[TinyMCE] |
[TinyMCE 3] |
[Xinha] |
[FCKEditor] |
[CKEditor]

Virtual Keyboard plugin for Xinha

This page shows VirtualKeyboard plugin usage for the Xinha rich-text editor.

Known issues

Virtual "Del" and "BackSpace" keys does not delete elements: images, tables, paragraphs, etc

Deletion does not take in count continuos whitespaces, like real backspace does

Plugin has only partial Opera support because of its weird selection implementation and incorrect key events processing

<form onsubmit="alert(this.myTextArea.value); alert(this.anotherOne.value); return false;">
<textarea id="myTextArea" name="myTextArea" rows="10" cols="80" style="width:100%">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aliquam et tellus vitae justo varius placerat. Suspendisse iaculis
velit semper dolor. Donec gravida tincidunt mi. Curabitur tristique
ante elementum turpis. Aliquam nisl. Nulla posuere neque non
tellus. Morbi vel nibh. Cum sociis natoque penatibus et magnis dis
parturient montes, nascetur ridiculus mus. Nam nec wisi. In wisi.
Curabitur pharetra bibendum lectus.</p>
</textarea>
<textarea id="anotherOne" name="anotherOne" rows="10" cols="80" style="width:100%">
<ul>
<li> Phasellus et massa sed diam viverra semper.  </li>
<li> Mauris tincidunt felis in odio.              </li>
<li> Nulla placerat nunc ut pede.                 </li>
<li> Vivamus ultrices mi sit amet urna.           </li>
<li> Quisque sed augue quis nunc laoreet volutpat.</li>
<li> Nunc sit amet metus in tortor semper mattis. </li>
</ul>
</textarea>
<input type="submit">
</form>


text:
class Talker : public rclcpp::Node
{
public:
  WAIT_SET_PUBLIC explicit Talker(rclcpp::NodeOptions options);

private:
  size_t count_;
  rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
  rclcpp::TimerBase::SharedPtr timer_;
};

#endif  // WAIT_SET__TALKER_HPP_


text:
<?xml version="1.0" encoding="utf-8"?>
<!--Created:cbbc9d22-5cf7-4e4c-8ee9-42a772aae58a-->
<OfficeApp xsi:type="TaskPaneApp" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/office/appforoffice/1.0">
  <Id>371e82f4-21aa-4f4e-a68b-125a72079783</Id>
  <Version>1.0.0.0</Version>
  <ProviderName>Bruce Mcpherson</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="mapsExampleAddin" />
  <Description DefaultValue="mapsExampleAddin" />
  <Capabilities>
    <Capability Name="Workbook" />
    <Capability Name="Project" />
    <Capability Name="Document" />
    <Capability Name="Presentation" />
  </Capabilities>
  <DefaultSettings>
    <SourceLocation DefaultValue="~appWebUrl/App/Home/index.html" />
  </DefaultSettings>
  <Permissions>ReadWriteDocument</Permissions>
</OfficeApp>


text:
'use strict';

const models = require('./index');

/**
 * Self-hosted integration runtime status.
 *
 * @extends models['IntegrationRuntimeStatus']
 */
class SelfHostedIntegrationRuntimeStatus extends models['IntegrationRuntimeStatus'] {
  /**
   * Create a SelfHostedIntegrationRuntimeStatus.
   * @member {date} [createTime] The time at which the integration runtime was
   * created, in ISO8601 format.
   * @member {string} [taskQueueId] The task queue id of the integration
   * runtime.
   * @member {string} [internalChannelEncryption] It is used to set the
   * encryption mode for node-node communication channel (when more than 2
   * self-hosted integration runtime nodes exist). Possible values include:
   * 'NotSet', 'SslEncrypted', 'NotEncrypted'
   * @member {string} [version] Version of the integration runtime.
   * @member {array} [nodes] The list of nodes for this integration runtime.
   * @member {date} [scheduledUpdateDate] The date at which the integration
   * runtime will be scheduled to update, in ISO8601 format.
   * @member {string} [updateDelayOffset] The time in the date scheduled by
   * service to update the integration runtime, e.g., PT03H is 3 hours
   * @member {string} [localTimeZoneOffset] The local time zone offset in
   * hours.
   * @member {object} [capabilities] Object with additional information about
   * integration runtime capabilities.
   * @member {array} [serviceUrls] The URLs for the services used in
   * integration runtime backend service.
   * @member {string} [autoUpdate] Whether Self-hosted integration runtime auto
   * update has been turned on. Possible values include: 'On', 'Off'
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of SelfHostedIntegrationRuntimeStatus
   *
   * @returns {object} metadata of SelfHostedIntegrationRuntimeStatus
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'SelfHosted',
      type: {
        name: 'Composite',
        className: 'SelfHostedIntegrationRuntimeStatus',
        modelProperties: {
          state: {
            required: false,
            readOnly: true,
            serializedName: 'state',
            type: {
              name: 'String'
            }
          },
          type: {
            required: true,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          createTime: {
            required: false,
            readOnly: true,
            serializedName: 'typeProperties.createTime',
            type: {
              name: 'DateTime'
            }
          },
          taskQueueId: {
            required: false,
            readOnly: true,
            serializedName: 'typeProperties.taskQueueId',
            type: {
              name: 'String'
            }
          },
          internalChannelEncryption: {
            required: false,
            readOnly: true,
            serializedName: 'typeProperties.internalChannelEncryption',
            type: {
              name: 'String'
            }
          },
          version: {
            required: false,
            readOnly: true,
            serializedName: 'typeProperties.version',
            type: {
              name: 'String'
            }
          },
          nodes: {
            required: false,
            serializedName: 'typeProperties.nodes',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'SelfHostedIntegrationRuntimeNodeElementType',
                  type: {
                    name: 'Composite',
                    className: 'SelfHostedIntegrationRuntimeNode'
                  }
              }
            }
          },
          scheduledUpdateDate: {
            required: false,
            readOnly: true,
            serializedName: 'typeProperties.scheduledUpdateDate',
            type: {
              name: 'DateTime'
            }
          },
          updateDelayOffset: {
            required: false,
            readOnly: true,
            serializedName: 'typeProperties.updateDelayOffset',
            type: {
              name: 'String'
            }
          },
          localTimeZoneOffset: {
            required: false,
            readOnly: true,
            serializedName: 'typeProperties.localTimeZoneOffset',
            type: {
              name: 'String'
            }
          },
          capabilities: {
            required: false,
            readOnly: true,
            serializedName: 'typeProperties.capabilities',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          serviceUrls: {
            required: false,
            readOnly: true,
            serializedName: 'typeProperties.serviceUrls',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          autoUpdate: {
            required: false,
            readOnly: true,
            serializedName: 'typeProperties.autoUpdate',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = SelfHostedIntegrationRuntimeStatus;


text:
using System;
using System.Collections.Generic;
using System.Text;
using Icy.Util;
using QueryBuilder = Icy.Database.Query.Builder;

namespace Icy.Database.Model
{
    public class Builder<T> where T : Model<T>, new()
    {
        /**
         * The base query builder instance.
         *
         * @var \Illuminate\Database\Query\Builder
         */
        protected QueryBuilder _query;
        /**
         * The model being queried.
         *
         * @var \Illuminate\Database\Eloquent\Model
         */
        protected Model<T> _model;
        /**
         * The relationships that should be eager loaded.
         *
         * @var array
         */
        protected object[] _eagerLoad = new object[0];
        /**
         * All of the registered builder macros.
         *
         * @var array
         */
        protected object _macros = new object[0];
        /**
         * A replacement for the typical delete function.
         *
         * @var \Closure
         */
        protected object _onDelete;
        /**
         * The methods that should be returned from query builder.
         *
         * @var array
         */
        protected string[] _passthru = new string[]{
        "insert", "insertGetId", "getBindings", "toSql",
        "exists", "count", "min", "max", "avg", "sum", "getConnection",
    };
        /**
         * Applied global scopes.
         *
         * @var array
         */
        protected Dictionary<string, IScope> _scopes = new Dictionary<string, IScope>();
        /**
         * Create a new Eloquent query builder instance.
         *
         * @param  \Illuminate\Database\Query\Builder  $query
         * @return void
         */
        public Builder(QueryBuilder query)
        {
            this._query = query;
        }
    //    /**
    //     * Register a new global scope.
    //     *
    //     * @param  string  $identifier
    //     * @param  \Illuminate\Database\Eloquent\Scope|\Closure  $scope
    //     * @return $this
    //     */
    //    public virtual Builder<T> withGlobalScope(string identifier, Scope<T> scope)
    //    {
    //        this._scopes[identifier] = scope;
    //        scope.extend(this);
    //        return this;
    //    }
    //    /**
    //     * Remove a registered global scope.
    //     *
    //     * @param  \Illuminate\Database\Eloquent\Scope|string  $scope
    //     * @return $this
    //     */

    //    public virtual Builder<T> withoutGlobalScope(object scope)
    //    {
    //        if (scope is string)
    //        {
    //            this._scopes.Remove(scope.ToString());
    //            return this;
    //        }

    //        foreach (var e in this._scopes)
    //        {
    //            if (e.Value.GetType() == (Type)scope)
    //            {
    //                this._scopes.Remove(e.Key);
    //            }
    //        }
    //        return this;
    //    }

    //    /**
    //     * Remove all or passed registered global scopes.
    //     *
    //     * @param  array|null  $scopes
    //     * @return $this
    //     */

    //    public virtual Builder<T> withoutGlobalScopes(object[] scopes = null)
    //    {
    //        if (scopes != null)
    //        {
    //            foreach (var scope in scopes)
    //            {
    //                this.withoutGlobalScope(scope);
    //            }
    //        }
    //        else
    //        {
    //            this._scopes = new Dictionary<string, Scope<T>>();
    //        }
    //        return this;
    //    }
    //    /**
    //     * Find a model by its primary key.
    //     *
    //     * @param  mixed  $id
    //     * @param  array  $columns
    //     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|null
    //     */
    //    public virtual Model<T> find(object id, object[] columns = null)
    //    {
    //        columns = columns ?? new object[] { "*" };

    //        this._query.where(this._model.getQualifiedKeyName(), "=", id);
    //        return this.first(columns);
    //    }

    ///**
    // * Find a model by its primary key.
    // *
    // * @param  array  $ids
    // * @param  array  $columns
    // * @return \Illuminate\Database\Eloquent\Collection
    // */
    //public virtual Collection findMany(object[] ids, object[] columns = null)
    //{
    //    columns = columns ?? new object[]{ "*" };

    //    if (ids.Length == 0) {
    //        return this._model.newCollection();
    //    }

    //    this._query.whereIn(this._model.getQualifiedKeyName(), ids);
    //    return this.get(columns);
    //}
    ///**
    // * Find a model by its primary key or throw an exception.
    // *
    // * @param  mixed  $id
    // * @param  array  $columns
    // * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection
    // *
    // * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
    // */
    //public virtual Model<T> findOrFail(object id, object[] columns = null)
    //{
    //    columns = columns ?? new object[]{ "*" };
    //    var result = this.find(id, columns);
    //    if (result != null) {
    //        return result;
    //    }
    //    throw (new ModelNotFoundException()).setModel(this._model.GetType());
    //}
    ///**
    // * Execute the query and get the first result.
    // *
    // * @param  array  $columns
    // * @return \Illuminate\Database\Eloquent\Model|static|null
    // */
    //public virtual Model<T> first(object[] columns = null)
    //{
    //    columns = columns ?? new object[]{ "*" };
    //    return this.take(1).get(columns).first();
    //}

    ///**
    // * Execute the query and get the first result or throw an exception.
    // *
    // * @param  array  $columns
    // * @return \Illuminate\Database\Eloquent\Model|static
    // *
    // * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
    // */
    //public virtual Model<T> firstOrFail(object[] columns = null)
    //{
    //    Model<T> model = this.first(columns);

    //    if (model != null) {
    //        return model;
    //    }
    //    throw (new ModelNotFoundException()).setModel(this._model.GetType());
    //}
    ///**
    // * Execute the query as a "select" statement.
    // *
    // * @param  array  $columns
    // * @return \Illuminate\Database\Eloquent\Collection|static[]
    // */
    //public virtual Collection<T> get(object columns = null)
    //{
    //    columns = columns ?? new object[]{ "*" };
    //    var builder = this.applyScopes();
    //    Model<T>[] models = builder.getModels(columns);
    //    // If we actually found models we will also eager load any relationships that
    //    // have been specified as needing to be eager loaded, which will solve the
    //    // n+1 query issue for the developers to avoid running a lot of queries.
    //    if (models.Length > 0) {
    //        models = builder.eagerLoadRelations(models);
    //    }
    //    return builder.getModel().newCollection(models);
    //}
    ///**
    // * Get a single column's value from the first result of a query.
    // *
    // * @param  string  $column
    // * @return mixed
    // */
    //public virtual object value(column)
    //{
    //    Model<T> result = this.first(new object[]{ column });
    //    if (result != null) {
    //        return result.getAttribute(column);
    //    }
    //}
    ///**
    // * Chunk the results of the query.
    // *
    // * @param  int  $count
    // * @param  callable  $callback
    // * @return bool
    // */
    //public virtual bool chunk(int count, Func<Collection<T>, bool> callback)
    //{
    //    int page = 1;
    //    Collection<T> results = this.forPage(page, count).get();
    //    while (results.Length > 0) {
    //        // On each chunk result set, we will pass them to the callback and then let the
    //        // developer take care of everything within the callback, which allows us to
    //        // keep the memory low for spinning through large result sets for working.
    //        if (callback(results) == false) {
    //            return false;
    //        }
    //        page++;
    //        results = this.forPage(page, count).get();
    //    }
    //    return true;
    //}
    ///**
    // * Execute a callback over each item while chunking.
    // *
    // * @param  callable  $callback
    // * @param  int  $count
    // * @return bool
    // */
    //public virtual bool each(Func<Model<T>, int, bool> callback, int count = 1000)
    //{
    //    if ((this._query._orders == null || this._query._orders.Length == 0) && (this._query._unionOrders == null || this._query._unionOrders.Length == 0)) {
    //        this._query.orderBy(this._model.getQualifiedKeyName(), "asc");
    //    }
    //    return this.chunk(count, (results) => {
    //        for (var i = 0; i < results.Length; i++) {
    //            if (callback(results[i], i) == false) {
    //                return false;
    //            }
    //        }
    //        return true;
    //    });
    //}
    ///**
    // * Get an array with the values of a given column.
    // *
    // * @param  string  $column
    // * @param  string|null  $key
    // * @return \Illuminate\Support\Collection
    // */
    //public virtual Collection<T> pluck(string column, string key = null)
    //{
    //    $results = $this->toBase()->pluck($column, $key);
    //    // If the model has a mutator for the requested column, we will spin through
    //    // the results and mutate the values so that the mutated version of these
    //    // columns are returned as you would expect from these Eloquent models.
    //    if ($this->model->hasGetMutator($column)) {
    //        foreach ($results as $key => &$value) {
    //            $fill = [$column => $value];
    //            $value = $this->model->newFromBuilder($fill)->$column;
    //        }
    //    }
    //    return collect($results);
    //}

    }
}


text:
/*
 * Shows the manifests and allows manipulation.
 *
 * @author Bram Gotink (@bgotink)
 * @license MIT
 */

import { ManifestMetaData } from 'ingress-identity';

import _ from 'lodash';

import * as comm from './communication';
import showAlert from './alerts';
import * as log from '../log';
import translate from '../auto-translate';

let lastOrderRecorded: string[] = [];

function onOrderChanged() {
  const newOrder: string[] = $.makeArray(
    $('#source_list > ul > li').map(function (): string {
      return $(this).attr('data-key');
    })
  );
  const { length } = lastOrderRecorded;
  let updated = false;

  if (newOrder.length !== length) {
    // abort, strange things are happening
    return;
  }

  for (let i = 0; i < length; i++) {
    if (newOrder[i] !== lastOrderRecorded[i]) {
      updated = true;
      break;
    }
  }

  if (updated) {
    comm.changeManifestOrder(lastOrderRecorded, newOrder, status => {
      showAlert(`reorder-${status}`);
    });

    lastOrderRecorded = newOrder;
  }
}

function reloadManifestErrors() {
  if ($('#source_list > ul').data('errors-loaded')) {
    return;
  }
  $('#source_list > ul').data('errors-loaded', true);

  log.log('Reloading manifest errors...');
  comm.getManifestErrors(result => {
    log.log('Got manifest errors:', result);

    reloadManifestErrorsHelper(result, $('#source_list > ul'))
  });
}

type Errors = string[] | { [s: string]: Errors };

function reloadManifestErrorsHelper(errors: Errors, $elem: JQuery) {
  if (Array.isArray(errors)) {
    $elem.find('> p.error').remove();

    errors.forEach(err => {
      if (err.match(/Sign in/i) && err.substr(0, 2) === '<a' && err.substr(-4) === '') {
        $elem.append($('
').append($(err)));
      } else {
        $elem.append($('
').text(err));
      }
    });
  } else {
    _.forEach(errors, (value: Errors, key: string) => {
      if (key === '.manifest' && (value as string[]).length && $elem.find('> .panel > .panel-body').length === 0) {
        $('
').insertBefore($elem.find('> .panel > .list-group'));
      }

      reloadManifestErrorsHelper(value, $elem.find(`[data-key="${key}"]`));
    });
  }
}

export function reloadManifests() {
  log.log('Reloading manifests...');
  comm.getManifests((result) => {
    const manifestList: JQuery[] = [];

    log.log('Got manifest info:', result);

    if (_.isEmpty(result)) {
      $('#source_list')
        .html('')
        .append(
          $('
')
            .text(translate('empty_1' /* 'No manifests loaded right now, try adding some!' */))
        )
        .append(
          $('
')
            .text(translate('empty_2' /* 'If you have just reloaded the extension, the manifests will automatically be shown here when the data is ready.' */))
        )
        .append(
          $('
')
            .text(translate('empty_3' /* 'If you believe this is in error, try reloading this page or pressing "Force reload".' */))
        );

      return;
    }

    _.forEach(result, (value) => {
      const sourceList: JQuery[] = [];
      const { key } = value;

      log.log('Manifest key %s', key);
      log.log(value);

      _.forEach(value.sources, (source, key) => {
        log.log('-- Source key %s', key);

        // Clean up info to show, in case the manifest is faulty
        source.faction = source.faction || 'unknown';
        source.count = source.count || 0;
        source.tag = source.tag || source.key;
        source.version = source.version || '0';

        sourceList.push(
          $('
')
            .addClass(`list-group-item source faction-${source.faction}`)
            .attr('data-key', key)
            .append(source.url
              ? $('').text(source.tag).attr('target', '_blank').attr('href', source.url)
              : $('').text(source.tag)
            )
            .append($('
').text(translate('manifest_info', source /* 'Faction: {faction}, {count} players, version {version}' */)))
        );
      });

      manifestList.push(
        $('
')
          .addClass('manifest')
          .data('key', key)
          .attr('data-key', key)
          .append(
            $('
')
              .append(
                $('
')
                  .append(
                    $('')
                      .append(
                        $('')
                          .text(typeof value.name === 'string' && value.name.trim().length ? value.name : key)
                          .addClass('manifest-key')
                      )
                  )
                  .append(
                    $('')
                      .addClass('buttons')
                      .append(value.url
                        ? $('')
                            .attr('aria-hidden', 'true')
                            .attr('title', translate('view' /* 'View' */))
                            .attr('href', value.url)
                            .attr('target', '_blank')
                            .addClass('link')
                            .append($(''))
                        : null
                      )
                      .append(
                        $('<button>')
                          .attr('type', 'button')
                          .attr('aria-hidden', 'true')
                          .attr('title', translate('rename' /* 'Rename' */))
                          .addClass('rename')
                          .append($(''))
                      )
                      .append(
                        $('<button>')
                          .attr('type', 'button')
                          .attr('aria-hidden', 'true')
                          .attr('title', translate('remove' /* 'Remove' */))
                          .addClass('remove')
                          .append($(''))
                      )
                  )
              )
              .append(
                $('
')
                  .addClass('list-group')
                  .append(sourceList)
              )
          )
      );
    });

    $('#source_list')
      .html('')
      .append(
        $('
')
          .addClass('list-unstyled')
          .append(manifestList)
      );
    $('#reload_sources').button('reset');

    lastOrderRecorded = $.makeArray(
      $('#source_list > ul > li').map(function () {
        return $(this).attr('data-key');
      })
    );

    $('#source_list > ul')
        .sortable({
            axis: 'y',
            containment: 'parent',
            handle: '.panel-heading',
            cursor: 'grabbing',
            distance: 5,
            revert: true,
            stop: onOrderChanged,
        });
    $('#source_list .panel-heading')
        .disableSelection();

    reloadManifestErrors();
  });
}

function addManifest() {
  const newManifest = $('#manifest_input').val().trim();
  if (newManifest === '') {
    return;
  }

  log.log('Adding manifest %s', newManifest);

  $('#manifest_input, #name_input').prop('disabled', true);
  $('button.manifest_add').button('loading');

  comm.addManifest(newManifest, $('#name_input').val(), result => {
    if (result !== 'failed') {
      $('#manifest_input').val('');
      $('#name_input').val('');
    }

    $('#manifest_input, #name_input').prop('disabled', false);
    $('button.manifest_add').button('reset');

    showAlert(`add-${result}`);
  });
}

export function initManifests() {
  $('button.manifest_add').on('click.ii.add', addManifest);
  $('form.manifest_add').on('submit.ii.add', _ => {
    addManifest();
    return false;
  });

  $('#source_list').on('click.ii.remove', '.manifest .remove', function () {
    comm.removeManifest($(this).closest('.manifest').data('key'), result => {
      showAlert(`remove-${result}`);
    });
  });

  $('#source_list').on('click.ii.rename', '.manifest .rename', function () {
    const $this = $(this);
    const $manifest = $this.closest('.manifest');
    const $key = $manifest.find('.manifest-key');

    if ($key.hasClass('form-control')) {
      // already done
      return;
    }

    log.log('Creating input to rename manifest %s', $key.text());
    let oldName = $key.text() === $manifest.data('key') ? '' : $key.text();

    $key.replaceWith(
      $('<input type="text" class="form-control manifest-key">')
        .val(oldName)
        .data('url', $key.prop('tagName') === 'A' ? $key.attr('href') : null)
        .on('keypress', function (e) {
          if (e.which !== 13) {
            return undefined;
          }

          const $this = $(this);
          const $manifest = $this.closest('.manifest');
          const key = $manifest.data('key');
          let newName: string = $this.val();

          if (oldName.trim() !== newName.trim()) {
            if (!newName.trim().length) {
              newName = null;
            }

            if (!oldName.trim().length) {
              oldName = null;
            }

            log.log('Renaming manifest %s from %s to %s', key, oldName, newName);
            comm.renameManifest(key, oldName, newName, status => {
              showAlert(`rename-${status}`);
            })
          }

          let $replacement: JQuery;
          if (typeof $this.data('url') === 'string') {
            $replacement = $('')
              .attr('href', $this.data('url'));
          } else {
            $replacement = $('
');
          }

          $replacement.text(newName || key)
            .addClass('manifest-key');

          $this.replaceWith($replacement);

          return false;
        })
    );
  });

  reloadManifests();
}


text:
package com.messageyes.facebook.messenger.bean;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import lombok.Data;

/**
 * StatusUpdate is a type of event that can be received in a {@link Callback} @{link Entry}. It represents
 * a status update of "delivered" or "read" on outbound message(s) sent to a user.
 *
 * https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-delivered
 * https://developers.facebook.com/docs/messenger-platform/webhook-reference/message-read
 */
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class StatusUpdate {
    /**
     * The list of messages to update may or may not be populated. If not, the watermark must be used.
     */
    private List<String> mids;

    private Long watermark;
    private Long seq;
}


text:
package us.feliscat.text.normalizer.en

import us.feliscat.text.StringOption

/**
 * @author K.Sakamoto
 *         Created on 15/10/28
 */
class EnglishNormalizedCharacter(private var character: Char) {
  character = EnglishNormalizer.normalize(StringOption(character.toString)).get.head

  def toChar: Char = {
    character
  }
}


text:
Matcha Framework
======

Matcha is a Java connector implementation for [Ext JS](http://sencha.com) supporting [Ext Direct](http://www.sencha.com/products/extjs/extdirect/) technology and providing utility classes allowing to communicate with [Ext.data.Store](http://docs.sencha.com/extjs/#!/api/Ext.data.Store), [Ext.grid.Panel](http://docs.sencha.com/extjs/#!/api/Ext.form.Panel), [Ext.form.Panel](http://docs.sencha.com/extjs/#!/api/Ext.form.Panel)...

Matcha uses the [JSR-330](https://jcp.org/en/jsr/detail?id=330) dependency injection as basis and, [Guice 3.0](https://code.google.com/p/google-guice/) and [Spring Framework 3.1.x](http://projects.spring.io/spring-framework/) as extension.

Matcha is a Java Maven project and is composed of four main modules:

* **matcha-api** module contains all classes allowing facilitate communication with the Ext JS client-side application.
* **matcha-direct**, **matcha-direct-guice**, **matcha-direct-spring** modules are a implementation of Ext Direct API for Ext JS. It is based on [directjngine](https://code.google.com/p/directjngine/) but proposes a better integration with different DI and HTTP server-side implementation as [Java Servlet API](http://www.oracle.com/technetwork/java/index-jsp-135475.html), [JAX-RS](https://jax-rs-spec.java.net/), [Restlet](http://restlet.org/), and simplify configuration, accepts form parameter multi values for example checkbox and so on.
* **matcha-example** module proposes different use cases and integration facilitating the understanding.
* **matcha-testing** is a module facilitating the unit testing or integration testing  creation.

## Continious Intergration

[![Build Status](https://travis-ci.org/devacfr/matcha.png)](https://travis-ci.org/devacfr/matcha)

## Contribution Policy

Contributions via GitHub pull requests are gladly accepted from their original author.
Along with any pull requests, please state that the contribution is your original work and
that you license the work to the project under the project's open source license.
Whether or not you state this explicitly, by submitting any copyrighted material via pull request,
email, or other means you agree to license the material under the project's open source license and
warrant that you have the legal authority to do so.

## Licence

This software uses the [ExtJs library](http://extjs.com), which is distributed under the GPL v3 license (see http://extjs.com/license).

	This software is licensed under the Apache 2 license, quoted below.

	Copyright 2014 Christophe Friederich

	Licensed under the Apache License, Version 2.0 (the "License"); you may not
	use this file except in compliance with the License. You may obtain a copy of
	the License at http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
	License for the specific language governing permissions and limitations under
	the License.

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/devacfr/matcha/trend.png)](https://bitdeli.com/free "Bitdeli Badge")


text:
package com.doomdev.fybersampel.data.util;

/**
 * This class contain static final attributes useing global in project
 * Created by and on 10.01.16.
 */
public interface Const {
    /**
     * Fyber Api Bae url
     **/
    String BASE_URL = "http://api.fyber.com/feed/v1/";
    /**
     * url suffix, to get offers in json format
     **/
    String FORMAT_JSON = "offers.json?";
    /**
     * complet url
     **/
    String FULL_URL = Const.BASE_URL + FORMAT_JSON;
    /**
     * This is custom header,where the original error message and code will be store
     **/
    String RESPONSE_HEADER_PARAM_ERROR_MESSAGE = "detail_error_message";
    /**
     * This is parameter in the custom header,where the error code will be store
     **/
    String RESPONSE_HEADER_PARAM_ERROR_MESSAGE_JSON_CODE = "code";
    /**
     * This is parameter in the custom header,where the error message will be store
     **/
    String RESPONSE_HEADER_PARAM_ERROR_MESSAGE_JSON_MESSAGE = "message";
    /**
     * the accept parameter application/json
     **/
    String ACCEPT_PARAM = "application/json";
    /**
     * the content parameter application/json
     **/
    String CONTENT_PARAM = "application/json";
}


text:
package com.mysql.jdbc.jdbc2.optional;

import java.lang.reflect.Constructor;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.XAConnection;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;

import com.mysql.jdbc.ConnectionImpl;
import com.mysql.jdbc.Constants;
import com.mysql.jdbc.Util;
import com.mysql.jdbc.log.Log;

/*
 * XA BEGIN <xid> [JOIN | RESUME] XA START TRANSACTION <xid> [JOIN | RESUME] XA
 * COMMIT <xid> [ONE PHASE] XA END <xid> [SUSPEND [FOR MIGRATE]] XA PREPARE
 * <xid> XA RECOVER XA ROLLBACK <xid>
 */

/**
 * An object that provides support for distributed transactions. An
 * XAConnection object may be enlisted in a distributed
 * transaction by means of an XAResource object. A transaction
 * manager, usually part of a middle tier server, manages an
 * XAConnection object through the XAResource
 * object.
 *

 * An application programmer does not use this interface directly; rather, it is
 * used by a transaction manager working in the middle tier server.
 *
 * @since 1.4
 */
public class MysqlXAConnection extends MysqlPooledConnection implements
		XAConnection, XAResource {
	private static my.Debug DEBUG=new my.Debug(my.Debug.MysqlDataSource);//我加上的

	private com.mysql.jdbc.ConnectionImpl underlyingConnection;

	private final static Map MYSQL_ERROR_CODES_TO_XA_ERROR_CODES;

	private Log log;

	protected boolean logXaCommands;

	static {
		HashMap temp = new HashMap();

		temp.put(Constants.integerValueOf(1397), Constants.integerValueOf(XAException.XAER_NOTA));
		temp.put(Constants.integerValueOf(1398), Constants.integerValueOf(XAException.XAER_INVAL));
		temp.put(Constants.integerValueOf(1399), Constants.integerValueOf(XAException.XAER_RMFAIL));
		temp.put(Constants.integerValueOf(1400), Constants.integerValueOf(XAException.XAER_OUTSIDE));
		temp.put(Constants.integerValueOf(1401), Constants.integerValueOf(XAException.XAER_RMERR));
		temp.put(Constants.integerValueOf(1402), Constants.integerValueOf(XAException.XA_RBROLLBACK));

		MYSQL_ERROR_CODES_TO_XA_ERROR_CODES = Collections.unmodifiableMap(temp);
	}

	private static final Constructor JDBC_4_XA_CONNECTION_WRAPPER_CTOR;

	static {
		if (Util.isJdbc4()) {
			try {
				JDBC_4_XA_CONNECTION_WRAPPER_CTOR = Class.forName(
						"com.mysql.jdbc.jdbc2.optional.JDBC4MysqlXAConnection")
						.getConstructor(
								new Class[] { ConnectionImpl.class, Boolean.TYPE });
			} catch (SecurityException e) {
				throw new RuntimeException(e);
			} catch (NoSuchMethodException e) {
				throw new RuntimeException(e);
			} catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
		} else {
			JDBC_4_XA_CONNECTION_WRAPPER_CTOR = null;
		}
	}

	protected static MysqlXAConnection getInstance(ConnectionImpl mysqlConnection,
			boolean logXaCommands) throws SQLException {
		try {//我加上的
		DEBUG.P(MysqlXAConnection.class,"getInstance(2)");
		DEBUG.P("logXaCommands="+logXaCommands);
		DEBUG.P("(!Util.isJdbc4())="+(!Util.isJdbc4()));

		if (!Util.isJdbc4()) {
			return new MysqlXAConnection(mysqlConnection, logXaCommands);
		}

		return (MysqlXAConnection) Util.handleNewInstance(
				JDBC_4_XA_CONNECTION_WRAPPER_CTOR, new Object[] {
						mysqlConnection,
						Boolean.valueOf(logXaCommands) }, mysqlConnection.getExceptionInterceptor());
		}finally{//我加上的
		DEBUG.P(0,MysqlXAConnection.class,"getInstance(2)");
		}
	}

	/**
	 * @param connection
	 */
	public MysqlXAConnection(ConnectionImpl connection, boolean logXaCommands)
			throws SQLException {
		super(connection);
		this.underlyingConnection = connection;
		this.log = connection.getLog();
		this.logXaCommands = logXaCommands;
	}

	/**
	 * Retrieves an XAResource object that the transaction
	 * manager will use to manage this XAConnection object's
	 * participation in a distributed transaction.
	 *
	 * @return the XAResource object
	 * @exception SQLException
	 *                if a database access error occurs
	 */
	public XAResource getXAResource() throws SQLException {
		return this;
	}

	/**
	 * Obtains the current transaction timeout value set for this XAResource
	 * instance. If XAResource.setTransactionTimeout was not used prior to
	 * invoking this method, the return value is the default timeout set for the
	 * resource manager; otherwise, the value used in the previous
	 * setTransactionTimeout call is returned.
	 *
	 * @return the transaction timeout value in seconds.
	 *
	 * @throws XAException
	 *             An error has occurred. Possible exception values are
	 *             XAER_RMERR and XAER_RMFAIL.
	 */
	public int getTransactionTimeout() throws XAException {
		return 0;
	}

	/**
	 * Sets the current transaction timeout value for this XAResource instance.
	 * Once set, this timeout value is effective until setTransactionTimeout is
	 * invoked again with a different value.
	 *
	 * To reset the timeout value to the default value used by the resource
	 * manager, set the value to zero. If the timeout operation is performed
	 * successfully, the method returns true; otherwise false.
	 *
	 * If a resource manager does not support explicitly setting the transaction
	 * timeout value, this method returns false.
	 *
	 * @parameter seconds The transaction timeout value in seconds.
	 *
	 * @return true if the transaction timeout value is set successfully;
	 *         otherwise false.
	 *
	 * @throws XAException
	 *             An error has occurred. Possible exception values are
	 *             XAER_RMERR, XAER_RMFAIL, or XAER_INVAL.
	 */
	public boolean setTransactionTimeout(int arg0) throws XAException {
		return false;
	}

	/**
	 * This method is called to determine if the resource manager instance
	 * represented by the target object is the same as the resouce manager
	 * instance represented by the parameter xares.
	 *
	 * @parameter xares An XAResource object whose resource manager instance is
	 *            to be compared with the resource manager instance of the
	 *            target object.
	 *
	 * @return true if it's the same RM instance; otherwise false.
	 *
	 * @throws XAException
	 *             An error has occurred. Possible exception values are
	 *             XAER_RMERR and XAER_RMFAIL.
	 */
	//RM是resource manager的缩写
	public boolean isSameRM(XAResource xares) throws XAException {

		if (xares instanceof MysqlXAConnection) {
			return this.underlyingConnection
					.isSameResource(((MysqlXAConnection) xares).underlyingConnection);
		}

		return false;
	}

	/**
	 * This method is called to obtain a list of prepared transaction branches
	 * from a resource manager. The transaction manager calls this method during
	 * recovery to obtain the list of transaction branches that are currently in
	 * prepared or heuristically completed states.
	 *
	 * The flag parameter indicates where the recover scan should start or end,
	 * or start and end. This method may be invoked one or more times during a
	 * recovery scan. The resource manager maintains a cursor which marks the
	 * current position of the prepared or heuristically completed transaction list.
	 * Each invocation of the recover method moves the cursor passed the set of Xids
	 * that are returned.
	 *
	 * Two consecutive invocation of this method that starts from the
	 * beginning of the list must return the same list of transaction branches
	 * unless one of the following takes place:
	 *
	 * - the transaction manager invokes the commit, forget, prepare, or rollback method for that resource
	 * manager, between the two consecutive invocation of the recovery scan.
	 *
	 * - the resource manager heuristically completes some transaction branches
	 * between the two invocation of the recovery scan.
	 *
	 * @param flag
	 *            One of TMSTARTRSCAN, TMENDRSCAN, TMNOFLAGS. TMNOFLAGS must be
	 *            used when no other flags are set in the parameter.
	 *
	 * @returns The resource manager returns zero or more XIDs of the
	 *          transaction branches that are currently in a prepared or
	 *          heuristically completed state. If an error occurs during the
	 *          operation, the resource manager should throw the appropriate
	 *          XAException.
	 *
	 * @throws XAException
	 *             An error has occurred. Possible values are XAER_RMERR,
	 *             XAER_RMFAIL, XAER_INVAL, and XAER_PROTO.
	 */
	public Xid[] recover(int flag) throws XAException {
		return recover(this.underlyingConnection, flag);
	}

	protected static Xid[] recover(Connection c, int flag) throws XAException {
		/*
		    The XA RECOVER statement returns information for those XA transactions on the MySQL server that are in the PREPARED state. (See Section 13.4.7.2, �XA Transaction States�.) The output includes a row for each such XA transaction on the server, regardless of which client started it.

			XA RECOVER output rows look like this (for an example xid value consisting of the parts 'abc', 'def', and 7):

			mysql> XA RECOVER;
			+----------+--------------+--------------+--------+
			| formatID | gtrid_length | bqual_length | data   |
			+----------+--------------+--------------+--------+
			|        7 |            3 |            3 | abcdef |
			+----------+--------------+--------------+--------+

			The output columns have the following meanings:

      			formatID is the formatID part of the transaction xid
			    gtrid_length is the length in bytes of the gtrid part of the xid
			    bqual_length is the length in bytes of the bqual part of the xid
 			    data is the concatenation of the gtrid and bqual parts of the xid
		 */

		boolean startRscan = ((flag & TMSTARTRSCAN) > 0);
		boolean endRscan = ((flag & TMENDRSCAN) > 0);

		if (!startRscan && !endRscan && flag != TMNOFLAGS) {
			throw new MysqlXAException(XAException.XAER_INVAL,
					"Invalid flag, must use TMNOFLAGS, or any combination of TMSTARTRSCAN and TMENDRSCAN",
					null);
		}

		//
		// We return all recovered XIDs at once, so if not
		// TMSTARTRSCAN, return no new XIDs
		//
		// We don't attempt to maintain state to check for TMNOFLAGS
		// "outside" of a scan
		//

		if (!startRscan) {
			return new Xid[0];
		}

		ResultSet rs = null;
		Statement stmt = null;

		List recoveredXidList = new ArrayList();

		try {
			// TODO: Cache this for lifetime of XAConnection
			stmt = c.createStatement();

			rs = stmt.executeQuery("XA RECOVER");

			while (rs.next()) {
				final int formatId = rs.getInt(1);
				int gtridLength = rs.getInt(2);
				int bqualLength = rs.getInt(3);
				byte[] gtridAndBqual = rs.getBytes(4);

				final byte[] gtrid = new byte[gtridLength];
				final byte[] bqual = new byte[bqualLength];

				if (gtridAndBqual.length != (gtridLength + bqualLength)) {
					throw new MysqlXAException(XAException.XA_RBPROTO,
							"Error while recovering XIDs from RM. GTRID and BQUAL are wrong sizes",
							null);
				}

				System.arraycopy(gtridAndBqual, 0, gtrid, 0,
						gtridLength);
				System.arraycopy(gtridAndBqual, gtridLength, bqual, 0,
						bqualLength);

				recoveredXidList.add(new MysqlXid(gtrid, bqual,
						formatId));
			}
		} catch (SQLException sqlEx) {
			throw mapXAExceptionFromSQLException(sqlEx);
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException sqlEx) {
					throw mapXAExceptionFromSQLException(sqlEx);
				}
			}

			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException sqlEx) {
					throw mapXAExceptionFromSQLException(sqlEx);
				}
			}
		}

		int numXids = recoveredXidList.size();

		Xid[] asXids = new Xid[numXids];
		Object[] asObjects = recoveredXidList.toArray();

		for (int i = 0; i < numXids; i++) {
			asXids[i] = (Xid) asObjects[i];
		}

		return asXids;
	}

	/**
	 * Asks the resource manager to prepare for a transaction commit of the
	 * transaction specified in xid.
	 *
	 * @parameter xid A global transaction identifier.
	 *
	 * @returns A value indicating the resource manager's vote on the outcome of
	 *          the transaction.
	 *
	 * The possible values are: XA_RDONLY or XA_OK. If the resource manager
	 * wants to roll back the transaction, it should do so by raising an
	 * appropriate XAException in the prepare method.
	 *
	 * @throws XAException
	 *             An error has occurred. Possible exception values are: XA_RB*,
	 *             XAER_RMERR, XAER_RMFAIL, XAER_NOTA, XAER_INVAL, or
	 *             XAER_PROTO.
	 */
	public int prepare(Xid xid) throws XAException {
		StringBuffer commandBuf = new StringBuffer();
		commandBuf.append("XA PREPARE ");
		commandBuf.append(xidToString(xid));

		dispatchCommand(commandBuf.toString());

		return XA_OK; // TODO: Check for read-only
	}

	/**
	 * Tells the resource manager to forget about a heuristically completed
	 * transaction branch.
	 *
	 * @parameter xid A global transaction identifier.
	 *
	 * @throws XAException
	 *             An error has occurred. Possible exception values are
	 *             XAER_RMERR, XAER_RMFAIL, XAER_NOTA, XAER_INVAL, or
	 *             XAER_PROTO.
	 */
	public void forget(Xid xid) throws XAException {
		// mysql doesn't support this
	}

	/**
	 * Informs the resource manager to roll back work done on behalf of a
	 * transaction branch.
	 *
	 * @parameter xid A global transaction identifier.
	 *
	 * @throws XAException
	 *             An error has occurred. Possible XAExceptions are XA_HEURHAZ,
	 *             XA_HEURCOM, XA_HEURRB, XA_HEURMIX, XAER_RMERR, XAER_RMFAIL,
	 *             XAER_NOTA, XAER_INVAL, or XAER_PROTO.
	 *
	 * If the transaction branch is already marked rollback-only the resource
	 * manager may throw one of the XA_RB* exceptions.
	 *
	 * Upon return, the resource manager has rolled back the branch's work and
	 * has released all held resources.
	 */
	public void rollback(Xid xid) throws XAException {
		StringBuffer commandBuf = new StringBuffer();
		commandBuf.append("XA ROLLBACK ");
		commandBuf.append(xidToString(xid));

		try {
			dispatchCommand(commandBuf.toString());
		} finally {
			this.underlyingConnection.setInGlobalTx(false);
		}
	}

	/**
	 * Ends the work performed on behalf of a transaction branch.
	 *
	 * The resource manager disassociates the XA resource from the transaction
	 * branch specified and lets the transaction complete.
	 *
	 * If TMSUSPEND is specified in the flags, the transaction branch is
	 * temporarily suspended in an incomplete state. The transaction context is
	 * in a suspended state and must be resumed via the start method with
	 * TMRESUME specified.
	 *
	 * If TMFAIL is specified, the portion of work has failed. The resource
	 * manager may mark the transaction as rollback-only
	 *
	 * If TMSUCCESS is specified, the portion of work has completed
	 * successfully.
	 *
	 * @parameter xid A global transaction identifier that is the same as the
	 *            identifier used previously in the start method.
	 *
	 * @parameter flags One of TMSUCCESS, TMFAIL, or TMSUSPEND.
	 *
	 * @throws XAException -
	 *             An error has occurred. Possible XAException values are
	 *             XAER_RMERR, XAER_RMFAIL, XAER_NOTA, XAER_INVAL, XAER_PROTO,
	 *             or XA_RB*.
	 */
	public void end(Xid xid, int flags) throws XAException {
		StringBuffer commandBuf = new StringBuffer();
		commandBuf.append("XA END ");
		commandBuf.append(xidToString(xid));

		switch (flags) {
		case TMSUCCESS:
			break; // no-op
		case TMSUSPEND:
			commandBuf.append(" SUSPEND");
			break;
		case TMFAIL:
			break; // no-op
		default:
			throw new XAException(XAException.XAER_INVAL);
		}

		dispatchCommand(commandBuf.toString());
	}

	/**
	 * Starts work on behalf of a transaction branch specified in xid.
	 *
	 * If TMJOIN is specified, the start applies to joining a transaction
	 * previously seen by the resource manager.
	 *
	 * If TMRESUME is specified, the start applies to resuming a suspended
	 * transaction specified in the parameter xid.
	 *
	 * If neither TMJOIN nor TMRESUME is specified and the transaction specified
	 * by xid has previously been seen by the resource manager, the resource
	 * manager throws the XAException exception with XAER_DUPID error code.
	 *
	 * @parameter xid A global transaction identifier to be associated with the
	 *            resource.
	 *
	 * @parameter flags One of TMNOFLAGS, TMJOIN, or TMRESUME.
	 *
	 * @throws XAException
	 *             An error has occurred. Possible exceptions are XA_RB*,
	 *             XAER_RMERR, XAER_RMFAIL, XAER_DUPID, XAER_OUTSIDE, XAER_NOTA,
	 *             XAER_INVAL, or XAER_PROTO.
	 */
	public void start(Xid xid, int flags) throws XAException {
		try {//我加上的
		DEBUG.P(this,"start(2)");
		DEBUG.P("xid="+xid);
		DEBUG.P("flags="+flags);

		StringBuffer commandBuf = new StringBuffer();
		commandBuf.append("XA START ");
		commandBuf.append(xidToString(xid));

		switch (flags) {
		case TMJOIN:
			commandBuf.append(" JOIN");
			break;
		case TMRESUME:
			commandBuf.append(" RESUME");
			break;
		case TMNOFLAGS:
			// no-op
			break;
		default:
			throw new XAException(XAException.XAER_INVAL);
		}

		DEBUG.P("commandBuf="+commandBuf);

		dispatchCommand(commandBuf.toString());

		this.underlyingConnection.setInGlobalTx(true);

		}finally{//我加上的
		DEBUG.P(0,this,"start(2)");
		}
	}

	/**
	 * Commits the global transaction specified by xid.
	 *
	 * @parameter xid A global transaction identifier
	 * @parameter onePhase - If true, the resource manager should use a
	 *            one-phase commit protocol to commit the work done on behalf of
	 *            xid.
	 *
	 * @throws XAException
	 *             An error has occurred. Possible XAExceptions are XA_HEURHAZ,
	 *             XA_HEURCOM, XA_HEURRB, XA_HEURMIX, XAER_RMERR, XAER_RMFAIL,
	 *             XAER_NOTA, XAER_INVAL, or XAER_PROTO.
	 *
	 * If the resource manager did not commit the transaction and the parameter
	 * onePhase is set to true, the resource manager may throw one of the XA_RB*
	 * exceptions.
	 *
	 * Upon return, the resource manager has rolled back the branch's work and
	 * has released all held resources.
	 */

	public void commit(Xid xid, boolean onePhase) throws XAException {
		StringBuffer commandBuf = new StringBuffer();
		commandBuf.append("XA COMMIT ");
		commandBuf.append(xidToString(xid));

		if (onePhase) {
			commandBuf.append(" ONE PHASE");
		}

		try {
			dispatchCommand(commandBuf.toString());
		} finally {
			this.underlyingConnection.setInGlobalTx(false);
		}
	}

	private ResultSet dispatchCommand(String command) throws XAException {
		Statement stmt = null;

		try {
			if (this.logXaCommands) {
				this.log.logDebug("Executing XA statement: " + command);
			}

			// TODO: Cache this for lifetime of XAConnection
			stmt = this.underlyingConnection.createStatement();

			stmt.execute(command);

			ResultSet rs = stmt.getResultSet();

			return rs;
		} catch (SQLException sqlEx) {
			throw mapXAExceptionFromSQLException(sqlEx);
		} finally {
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException sqlEx) {
				}
			}
		}
	}

	protected static XAException mapXAExceptionFromSQLException(SQLException sqlEx) {

		Integer xaCode = (Integer) MYSQL_ERROR_CODES_TO_XA_ERROR_CODES
				.get(Constants.integerValueOf(sqlEx.getErrorCode()));

		if (xaCode != null) {
			return new MysqlXAException(xaCode.intValue(), sqlEx.getMessage(), null);
		}

		// Punt? We don't know what the error code is here
		return new MysqlXAException(sqlEx.getMessage(), null);
	}

	private static String xidToString(Xid xid) {
		byte[] gtrid = xid.getGlobalTransactionId();

		byte[] btrid = xid.getBranchQualifier();

		int lengthAsString = 6; // for (0x and ,) * 2

		if (gtrid != null) {
			lengthAsString += (2 * gtrid.length);
		}

		if (btrid != null) {
			lengthAsString += (2 * btrid.length);
		}

		String formatIdInHex = Integer.toHexString(xid.getFormatId());

		lengthAsString += formatIdInHex.length();
		lengthAsString += 3; // for the '.' after formatId

		StringBuffer asString = new StringBuffer(lengthAsString);

		asString.append("0x");

		if (gtrid != null) {
			for (int i = 0; i < gtrid.length; i++) {
				String asHex = Integer.toHexString(gtrid[i] & 0xff);

				if (asHex.length() == 1) {
					asString.append("0");
				}

				asString.append(asHex);
			}
		}

		asString.append(",");

		if (btrid != null) {
			asString.append("0x");

			for (int i = 0; i < btrid.length; i++) {
				String asHex = Integer.toHexString(btrid[i] & 0xff);

				if (asHex.length() == 1) {
					asString.append("0");
				}

				asString.append(asHex);
			}
		}

		asString.append(",0x");
		asString.append(formatIdInHex);

		return asString.toString();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.sql.PooledConnection#getConnection()
	 */
	public synchronized Connection getConnection() throws SQLException {
		Connection connToWrap = getConnection(false, true);

		return connToWrap;
	}
}


text:
Your Account

User Information

      Here you can look up and change your account information. You can change all information but
      your username. At the bottom of the page you can delete your account permanently.

    <form name="userForm">

          Username
          <input class="form-control" type="text" id="username" ng-model="user.username"
                 ng-init="user.username=account.data.username" readonly>

          Name
          <input class="form-control" type="text" id="name" placeholder="Enter your name"
                 ng-model="user.name">

          Date of Birth
          <input class="form-control" type="date" id="dob" placeholder="Format DD.MM.YYYY"
                 ng-model="user.dob">

          E-Mail
          <input class="form-control" type="email" id="email" placeholder="Enter your email"
                 ng-model="user.email">

          Password
          <input class="form-control" type="password" id="password"
                 placeholder="Enter password" ng-model="user.password">

          Confirm Password
          <input class="form-control" type="password" id="confirmPW"
                 placeholder="Enter password. Again..." ng-model="user.confirmPW">

      <button class="btn btn-default col-md-2 col-sm-3 col-xs-12" ng-click="updateUser()">Update
        Info
      </button>
    </form>

Delete Account

      If you click this button your account will be permanently deleted. You will not be prompted
      any confirmation requests.

    <button class="btn btn-danger col-md-2 col-sm-3 col-xs-12" ng-click="deleteUser()">Delete User
    </button>


text:
<%-
@entity = MDWA::DSL.entity('Endereco')
@model = @entity.generator_model
-%>
module A::EnderecosHelper
end


text:
@interface DownloadableContentStoreAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
    UIWindow *window;
    UITabBarController *tabBarController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;

- (void)windowDidBecomeHidden:(UIWindow *)hiddenWindow;

@end


text:
require 'rubygems'
require 'forwardable'

module Nytimes
	module Articles
		##
		# The ResultSet is returned by Article#search and contains an array of up to 10 results out of the total matches. For your convenience, this
		# object provides a selection of array methods on the underlying collection of articles.
		class ResultSet < Base
			extend Forwardable

			##
			# The offset of the result_set. Note that this is essentially the ordinal position of the batch among all results. First 10 results are offset
			# 0, the next 10 are offset 1, etc.
			attr_reader :offset

			##
			# The total results that matched the query.
			attr_reader :total_results

			##
			# The results array of articles returned. Note that if you call Articles#find with :fields => :none, this will return nil even if
			# there are matching results.
			attr_reader :results

			##
			# If you have specified a list of <tt>:facets</tt> for Article#search, they will be returned in a hash keyed by the facet name here.
			attr_reader :facets

			BATCH_SIZE = 10

			def_delegators :@results, :&, :*, :+, :-, :[], :at, :collect, :compact, :each, :each_index, :empty?, :fetch, :first, :include?, :index, :last, :length, :map, :nitems, :reject, :reverse, :reverse_each, :rindex, :select, :size, :slice

			def initialize(params)
				@offset = params[:offset]
				@total_results = params[:total_results]
				@results = params[:results]
				@facets = FacetHash.init_from_api(params[:facets])
			end

			##
			# For your convenience, the page_number method is an alternate version of #offset that counts up from 1.
			def page_number
				return 0 if @total_results == 0
				@offset + 1
			end

			##
			# Calculates the total number of pages in the results based on the standard batch size and total results.
			def total_pages
				return 0 if @total_results == 0
				(@total_results.to_f / BATCH_SIZE).ceil
			end

			##
			# Used to initialize a new result_set from Article#search.
			def self.init_from_api(api_hash)
				self.new(:offset => integer_field(api_hash['offset']),
								 :total_results => integer_field(api_hash['total']),
								 :results => api_hash['results'].map {|r| Article.init_from_api(r)},
								 :facets => Facet.init_from_api(api_hash['facets'])
								)
			end
		end
	end
end


text:
#include <Inventor/scxml/ScXMLTransitionElt.h>

/*!
  \class ScXMLTransitionElt ScXMLTransitionElt.h Inventor/scxml/ScXMLTransitionElt.h
  \brief the \c <transition> SCXML element.

  The \c <transition> element is used for invoking executable code
  and transition from the current active states in a state machine to a
  new set of active states.

  By plural active states, it is meant that all the parent states of active
  states are also active at the same time, which is helpful when organizing
  common event triggered \c <transition> transitions.  Putting transitions
  in the root \c <scxml> element means that they are always active.

  You also have the concept of parallel states in SCXML. This is not \a yet
  supported in Coin SCXML.

  The following attributes are accepted:
  \li \c event
  \li \c cond
  \li \c target
  \li \c anchor - not supported

  The \c event attribute specifies the event that the transition will trigger
  for, if the \c <transition> element is in an active state.  The \a
  event attribute can be specified with wildcard matching using \c "*", but
  with the following restrictions:
  \li \c "*" must be at the end of the event name match.
  \li \c "*" must match full dot-separated words.

  Example 1: \c event="*"

  Example 2: \c event="error.*"

  The \c cond attribute can be used to specify additional conditions that must
  be met for the \c <transition> to be triggered.  The condition
  expression language depends on which profile the SCXML state machine uses.

  The \c "minimum" profile only specifies one function, which is the
  \c In({ID}) function.  In() evaluates to TRUE if the state machine is
  currently in the state with the given ID.

  The \c "x-coin" profile implements a number of expressions that evaluates to
  a truth value.  While in development, documenting the expression language
  seems like too much overhead, so that part will have to wait.  The source
  code can do the talking.  See Coin/src/scxml/eval-coin-tab.y.

  The \c target attribute specifies the target states to transition to.  If
  parallel states had been implemented, you would be able to specify multiple
  states in this attribute, but for now you can only specify one target state.
  If \c target is dropped, then the transition does not change what the active
  state is and will just execute the executable parts it contains.  If
  \c target is the \c id of the \c state the \c <transition> is in, the
  state will be left/exited and then reentered again.  For active substates,
  this means they will also be exited of course.

  The \c anchor attribute is not supported.

  \c <transition> elements can contain executable SCXML elements as
  XML children, meaning \c <if> /\c <elseif> / \c <else>,
  \c <assign>, \c <send>, \c <event>, \c <log>.

  \since Coin 3.0
  \sa ScXMLIfElt, ScXMLAssignElt, ScXMLSendElt, ScXMLEventElt, ScXMLLogElt
  \ingroup scxml
*/

#include <cassert>
#include <cstring>
#include <algorithm>
#include <vector>

#include <boost/scoped_ptr.hpp>

#include <Inventor/errors/SoDebugError.h>
#include <Inventor/C/XML/element.h>
#include <Inventor/scxml/ScXML.h>
#include <Inventor/scxml/ScXMLEvent.h>
#include <Inventor/scxml/ScXMLStateMachine.h>
#include <Inventor/scxml/ScXMLLogElt.h>
#include <Inventor/scxml/ScXMLSendElt.h>
#include <Inventor/scxml/ScXMLAssignElt.h>
#include <Inventor/scxml/ScXMLEventElt.h>
#include <Inventor/scxml/ScXMLIfElt.h>
#include <Inventor/scxml/ScXMLScriptElt.h>
#include <Inventor/scxml/ScXMLInvokeElt.h>
#include <Inventor/scxml/ScXMLEvaluator.h>

#include "scxml/ScXMLCommonP.h"
#include "SbBasicP.h"

// *************************************************************************

class ScXMLTransitionEltReader : public ScXMLEltReader {
public:
  ScXMLTransitionEltReader(void);
  virtual ScXMLElt * read(ScXMLElt * container, cc_xml_elt * xmlelt, ScXMLDocument * doc, ScXMLStateMachine * sm);
};

ScXMLTransitionEltReader::ScXMLTransitionEltReader(void)
: ScXMLEltReader("transition")
{
}

ScXMLElt *
ScXMLTransitionEltReader::read(ScXMLElt * container, cc_xml_elt * xmlelt, ScXMLDocument * doc, ScXMLStateMachine * sm)
{
  assert(container && xmlelt);
  ScXMLTransitionElt * transition = new ScXMLTransitionElt;
  transition->setContainer(container);
  this->setXMLAttributes(transition, xmlelt);

  // handle XML attributes
  if (unlikely(!transition->handleXMLAttributes())) {
    delete transition;
    return NULL;
  }

  const int numchildren = cc_xml_elt_get_num_children(xmlelt);
  for (int c = 0; c < numchildren; ++c) {
    cc_xml_elt * element = cc_xml_elt_get_child(xmlelt, c);
    const char * elementtype = cc_xml_elt_get_type(element);

    if (strcmp(elementtype, COIN_XML_CDATA_TYPE) == 0) {
      // ignore CDATA
      continue;
    }

    if (strcmp(elementtype, "log") == 0) {
      // <log> - zero or more times
      ScXMLEltReader * logreader = ScXMLLogElt::getElementReader();
      assert(logreader);
      ScXMLElt * logobj = logreader->read(transition, element, doc, sm);
      if (unlikely(!logobj)) {
        delete transition;
        return NULL;
      }
      assert(logobj->isOfType(ScXMLLogElt::getClassTypeId()));
      transition->addExecutable(static_cast<ScXMLLogElt *>(logobj));
    }
    else if (strcmp(elementtype, "event") == 0) {
      // <event> - zero or more times
      ScXMLEltReader * eventreader = ScXMLEventElt::getElementReader();
      assert(eventreader);
      ScXMLElt * eventobj = eventreader->read(transition, element, doc, sm);
      if (unlikely(!eventobj)) {
        delete transition;
        return NULL;
      }
      assert(eventobj->isOfType(ScXMLEventElt::getClassTypeId()));
      transition->addExecutable(static_cast<ScXMLEventElt *>(eventobj));
    }
    else if (strcmp(elementtype, "assign") == 0) {
      // <assign> - zero or more times
      ScXMLEltReader * assignreader = ScXMLAssignElt::getElementReader();
      assert(assignreader);
      ScXMLElt * assignobj = assignreader->read(transition, element, doc, sm);
      if (unlikely(!assignobj)) {
        delete transition;
        return NULL;
      }
      assert(assignobj->isOfType(ScXMLAssignElt::getClassTypeId()));
      transition->addExecutable(static_cast<ScXMLAssignElt *>(assignobj));
    }
    else if (strcmp(elementtype, "send") == 0) {
      // <send> - zero or more times
      ScXMLEltReader * sendreader = ScXMLSendElt::getElementReader();
      assert(sendreader);
      ScXMLElt * sendobj = sendreader->read(transition, element, doc, sm);
      if (unlikely(!sendobj)) {
        delete transition;
        return NULL;
      }
      assert(sendobj->isOfType(ScXMLSendElt::getClassTypeId()));
      transition->addExecutable(static_cast<ScXMLSendElt *>(sendobj));
    }
    else if (strcmp(elementtype, "if") == 0) {
      // <if> - zero or more times
      ScXMLEltReader * ifreader = ScXMLIfElt::getElementReader();
      assert(ifreader);
      ScXMLElt * ifobj = ifreader->read(transition, element, doc, sm);
      if (unlikely(!ifobj)) {
        delete transition;
        return NULL;
      }
      assert(ifobj->isOfType(ScXMLIfElt::getClassTypeId()));
      transition->addExecutable(static_cast<ScXMLIfElt *>(ifobj));
    }
    else if (strcmp(elementtype, "script") == 0) {
      // <script> - zero or more times
      ScXMLEltReader * scriptreader = ScXMLScriptElt::getElementReader();
      assert(scriptreader);
      ScXMLElt * scriptobj = scriptreader->read(transition, element, doc, sm);
      if (unlikely(!scriptobj)) {
        delete transition;
        return NULL;
      }
      assert(scriptobj->isOfType(ScXMLScriptElt::getClassTypeId()));
      transition->addExecutable(static_cast<ScXMLScriptElt *>(scriptobj));
    }
    else if (strcmp(elementtype, "invoke") == 0) {
      // <invoke> - zero or more times
      ScXMLEltReader * invokereader = ScXMLInvokeElt::getElementReader();
      assert(invokereader);
      ScXMLElt * invokeobj = invokereader->read(transition, element, doc, sm);
      if (unlikely(!invokeobj)) {
        delete transition;
        return NULL;
      }
      assert(invokeobj->isOfType(ScXMLInvokeElt::getClassTypeId()));
      transition->addExecutable(static_cast<ScXMLInvokeElt *>(invokeobj));
    }
    else {
      SoDebugError::post("ScXMLTransitionEltReader::read",
                         "unexpected XML element '<%s>' found in <transition>",
                         elementtype);
      delete transition;
      return NULL;
    }
  }
  return transition;
} // read

// *************************************************************************

class ScXMLTransitionElt::PImpl {
public:
  PImpl(void) { }
  ~PImpl(void)
  {
    SCXML__CLEAR_STD_VECTOR(this->executablelist, ScXMLExecutableElt *);
  }

  std::vector<ScXMLExecutableElt *> executablelist;
};

#define PRIVATE(obj) ((obj)->pimpl)

SCXML_ELEMENT_SOURCE(ScXMLTransitionElt);

void
ScXMLTransitionElt::initClass(void)
{
  SCXML_OBJECT_INIT_CLASS(ScXMLTransitionElt, ScXMLElt, "ScXMLElt");
  SCXML_ELEMENT_REGISTER_READER(ScXMLTransitionElt, "transition", ScXMLTransitionEltReader);
}

void
ScXMLTransitionElt::cleanClass(void)
{
  SCXML_ELEMENT_UNREGISTER_READER(ScXMLTransitionElt);
  ScXMLTransitionElt::classTypeId = SoType::badType();
}

ScXMLTransitionElt::ScXMLTransitionElt(void)
: event(NULL),
  cond(NULL),
  target(NULL),
  anchor(NULL),
  needprefixmatching(FALSE),
  eventkey(SbName::empty()),
  targetkey(SbName::empty())
{
}

ScXMLTransitionElt::~ScXMLTransitionElt(void)
{
  this->setEventAttribute(NULL);
  this->setCondAttribute(NULL);
  this->setTargetAttribute(NULL);
  this->setAnchorAttribute(NULL);
}

void
ScXMLTransitionElt::setEventAttribute(const char * eventstr)
{
  if (this->event && this->event != this->getXMLAttribute("event")) {
    delete [] this->event;
  }
  this->event = NULL;
  this->eventkey = SbName::empty();
  this->needprefixmatching = FALSE;

  if (eventstr) {
    // You can do *-matching on event identifiers in transitions.
    // According to the spec., the allowed thing to do is to let the
    // event attribute _end_ with ".*", which should match zero or
    // more succeeding tokens - we need in other words not implement
    // any form of generic pattern matching here...
    const char * ptr = strstr(eventstr, ".*");
    if ((ptr != NULL) && (strlen(ptr) == 2)) {
      this->needprefixmatching = TRUE;
      // we'll chop off the pattern matching key and use the boolean
      const int len = strlen(eventstr) - 1;
      this->event = new char [ len ];
      strncpy(this->event, eventstr, len - 1);
      this->event[ len - 1 ] = '\0';
      this->eventkey = this->event;
    } else {
      this->event = new char [ strlen(eventstr) + 1 ];
      strcpy(this->event, eventstr);
      this->eventkey = this->event;
    }
  }
}

// const char * ScXMLTransition::getEventAttribute(void) const

void
ScXMLTransitionElt::setCondAttribute(const char * condstr)
{
  SCXML__SET_ATTRIBUTE_VALUE(this->cond, "cond", condstr);
}

// const char * ScXMLTransition::getCondAttribute(void) const

void
ScXMLTransitionElt::setTargetAttribute(const char * targetstr)
{
  SCXML__SET_ATTRIBUTE_VALUE(this->target, "target", targetstr);
}

// const char * ScXMLTransition::getTargetAttribute(void) const

void
ScXMLTransitionElt::setAnchorAttribute(const char * anchorstr)
{
  SCXML__SET_ATTRIBUTE_VALUE(this->anchor, "anchor", anchorstr);
}

// const char * ScXMLTransition::getAnchorAttribute(void) const

SbBool
ScXMLTransitionElt::handleXMLAttributes(void)
{
  if (!inherited::handleXMLAttributes()) return FALSE;

  this->setEventAttribute(this->getXMLAttribute("event"));
  this->setCondAttribute(this->getXMLAttribute("cond"));
  this->setTargetAttribute(this->getXMLAttribute("target"));
  this->setAnchorAttribute(this->getXMLAttribute("anchor"));

  if (this->target && this->anchor) {
    SoDebugError::post("ScXMLTransitionElt::handleXMLAttributes",
                       "only one of 'target' and 'anchor' may be specified at once");

    return FALSE;
  }

  return TRUE;
}

void
ScXMLTransitionElt::copyContents(const ScXMLElt * rhs)
{
  inherited::copyContents(rhs);
  const ScXMLTransitionElt * orig = coin_assert_cast<const ScXMLTransitionElt *>(rhs);
  this->setEventAttribute(orig->getEventAttribute());
  this->setCondAttribute(orig->getCondAttribute());
  this->setTargetAttribute(orig->getTargetAttribute());
  this->setAnchorAttribute(orig->getAnchorAttribute());
  int c = 0;
  for (c = 0; c < orig->getNumExecutables(); ++c) {
    ScXMLExecutableElt * executable =
      coin_assert_cast<ScXMLExecutableElt *>(orig->getExecutable(c)->clone());
    this->addExecutable(executable);
  }
}

const ScXMLElt *
ScXMLTransitionElt::search(const char * attrname, const char * attrvalue) const
{
  const ScXMLElt * hit = inherited::search(attrname, attrvalue);
  if (hit) {
    return hit;
  }
  if (strcmp(attrname, "event") == 0) {
    if (this->event && strcmp(attrvalue, this->event) == 0) {
      return this;
    }
  }
  else if (strcmp(attrname, "cond") == 0) {
    if (this->cond && strcmp(attrvalue, this->cond) == 0) {
      return this;
    }
  }
  else if (strcmp(attrname, "target") == 0) {
    if (this->target && strcmp(attrvalue, this->target) == 0) {
      return this;
    }
  }
  else if (strcmp(attrname, "anchor") == 0) {
    if (this->anchor && strcmp(attrvalue, this->anchor) == 0) {
      return this;
    }
  }
  return NULL;
}

/*!
  Returns whether this is a conditionless SCXML transition or not.

  A conditionless transition should always be taken.
*/

SbBool
ScXMLTransitionElt::isConditionLess(void) const
{
  if (this->cond == NULL) return TRUE;
  if (strlen(this->cond) == 0) return TRUE;
  return FALSE;
}

/*!
  Returns whether this is a transition without a target setting or not.

  When a targetless transition is taken, the state machine's state
  does not change. This differs from setting the target to its own
  state, which will cause the state machine to leave the state and
  reenter it again.
*/

SbBool
ScXMLTransitionElt::isTargetLess(void) const
{
  return (this->target == NULL);
}

/*!
  Returns whether this transition is referencing its container or not.

  If TRUE, this means you should end up in the same state as you
  started with when doing this transition.  Note however that as
  opposed to a targetless transition, this transition should actually
  exit the state and then reenter it again.  Executable content will
  be invoked after exiting the state, before reentering.
*/

SbBool
ScXMLTransitionElt::isSelfReferencing(void) const
{
  if (this->target != NULL && this->getContainer()) {
    const char * containerid = this->getContainer()->getXMLAttribute("id");
    if (strcmp(containerid, this->target) == 0) return TRUE;
  }
  return FALSE;
}

/*!
  This function returns TRUE if the transition matches the given \a eventobj
  object and FALSE otherwise.
*/
SbBool
ScXMLTransitionElt::isEventMatch(const ScXMLEvent * eventobj) const
{
  static const SbName globallkey("*");
  assert(eventobj);
  SbName eventid = eventobj->getEventName();

  if ((this->eventkey == SbName::empty()) ||
      (this->eventkey == globallkey)) return TRUE;

  if (!this->needprefixmatching) {
    return (eventid == this->eventkey);
  }

  if (this->eventkey == eventid) return TRUE;

  const int keylen = strlen(this->eventkey.getString());
  if (keylen < static_cast<int>(strlen(eventid.getString()))) {
    if ((eventid.getString()[keylen] == '.') &&
        strncmp(this->eventkey.getString(), eventid.getString(), keylen) == 0) {
      return TRUE; // this->event matches up to eventobj token separator
    }
  }

  return FALSE;
}

// executable content

/*!
  This function uses the statemachine evaluator to evaluate its condition expression, and
  returns TRUE or FALSE based on the evaluation.

  On expression error, error events are emit'ed to the SCXML state machine.

  If the transition is conditionless, this function will return TRUE.
*/
SbBool
ScXMLTransitionElt::evaluateCondition(ScXMLStateMachine * statemachine)
{
  if (this->isConditionLess()) {
    return TRUE;
  }
  ScXMLEvaluator * evaluator = statemachine->getEvaluator();
  assert(evaluator);
  boost::scoped_ptr<ScXMLDataObj> cond(evaluator->evaluate(this->getCondAttribute()));
  if (cond.get()) {
    ScXMLDataObj * res = cond.get();
    if (cond->isOfType(ScXMLExprDataObj::getClassTypeId())) {
      ScXMLExprDataObj * exprobj = static_cast<ScXMLExprDataObj *>(cond.get());
      res = exprobj->evaluate(statemachine);
      if (!res) {
        if (COIN_DEBUG) {
          SoDebugError::post("ScXMLTransitionElt::evaluateCondition",
                             "expression evaluation failed (%s)\n",
                             this->getCondAttribute());
        }
        statemachine->queueInternalEvent("error.InvalidCondExpr.Transition");
        return FALSE;
      }
    }
    if (res->isOfType(ScXMLBoolDataObj::getClassTypeId())) {
      ScXMLBoolDataObj * boolres = static_cast<ScXMLBoolDataObj *>(res);
      return boolres->getBool();
    }
    else {
      statemachine->queueInternalEvent("error.eval.minimum.Transition.NO_TRUTH_COND_EXPRESSION");
      return FALSE;
    }
  }
  else {
    statemachine->queueInternalEvent("error.eval.minimum.Transition.INVALID_COND_EXPRESSION");
    return FALSE;
  }
  return TRUE;
}

/*!
  Calls invoke on all the ScXMLInvoke children.
*/
void
ScXMLTransitionElt::execute(ScXMLStateMachine * statemachine) const
{
  std::vector<ScXMLExecutableElt *>::const_iterator it = PRIVATE(this)->executablelist.begin();
  while (it != PRIVATE(this)->executablelist.end()) {
    (*it)->execute(statemachine);
    ++it;
  }
}

SCXML_LIST_OBJECT_API_IMPL(ScXMLTransitionElt, ScXMLExecutableElt, PRIVATE(this)->executablelist, Executable, Executables);

#undef PRIVATE


text:
@interface UIWindow (Extension)

- (void)switchRootViewController;

@end


text:
define(['./forOwn', '../function/makeIterator_'], function(forOwn, makeIterator) {

    /**
     * Creates a new object with all the properties where the callback returns
     * true.
     */
    /**
     * Description
     * @method filterValues
     * @param {} obj
     * @param {} callback
     * @param {} thisObj
     * @return output
     */
    function filterValues(obj, callback, thisObj) {
        callback = makeIterator(callback, thisObj);
        var output = {};
        forOwn(obj, function(value, key, obj) {
            if (callback(value, key, obj)) {
                output[key] = value;
            }
        });

        return output;
    }
    return filterValues;
});


text:
name             "keys"
maintainer       "Christian Nicolai"
maintainer_email "cn@mycrobase.de"
license          "Apache 2.0"
description      ""
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          "1.1.0"

supports "debian"