text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>
  <!-- 全局配置文件 -->
  <context-param>
  <param-name>wang</param-name>
  <param-value>xiaobo</param-value>
  </context-param>

  <context-param>
  <param-name>xiao</param-name>
  <param-value>bo</param-value>
  </context-param>

  <listener>
  <listener-class>
  cn.wedfrend.listener.MyHttpSessionAttributeListener
  </listener-class>
  </listener>

  <filter>
  <filter-name>third</filter-name>
  <filter-class>cn.wedfrend.filter.ContextFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>third</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter>
  <filter-name>second</filter-name>
  <filter-class>cn.wedfrend.filter.SecondFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>second</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter>
  <filter-name>fister</filter-name>
  <filter-class>cn.wedfrend.filter.FirstFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>fister</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- 这里设置的直接是时间  以分钟为单位-->
  <session-config>
  	<session-timeout>13</session-timeout>
  </session-config>

  <servlet>
    <servlet-name>LoadServlet</servlet-name>
    <servlet-class>cn.wedfrend.servlet.LoadServlet</servlet-class>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>cn.wedfrend.servlet.MyServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>UpdateServlet</servlet-name>
    <servlet-class>cn.wedfrend.servlet.UpdateServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ChangeServlet</servlet-name>
    <servlet-class>cn.wedfrend.servlet.ChangeServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>DeleteServlet</servlet-name>
    <servlet-class>cn.wedfrend.servlet.DeleteServlet</servlet-class>
    <init-param>
    <param-name></param-name>
    <param-value></param-value>
    </init-param>

  </servlet>

  <servlet-mapping>
    <servlet-name>LoadServlet</servlet-name>
    <url-pattern>/load</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/my</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>UpdateServlet</servlet-name>
    <url-pattern>/servlet/UpdateServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>ChangeServlet</servlet-name>
    <url-pattern>/change</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>DeleteServlet</servlet-name>
    <url-pattern>/del</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>load.jsp</welcome-file>
  </welcome-file-list>
</web-app>


text:
import { combineReducers } from "redux";
import { CARGAR_RESERVAS, SOLICITAR_RESERVAS } from "../actions/tableroReservas";

const reservas = (state = [], action) => {
  switch (action.type) {
    case CARGAR_RESERVAS:
      return action.reservas;
    default:
      return state;
  }
};

const estaCargando = (state = false, action) => {
  switch (action.type) {
    case SOLICITAR_RESERVAS:
      return true;
    case CARGAR_RESERVAS:
      return false;
    default:
      return state;
  }
};

export default combineReducers({
  reservas,
  estaCargando
});

redpajama_set_name: RedPajamaGithub


text:
package instance

import (
	"strings"

	"github.com/docker/infrakit/pkg/spi/group"
	"github.com/docker/infrakit/pkg/spi/instance"
	"github.com/docker/infrakit/pkg/types"
	"github.com/go-openapi/runtime"
	"github.com/golang/mock/gomock"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/spiegela/gorackhd/client/nodes"
	"github.com/spiegela/gorackhd/client/skus"
	"github.com/spiegela/gorackhd/jwt"
	"github.com/spiegela/gorackhd/mock"
	"github.com/spiegela/gorackhd/models"
)

var nodeMock *mock.MockNodeIface

var _ = Describe("Infrakit.Rackhd.Plugin.Instance", func() {
	var (
		auth       runtime.ClientAuthInfoWriter
		instanceID instance.ID
		mockCtrl   *gomock.Controller
		mockClient *mock.MockIface
		pluginImpl instance.Plugin
	)

	BeforeEach(func() {
		auth = jwt.BearerJWTToken("test-jwt-token")
		instanceID = instance.ID("58b028330b0d3789044b2ba3")
		mockCtrl = gomock.NewController(GinkgoT())
		mockClient = mock.NewMockIface(mockCtrl)

		pluginImpl = rackHDInstancePlugin{
			Client:   mockClient,
			Username: "admin",
			Password: "admin123",
		}
	})

	AfterEach(func() {
		mockCtrl.Finish()
	})

	Context("While logged in", func() {
		BeforeEach(func() {
			mockClient.EXPECT().Login("admin", "admin123").Return(auth, nil)
		})

		Context("when working with nodes", func() {
			BeforeEach(func() {
				nodeMock = mock.NewMockNodeIface(mockCtrl)
				mockClient.EXPECT().
					Nodes().Times(1).Return(nodeMock)
			})

			Context("before provisioning", func() {
				BeforeEach(func() {
					nodeMock.EXPECT().
						NodesPostWorkflowByID(gomock.Any(), gomock.Any()).
						Times(1).
						Return(nil, nil)

					nodeMock.EXPECT().
						NodesPatchTagByID(gomock.Any(), gomock.Any()).
						Times(1).
						Return(&nodes.NodesPatchTagByIDOK{}, nil)

					skuMock := mock.NewMockSkuIface(mockCtrl)
					skuMock.EXPECT().
						SkusGet(gomock.Any(), gomock.Any()).
						Times(1).
						Return(&skus.SkusGetOK{Payload: _Skus()}, nil)

					skuMock.EXPECT().
						SkusIDGetNodes(gomock.Any(), gomock.Any()).
						Times(1).
						Return(&skus.SkusIDGetNodesOK{Payload: _SkuNodes(false)}, nil)

					mockClient.EXPECT().
						Nodes().Times(1).Return(nodeMock)

					mockClient.EXPECT().
						Skus().Times(2).Return(skuMock)
				})

				It("should return an ID without error", func() {
					id, err := pluginImpl.Provision(instance.Spec{Properties: inputJSON})
					Expect(err).To(BeNil())
					Expect(*id).To(Equal(instanceID))
				})
			})

			Context("after provisioning", func() {
				BeforeEach(func() {
					nodeMock.EXPECT().
						NodesGetAll(gomock.Any(), gomock.Any()).
						Times(1).
						Return(&nodes.NodesGetAllOK{Payload: _Nodes(true)}, nil)
				})

				It("should read tags back during a describe operation", func() {
					tags := make(map[string]string)
					tags["tier"] = "web"
					descriptions, err := pluginImpl.DescribeInstances(tags, false)
					Expect(len(descriptions)).To(Equal(1))
					Expect(descriptions[0].ID).To(Equal(instanceID))
					// Expect(descriptions[0].LogicalID).To(Exist())
					Expect(descriptions[0].Tags[group.ConfigSHATag]).To(Equal("006438mMXW8gXeYtUxgf9Zbg94Y"))
					Expect(descriptions[0].Tags[group.GroupTag]).To(Equal("cattle"))
					Expect(descriptions[0].Tags["project"]).To(Equal("infrakit"))
					Expect(descriptions[0].Tags["tier"]).To(Equal("web"))
					Expect(err).To(BeNil())
				})
			})

			Context("when destroying", func() {

				BeforeEach(func() {
					nodeMock.EXPECT().
						NodesPostWorkflowByID(gomock.Any(), gomock.Any()).
						Times(1).
						Return(nil, nil)
				})

				It("should delete without error", func() {
					err := pluginImpl.Destroy(instanceID, instance.Termination)
					Expect(err).To(BeNil())
				})
			})

		})

		Context("when writing tags", func() {
			BeforeEach(func() {
				nodesMock := mock.NewMockNodeIface(mockCtrl)
				nodesMock.EXPECT().
					NodesPatchTagByID(gomock.Any(), gomock.Any()).
					Times(1).
					Return(&nodes.NodesPatchTagByIDOK{}, nil)

				mockClient.EXPECT().
					Nodes().Times(1).Return(nodesMock)
			})

			It("should tag a node during a label operation", func() {
				labels := make(map[string]string)
				labels[group.ConfigSHATag] = "006438mMXW8gXeYtUxgf9Zbg94Y"
				labels[group.GroupTag] = "cattle"
				labels["project"] = "infrakit"
				labels["tier"] = "web"
				err := pluginImpl.Label(instanceID, labels)
				Expect(err).To(BeNil())
			})
		})
	})

	It("should return no error when validating valid specs", func() {
		err := pluginImpl.Validate(inputJSON)
		Expect(err).To(BeNil())
	})

	It("should error when no workflow is provided", func() {
		var errorJSON = types.AnyString(`{
			"SKUName": "vQuanta D51 SKU"
		}`)
		err := pluginImpl.Validate(errorJSON)
		Expect(strings.HasPrefix(err.Error(), "no-workflow")).To(BeTrue())
	})

	It("should error when no SKU name is provided", func() {
		var errorJSON = types.AnyString(`{
			"Workflow": {
				"name": "Graph.InstallCentOS"
			}
		}`)
		err := pluginImpl.Validate(errorJSON)
		Expect(strings.HasPrefix(err.Error(), "no-sku-name")).To(BeTrue())
	})
})

func _Skus() []*models.Skus20Sku {
	skus := []*models.Skus20Sku{
		{
			Name:               "vQuanta D51 SKU",
			DiscoveryGraphName: "Graph.vQuanta.Default",
			ID:                 "023cede5-10a3-4480-8193-3979e723f766",
		},
	}
	return skus
}

func _Nodes(provisioned bool) []*models.Node20Node {
	names := []string{
		"Enclosure Node QTFCJ05160195",
		"52:54:be:ef:81:6d",
		"52:54:be:ef:81:6e",
	}
	var tags1 []string
	var tags2 []string
	if provisioned {
		tags1 = append(tags1, group.ConfigSHATag+"=006438mMXW8gXeYtUxgf9Zbg94Y")
		tags1 = append(tags1, group.GroupTag+"=cattle")
		tags1 = append(tags1, "project=infrakit")
		tags1 = append(tags1, "tier=web")
		tags2 = append(tags1, group.ConfigSHATag+"=007429nMYW5gWExtUxfG8AcaF2Z")
		tags2 = append(tags1, group.GroupTag+"=cattle")
		tags2 = append(tags1, "project=infrakit")
		tags2 = append(tags1, "tier=app")
	}
	nodes := []*models.Node20Node{
		{
			AutoDiscover: "false",
			ID:           "58b02931ca8c52d204e60388",
			Name:         names[0],
			Type:         "enclosure",
		},
		{
			AutoDiscover: "false",
			ID:           "58b028330b0d3789044b2ba3",
			Name:         names[1],
			Type:         "compute",
			Tags:         strings.Join(tags1, ","),
		},
		{
			AutoDiscover: "false",
			ID:           "58b028330b0d3789044b2ba4",
			Name:         names[2],
			Type:         "compute",
			Tags:         strings.Join(tags2, ","),
		},
	}
	return nodes
}

func _SkuNodes(provisioned bool) []*models.Node20SkuNode {
	names := []string{
		"Enclosure Node QTFCJ05160195",
		"52:54:be:ef:81:6d",
		"52:54:be:ef:81:6e",
	}
	var tags1 []string
	var tags2 []string
	if provisioned {
		tags1 = append(tags1, group.ConfigSHATag+"=006438mMXW8gXeYtUxgf9Zbg94Y")
		tags1 = append(tags1, group.GroupTag+"=cattle")
		tags1 = append(tags1, "project=infrakit")
		tags1 = append(tags1, "tier=web")
		tags2 = append(tags1, group.ConfigSHATag+"=007429nMYW5gWExtUxfG8AcaF2Z")
		tags2 = append(tags1, group.GroupTag+"=cattle")
		tags2 = append(tags1, "project=infrakit")
		tags2 = append(tags1, "tier=app")
	}
	nodes := []*models.Node20SkuNode{
		{
			AutoDiscover: false,
			ID:           "58b02931ca8c52d204e60388",
			Name:         names[0],
			Type:         "enclosure",
		},
		{
			AutoDiscover: false,
			ID:           "58b028330b0d3789044b2ba3",
			Name:         names[1],
			Type:         "compute",
			Tags:         tags1,
		},
		{
			AutoDiscover: false,
			ID:           "58b028330b0d3789044b2ba4",
			Name:         names[2],
			Type:         "compute",
			Tags:         tags2,
		},
	}
	return nodes
}

var inputJSON = types.AnyString(`{
	"Workflow": {
		"name": "Graph.InstallCentOS",
		"options": {
			"install-os": {
				"version": "7.0",
				"repo": "{{file.server}}/Centos/7.0",
				"rootPassword": "root"
			}
		}
	},
	"SKUName": "vQuanta D51 SKU"
}`)


text:
@interface EditOpportunityViewController : BaseViewController<UITextFieldDelegate, SelectIndexDelegate,MDSearchBarViewControllerDelegate, UITableViewDelegate, UITableViewDataSource,UIActionSheetDelegate>

//DATA
@property (nonatomic, retain) NSDictionary *dataSend;

//Header
@property (weak, nonatomic) IBOutlet UIView *headerViewBar;
@property (weak, nonatomic) IBOutlet UILabel *fullNameLB;

@property (weak, nonatomic) IBOutlet UILabel *lblFormTitle;

@property (weak, nonatomic) IBOutlet UIButton *btnHome;
- (IBAction)homeBack:(id)sender;

@property (weak, nonatomic) IBOutlet UIView *mainView;

@property (weak, nonatomic) IBOutlet UIView *headerMainView;

@property (weak, nonatomic) IBOutlet UIView *bodyMainView;

@property (weak, nonatomic) IBOutlet UIView *viewMainBodyInfo;

@property (nonatomic,retain) IBOutlet UILabel *barLabel;

@property (weak, nonatomic) IBOutlet UIView *footerView;
- (IBAction)actionChooseStatus:(id)sender;
@property (strong, nonatomic) IBOutlet UIButton *btnStatus;
@property (strong, nonatomic) IBOutlet UITextField *txtStatus;
@property (strong, nonatomic) IBOutlet UIButton *btnNextTask;
@property (strong, nonatomic) IBOutlet UITextField *txtNextTask;
- (IBAction)actionChooseNextTask:(id)sender;
@property (strong, nonatomic) IBOutlet UITextField *txtLevel;
@property (strong, nonatomic) IBOutlet UIButton *btnLevel;
- (IBAction)actionChooseLevel:(id)sender;
@property (strong, nonatomic) IBOutlet UIProgressView *pgLevel;
@property (strong, nonatomic) IBOutlet UITextField *txtCustomer;
@property (strong, nonatomic) IBOutlet UIButton *btnCustomer;
- (IBAction)actionChooseCustomer:(id)sender;
@property (strong, nonatomic) IBOutlet UITextField *dtStartDate;
@property (strong, nonatomic) IBOutlet UIButton *btnStartDate;

@property (strong, nonatomic) IBOutlet UIButton *btnStartDateClear;
@property (strong, nonatomic) IBOutlet UITextField *dtEndDate;
@property (strong, nonatomic) IBOutlet UIButton *dfEndDateClear;
@property (strong, nonatomic) IBOutlet UIButton *btnEndDate;
- (IBAction)actionStartDateSelect:(id)sender;
- (IBAction)actionEndDateSelect:(id)sender;
- (IBAction)actionEndDateClear:(id)sender;
- (IBAction)actionStartDateClear:(id)sender;
@property (strong, nonatomic) IBOutlet UITextField *txtStartDateTime;
@property (strong, nonatomic) IBOutlet UIButton *btnStartDateTime;
- (IBAction)actionSelectStartDateTime:(id)sender;
@property (strong, nonatomic) IBOutlet UITextField *txtEndDateTime;
@property (strong, nonatomic) IBOutlet UIButton *btnEndDateTime;
- (IBAction)actionSelectEndDateTime:(id)sender;
- (IBAction)actionSave:(id)sender;
@property (strong, nonatomic) IBOutlet UITextField *txtName;
@property (strong, nonatomic) IBOutlet UITextField *txtType;
@property (weak, nonatomic) IBOutlet UITextField *txtNote;
@property (weak, nonatomic) IBOutlet UIButton *btnType;
- (IBAction)actionChooseType:(id)sender;

@property (weak, nonatomic) IBOutlet MDSearchBar *txtSearchCustomer;
@property (nonatomic) int searchResultCount;

@property (weak, nonatomic) IBOutlet UILabel *lblDetailInfo;
@property (weak, nonatomic) IBOutlet UILabel *lblName;
@property (weak, nonatomic) IBOutlet UILabel *lblStartDate;

@property (weak, nonatomic) IBOutlet UILabel *lblType;
@property (weak, nonatomic) IBOutlet UILabel *lblCustomer;
@property (weak, nonatomic) IBOutlet UILabel *lblLevel;
@property (weak, nonatomic) IBOutlet UILabel *lblEndDate;
@property (weak, nonatomic) IBOutlet UILabel *lblNextTask;
@property (weak, nonatomic) IBOutlet UILabel *lblNote;
@property (weak, nonatomic) IBOutlet UIButton *btnSave;
- (IBAction)actionAddProduct:(id)sender;

@property (strong, nonatomic) IBOutlet UITableView *tbProduct;

//For iPhone only
@property(strong,nonatomic) IBOutlet UIDatePicker* datePicker;

////////////// KHAI BAO BIEN CHUNG//////////
@property (nonatomic, retain) UIPopoverController *listPopover;
////////////// KHAI BAO BIEN CHUNG//////////

//danh sách nhưng tooltip
@property (nonatomic, retain) NSMutableArray *visiblePopTipViews;
@property (nonatomic, strong) id currentPopTipViewTarget;

@end


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>
Continuation (Jetty Server Project 6.1.26 API)
</TITLE>

<META NAME="date" CONTENT="2010-11-11">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../javadoc.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.mortbay.util.ajax

Interface Continuation

All Known Implementing Classes:
SelectChannelConnector.RetryContinuation, WaitingContinuation

public interface Continuation

Continuation.

 A continuation is a mechanism by which a HTTP Request can be
 suspended and restarted after a timeout or an asynchronous event
 has occured.
 Blocking continuations will block the process of the request during a
 call to suspend(long).
 Non-blocking continuation can abort the current request and arrange for it
 to be retried when resume() is called or the timeout expires.

 In order to supprt non-blocking continuations, it is important that
 all actions taken by a filter or servlet before a call to
 suspend(long) are either idempotent (can be retried) or
 are made conditional on isPending() so they are not performed on
 retried requests.

 With the appropriate HTTP Connector, this allows threadless waiting
 for events (see SelectChannelConnector).

Author:

gregw

Method Summary

 java.lang.Object
getObject()

          Arbitrary object associated with the continuation for context.

 boolean
isNew()

          Is this a newly created Continuation.

 boolean
isPending()

          Get the pending status?
 A continuation is pending while the handling of a call to suspend has not completed.

 boolean
isResumed()

          Get the resumed status?

 void
reset()

          Reset the continuation.

 void
resume()

          Resume the request.

 void
setObject(java.lang.Object o)

          Arbitrary object associated with the continuation for context.

 boolean
suspend(long timeout)

          Suspend handling.

Method Detail

suspend

boolean suspend(long timeout)

Suspend handling.
 This method will suspend the request for the timeout or until resume is
 called.

Parameters:
timeout. - A timeout of < 0 will cause an immediate return. I timeout of 0 will wait indefinitely.

Returns:
True if resume called or false if timeout.

resume

void resume()

Resume the request.
 Resume a suspended request.  The passed event will be returned in the getObject method.

reset

void reset()

Reset the continuation.
 Cancel any pending status of the continuation.

isNew

boolean isNew()

Is this a newly created Continuation.

 A newly created continuation has not had #getEvent(long) called on it.

Returns:
True if the continuation has just been created and has not yet suspended the request.

isPending

boolean isPending()

Get the pending status?
 A continuation is pending while the handling of a call to suspend has not completed.
 For blocking continuations, pending is true only during the call to suspend(long).
 For non-blocking continuations, pending is true until a second call to suspend(long),
 thus this method can be used to determine if a request is being retried.

Returns:
True if the continuation is handling a call to suspend.

isResumed

boolean isResumed()

Get the resumed status?

Returns:
True if the continuation is has been resumed.

getObject

java.lang.Object getObject()

Arbitrary object associated with the continuation for context.

Returns:
An arbitrary object associated with the continuation

setObject

void setObject(java.lang.Object o)

Arbitrary object associated with the continuation for context.

Parameters:
o - An arbitrary object to associate with the continuation

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 1995-2010 Mort Bay Consulting. All Rights Reserved.


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for RetrieveAnswerFileForProfileRequestType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="RetrieveAnswerFileForProfileRequestType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="_this" type="{urn:vim25}ManagedObjectReference"/>
 *         <element name="host" type="{urn:vim25}ManagedObjectReference"/>
 *         <element name="applyProfile" type="{urn:vim25}HostApplyProfile"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RetrieveAnswerFileForProfileRequestType", propOrder = {
    "_this",
    "host",
    "applyProfile"
})
public class RetrieveAnswerFileForProfileRequestType {

    @XmlElement(required = true)
    protected ManagedObjectReference _this;
    @XmlElement(required = true)
    protected ManagedObjectReference host;
    @XmlElement(required = true)
    protected HostApplyProfile applyProfile;

    /**
     * Gets the value of the this property.
     *
     * @return
     *     possible object is
     *     {@link ManagedObjectReference }
     *
     */
    public ManagedObjectReference getThis() {
        return _this;
    }

    /**
     * Sets the value of the this property.
     *
     * @param value
     *     allowed object is
     *     {@link ManagedObjectReference }
     *
     */
    public void setThis(ManagedObjectReference value) {
        this._this = value;
    }

    /**
     * Gets the value of the host property.
     *
     * @return
     *     possible object is
     *     {@link ManagedObjectReference }
     *
     */
    public ManagedObjectReference getHost() {
        return host;
    }

    /**
     * Sets the value of the host property.
     *
     * @param value
     *     allowed object is
     *     {@link ManagedObjectReference }
     *
     */
    public void setHost(ManagedObjectReference value) {
        this.host = value;
    }

    /**
     * Gets the value of the applyProfile property.
     *
     * @return
     *     possible object is
     *     {@link HostApplyProfile }
     *
     */
    public HostApplyProfile getApplyProfile() {
        return applyProfile;
    }

    /**
     * Sets the value of the applyProfile property.
     *
     * @param value
     *     allowed object is
     *     {@link HostApplyProfile }
     *
     */
    public void setApplyProfile(HostApplyProfile value) {
        this.applyProfile = value;
    }

}


text:
using KinectMLConnect;
using Microsoft.Kinect.Tools;
using Microsoft.Kinect;
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
using System.ComponentModel;

namespace XEF2MATCore
{
    /// <summary>
    /// The types of Kinect streams
    /// </summary>
    public enum KinectStreamType { Depth, IR, Opaque, Body}
    /// <summary>
    /// The intrisic parameters of the Kinect sensor
    /// </summary>
    public class KinectParameter
    {
        public const int WIDTH = 512;          // Width of the depth image
        public const int HEIGHT = 424;         // Height of the depth image
    }
    /// <summary>
    /// The core class that implements the conversion function
    /// </summary>
    public class Xef2MatCore
    {
        /// <value>
        /// Gets the file path where the .xef file is placed
        /// </value>
        public string Path { get; private set; }
        /// <value>
        /// The depth stream extracted from the .xef file
        /// </value>
        public KStudioEventStream DepthStream { get; private set; }
        /// <value>
        /// The IR stream extracted from the .xef file
        /// </value>
        public KStudioEventStream IRStream { get; private set; }
        /// <value>
        /// The flag that indicates if the streams have been loaded
        /// </value>
        public Boolean IsStreamLoaded { get; private set; } = false;

        /// <summary>
        /// The delegate that fires when a .xef file is loaded
        /// </summary>
        public delegate void FileLoadedHandler();
        /// <summary>
        /// The event that is related to <see cref="Xef2MatCore.FileLoadedHandler"/>
        /// </summary>
        public event FileLoadedHandler FileLoaded;
        /// <summary>
        /// The method that fires after the .xef is successfully loaded
        /// </summary>
        public void OnFileLoaded()
        {
            IsStreamLoaded = true;
            FileLoaded?.Invoke();
        }

        /// <summary>
        /// The delegate that fires every time a frame of the stream is processed
        /// </summary>
        /// <param name="name">The name of the stream (e.g. "Depth", "IR")</param>
        /// <param name="progress">The value of the overall process (0.0~100.0)</param>
        public delegate void ConvertProgressHandler(string name, double progress);
        /// <summary>
        /// The event that is related to <see cref="Xef2MatCore.ConvertProgressHandler"/>
        /// </summary>
        public event ConvertProgressHandler ProgressUpdated;
        /// <summary>
        /// The method that fires every time a frame of the stream is processed (progress updated)
        /// </summary>
        /// <param name="name">The name of the stream (e.g. "Depth", "IR")</param>
        /// <param name="progress">The value of the overall process (0.0~100.0)</param>
        public void OnProgressUpdated(string name, double progress) => ProgressUpdated?.Invoke(name, progress);

        /// <summary>
        /// The delegate that fires when a .xef file is finished to export
        /// </summary>
        public delegate void ExportHandler();
        /// <summary>
        /// The event that is related to <see cref="Xef2MatCore.ExportHandler"/>
        /// </summary>
        public event ExportHandler ExportFinished;
        /// <summary>
        /// The method that fires when a .xef file is finished to export
        /// </summary>
        public void OnExportFinished() => ExportFinished?.Invoke();

        /// <summary>
        /// The method loads a .xef file locates at <paramref name="path"/>, finds the depth/IR stream in the file,
        /// and then export the converted data into <paramref name="out_path"/>.
        /// </summary>
        /// <param name="path">The path to the .xef file</param>
        /// <param name="out_path">The output path to store the exported data</param>
        public void Load(string path, string out_path)
        {
            IsStreamLoaded = false;

            if (string.IsNullOrEmpty(path)) return;

            Path = path;
            using (KStudioClient client = KStudio.CreateClient())
            {
                var file = client.OpenEventFile(Path, KStudioEventFileFlags.None);
                if (file != null && file.EventStreams != null)
                {
                    DepthStream = file.EventStreams.First(t => t.DataTypeName.Equals("Nui Depth"));
                    IRStream = file.EventStreams.First(t => t.DataTypeName.Equals("Nui IR"));

                    OnFileLoaded();

                    string folder_path = string.IsNullOrWhiteSpace(out_path)
                        ? $"{Environment.CurrentDirectory}/output"
                        : out_path;

                    if (!Directory.Exists(folder_path)) Directory.CreateDirectory(folder_path);

                    StreamToMat(DepthStream, "Depth", folder_path);
                    StreamToMat(IRStream, "IR", folder_path);
                }
            }
            OnExportFinished();
        }

        /// <summary>
        /// The async version of the method that loads a .xef file locates at <paramref name="path"/>, finds the depth/IR stream in the file,
        /// and then export the converted data into the current working directory.
        /// </summary>
        /// <param name="path">The path to the .xef file</param>
        public async Task LoadAsync(string path)
        {
            IsStreamLoaded = false;

            if (string.IsNullOrEmpty(path)) return;

            Path = path;
            using (KStudioClient client = KStudio.CreateClient())
            {
                var file = client.OpenEventFile(Path, KStudioEventFileFlags.None);
                if (file != null && file.EventStreams != null)
                {
                    DepthStream = file.EventStreams.First(t => t.DataTypeName.Equals("Nui Depth"));
                    IRStream = file.EventStreams.First(t => t.DataTypeName.Equals("Nui IR"));

                    OnFileLoaded();

                    var folder_path = $"{Environment.CurrentDirectory}/output";
                    if (!Directory.Exists(folder_path)) Directory.CreateDirectory(folder_path);
                    await StreamToMatAsync(DepthStream, "Depth", folder_path);
                    await StreamToMatAsync(IRStream, "IR", folder_path);
                }
            }
            OnExportFinished();
        }

        /// <summary>
        /// The method converts the stream <paramref name="kstream"/> into a .mat file
        /// with the variable name <paramref name="name"/> and saves the .mat files to <paramref name="file_path"/>
        /// </summary>
        /// <param name="kstream">The stream to convert</param>
        /// <param name="name">The name of the converted variable</param>
        /// <param name="file_path">The folder to store the .mat files</param>
        private void StreamToMat(KStudioEventStream kstream, string name, string file_path)
        {
            var stream = kstream as KStudioSeekableEventStream;
            var outputData = new ushort[KinectParameter.WIDTH * KinectParameter.HEIGHT]; // Storage the data of the frames
            var frame_count = (int)stream.EventCount;
            var timing = new ushort[frame_count];

            for (uint i = 0; i < frame_count; i++)
            {
                var progress = (float)(i+1) / frame_count * 100;
                OnProgressUpdated(name, progress);

                var curr_event = stream.ReadEvent(i);

                //unsafe
                {
                    int size = outputData.Length * sizeof(ushort);
                    IntPtr ip = Marshal.AllocHGlobal(size);

                    uint bufferSize = 0;
                    curr_event.AccessUnderlyingEventDataBuffer(out bufferSize, out ip);

                    Copy(ip, outputData, 0, outputData.Length);
                }
                timing[i] = (ushort)curr_event.RelativeTime.TotalMilliseconds;

                var frame_path = $"{file_path}/{name}_{i.ToString("D5")}.mat";
                MATWriter.ToMatFile(
                    name,
                    frame_path,
                    outputData,
                    KinectParameter.HEIGHT, KinectParameter.WIDTH);
            }

            if (frame_count > 0)
            {
                var timing_path = $"{file_path}/TimeSteps.mat";
                MATWriter.ToMatFile(
                    "Time",
                    timing_path,
                    timing,
                    timing.Length, 1);
                OnProgressUpdated("TimeSpan", 100);
            }
        }

        /// <summary>
        /// The async version of the method that converts the stream <paramref name="kstream"/> into a .mat file
        /// with the variable name <paramref name="name"/> and saves the .mat files to <paramref name="file_path"/>
        /// </summary>
        /// <param name="kstream">The stream to convert</param>
        /// <param name="name">The name of the converted variable</param>
        /// <param name="file_path">The folder to store the .mat files</param>
        private async Task StreamToMatAsync(KStudioEventStream kstream, string name, string file_path)
        {
            var stream = kstream as KStudioSeekableEventStream;
            var outputData = new ushort[KinectParameter.WIDTH * KinectParameter.HEIGHT]; // Storage the data of the frames
            var frame_count = (int)stream.EventCount;
            var timing = new ushort[frame_count];

            for (uint i = 0; i < frame_count; i++)
            {
                var progress = (float)i / frame_count * 100;
                OnProgressUpdated(name, progress);

                await Task.Run(()=>
                {
                    var curr_event = stream.ReadEvent(i);

                    //unsafe
                    {
                        int size = outputData.Length * sizeof(ushort);
                        IntPtr ip = Marshal.AllocHGlobal(size);

                        uint bufferSize = 0;
                        curr_event.AccessUnderlyingEventDataBuffer(out bufferSize, out ip);

                        Copy(ip, outputData, 0, outputData.Length);
                    }
                    timing[i] = (ushort)curr_event.RelativeTime.TotalMilliseconds;

                    var frame_path = $"{file_path}/{name}_{i.ToString("D5")}.mat";
                    MATWriter.ToMatFile(
                        name,
                        frame_path,
                        outputData,
                        KinectParameter.HEIGHT, KinectParameter.WIDTH);
                });
            }

            if (frame_count > 0)
            {
                await Task.Run(() =>
                {
                    var timing_path = $"{file_path}/TimeSteps.mat";
                    MATWriter.ToMatFile(
                        "Time",
                        timing_path,
                        timing,
                        timing.Length, 1);
                });
                OnProgressUpdated("TimeSpan", 100);
            }
        }

        /// <summary>
        /// The method copies the data from <paramref name="source"/> in memory to an array <paramref name="destination"/>
        /// from the index <paramref name="startIndex"/> with length <paramref name="length"/>
        /// </summary>
        /// <param name="source">The pointer to the source data</param>
        /// <param name="destination">The array to store the source data</param>
        /// <param name="startIndex">The start index</param>
        /// <param name="length">The length to copy</param>
        public static void Copy(IntPtr source, ushort[] destination, int startIndex, int length)
        {
            unsafe
            {
                var sourcePtr = (ushort*)source;
                for (int i = startIndex; i < startIndex + length; ++i)
                {
                    destination[i] = *sourcePtr++;
                }
            }
        }
    }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM /builds/slave/rel-2.0-xr-osx64-bld/build/widget/public/nsITransferable.idl
 */

#ifndef __gen_nsITransferable_h__
#define __gen_nsITransferable_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

#ifndef __gen_nsISupportsArray_h__
#include "nsISupportsArray.h"
#endif

#ifndef __gen_nsIFormatConverter_h__
#include "nsIFormatConverter.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
// these probably shouldn't live here, but in some central repository shared
// by the entire app.
#define kTextMime                   "text/plain"
#define kUnicodeMime                "text/unicode"
#define kMozTextInternal          "text/x-moz-text-internal"  // text data which isn't suppoed to be parsed by other apps.
#define kHTMLMime                   "text/html"
#define kAOLMailMime                "AOLMAIL"
#define kPNGImageMime               "image/png"
#define kJPEGImageMime              "image/jpg"
#define kGIFImageMime               "image/gif"
#define kFileMime                   "application/x-moz-file"
#define kURLMime                    "text/x-moz-url"        // data contains url\ntitle
#define kURLDataMime                "text/x-moz-url-data"   // data contains url only
#define kURLDescriptionMime         "text/x-moz-url-desc"   // data contains description
#define kURLPrivateMime             "text/x-moz-url-priv"   // same as kURLDataMime but for private uses
#define kNativeImageMime            "application/x-moz-nativeimage"
#define kNativeHTMLMime             "application/x-moz-nativehtml"
// the source URL for a file promise
#define kFilePromiseURLMime         "application/x-moz-file-promise-url"
// the destination filename for a file promise
#define kFilePromiseDestFilename    "application/x-moz-file-promise-dest-filename"
// a dataless flavor used to interact with the OS during file drags
#define kFilePromiseMime            "application/x-moz-file-promise"
// a synthetic flavor, put into the transferable once we know the destination directory of a file drag
#define kFilePromiseDirectoryMime   "application/x-moz-file-promise-dir"
class nsITransferable; /* forward declaration */

/* starting interface:    nsIFlavorDataProvider */
#define NS_IFLAVORDATAPROVIDER_IID_STR "7e225e5f-711c-11d7-9fae-000393636592"

#define NS_IFLAVORDATAPROVIDER_IID \
  {0x7e225e5f, 0x711c, 0x11d7, \
    { 0x9f, 0xae, 0x00, 0x03, 0x93, 0x63, 0x65, 0x92 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIFlavorDataProvider : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IFLAVORDATAPROVIDER_IID)

  /**
    * Retrieve the data from this data provider.
    *
    * @param  aTransferable (in parameter) the transferable we're being called for.
    * @param  aFlavor (in parameter) the flavor of data to retrieve
    * @param  aData the data. Some variant of class in nsISupportsPrimitives.idl
    * @param  aDataLen the length of the data
    */
  /* void getFlavorData (in nsITransferable aTransferable, in string aFlavor, out nsISupports aData, out unsigned long aDataLen); */
  NS_SCRIPTABLE NS_IMETHOD GetFlavorData(nsITransferable *aTransferable, const char *aFlavor, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIFlavorDataProvider, NS_IFLAVORDATAPROVIDER_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIFLAVORDATAPROVIDER \
  NS_SCRIPTABLE NS_IMETHOD GetFlavorData(nsITransferable *aTransferable, const char *aFlavor, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIFLAVORDATAPROVIDER(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetFlavorData(nsITransferable *aTransferable, const char *aFlavor, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM) { return _to GetFlavorData(aTransferable, aFlavor, aData, aDataLen); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIFLAVORDATAPROVIDER(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetFlavorData(nsITransferable *aTransferable, const char *aFlavor, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFlavorData(aTransferable, aFlavor, aData, aDataLen); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsFlavorDataProvider : public nsIFlavorDataProvider
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIFLAVORDATAPROVIDER

  nsFlavorDataProvider();

private:
  ~nsFlavorDataProvider();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsFlavorDataProvider, nsIFlavorDataProvider)

nsFlavorDataProvider::nsFlavorDataProvider()
{
  /* member initializers and constructor code */
}

nsFlavorDataProvider::~nsFlavorDataProvider()
{
  /* destructor code */
}

/* void getFlavorData (in nsITransferable aTransferable, in string aFlavor, out nsISupports aData, out unsigned long aDataLen); */
NS_IMETHODIMP nsFlavorDataProvider::GetFlavorData(nsITransferable *aTransferable, const char *aFlavor, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

/* starting interface:    nsITransferable */
#define NS_ITRANSFERABLE_IID_STR "8b5314bc-db01-11d2-96ce-0060b0fb9956"

#define NS_ITRANSFERABLE_IID \
  {0x8b5314bc, 0xdb01, 0x11d2, \
    { 0x96, 0xce, 0x00, 0x60, 0xb0, 0xfb, 0x99, 0x56 }}

/**
  * nsIFlavorDataProvider allows a flavor to 'promise' data later,
  * supplying the data lazily.
  *
  * To use it, call setTransferData, passing the flavor string,
  * a nsIFlavorDataProvider QI'd to nsISupports, and a data size of 0.
  *
  * When someone calls getTransferData later, if the data size is
  * stored as 0, the nsISupports will be QI'd to nsIFlavorDataProvider,
  * and its getFlavorData called.
  *
  */
class NS_NO_VTABLE NS_SCRIPTABLE nsITransferable : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ITRANSFERABLE_IID)

  enum { kFlavorHasDataProvider = 0 };

  /**
    * Computes a list of flavors (mime types as nsISupportsCString) that the transferable
    * can export, either through intrinsic knowledge or output data converters.
    *
    * @param  aDataFlavorList fills list with supported flavors. This is a copy of
    *          the internal list, so it may be edited w/out affecting the transferable.
    */
  /* nsISupportsArray flavorsTransferableCanExport (); */
  NS_SCRIPTABLE NS_IMETHOD FlavorsTransferableCanExport(nsISupportsArray **_retval NS_OUTPARAM) = 0;

  /**
    * Given a flavor retrieve the data.
    *
    * @param  aFlavor (in parameter) the flavor of data to retrieve
    * @param  aData the data. Some variant of class in nsISupportsPrimitives.idl
    * @param  aDataLen the length of the data
    */
  /* void getTransferData (in string aFlavor, out nsISupports aData, out unsigned long aDataLen); */
  NS_SCRIPTABLE NS_IMETHOD GetTransferData(const char *aFlavor, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM) = 0;

  /**
    * Returns the best flavor in the transferable, given those that have
    * been added to it with |AddFlavor()|
    *
    * @param  aFlavor (out parameter) the flavor of data that was retrieved
    * @param  aData the data. Some variant of class in nsISupportsPrimitives.idl
    * @param  aDataLen the length of the data
    */
  /* void getAnyTransferData (out string aFlavor, out nsISupports aData, out unsigned long aDataLen); */
  NS_SCRIPTABLE NS_IMETHOD GetAnyTransferData(char **aFlavor NS_OUTPARAM, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM) = 0;

  /**
    * Returns true if the data is large.
    */
  /* boolean isLargeDataSet (); */
  NS_SCRIPTABLE NS_IMETHOD IsLargeDataSet(PRBool *_retval NS_OUTPARAM) = 0;

  /**
    * Computes a list of flavors (mime types as nsISupportsCString) that the transferable can
    * accept into it, either through intrinsic knowledge or input data converters.
    *
    * @param  outFlavorList fills list with supported flavors. This is a copy of
    *          the internal list, so it may be edited w/out affecting the transferable.
    */
  /* nsISupportsArray flavorsTransferableCanImport (); */
  NS_SCRIPTABLE NS_IMETHOD FlavorsTransferableCanImport(nsISupportsArray **_retval NS_OUTPARAM) = 0;

  /**
    * Sets the data in the transferable with the specified flavor. The transferable
    * will maintain its own copy the data, so it is not necessary to do that beforehand.
    *
    * @param  aFlavor the flavor of data that is being set
    * @param  aData the data, either some variant of class in nsISupportsPrimitives.idl,
    *         an nsIFile, or an nsIFlavorDataProvider (see above)
    * @param  aDataLen the length of the data, or 0 if passing a nsIFlavorDataProvider
    */
  /* void setTransferData (in string aFlavor, in nsISupports aData, in unsigned long aDataLen); */
  NS_SCRIPTABLE NS_IMETHOD SetTransferData(const char *aFlavor, nsISupports *aData, PRUint32 aDataLen) = 0;

  /**
    * Add the data flavor, indicating that this transferable
    * can receive this type of flavor
    *
    * @param  aDataFlavor a new data flavor to handle
    */
  /* void addDataFlavor (in string aDataFlavor); */
  NS_SCRIPTABLE NS_IMETHOD AddDataFlavor(const char *aDataFlavor) = 0;

  /**
    * Removes the data flavor matching the given one (string compare) and the data
    * that goes along with it.
    *
    * @param  aDataFlavor a data flavor to remove
    */
  /* void removeDataFlavor (in string aDataFlavor); */
  NS_SCRIPTABLE NS_IMETHOD RemoveDataFlavor(const char *aDataFlavor) = 0;

  /* attribute nsIFormatConverter converter; */
  NS_SCRIPTABLE NS_IMETHOD GetConverter(nsIFormatConverter **aConverter) = 0;
  NS_SCRIPTABLE NS_IMETHOD SetConverter(nsIFormatConverter *aConverter) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsITransferable, NS_ITRANSFERABLE_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSITRANSFERABLE \
  NS_SCRIPTABLE NS_IMETHOD FlavorsTransferableCanExport(nsISupportsArray **_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD GetTransferData(const char *aFlavor, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD GetAnyTransferData(char **aFlavor NS_OUTPARAM, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD IsLargeDataSet(PRBool *_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD FlavorsTransferableCanImport(nsISupportsArray **_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD SetTransferData(const char *aFlavor, nsISupports *aData, PRUint32 aDataLen); \
  NS_SCRIPTABLE NS_IMETHOD AddDataFlavor(const char *aDataFlavor); \
  NS_SCRIPTABLE NS_IMETHOD RemoveDataFlavor(const char *aDataFlavor); \
  NS_SCRIPTABLE NS_IMETHOD GetConverter(nsIFormatConverter **aConverter); \
  NS_SCRIPTABLE NS_IMETHOD SetConverter(nsIFormatConverter *aConverter);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSITRANSFERABLE(_to) \
  NS_SCRIPTABLE NS_IMETHOD FlavorsTransferableCanExport(nsISupportsArray **_retval NS_OUTPARAM) { return _to FlavorsTransferableCanExport(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD GetTransferData(const char *aFlavor, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM) { return _to GetTransferData(aFlavor, aData, aDataLen); } \
  NS_SCRIPTABLE NS_IMETHOD GetAnyTransferData(char **aFlavor NS_OUTPARAM, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM) { return _to GetAnyTransferData(aFlavor, aData, aDataLen); } \
  NS_SCRIPTABLE NS_IMETHOD IsLargeDataSet(PRBool *_retval NS_OUTPARAM) { return _to IsLargeDataSet(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD FlavorsTransferableCanImport(nsISupportsArray **_retval NS_OUTPARAM) { return _to FlavorsTransferableCanImport(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD SetTransferData(const char *aFlavor, nsISupports *aData, PRUint32 aDataLen) { return _to SetTransferData(aFlavor, aData, aDataLen); } \
  NS_SCRIPTABLE NS_IMETHOD AddDataFlavor(const char *aDataFlavor) { return _to AddDataFlavor(aDataFlavor); } \
  NS_SCRIPTABLE NS_IMETHOD RemoveDataFlavor(const char *aDataFlavor) { return _to RemoveDataFlavor(aDataFlavor); } \
  NS_SCRIPTABLE NS_IMETHOD GetConverter(nsIFormatConverter **aConverter) { return _to GetConverter(aConverter); } \
  NS_SCRIPTABLE NS_IMETHOD SetConverter(nsIFormatConverter *aConverter) { return _to SetConverter(aConverter); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSITRANSFERABLE(_to) \
  NS_SCRIPTABLE NS_IMETHOD FlavorsTransferableCanExport(nsISupportsArray **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->FlavorsTransferableCanExport(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD GetTransferData(const char *aFlavor, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetTransferData(aFlavor, aData, aDataLen); } \
  NS_SCRIPTABLE NS_IMETHOD GetAnyTransferData(char **aFlavor NS_OUTPARAM, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAnyTransferData(aFlavor, aData, aDataLen); } \
  NS_SCRIPTABLE NS_IMETHOD IsLargeDataSet(PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsLargeDataSet(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD FlavorsTransferableCanImport(nsISupportsArray **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->FlavorsTransferableCanImport(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD SetTransferData(const char *aFlavor, nsISupports *aData, PRUint32 aDataLen) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetTransferData(aFlavor, aData, aDataLen); } \
  NS_SCRIPTABLE NS_IMETHOD AddDataFlavor(const char *aDataFlavor) { return !_to ? NS_ERROR_NULL_POINTER : _to->AddDataFlavor(aDataFlavor); } \
  NS_SCRIPTABLE NS_IMETHOD RemoveDataFlavor(const char *aDataFlavor) { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveDataFlavor(aDataFlavor); } \
  NS_SCRIPTABLE NS_IMETHOD GetConverter(nsIFormatConverter **aConverter) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetConverter(aConverter); } \
  NS_SCRIPTABLE NS_IMETHOD SetConverter(nsIFormatConverter *aConverter) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetConverter(aConverter); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsTransferable : public nsITransferable
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSITRANSFERABLE

  nsTransferable();

private:
  ~nsTransferable();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsTransferable, nsITransferable)

nsTransferable::nsTransferable()
{
  /* member initializers and constructor code */
}

nsTransferable::~nsTransferable()
{
  /* destructor code */
}

/* nsISupportsArray flavorsTransferableCanExport (); */
NS_IMETHODIMP nsTransferable::FlavorsTransferableCanExport(nsISupportsArray **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void getTransferData (in string aFlavor, out nsISupports aData, out unsigned long aDataLen); */
NS_IMETHODIMP nsTransferable::GetTransferData(const char *aFlavor, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void getAnyTransferData (out string aFlavor, out nsISupports aData, out unsigned long aDataLen); */
NS_IMETHODIMP nsTransferable::GetAnyTransferData(char **aFlavor NS_OUTPARAM, nsISupports **aData NS_OUTPARAM, PRUint32 *aDataLen NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* boolean isLargeDataSet (); */
NS_IMETHODIMP nsTransferable::IsLargeDataSet(PRBool *_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsISupportsArray flavorsTransferableCanImport (); */
NS_IMETHODIMP nsTransferable::FlavorsTransferableCanImport(nsISupportsArray **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void setTransferData (in string aFlavor, in nsISupports aData, in unsigned long aDataLen); */
NS_IMETHODIMP nsTransferable::SetTransferData(const char *aFlavor, nsISupports *aData, PRUint32 aDataLen)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void addDataFlavor (in string aDataFlavor); */
NS_IMETHODIMP nsTransferable::AddDataFlavor(const char *aDataFlavor)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void removeDataFlavor (in string aDataFlavor); */
NS_IMETHODIMP nsTransferable::RemoveDataFlavor(const char *aDataFlavor)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* attribute nsIFormatConverter converter; */
NS_IMETHODIMP nsTransferable::GetConverter(nsIFormatConverter **aConverter)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTransferable::SetConverter(nsIFormatConverter *aConverter)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsITransferable_h__ */


text:
package org.archive.io.warc;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Date;
import java.util.zip.GZIPOutputStream;

import org.archive.format.ArchiveFileConstants;
import org.archive.format.warc.WARCConstants;
import org.archive.util.DateUtils;

/**
 * WARCRecordInfo with default values and convenience factory methods.
 *
 * TODO: use existing well-tested HTTP library for generating HTTP content-block.
 *
 * @see TestWARCReader
 * @contributor kenji
 *
 */
public class TestWARCRecordInfo extends WARCRecordInfo implements WARCConstants, ArchiveFileConstants {

    public final static String REVISIT_WARC_PROFILE =
            "http://netpreserve.org/warc/1.0/revisit/identical-payload-digest";

    public TestWARCRecordInfo(byte[] content) {
        this.type = WARCRecordType.response;
        this.url = "http://test.example.com/";
        this.mimetype = "application/http; msgtype=response";
        try {
            this.recordId = new URI("uri:recordidentifier");
        } catch (URISyntaxException ex) {
            throw new RuntimeException("unexpected error", ex);
        }
        this.contentStream = new ByteArrayInputStream(content);
        this.contentLength = content.length;
        // NB: create14DigitDate must be in ISOZ format (name "14DigitDate" is confusing)
        this.create14DigitDate = DateUtils.getLog14Date();
    }

    /**
     * translates DT14 (YYYYmmddHHMMSS) to ISOZ format used in WARC-Date header.
     * @param dt14
     * @return ISOZ (YYYY-mm-ddTHH:MM:SSZ)
     * @exception IOException dt14 is in bad format (wrapping ParseException to simply error handling)
     */
    public static String dt14ToISOZ(String dt14) throws IOException {
        try {
            Date date = DateUtils.parse14DigitDate(dt14);
            return DateUtils.getLog14Date(date);
        } catch (ParseException ex) {
            throw new IOException("invalid DT14 " + dt14, ex);
        }
    }
    /**
     * utility method for updating create14DigitDate from DT14.
     * @param dt14 DT14 (YYYYmmddHHMMSS)
     * @throws IOException dt14 is in bad format.
     */
    public void setCreate14DigitDateFromDT14(String dt14) throws IOException {
        create14DigitDate = dt14ToISOZ(dt14);
    }

    // factory methods

    /**
     * return TestWARCRecordInfo for HTTP Response with entity {@code payload}.
     * Content-Type is {@code text/plain}, and {@code payload} is encoded in UTF-8.
     * @param payload
     * @return
     * @throws IOException
     */
    public static TestWARCRecordInfo createHttpResponse(String payload)
            throws IOException {
        return new TestWARCRecordInfo(buildHttpResponseBlock("text/plain", payload.getBytes("UTF-8")));
    }
    /**
     * return TestWARCRecordInfo for HTTP Response with entity {@code payload}.
     * @param ctype Content-Type value
     * @param payloadBytes payload bytes
     * @return WARCRecordInfo with default values set to key properties.
     * @throws IOException
     */
    public static TestWARCRecordInfo createHttpResponse(String ctype, byte[] payloadBytes)
            throws IOException {
        return new TestWARCRecordInfo(buildHttpResponseBlock(ctype, payloadBytes));
    }
    /**
     * return TestWARCRecordInfo for HTTP Response with response status line {@code status},
     * entity {@code payload} of content-type {@code ctype}.
     * @param status status line, such as {@code "200 OK"}
     * @param ctype content-type
     * @param payloadBytes payload bytes
     * @return TestWARCRecordInfo
     * @throws IOException
     */
	public static TestWARCRecordInfo createHttpResponse(String status,
			String ctype, byte[] payloadBytes) throws IOException {
		return new TestWARCRecordInfo(buildHttpResponseBlock(status, ctype, payloadBytes));
	}
    public static TestWARCRecordInfo createCompressedHttpResponse(String ctype,
            byte[] payloadBytes) throws IOException {
        return new TestWARCRecordInfo(buildCompressedHttpResponseBlock(ctype, payloadBytes));
    }
    public static TestWARCRecordInfo createRevisitHttpResponse(String ctype, int len, boolean withHeader)
            throws IOException {
        return createRevisitHttpResponse(ctype, len, withHeader, false);
    }
    public static TestWARCRecordInfo createRevisitHttpResponse(String ctype, int len, boolean withHeader, boolean gzipContent)
            throws IOException {
        TestWARCRecordInfo recinfo = new TestWARCRecordInfo(buildRevisitHttpResponseBlock(ctype, len, withHeader, gzipContent));
        recinfo.setType(WARCRecordType.revisit);
        recinfo.addExtraHeader("WARC-Truncated", "length");
        recinfo.addExtraHeader("WARC-Profile", REVISIT_WARC_PROFILE);
        return recinfo;

    }
    public static TestWARCRecordInfo createRevisitHttpResponse(String ctype, int len)
            throws IOException {
        return createRevisitHttpResponse(ctype, len, true);
    }
    /**
     * creates TestWARCRecordInfo with URL-Agnostic Revisit WARC record content.
     *

     *
{@code WARC-Refers-To-Target-URI} = {@code http://example.com/}

     *
{@code WARC-Refers-To-Date} = {@code 2014-01-01T10:10:10Z}

     *

     * @param ctype Content-Type
     * @param len Content-Length (arbitrary)
     * @return TestWARCRecordInfo
     * @throws IOException
     */
	public static TestWARCRecordInfo createUrlAgnosticRevisitHttpResponse(
			String ctype, int len) throws IOException {
		TestWARCRecordInfo recinfo = new TestWARCRecordInfo(
			TestWARCRecordInfo.buildRevisitHttpResponseBlock(ctype, len, true,
				false));
		recinfo.setType(WARCRecordType.revisit);
		recinfo.addExtraHeader("WARC-Truncated", "length");
		recinfo.addExtraHeader("WARC-Profile", TestWARCRecordInfo.REVISIT_WARC_PROFILE);
		recinfo.addExtraHeader("WARC-Refers-To-Target-URI", "http://example.com/");
		recinfo.addExtraHeader("WARC-Refers-To-Date", "2014-01-01T10:10:10Z");
		return recinfo;
    }

    public static byte[] buildHttpResponseBlock(String payload) throws IOException {
        return buildHttpResponseBlock("text/plain", payload.getBytes());
    }

    /**
     * short cut for generating "200 OK" HTTP response content-block.
     * @param ctype HTTP Content-Type, such as {@code "text/plain"}, {@code "image/gif"}
     * @param payloadBytes payload bytes
     * @return content-block bytes with HTTP status line, HTTP headers and payload.
     * @throws IOException
     */
    public static byte[] buildHttpResponseBlock(String ctype, byte[] payloadBytes) throws IOException {
        return buildHttpResponseBlock("200 OK", ctype, payloadBytes);
    }

    private static void writeChunked(OutputStream out, byte[] data) throws IOException {
        int s = 0;
        while (s < data.length) {
            int n = data.length - s;
            if (n > 0x1000) n = 0x1000;
            out.write(String.format("%x" + CRLF, n).getBytes("UTF-8"));
            out.write(data, s, n);
            out.write(CRLF.getBytes("UTF-8"));
            s += n;
        }
        out.write(("0" + CRLF + CRLF).getBytes("UTF-8"));
    }
    /**
     * return content-block bytes for HTTP response.
     * @param status HTTP status code and status text separated by a space. ex. {@code "200 OK"}.
     * @param ctype HTTP Content-Type
     * @param payloadBytes payload bytes
     * @param chunked if true, use chunked transfer-encoding
     * @return content-block bytes with HTTP status line, HTTP headers and payload.
     * @throws IOException
     */
    public static byte[] buildHttpResponseBlock(String status, String ctype, byte[] payloadBytes, boolean chunked)
            throws IOException {
        ByteArrayOutputStream blockbuf = new ByteArrayOutputStream();
        Writer bw = new OutputStreamWriter(blockbuf);
        bw.write("HTTP/1.0 " + status + CRLF);
        if (chunked) {
            bw.write("Transfer-Encoding: chunked" + CRLF);
        } else {
            bw.write("Content-Length: " + payloadBytes.length + CRLF);
        }
		if (ctype != null) {
			bw.write("Content-Type: " + ctype + CRLF);
		}
        bw.write(CRLF);
        bw.flush();
        if (chunked) {
            writeChunked(blockbuf, payloadBytes);
        } else {
            blockbuf.write(payloadBytes);
        }
        bw.close();
        return blockbuf.toByteArray();
    }
    public static byte[] buildHttpResponseBlock(String status, String ctype, byte[] payloadBytes) throws IOException {
        return buildHttpResponseBlock(status, ctype, payloadBytes, false);
    }

    public static byte[] buildHttpRedirectResponseBlock(String location) throws IOException {
		return buildHttpRedirectResponseBlock("302 Moved Temporarily", location);
    }

	public static byte[] buildHttpRedirectResponseBlock(String statusline,
			String location) throws IOException {
		assert statusline.startsWith("3");
        ByteArrayOutputStream blockbuf = new ByteArrayOutputStream();
        Writer bw = new OutputStreamWriter(blockbuf);
        bw.write("HTTP/1.0 " + statusline + CRLF);
        bw.write("Content-Length: " + 0 + CRLF);
        bw.write("Content-Type: text/html" + CRLF);
        bw.write("Location: " + location + CRLF);
        bw.write(CRLF);
        bw.close();
        return blockbuf.toByteArray();
    }

    public static byte[] buildCompressedHttpResponseBlock(String ctype,
            byte[] payloadBytes, boolean chunked) throws IOException {
        ByteArrayOutputStream gzippedPayloadBytes = new ByteArrayOutputStream();
        GZIPOutputStream zout = new GZIPOutputStream(gzippedPayloadBytes);
        zout.write(payloadBytes);
        zout.close();
        payloadBytes = gzippedPayloadBytes.toByteArray();
        ByteArrayOutputStream blockbuf = new ByteArrayOutputStream();
        Writer bw = new OutputStreamWriter(blockbuf);
        bw.write("HTTP/1.0 200 OK" + CRLF);
        if (chunked) {
            bw.write("Transfer-Encoding: chunked" + CRLF);
        } else {
            bw.write("Content-Length: " + payloadBytes.length + CRLF);
        }
        bw.write("Content-Type: " + ctype + CRLF);
        bw.write("Content-Encoding: gzip" + CRLF);
        bw.write(CRLF);
        bw.flush();
        if (chunked) {
            writeChunked(blockbuf, payloadBytes);
        } else {
            blockbuf.write(payloadBytes);
        }
        bw.close();
        return blockbuf.toByteArray();
    }
    public static byte[] buildCompressedHttpResponseBlock(String ctype, byte[] payloadBytes) throws IOException {
        return buildCompressedHttpResponseBlock(ctype, payloadBytes, false);
    }

    /**
     * generates WARC content for new revisit record.
     * @param ctype value for Content-Type
     * @param len value for Content-Length
     * @param withHeader include HTTP status line and headers.
     *      passing false generates old-style revisit content block.
     * @param gzipContent if true, block will have "Content-Encoding: gzip" header.
     *      (this shall match the compress-ness of previous capture).
     * @return record content as byte array
     * @throws IOException
     */
	public static byte[] buildRevisitHttpResponseBlock(String ctype, int len,
			boolean withHeader, boolean gzipContent) throws IOException {
		ByteArrayOutputStream blockbuf = new ByteArrayOutputStream();
		Writer bw = new OutputStreamWriter(blockbuf);
		if (withHeader) {
			bw.write("HTTP/1.0 200 OK" + CRLF);
			if (len >= 0) {
				bw.write("Content-Length: " + len + CRLF);
			}
			bw.write("Content-Type: " + ctype + CRLF);
			if (gzipContent)
				bw.write("Content-Encoding: gzip" + CRLF);
			bw.write(CRLF);
			bw.flush();
			bw.close();
		}
		return blockbuf.toByteArray();
	}

    // POPULAR PAYLOAD SAMPLES

    // ubiquitous 1-pixel transparent GIF, if you wonder.
    public static final byte[] PAYLOAD_GIF = new byte[] {
		71, 73, 70, 56, 57, 97, 1, 0, 1, 0, -128, 0, 0, -64, -64, -64,
		0, 0, 0, 33, -7, 4, 1, 0, 0, 0, 0, 44, 0, 0, 0, 0,
		1, 0, 1, 0, 0, 2, 2, 68, 1, 0, 59, 13, 10, 13, 10
    };

}


text:
namespace lt = libtorrent;

struct session_view
{
	session_view();

	void set_pos(int pos);

	int pos() const;

	int height() const;

	void render();

	void print_utp_stats(bool p) { m_print_utp_stats = p; }
	bool print_utp_stats() const { return m_print_utp_stats; }

	void update_counters(boost::uint64_t* stats_counters, int num_cnt
		, boost::uint64_t t);

private:

	int m_position;
	int m_width;

	// there are two sets of counters. the current one and the last one. This
	// is used to calculate rates
	std::vector<boost::uint64_t> m_cnt[2];

	// the timestamps of the counters in m_cnt[0] and m_cnt[1]
	// respectively. The timestamps are microseconds since session start
	boost::uint64_t m_timestamp[2];

	bool m_print_utp_stats;

	int m_queued_bytes_idx;
	int m_wasted_bytes_idx;
	int m_failed_bytes_idx;
	int m_num_peers_idx;
	int m_recv_payload_idx;
	int m_sent_payload_idx;
	int m_unchoked_idx;
	int m_unchoke_slots_idx;
	int m_limiter_up_queue_idx;
	int m_limiter_down_queue_idx;
	int m_queued_writes_idx;
	int m_queued_reads_idx;
	int m_writes_cache_idx;
	int m_reads_cache_idx;
	int m_pinned_idx;
	int m_num_blocks_read_idx;
	int m_cache_hit_idx;
	int m_blocks_in_use_idx;
	int m_blocks_written_idx;
	int m_write_ops_idx;

	int m_mfu_size_idx;
	int m_mfu_ghost_idx;
	int m_mru_size_idx;
	int m_mru_ghost_idx;

	int m_utp_idle;
	int m_utp_syn_sent;
	int m_utp_connected;
	int m_utp_fin_sent;
	int m_utp_close_wait;
};

#endif


text:
Implementations of brute force EM, forward-backward EM, and Viterbi to find
the best matching tag sequence for a simple observation of sequence.
Based on Kevin Knight's classnotes for CSCI 662 (Advanced NLP), p73:
http://d.pr/i/ADyl

### Purpose
Research, understanding the algorithms, etc. So it's a bit hack-y.

### Code Organization
- Main file: TwoTagExample.cc. This runs the brute force and the efficient
  method.
- **The following files are needed to apply Efficient EM and Viterbi methods on
  your own datasets:**
  - TrellisAid.h
  - TrellisAid.cc
  - NotationConstants.h
  - GraphAid.h
  - GraphAid.cc
  - NLPHelper.h - technically shouldn't be needed, can decouple (TODO)

## Running
Compile using cmake. Example:

    mkdir build && cd build
    cmake ..
    make

Run the generated executable. Alternatively run any test executables, but make
sure you do `cmake -Dtest=ON ..` first.

### Examples
Forward-backward and Viterbi:

    ./two_tag_example

Brute force (pass any param):

    ./two_tag_example -b


text:
<?php

class CheckoutapipaymentValidationModuleFrontController extends ModuleFrontController
{
    public function postProcess()
    {
        $cart = $this->context->cart;

        if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active)
            Tools::redirect('index.php?controller=order&step=1');

        // Check that this payment option is still available in case the customer changed his address just before the end of the checkout process
        $authorized = false;

        foreach (Module::getPaymentModules() as $module)
            if ($module['name'] == 'checkoutapipayment')
            {
                $authorized = true;
                break;
            }

        if (!$authorized) {
            die($this->module->l('This payment method is not available.', 'validation'));
        }

        $customer = new Customer($cart->id_customer);

        if (!Validate::isLoadedObject($customer))
            Tools::redirect('index.php?controller=order&step=1');

        $this->_placeorder();
    }

    public function _placeorder()
    {
        $cart = $this->context->cart;
        $total = $cart->getOrderTotal(true, Cart::BOTH);
        $currency = $this->context->currency;
        $customer = new Customer((int)$cart->id_customer);
        //building charge
        $respondCharge = $this->_createCharge();
        $Api = CheckoutApi_Api::getApi(array('mode' => Configuration::get('CHECKOUTAPI_TEST_MODE')));
        $amountCents = $Api->valueToDecimal($total,$currency->iso_code);

        $toValidate = array(
            'currency' => $currency->iso_code,
            'value' => $amountCents,
        );

        $validateRequest = $Api::validateRequest($toValidate,$respondCharge);

        if( $respondCharge->isValid()) {
            if (preg_match('/^1[0-9]+$/', $respondCharge->getResponseCode())) {
              if( $respondCharge->getChargeMode() != 2) {

                if($respondCharge->getChargeMode() == 3){
                    $localPayment = $respondCharge->getLocalPayment();

                    $lpRedirectUrl = $localPayment->getPaymentUrl();
                    Tools::redirectLink($lpRedirectUrl);
                }

                $message = 'Your payment was sucessfull with Checkout.com with transaction Id '.$respondCharge->getId();

                if(!$validateRequest['status']){
                  foreach($validateRequest['message'] as $errormessage){
                    $message .= $errormessage . '. ';
                  }
                }

                $order_state =( Configuration::get('CHECKOUTAPI_PAYMENT_ACTION') == 'authorize_capture' &&
                $respondCharge->getCaptured())
                ? Configuration::get('PS_OS_PAYMENT'):Configuration::get('PS_OS_CHECKOUT');

                $this->module->validateOrder((int)$cart->id, $order_state,
                $total, $this->module->displayName, $message, array
                ('transaction_id'=>$respondCharge->getId()),(int)$currency->id, false, $customer->secure_key);

                $config['authorization'] = Configuration::get('CHECKOUTAPI_SECRET_KEY');
                $config['mode'] = Configuration::get('CHECKOUTAPI_TEST_MODE');
                $Api = CheckoutApi_Api::getApi($config);
                $Api->updateTrackId($respondCharge, $this->module->currentOrder);

                if(Configuration::get('CHECKOUTAPI_INTEGRATION_TYPE') == 'hosted' && !empty($_COOKIE['saveCardCheckbox'])){
                    $saveCardCheck = $_COOKIE['saveCardCheckbox'];
                } elseif(!empty($_POST['save-card-checkbox'])){
                        $saveCardCheck = $_POST['save-card-checkbox'];
                } else {
                    $saveCardCheck = 0;
                }

                $this->_saveCard($respondCharge,$customer,$saveCardCheck);

                if (isset($_COOKIE['saveCardCheckbox'])) {
                    setcookie("saveCardCheckbox", "", time()-3600);
                }

              } else {
                  $redirectUrl = $respondCharge->getRedirectUrl();
                  if (!empty($redirectUrl)){

                    if(!empty($_POST['save-card-checkbox'])){
                        $this->context->cookie->saveCardCheckbox = '1';
                    }

                    Tools::redirectLink($redirectUrl);
                  }else {
                    //$dbLog = models_FactoryInstance::getInstance( 'models_DataLayer' );
                    //$dbLog->logCharge($this->module->currentOrder,'',$respondCharge);
                  }
              }
            } else {

                $this->module->validateOrder((int)$cart->id, Configuration::get('PS_OS_ERROR'),
                    $total, $this->module->displayName, 'An error has occcur while processing this transaction ('.$respondCharge->getResponseMessage().')',
                    array ('transaction_id'=>$respondCharge->getId()), (int)$currency->id, false, $customer->secure_key);

            }
            // $dbLog = models_FactoryInstance::getInstance( 'models_DataLayer' );
            // $dbLog->logCharge($this->module->currentOrder,$respondCharge->getId(),$respondCharge);

        } else  {
            $this->module->validateOrder((int)$cart->id, Configuration::get('PS_OS_ERROR'),
                $total, $this->module->displayName, $respondCharge->getExceptionState()->getErrorMessage(), NULL, (int)$currency->id,
                false, $customer->secure_key);

            $dbLog = models_FactoryInstance::getInstance( 'models_DataLayer' );
        }

        Tools::redirectLink(__PS_BASE_URI__.'order-confirmation.php?key='.$customer->secure_key.'&id_cart='
            .(int)$this->context->cart->id.'&id_module='.(int)$this->module->id.'&id_order='
            .(int)$this->module->currentOrder);

    }

    private function _createCharge()
    {
        $config = array();
        $cart = $this->context->cart;
        $currency = $this->context->currency;
        $customer = new Customer((int)$cart->id_customer);
        $billingAddress = new Address((int)$cart->id_address_invoice);
        $shippingAddress = new Address((int)$cart->id_address_delivery);
        $total = (float)$cart->getOrderTotal(true, Cart::BOTH);
        $scretKey =  Configuration::get('CHECKOUTAPI_SECRET_KEY');
        $orderId =(int)$cart->id;
        $Api = CheckoutApi_Api::getApi(array('mode' => Configuration::get('CHECKOUTAPI_TEST_MODE'),'authorization' => $scretKey));
        $amountCents = $Api->valueToDecimal($total, $currency->iso_code);
        $config['authorization'] = $scretKey;
        $config['mode'] = Configuration::get('CHECKOUTAPI_TEST_MODE');
        $config['timeout'] =  Configuration::get('CHECKOUTAPI_GATEWAY_TIMEOUT');
        $chargeModeValue = 1;
        $billPhoneLength = strlen($billingAddress->phone);

        $billingAddressConfig = array(
            'addressLine1' => $billingAddress->address1,
            'addressLine2' => $billingAddress->address2,
            'postcode' => $billingAddress->postcode,
            'country' => checkoutapipayment::getIsoCodeById($billingAddress->id_country),
            'city' => $billingAddress->city,
        );

        if ($billPhoneLength > 6) {
          $bilPhoneArray = array(
              'phone' => array('number' => $billingAddress->phone)
          );
          $billingAddressConfig = array_merge_recursive($billingAddressConfig, $bilPhoneArray);
        }

        $shipPhoneLength = strlen($shippingAddress->phone);
        $shippingAddressConfig = array(
            'addressLine1' => $shippingAddress->address1,
            'addressLine2' => $shippingAddress->address2,
            'postcode' => $shippingAddress->postcode,
            'country' => checkoutapipayment::getIsoCodeById($shippingAddress->id_country),
            'city' => $shippingAddress->city,
        );

        if ($shipPhoneLength > 6) {
          $shipPhoneArray = array(
              'phone' => array('number' => $shippingAddress->phone)
          );
          $shippingAddressConfig = array_merge_recursive($shippingAddressConfig, $shipPhoneArray);
        }

        $products = array();
        foreach ($cart->getProducts() as $item ) {
            $products[] = array (
                'name'          => strip_tags($item['name']),
                'sku'           => strip_tags($item['reference']),
                'price'         => $item['price'],
                'quantity'      => $item['cart_quantity']
            );
        }

        if(Configuration::get('CHECKOUTAPI_IS_3D')) {
            $chargeModeValue = 2;
        }

        $config['postedParam'] = array (
            'email'             => $customer->email ,
            'value'             => $amountCents,
            'currency'          => $currency->iso_code,
            'trackId'           => $orderId,
            'description'       => "Cart Id::$orderId",
            'shippingDetails'   => $shippingAddressConfig,
            'products'          => $products,
            'customerIp'        => $_SERVER['REMOTE_ADDR'],
            'chargeMode'        => $chargeModeValue,
            'metadata' => array(
                'server'            => _PS_BASE_URL_.__PS_BASE_URI__,
                'order_id'          => $orderId,
                'ps_version'        => _PS_VERSION_,
                'plugin_version'    => $this->module->version,
                'lib_version'       => CheckoutApi_Client_Constant::LIB_VERSION,
                'integration_type'  => Configuration::get('CHECKOUTAPI_INTEGRATION_TYPE'),
                'time'              => date('Y-m-d H:i:s')
            )
        );

        if(!empty($_POST['isSavedCard']) && $_POST['isSavedCard'] == 'false'){
            $config['postedParam'] = array_merge_recursive($config['postedParam'], array(
                                                'card' => array(
                                                            'billingDetails'    => $billingAddressConfig
                                                          )
                                            ));
        }else{
            $config['postedParam'] = array_merge_recursive($config['postedParam'], array(
                                                'billingDetails' => $billingAddressConfig
                                            ));
        }

       return $this->module->getInstanceMethod()->createCharge($config,$cart);
    }

    private function _saveCard($respondCharge,$customer,$saveCardCheck)
    {

        $customerId = $customer->id;

        if (empty($respondCharge) || !$customerId) {
            return false;
        }

        if($saveCardCheck != 1){
            return false;
        }

        $last4      = $respondCharge->getCard()->getLast4();
        $cardId     = $respondCharge->getCard()->getId();
        $cardType   = $respondCharge->getCard()->getPaymentMethod();

        if (empty($last4) || empty($cardId) || empty($cardType)) {
            return false;
        }

        if ($this->_cardExist($customerId, $cardId, $cardType)) {
           return false;
        }

        $db = Db::getInstance();
        $db->insert('checkout_customer_cards', array(
            'customer_id'   => $customerId,
            'card_id'       => $cardId,
            'card_number'   => $last4,
            'card_type'     => $cardType,
            'card_enabled'  => $saveCardCheck,

        ),false,true, Db::REPLACE);

        return true;
    }

    private function _cardExist($customerId,$cardId,$cardType){

        $db = Db::getInstance();
        $sql = 'SELECT * FROM '._DB_PREFIX_."checkout_customer_cards WHERE `customer_id` = '{$customerId}' AND `card_type` = '{$cardType}' AND card_id = '{$cardId}'";
        $row = Db::getInstance()->s($sql);

        if($row){
            return true;
        }

        return false;
    }

    private function _captureConfig()
    {
        $to_return = array (
            'autoCapture' => CheckoutApi_Client_Constant::AUTOCAPUTURE_CAPTURE,
            'autoCapTime' => Configuration::get('CHECKOUTAPI_AUTOCAPTURE_DELAY')
        );

        return $to_return;
    }

    private function _authorizeConfig()
    {
        $to_return = array (
            'autoCapture' => CheckoutApi_Client_Constant::AUTOCAPUTURE_AUTH,
            'autoCapTime' => 0
        );

        return $to_return;
    }
}


text:
class SessionToken < AbstractJwtToken
  MUST_VERIFY = "Verify account first"
  MQTT = ENV.fetch("MQTT_HOST")
  # If you are not using the standard MQTT broker (eg: you use a 3rd party
  # MQTT vendor), you will need to change this line.
  DEFAULT_MQTT_WS =
    "#{ENV["FORCE_SSL"] ? "wss://" : "ws://"}#{ENV.fetch("MQTT_HOST")}:3002/ws"
  MQTT_WS = ENV["MQTT_WS"] || DEFAULT_MQTT_WS
  EXPIRY = 40.days
  VHOST = ENV.fetch("MQTT_VHOST") { "/" }
  DEFAULT_OS = "https://api.github.com/repos/farmbot/farmbot_os/releases" +
               "/latest"

  def self.issue_to(user,
                    iat: Time.now.to_i,
                    exp: EXPIRY.from_now.to_i,
                    iss: $API_URL,
                    aud: AbstractJwtToken::UNKNOWN_AUD,
                    fbos_version:) # Gem::Version
    unless user.verified?
      Rollbar.info("Verification Error", email: user.email)
      raise Errors::Forbidden, MUST_VERIFY
    end
    jti = SecureRandom.uuid
    TokenIssuance.create!(device_id: user.device.id,
                          exp: exp,
                          jti: jti,
                          aud: aud)
    self.new([{ aud: aud,
                sub: user.id,
                iat: iat,
                jti: jti,
                iss: iss,
                exp: exp,
                mqtt: MQTT,
                bot: "device_#{user.device.id}",
                vhost: VHOST,
                mqtt_ws: MQTT_WS }])
  end

  def self.as_json(user, aud, fbos_version)
    { token: SessionToken.issue_to(user, iss: $API_URL,
                                         aud: aud,
                                         fbos_version: fbos_version),
      user: user }
  end
end