text:
.. image:: _static/turbo.png

Introduction
------------
Turbo.lua is a framework built for LuaJIT 2 to simplify the task of building fast and scalable network applications. It uses a event-driven, non-blocking, no thread design to deliver excellent performance and minimal footprint to high-load applications while also providing excellent support for embedded uses. The toolkit can be used for HTTP REST API's, traditional dynamic web pages through templating, open connections like WebSockets, or just as high level building blocks for native speed network applications.

First and foremost the framework is aimed at the HTTP(S) protocol. This means web developers and HTTP API developers are the first class citizens. But the framework contains generic nuts and bolts such as; a I/O loop, IO Stream classes, customizeable TCP (with SSL) server classes giving it value for everyone doing any kind of high performance network application.

Hello World
===========

The traditional and mandatory 'Hello World'

.. code-block:: lua

    local turbo = require("turbo")

    local HelloWorldHandler = class("HelloWorldHandler", turbo.web.RequestHandler)

    function HelloWorldHandler:get()
        self:write("Hello World!")
    end

    turbo.web.Application({
        {"/hello", HelloWorldHandler}
    }):listen(8888)
    turbo.ioloop.instance():start()

LuaJIT 2 is REQUIRED, PUC-RIO Lua is unsupported.

Git repository is available at https://github.com/kernelsauce/turbo.

It's main features and design principles are:

- Simple and intuitive API (much like Tornado).

- Low-level operations is possible if the users wishes that.

- Implemented in straight Lua and LuaJIT FFI on Linux, so the user can study and modify inner workings without too much effort. The Windows implementation uses some Lua modules to make compability possible.

- Good documentation

- Event driven, asynchronous and threadless design

- Small footprint

- SSL support (requires OpenSSL or LuaSec module for Windows)

Travis Linux CI

.. image:: https://api.travis-ci.org/kernelsauce/turbo.png
   :target: http://travis-ci.org/kernelsauce/turbo

Appveyor Windows CI

.. image:: https://api.travis-ci.org/kernelsauce/turbo.png
   :target: https://ci.appveyor.com/project/kernelsauce/turbo

Supported Architectures
-----------------------
x86, x64, ARM, PPC, MIPSEL

Supported Operating Systems
---------------------------
Linux distros (x86, x64), OSX (Intel-based) and Windows x64. Possibly others using LuaSocket, but not tested or supported.

Installation
------------

You can use LuaRocks to install Turbo on Linux.

``luarocks install turbo``

If installation fails make sure that you have these required pacakages:

``apt-get install luajit luarocks git build-essential libssl-dev``

For Windows use the included install.bat. This will install all dependencies: Visual Studio, git, mingw, gnuwin, openssl using Chocolatey. LuaJIT, the LuaRocks package manager and Turbo will be installed at C:\\turbo.lua. It will also install LuaSocket, LuaFileSystem and LuaSec with LuaRocks. The Windows environment will be ready to use upon success.

Try: ``luajit C:\turbo.lua\src\turbo\examples\helloworld.lua``

If any of the .dll or. so's are placed at non-default location then use environment variables to point to the correct place:

E.g:
``SET TURBO_LIBTFFI=C:\turbo.lua\src\turbo\libtffi_wrap.dll`` and
``SET TURBO_LIBSSL=C:\Program Files\OpenSSL\libeay32.dll``

Applies for Linux based OS and OSX only:

Turbo.lua can also be installed by the included Makefile. Simply download and run ``make install`` (requires root priv). It is installed in the default Lua 5.1 and LuaJIT 2.0 module directory.

You can specify your own prefix by using ``make install PREFIX=<prefix>``, and you can specify LuaJIT version with a ``LUAJIT_VERSION=2.0.0`` style parameter.

To compile without support for OpenSSL (and SSL connections) use the make option SSL=none.
To compile with axTLS support instead of OpenSSL use the make option SSL=axTLS.

In essence the toolkit can run from anywere, but is must be able to load the libtffi_wrap.so at run time.
To verify a installation you can try running the applications in the examples folder.

Object oriented Lua
-------------------
Turbo.lua are programmed in a object oriented fashion. There are many ways to do
object orientation in Lua, this library uses the Middleclass module. Which is documented
at https://github.com/kikito/middleclass/wiki. Middleclass is being used internally in
Turbo Web, but is also exposed to the user when inheriting from classes such as the
``turbo.web.RequestHandler`` class. Middleclass is a very lightweight, fast and very
easy to learn if you are used to Python, Java or C++.

Packaging
---------
The included Makefile supports packaging the current tree as a versioned tar.gz file.
This file will include only the neccessary bits and pieces for Turbo to run. The files
will be built as bytecode (luajit -b -g) with debug info. This reduces size drastically.
Suitable for embedded devices with limited storage... It also reduces the startup time.

Use ``make package``. Only tested on Linux and OSX.

this results in a turbo.x.x.x.tar.gz file and a package/ directory being created.

Dependencies
------------
All of the modules of Turbo.lua are made with the class implementation that Middleclass provides.
https://github.com/kikito/middleclass.

The HTTP parser by Ryan Dahl is used for HTTP parsing. This is built and installed as part of the package.

OpenSSL is required for SSL support. It is possible to run without this feature, and thus not need an SSL library.

License
-------
Copyright 2011 - 2016 John Abrahamsen

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.

Many of the modules in the software package are derivatives of the
Tornado web server. Tornado is also licensed under Apache 2.0 license.
For more details on Tornado please see:

http://www.tornadoweb.org/

Tutorials
---------

.. toctree::
    :maxdepth: 3

    get_started
    modules

API documentation
-----------------

.. toctree::
   :maxdepth: 3

   apiref
   web
   websocket
   iosimple
   iostream
   ioloop
   async
   thread
   escape
   turbovisor
   httputil
   httpserver
   tcpserver
   structs
   hash
   util
   sockutil
   log


text:
class AddPreferencesCountToStudents < ActiveRecord::Migration
  def change
  	add_column :students, :preferences_count, :integer, default: 0
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Puesto_model extends CI_Model {

    function __construct(){
        parent::__construct();
        $this->load->database();
        $this->load->library('table');
    }

    function getPuesto(){
		$query = $this->db->query('SELECT * FROM puesto');
        $result = $query->result_array();
        return $result;
    }

}


text:
type: blog
---
{% include header.html %}

{{ page.title }}

{{ page.summary }}

{{ page.category }}

{{ page.date | date_to_string }}

Tweet

Email

Facebook

						{{ content }}
						{% include comments.html %}

{% include footer.html %}
{% include closure.html %}


text:
package com.eebbk.utils;

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

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class PendingIntentManager implements Serializable{

	private static List<PendingIntent> mPIManager = new ArrayList<PendingIntent>();
	private static List<String> mRequestCodeManager = new ArrayList<String>();
	private AlarmManager mAlarmManager;

	//Ìí¼ÓÒ»¸öÒâͼIDµ½ÒâͼÁбí
	public static void addRequestCode(String requestCode){
		mRequestCodeManager.add(requestCode);
	}
	//Ñ°ÕÒ¶ÔÓ¦ÒâͼID
	public static String findPendingIntent(String requestCode){
		String aim = mRequestCodeManager.get(mRequestCodeManager.indexOf(requestCode));
		return aim;
	}
	//´ÓÒÑÌí¼ÓÒâͼÁбíÖÐÒƳý¶ÔÓ¦µÄÒâͼ
	public static void removeOnePendingIntent(String requestCode){
		mRequestCodeManager.remove(requestCode);
	}

	public static void cancelOnePendingIntent(Context context,String id){
		Intent i = new Intent("Alarm_Boot");
		PendingIntent pi = PendingIntent.getBroadcast(context, Integer.parseInt(id), i, 0);

	}

}


text:
import { Glue42Web } from "../../web";
import { GlueBridge } from "../communication/bridge";
import { BasicInstanceData, InstanceData, operations } from "./protocol";

export class InstanceModel {
    private me!: Glue42Web.AppManager.Instance;
    private readonly myCtxKey: string;

    constructor(private readonly data: InstanceData, private readonly bridge: GlueBridge, private readonly application: Glue42Web.AppManager.Application) {
        this.myCtxKey = `___instance___${this.data.id}`;
    }

    public toApi(): Glue42Web.AppManager.Instance {
        const agm = this.bridge.getInteropInstance(this.data.id);

        const api: Glue42Web.AppManager.Instance = {
            id: this.data.id,
            agm,
            application: this.application,
            stop: this.stop.bind(this),
            getContext: this.getContext.bind(this)
        };

        this.me = Object.freeze(api);

        return this.me;
    }

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    private async getContext(): Promise<any> {
        return this.bridge.contextLib.get(this.myCtxKey);
    }

    private async stop(): Promise<void> {
        await this.bridge.send<BasicInstanceData, void>("appManager", operations.instanceStop, { id: this.data.id });
    }
}


text:
package main

import (
	"errors"
	"fmt"
	"io"
	"os"
	"os/signal"

	"github.com/urfave/cli"
	"github.com/wmiller848/GoGP/context"
)

func run(pipe io.Reader, score float64, inputs, population, generations int, auto, visual bool) error {
	if inputs <= 0 {
		return errors.New("Count mut be greater then 0")
	}

	ctx := context.New()
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for range c {
			fitest := ctx.Fitest()
			prgm, _ := fitest.MarshalProgram()
			fmt.Printf("%+v\n", string(prgm))
			os.Exit(0)
		}
	}()
	if visual {
		go func() {
			ctx.RunWithInlineScore(pipe, score, inputs, population, generations, auto)
		}()
		ctx.NewTerminal()
		fitest := ctx.Fitest()
		prgm, _ := fitest.MarshalProgram()
		fmt.Printf("%+v\n", string(prgm))
	} else {
		_, fitest := ctx.RunWithInlineScore(pipe, score, inputs, population, generations, auto)
		prgm, _ := fitest.MarshalProgram()
		fmt.Printf("%+v\n", string(prgm))
	}
	return nil
}

func main() {
	app := cli.NewApp()
	app.Name = "GoGP"
	app.Usage = "Learn a program for matching data based off training data"
	app.Commands = []cli.Command{
		{
			Name:    "learn",
			Aliases: []string{"l"},
			Flags: []cli.Flag{
				cli.IntFlag{
					Name:   "count, c",
					Usage:  "Number of input fields to learn",
					EnvVar: "GOGP_COUNT",
					Value:  0,
				},
				cli.Float64Flag{
					Name:   "score, s",
					Usage:  "Float value for desired percentage score of program. 0.10 = 10%",
					EnvVar: "GOGP_SCORE",
					Value:  0.90,
				},
				cli.IntFlag{
					Name:   "population, p",
					Usage:  "Number of programs to keep in the pool",
					EnvVar: "GOGP_POPULATION",
					Value:  20,
				},
				cli.IntFlag{
					Name:   "generations, g",
					Usage:  "Number of generations to iterate through",
					EnvVar: "GOGP_GENERATIONS",
					Value:  100,
				},
				cli.BoolFlag{
					Name:   "verbose, v",
					Usage:  "Output more then just the evolved program",
					EnvVar: "GOGP_VERBOSE",
				},
				cli.BoolFlag{
					Name:   "auto, a",
					Usage:  "Run until a reasonable score is found",
					EnvVar: "GOGP_AUTO",
				},
			},
			Action: func(c *cli.Context) error {
				args := c.Args()
				var pipe io.Reader
				if len(args) == 0 {
					pipe = os.Stdin
				} else if len(args) == 1 {
					// Handle file io
				} else {
					fmt.Println("Too many arguments, provide path to one file.")
					return errors.New("to many arguments")
				}
				run(pipe, c.Float64("score"), c.Int("count"), c.Int("population"), c.Int("generations"), !c.Bool("auto"), c.Bool("verbose"))
				return nil
			},
		},
	}
	app.Run(os.Args)
}


text:
package com.vaadin.client.ui;

import java.util.ArrayList;
import java.util.EventObject;
import java.util.Iterator;

import com.google.gwt.aria.client.Roles;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.AnimationUtil;
import com.vaadin.client.AnimationUtil.AnimationEndListener;
import com.vaadin.client.ApplicationConnection;
import com.vaadin.client.BrowserInfo;
import com.vaadin.client.UIDL;
import com.vaadin.client.WidgetUtil;
import com.vaadin.client.ui.aria.AriaHelper;
import com.vaadin.shared.Position;
import com.vaadin.shared.ui.ui.NotificationRole;
import com.vaadin.shared.ui.ui.UIConstants;
import com.vaadin.shared.ui.ui.UIState.NotificationTypeConfiguration;

public class VNotification extends VOverlay {

    public static final Position CENTERED = Position.MIDDLE_CENTER;
    public static final Position CENTERED_TOP = Position.TOP_CENTER;
    public static final Position CENTERED_BOTTOM = Position.BOTTOM_CENTER;
    public static final Position TOP_LEFT = Position.TOP_LEFT;
    public static final Position TOP_RIGHT = Position.TOP_RIGHT;
    public static final Position BOTTOM_LEFT = Position.BOTTOM_LEFT;
    public static final Position BOTTOM_RIGHT = Position.BOTTOM_RIGHT;

    private static final String STYLENAME_POSITION_TOP = "v-position-top";
    private static final String STYLENAME_POSITION_RIGHT = "v-position-right";
    private static final String STYLENAME_POSITION_BOTTOM = "v-position-bottom";
    private static final String STYLENAME_POSITION_LEFT = "v-position-left";
    private static final String STYLENAME_POSITION_MIDDLE = "v-position-middle";
    private static final String STYLENAME_POSITION_CENTER = "v-position-center";
    private static final String STYLENAME_POSITION_ASSISTIVE = "v-position-assistive";

    public static final String CAPTION = "caption";
    public static final String DESCRIPTION = "description";
    public static final String DETAILS = "details";

    /**
     * Position that is only accessible for assistive devices, invisible for
     * visual users.
     */
    public static final Position ASSISTIVE = Position.ASSISTIVE;

    public static final int DELAY_FOREVER = -1;
    public static final int DELAY_NONE = 0;

    private static final String STYLENAME = "v-Notification";
    private static final int mouseMoveThreshold = 7;
    private static final int Z_INDEX_BASE = 20000;
    public static final String STYLE_SYSTEM = "system";

    private static final ArrayList<VNotification> notifications = new ArrayList<>();

    private boolean infiniteDelay = false;
    private int hideDelay = 0;

    private Timer delay;

    private int x = -1;
    private int y = -1;

    private String temporaryStyle;

    private ArrayList<EventListener> listeners;
    private static final int TOUCH_DEVICE_IDLE_DELAY = 1000;

    /**
     * Default constructor. You should use GWT.create instead.
     */
    public VNotification() {
        setStyleName(STYLENAME);
        sinkEvents(Event.ONCLICK);
        getElement().getStyle().setZIndex(Z_INDEX_BASE);
    }

    /**
     * @deprecated Use static {@link #createNotification(int)} instead to enable
     *             GWT deferred binding.
     *
     * @param delayMsec
     */
    @Deprecated
    public VNotification(int delayMsec) {
        this();
        setDelay(delayMsec);

        if (BrowserInfo.get().isTouchDevice()) {
            new Timer() {
                @Override
                public void run() {
                    if (isAttached()) {
                        hide();
                    }
                }
            }.schedule(delayMsec + TOUCH_DEVICE_IDLE_DELAY);
        }
    }

    /**
     * @deprecated Use static {@link #createNotification(int, int, int)} instead
     *             to enable GWT deferred binding.
     *
     * @param delayMsec
     * @param fadeMsec
     * @param startOpacity
     */
    @Deprecated
    public VNotification(int delayMsec, int fadeMsec, int startOpacity) {
        this(delayMsec);
        AnimationUtil.setAnimationDuration(getElement(), fadeMsec + "ms");
        getElement().getStyle().setOpacity(startOpacity / 100);
    }

    private void setDelay(int delayMsec) {
        if (delayMsec < 0) {
            infiniteDelay = true;
            hideDelay = 0;
        } else {
            infiniteDelay = false;
            hideDelay = delayMsec;
        }
    }

    @Override
    public void show() {
        show(CENTERED);
    }

    public void show(String style) {
        show(CENTERED, style);
    }

    public void show(com.vaadin.shared.Position position) {
        show(position, null);
    }

    public void show(Widget widget, Position position, String style) {
        NotificationTypeConfiguration styleSetup = getUiState(style);
        setWaiAriaRole(styleSetup);

        FlowPanel panel = new FlowPanel();
        if (hasPrefix(styleSetup)) {
            panel.add(new Label(styleSetup.prefix));
            AriaHelper.setVisibleForAssistiveDevicesOnly(panel.getElement(),
                    true);
        }

        panel.add(widget);

        if (hasPostfix(styleSetup)) {
            panel.add(new Label(styleSetup.postfix));
            AriaHelper.setVisibleForAssistiveDevicesOnly(panel.getElement(),
                    true);
        }
        setWidget(panel);
        show(position, style);
    }

    private boolean hasPostfix(NotificationTypeConfiguration styleSetup) {
        return styleSetup != null && styleSetup.postfix != null
                && !styleSetup.postfix.isEmpty();
    }

    private boolean hasPrefix(NotificationTypeConfiguration styleSetup) {
        return styleSetup != null && styleSetup.prefix != null
                && !styleSetup.prefix.isEmpty();
    }

    public void show(String html, Position position, String style) {
        NotificationTypeConfiguration styleSetup = getUiState(style);
        String assistiveDeviceOnlyStyle = AriaHelper.ASSISTIVE_DEVICE_ONLY_STYLE;

        setWaiAriaRole(styleSetup);

        String type = "";
        String usage = "";

        if (hasPrefix(styleSetup)) {
            type = ""
                    + styleSetup.prefix + "";
        }

        if (hasPostfix(styleSetup)) {
            usage = ""
                    + styleSetup.postfix + "";
        }

        setWidget(new HTML(type + html + usage));
        show(position, style);
    }

    private NotificationTypeConfiguration getUiState(String style) {
        if (getApplicationConnection() == null
                || getApplicationConnection().getUIConnector() == null) {
            return null;
        }

        return getApplicationConnection().getUIConnector()
                .getState().notificationConfigurations.get(style);
    }

    private void setWaiAriaRole(NotificationTypeConfiguration styleSetup) {
        Roles.getAlertRole().set(getElement());

        if (styleSetup != null && styleSetup.notificationRole != null) {
            if (NotificationRole.STATUS == styleSetup.notificationRole) {
                Roles.getStatusRole().set(getElement());
            }
        }
    }

    public void show(Position position, String style) {
        if (temporaryStyle != null) {
            removeStyleName(temporaryStyle);
            removeStyleDependentName(temporaryStyle);
            temporaryStyle = null;
        }
        if (style != null && style.length() > 0) {
            temporaryStyle = style;
            addStyleName(style);
            addStyleDependentName(style);
        }

        setPosition(position);
        super.show();
        updatePositionOffsets(position);
        notifications.add(this);
        positionOrSizeUpdated();
        /**
         * Android 4 fails to render notifications correctly without a little
         * nudge (#8551) Chrome 41 now requires this too (#17252)
         */
        if (BrowserInfo.get().isAndroid() || isChrome41OrHigher()) {
            WidgetUtil.setStyleTemporarily(getElement(), "display", "none");
        }
    }

    private boolean isChrome41OrHigher() {
        return BrowserInfo.get().isChrome()
                && BrowserInfo.get().getBrowserMajorVersion() >= 41;
    }

    protected void hideAfterDelay() {
        if (delay == null) {
            delay = new Timer() {
                @Override
                public void run() {
                    VNotification.super.hide();
                }
            };
            delay.schedule(hideDelay);
        }
    }

    @Override
    public void hide() {
        if (delay != null) {
            delay.cancel();
        }
        // Run only once
        if (notifications.contains(this)) {
            DOM.removeEventPreview(this);

            // Still animating in, wait for it to finish before touching
            // the animation delay (which would restart the animation-in
            // in some browsers)
            if (getStyleName()
                    .contains(VOverlay.ADDITIONAL_CLASSNAME_ANIMATE_IN)) {
                AnimationUtil.addAnimationEndListener(getElement(),
                        new AnimationEndListener() {
                            @Override
                            public void onAnimationEnd(NativeEvent event) {
                                if (AnimationUtil.getAnimationName(event)
                                        .contains(
                                                VOverlay.ADDITIONAL_CLASSNAME_ANIMATE_IN)) {
                                    VNotification.this.hide();
                                }
                            }
                        });
            } else {
                VNotification.super.hide();
                fireEvent(new HideEvent(this));
                notifications.remove(this);
            }
        }
    }

    private void updatePositionOffsets(com.vaadin.shared.Position position) {
        final Element el = getElement();

        // Remove all offsets (GWT PopupPanel defaults)
        el.getStyle().clearTop();
        el.getStyle().clearLeft();

        switch (position) {
        case MIDDLE_LEFT:
        case MIDDLE_RIGHT:
            center();
            el.getStyle().clearLeft();
            break;
        case TOP_CENTER:
        case BOTTOM_CENTER:
            center();
            el.getStyle().clearTop();
            break;
        case MIDDLE_CENTER:
            center();
            break;
        }
    }

    public void setPosition(com.vaadin.shared.Position position) {
        final Element el = getElement();

        // Remove any previous positions
        el.removeClassName(STYLENAME_POSITION_TOP);
        el.removeClassName(STYLENAME_POSITION_RIGHT);
        el.removeClassName(STYLENAME_POSITION_BOTTOM);
        el.removeClassName(STYLENAME_POSITION_LEFT);
        el.removeClassName(STYLENAME_POSITION_MIDDLE);
        el.removeClassName(STYLENAME_POSITION_CENTER);
        el.removeClassName(STYLENAME_POSITION_ASSISTIVE);

        switch (position) {
        case TOP_LEFT:
            el.addClassName(STYLENAME_POSITION_TOP);
            el.addClassName(STYLENAME_POSITION_LEFT);
            break;
        case TOP_RIGHT:
            el.addClassName(STYLENAME_POSITION_TOP);
            el.addClassName(STYLENAME_POSITION_RIGHT);
            break;
        case MIDDLE_LEFT:
            el.addClassName(STYLENAME_POSITION_MIDDLE);
            el.addClassName(STYLENAME_POSITION_LEFT);
            break;
        case MIDDLE_RIGHT:
            el.addClassName(STYLENAME_POSITION_MIDDLE);
            el.addClassName(STYLENAME_POSITION_RIGHT);
            break;
        case BOTTOM_RIGHT:
            el.addClassName(STYLENAME_POSITION_BOTTOM);
            el.addClassName(STYLENAME_POSITION_RIGHT);
            break;
        case BOTTOM_LEFT:
            el.addClassName(STYLENAME_POSITION_BOTTOM);
            el.addClassName(STYLENAME_POSITION_LEFT);
            break;
        case TOP_CENTER:
            el.addClassName(STYLENAME_POSITION_TOP);
            el.addClassName(STYLENAME_POSITION_CENTER);
            break;
        case BOTTOM_CENTER:
            el.addClassName(STYLENAME_POSITION_BOTTOM);
            el.addClassName(STYLENAME_POSITION_CENTER);
            break;
        case ASSISTIVE:
            el.addClassName(STYLENAME_POSITION_ASSISTIVE);
            break;
        }
    }

    @Override
    public void onBrowserEvent(Event event) {
        hide();
    }

    @Override
    /*
     * Fix for #14689: {@link #onEventPreview(Event)} method is deprecated and
     * it's called now only for the very first handler (see super impl). We need
     * it to work for any handler. So let's call old {@link
     * #onEventPreview(Event)} method explicitly with updated logic for {@link
     * #onPreviewNativeEvent(Event)}.
     */
    protected void onPreviewNativeEvent(NativePreviewEvent event) {
        if (!onEventPreview(Event.as(event.getNativeEvent()))) {
            event.cancel();
        }
    }

    @Override
    public boolean onEventPreview(Event event) {
        int type = DOM.eventGetType(event);
        // "modal"
        if (infiniteDelay || temporaryStyle == STYLE_SYSTEM) {
            if (type == Event.ONCLICK || type == Event.ONTOUCHEND) {
                if (DOM.isOrHasChild(getElement(), DOM.eventGetTarget(event))) {
                    hide();
                    return false;
                }
            } else if (type == Event.ONKEYDOWN
                    && event.getKeyCode() == KeyCodes.KEY_ESCAPE) {
                hide();
                return false;
            }
            if (temporaryStyle == STYLE_SYSTEM) {
                return true;
            } else {
                return false;
            }
        }
        // default
        switch (type) {
        case Event.ONMOUSEMOVE:
            if (x < 0) {
                x = DOM.eventGetClientX(event);
                y = DOM.eventGetClientY(event);
            } else if (Math
                    .abs(DOM.eventGetClientX(event) - x) > mouseMoveThreshold
                    || Math.abs(DOM.eventGetClientY(event)
                            - y) > mouseMoveThreshold) {
                hideAfterDelay();
            }
            break;
        case Event.ONMOUSEDOWN:
        case Event.ONMOUSEWHEEL:
        case Event.ONSCROLL:
            hideAfterDelay();
            break;
        case Event.ONKEYDOWN:
            if (event.getRepeat()) {
                return true;
            }
            hideAfterDelay();
            break;
        default:
            break;
        }
        return true;
    }

    public void addEventListener(EventListener listener) {
        if (listeners == null) {
            listeners = new ArrayList<>();
        }
        listeners.add(listener);
    }

    public void removeEventListener(EventListener listener) {
        if (listeners == null) {
            return;
        }
        listeners.remove(listener);
    }

    private void fireEvent(HideEvent event) {
        if (listeners != null) {
            for (Iterator<EventListener> it = listeners.iterator(); it
                    .hasNext();) {
                EventListener l = it.next();
                l.notificationHidden(event);
            }
        }
    }

    public static void showNotification(ApplicationConnection client,
            final UIDL notification) {
        boolean onlyPlainText = notification.hasAttribute(
                UIConstants.NOTIFICATION_HTML_CONTENT_NOT_ALLOWED);
        String html = "";
        if (notification
                .hasAttribute(UIConstants.ATTRIBUTE_NOTIFICATION_ICON)) {
            String iconUri = notification.getStringAttribute(
                    UIConstants.ATTRIBUTE_NOTIFICATION_ICON);
            html += client.getIcon(iconUri).getElement().getString();
        }
        if (notification
                .hasAttribute(UIConstants.ATTRIBUTE_NOTIFICATION_CAPTION)) {
            String caption = notification.getStringAttribute(
                    UIConstants.ATTRIBUTE_NOTIFICATION_CAPTION);
            if (onlyPlainText) {
                caption = WidgetUtil.escapeHTML(caption);
                caption = caption.replaceAll("\\n", "
");
            }
            html += "
"
                    + caption + "
";
        }
        if (notification
                .hasAttribute(UIConstants.ATTRIBUTE_NOTIFICATION_MESSAGE)) {
            String message = notification.getStringAttribute(
                    UIConstants.ATTRIBUTE_NOTIFICATION_MESSAGE);
            if (onlyPlainText) {
                message = WidgetUtil.escapeHTML(message);
                message = message.replaceAll("\\n", "
");
            }
            html += "
"
                    + message + "
";
        }

        final String style = notification
                .hasAttribute(UIConstants.ATTRIBUTE_NOTIFICATION_STYLE)
                        ? notification.getStringAttribute(
                                UIConstants.ATTRIBUTE_NOTIFICATION_STYLE)
                        : null;

        final int pos = notification
                .getIntAttribute(UIConstants.ATTRIBUTE_NOTIFICATION_POSITION);
        Position position = Position.values()[pos];

        final int delay = notification
                .getIntAttribute(UIConstants.ATTRIBUTE_NOTIFICATION_DELAY);
        createNotification(delay, client.getUIConnector().getWidget())
                .show(html, position, style);
    }

    /**
     * Meant for internal usage only.
     *
     * @since 7.5.0
     * @param client
     *            application connection
     * @param style
     *            the dependent style name
     * @return the given dependent style name prefixed with current notification
     *         primary style
     */
    public static String getDependentStyle(ApplicationConnection client,
            String style) {
        VNotification notification = createNotification(-1,
                client.getUIConnector().getWidget());
        String styleName = notification.getStyleName();
        notification.addStyleDependentName(style);
        String extendedStyle = notification.getStyleName();
        return extendedStyle.substring(styleName.length()).trim();
    }

    public static VNotification createNotification(int delayMsec,
            Widget owner) {
        final VNotification notification = GWT.create(VNotification.class);
        notification.setWaiAriaRole(null);
        notification.setDelay(delayMsec);

        if (!notification.infiniteDelay && BrowserInfo.get().isTouchDevice()) {
            new Timer() {
                @Override
                public void run() {
                    if (notification.isAttached()) {
                        notification.hide();
                    }
                }
            }.schedule(delayMsec + TOUCH_DEVICE_IDLE_DELAY);
        }
        notification.setOwner(owner);
        return notification;
    }

    public class HideEvent extends EventObject {

        public HideEvent(Object source) {
            super(source);
        }
    }

    public interface EventListener extends java.util.EventListener {
        public void notificationHidden(HideEvent event);
    }

    /**
     * Moves currently visible notifications to the top of the event preview
     * stack. Can be called when opening other overlays such as subwindows to
     * ensure the notifications receive the events they need and don't linger
     * indefinitely. See #7136.
     *
     * TODO Should this be a generic Overlay feature instead?
     */
    public static void bringNotificationsToFront() {
        for (VNotification notification : notifications) {
            DOM.removeEventPreview(notification);
            DOM.addEventPreview(notification);
        }
    }

    /**
     * Shows an error notification and redirects the user to the given URL when
     * she clicks on the notification.
     *
     * If both message and caption are null, redirects the user to the url
     * immediately
     *
     * @since 7.5.1
     * @param connection
     *            A reference to the ApplicationConnection
     * @param caption
     *            The caption for the error or null to exclude the caption
     * @param message
     *            The message for the error or null to exclude the message
     * @param details
     *            A details message or null to exclude the details
     * @param url
     *            A url to redirect to after the user clicks the error
     *            notification
     */
    public static void showError(ApplicationConnection connection,
            String caption, String message, String details, String url) {

        StringBuilder html = new StringBuilder();
        if (caption != null) {
            html.append("
");
            html.append(caption);
            html.append("
");
        }
        if (message != null) {
            html.append("
");
            html.append(message);
            html.append("
");
        }

        if (html.length() > 0) {

            // Add error description
            if (details != null) {
                html.append("
");
                html.append("");
                html.append(details);
                html.append("
");
            }

            VNotification n = VNotification.createNotification(1000 * 60 * 45,
                    connection.getUIConnector().getWidget());
            n.addEventListener(new NotificationRedirect(url));
            n.show(html.toString(), VNotification.CENTERED_TOP,
                    VNotification.STYLE_SYSTEM);
        } else {
            WidgetUtil.redirect(url);
        }
    }

    /**
     * Listens for Notification hide event, and redirects. Used for system
     * messages, such as session expired.
     *
     */
    private static class NotificationRedirect
            implements VNotification.EventListener {
        String url;

        NotificationRedirect(String url) {
            this.url = url;
        }

        @Override
        public void notificationHidden(HideEvent event) {
            WidgetUtil.redirect(url);
        }

    }

}


text:
<!DOCTYPE html>
<meta charset='UTF-8'>
<title>core-js-pure</title>
<link rel='stylesheet' href='https://code.jquery.com/qunit/qunit-2.17.2.css'>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

            角色識別碼*:
            <input class="form-control" type="text">

            角色名稱*:
            <input class="form-control" type="text">

            聯絡方式*:

                <input type="radio" name="communicationMethod" value="1" />啟用

                <input type="radio" name="communicationMethod" value="0" />未啟用

角色權限:


text:
class AddNoteEventsToServices < ActiveRecord::Migration[4.2]
  def change
    add_column :services, :note_events, :boolean, default: true, null: false
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Meliola platysperma Theiss.

### Remarks
null


text:
package com.thang.view.other;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.plaf.basic.BasicComboPopup;

import com.thang.tools.model.ImagePath;
import com.thang.tools.util.ImageUtils;

public class StatusCombobox extends BasicComboPopup{

	private static final long serialVersionUID = 1L;

	private static JButton stBtn=null;//状态按钮
	private static JComboBox jcb=null;
	private static List<Status> sts=null;

	static{
		jcb=new JComboBox();
		//初始化数据
		sts=new ArrayList<Status>();
		sts.add(new Status("  聊天 ",ImageUtils.getImageIcon(ImagePath.Status_Call)));
	    sts.add(new Status("  在线 ",ImageUtils.getImageIcon(ImagePath.Status_Online)));
	    sts.add(new Status("  忙碌 ",ImageUtils.getImageIcon(ImagePath.Status_Busy)));

	    jcb.setBackground(Color.WHITE);
	    jcb.setBorder(BorderFactory.createEmptyBorder());
	    jcb.setModel(new DefaultComboBoxModel(sts.toArray()));
	    jcb.setEnabled(false);
        jcb.setVisible(false);

	    jcb.setRenderer(new DefaultListCellRenderer(){
			private static final long serialVersionUID = 1L;

			@Override
           public Component getListCellRendererComponent(JList jlist, Object value, int index, boolean isSelected, boolean hasFocus) {
               jlist.setVisibleRowCount(3);
               setOpaque(true);

               Status s=(Status)value;
               setText(s.getText());
               setIcon(s.getIcon());

               setBackground(isSelected?jlist.getSelectionBackground():jlist.getBackground());
               setForeground(isSelected?jlist.getSelectionForeground():jlist.getForeground());

                return this;
           }

       });

	    jcb.addItemListener(new ItemListener(){

            @Override
            public void itemStateChanged(ItemEvent ie) {
                Object obj=jcb.getSelectedItem();
                if(obj instanceof Status){
                     Status s=(Status)obj;
                     itemChanged(s);
                }

            }

        });

	}

	private static void itemChanged(Status s){
		stBtn.setIcon(s.getIcon());
	}

	public StatusCombobox(JButton btn){
		super(jcb);
		stBtn=btn;
		jcb.setBackground(stBtn.getBackground());
		jcb.setForeground(stBtn.getForeground());
		jcb.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
            	StatusCombobox.this.setVisible(false);
            }

       });
	}

}

class Status{

    private String text;
    private ImageIcon icon;

    public Status(){}

    public Status(String txt,ImageIcon icon){
         this.text=txt;
         this.icon=icon;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public ImageIcon getIcon() {
        return icon;
    }

    public void setIcon(ImageIcon icon) {
        this.icon = icon;
    }

}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: server-protobuf/user_authentication.proto

package org.intellimate.server.proto;

/**
 * Protobuf type {@code intellimate.UserAuthentication}
 */
public  final class UserAuthentication extends
    com.google.protobuf.GeneratedMessage implements
    // @@protoc_insertion_point(message_implements:intellimate.UserAuthentication)
    UserAuthenticationOrBuilder {
  // Use UserAuthentication.newBuilder() to construct.
  private UserAuthentication(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
    super(builder);
  }
  private UserAuthentication() {
    token_ = "";
    id_ = 0;
  }

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet
  getUnknownFields() {
    return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
  }
  private UserAuthentication(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    this();
    int mutable_bitField0_ = 0;
    try {
      boolean done = false;
      while (!done) {
        int tag = input.readTag();
        switch (tag) {
          case 0:
            done = true;
            break;
          default: {
            if (!input.skipField(tag)) {
              done = true;
            }
            break;
          }
          case 10: {
            java.lang.String s = input.readStringRequireUtf8();

            token_ = s;
            break;
          }
          case 16: {

            id_ = input.readInt32();
            break;
          }
        }
      }
    } catch (com.google.protobuf.InvalidProtocolBufferException e) {
      throw e.setUnfinishedMessage(this);
    } catch (java.io.IOException e) {
      throw new com.google.protobuf.InvalidProtocolBufferException(
          e).setUnfinishedMessage(this);
    } finally {
      makeExtensionsImmutable();
    }
  }
  public static final com.google.protobuf.Descriptors.Descriptor
      getDescriptor() {
    return org.intellimate.server.proto.UserAuthenticationOuterClass.internal_static_intellimate_UserAuthentication_descriptor;
  }

  protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return org.intellimate.server.proto.UserAuthenticationOuterClass.internal_static_intellimate_UserAuthentication_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            org.intellimate.server.proto.UserAuthentication.class, org.intellimate.server.proto.UserAuthentication.Builder.class);
  }

  public static final int TOKEN_FIELD_NUMBER = 1;
  private volatile java.lang.Object token_;
  /**
   * optional string token = 1;
   */
  public java.lang.String getToken() {
    java.lang.Object ref = token_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      token_ = s;
      return s;
    }
  }
  /**
   * optional string token = 1;
   */
  public com.google.protobuf.ByteString
      getTokenBytes() {
    java.lang.Object ref = token_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8(
              (java.lang.String) ref);
      token_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  public static final int ID_FIELD_NUMBER = 2;
  private int id_;
  /**
   * optional int32 id = 2;
   */
  public int getId() {
    return id_;
  }

  private byte memoizedIsInitialized = -1;
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  public void writeTo(com.google.protobuf.CodedOutputStream output)
                      throws java.io.IOException {
    if (!getTokenBytes().isEmpty()) {
      com.google.protobuf.GeneratedMessage.writeString(output, 1, token_);
    }
    if (id_ != 0) {
      output.writeInt32(2, id_);
    }
  }

  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (!getTokenBytes().isEmpty()) {
      size += com.google.protobuf.GeneratedMessage.computeStringSize(1, token_);
    }
    if (id_ != 0) {
      size += com.google.protobuf.CodedOutputStream
        .computeInt32Size(2, id_);
    }
    memoizedSize = size;
    return size;
  }

  private static final long serialVersionUID = 0L;
  public static org.intellimate.server.proto.UserAuthentication parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static org.intellimate.server.proto.UserAuthentication parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static org.intellimate.server.proto.UserAuthentication parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }
  public static org.intellimate.server.proto.UserAuthentication parseFrom(
      byte[] data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }
  public static org.intellimate.server.proto.UserAuthentication parseFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessage
        .parseWithIOException(PARSER, input);
  }
  public static org.intellimate.server.proto.UserAuthentication parseFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessage
        .parseWithIOException(PARSER, input, extensionRegistry);
  }
  public static org.intellimate.server.proto.UserAuthentication parseDelimitedFrom(java.io.InputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessage
        .parseDelimitedWithIOException(PARSER, input);
  }
  public static org.intellimate.server.proto.UserAuthentication parseDelimitedFrom(
      java.io.InputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessage
        .parseDelimitedWithIOException(PARSER, input, extensionRegistry);
  }
  public static org.intellimate.server.proto.UserAuthentication parseFrom(
      com.google.protobuf.CodedInputStream input)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessage
        .parseWithIOException(PARSER, input);
  }
  public static org.intellimate.server.proto.UserAuthentication parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessage
        .parseWithIOException(PARSER, input, extensionRegistry);
  }

  public Builder newBuilderForType() { return newBuilder(); }
  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }
  public static Builder newBuilder(org.intellimate.server.proto.UserAuthentication prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }
  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE
        ? new Builder() : new Builder().mergeFrom(this);
  }

  @java.lang.Override
  protected Builder newBuilderForType(
      com.google.protobuf.GeneratedMessage.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  /**
   * Protobuf type {@code intellimate.UserAuthentication}
   */
  public static final class Builder extends
      com.google.protobuf.GeneratedMessage.Builder<Builder> implements
      // @@protoc_insertion_point(builder_implements:intellimate.UserAuthentication)
      org.intellimate.server.proto.UserAuthenticationOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return org.intellimate.server.proto.UserAuthenticationOuterClass.internal_static_intellimate_UserAuthentication_descriptor;
    }

    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return org.intellimate.server.proto.UserAuthenticationOuterClass.internal_static_intellimate_UserAuthentication_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              org.intellimate.server.proto.UserAuthentication.class, org.intellimate.server.proto.UserAuthentication.Builder.class);
    }

    // Construct using org.intellimate.server.proto.UserAuthentication.newBuilder()
    private Builder() {
      maybeForceBuilderInitialization();
    }

    private Builder(
        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
      super(parent);
      maybeForceBuilderInitialization();
    }
    private void maybeForceBuilderInitialization() {
      if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
      }
    }
    public Builder clear() {
      super.clear();
      token_ = "";

      id_ = 0;

      return this;
    }

    public com.google.protobuf.Descriptors.Descriptor
        getDescriptorForType() {
      return org.intellimate.server.proto.UserAuthenticationOuterClass.internal_static_intellimate_UserAuthentication_descriptor;
    }

    public org.intellimate.server.proto.UserAuthentication getDefaultInstanceForType() {
      return org.intellimate.server.proto.UserAuthentication.getDefaultInstance();
    }

    public org.intellimate.server.proto.UserAuthentication build() {
      org.intellimate.server.proto.UserAuthentication result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }

    public org.intellimate.server.proto.UserAuthentication buildPartial() {
      org.intellimate.server.proto.UserAuthentication result = new org.intellimate.server.proto.UserAuthentication(this);
      result.token_ = token_;
      result.id_ = id_;
      onBuilt();
      return result;
    }

    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof org.intellimate.server.proto.UserAuthentication) {
        return mergeFrom((org.intellimate.server.proto.UserAuthentication)other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }

    public Builder mergeFrom(org.intellimate.server.proto.UserAuthentication other) {
      if (other == org.intellimate.server.proto.UserAuthentication.getDefaultInstance()) return this;
      if (!other.getToken().isEmpty()) {
        token_ = other.token_;
        onChanged();
      }
      if (other.getId() != 0) {
        setId(other.getId());
      }
      onChanged();
      return this;
    }

    public final boolean isInitialized() {
      return true;
    }

    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      org.intellimate.server.proto.UserAuthentication parsedMessage = null;
      try {
        parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        parsedMessage = (org.intellimate.server.proto.UserAuthentication) e.getUnfinishedMessage();
        throw e.unwrapIOException();
      } finally {
        if (parsedMessage != null) {
          mergeFrom(parsedMessage);
        }
      }
      return this;
    }

    private java.lang.Object token_ = "";
    /**
     * optional string token = 1;
     */
    public java.lang.String getToken() {
      java.lang.Object ref = token_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs =
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        token_ = s;
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     * optional string token = 1;
     */
    public com.google.protobuf.ByteString
        getTokenBytes() {
      java.lang.Object ref = token_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        token_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     * optional string token = 1;
     */
    public Builder setToken(
        java.lang.String value) {
      if (value == null) {
    throw new NullPointerException();
  }

      token_ = value;
      onChanged();
      return this;
    }
    /**
     * optional string token = 1;
     */
    public Builder clearToken() {

      token_ = getDefaultInstance().getToken();
      onChanged();
      return this;
    }
    /**
     * optional string token = 1;
     */
    public Builder setTokenBytes(
        com.google.protobuf.ByteString value) {
      if (value == null) {
    throw new NullPointerException();
  }
  checkByteStringIsUtf8(value);

      token_ = value;
      onChanged();
      return this;
    }

    private int id_ ;
    /**
     * optional int32 id = 2;
     */
    public int getId() {
      return id_;
    }
    /**
     * optional int32 id = 2;
     */
    public Builder setId(int value) {

      id_ = value;
      onChanged();
      return this;
    }
    /**
     * optional int32 id = 2;
     */
    public Builder clearId() {

      id_ = 0;
      onChanged();
      return this;
    }
    public final Builder setUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return this;
    }

    public final Builder mergeUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return this;
    }

    // @@protoc_insertion_point(builder_scope:intellimate.UserAuthentication)
  }

  // @@protoc_insertion_point(class_scope:intellimate.UserAuthentication)
  private static final org.intellimate.server.proto.UserAuthentication DEFAULT_INSTANCE;
  static {
    DEFAULT_INSTANCE = new org.intellimate.server.proto.UserAuthentication();
  }

  public static org.intellimate.server.proto.UserAuthentication getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  private static final com.google.protobuf.Parser<UserAuthentication>
      PARSER = new com.google.protobuf.AbstractParser<UserAuthentication>() {
    public UserAuthentication parsePartialFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
        return new UserAuthentication(input, extensionRegistry);
    }
  };

  public static com.google.protobuf.Parser<UserAuthentication> parser() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.protobuf.Parser<UserAuthentication> getParserForType() {
    return PARSER;
  }

  public org.intellimate.server.proto.UserAuthentication getDefaultInstanceForType() {
    return DEFAULT_INSTANCE;
  }

}


text:
To install the Gluu Server, please follow the instructions in [our docs](http://gluu.org/docs)

OX Install
======

This is a step by step instruction for installing the OX Server (oxAuth and oxTrust).

To access Gluu support, please register and open a ticket on Gluu Support

Table of contents

Prerequisites

Requirements

Setup OpenDJ

Setup Maven 3.x

Setup Tomcat 7

Configure oxAuth

Configure oxTrust

Configure Install Script

Advanced Install Script Configuration

Build Project

setup.properties

Prerequisites

This is a step by step instruction for installing the OX server (oxAuth and oxTrust).

Platform: CentOS 6.4

Requirements

OpenJDK 1.6 (Install openJDK1.6 using "yum") or java7

OpenJDK 1.6 devel package needed to compile the code into wars.

OpenDJ 2.7 or 2.6

Maven 3.x

Python 2.7.*

Tomcat 7

Make sure your machine name is in hosts file, if not then edit /etc/hosts and add this line at the end of file.

127.0.0.1 <your machine name>

Setup OpenDJ

Download from official openDJ site.

Extract it.

Now run this command:

$ opendj/setup --cli --baseDN o=gluu --ldapPort 1389 --adminConnectorPort 4444 --rootUserDN cn=Directory\ Manager --rootUserPassword passpass --no-prompt --noPropertiesFile

Now you need to stop the server. To do so, run this command:

$ opendj/bin/stop-ds

(note: example password: passpass but you must set your own password)

Setup Maven 3.x

If its not already present ($ which mvn) , then check your linux distribution for a package or download it from http://maven.apache.org/download.cgi

Make sure you export the ENV PATH to include /maven/installdir/bin

Setup Tomcat 7

Download Tomcat 7

Extract it.

Encrypted Password strings: (download the file gluu-encryptor.zip)

To get encrypted representation of your LDAP password you provided in the opendj setup phase, unzip the file and execute the command:

$ java -jar Gluu-Encryptor.jar passpass

Example: decrypted password: "passpass" → encrypted password: GENERATED_PASSWD

Configure oxAuth

Clone https://github.com/GluuFederation/oxAuth.git using this command:

$ git clone https://github.com/GluuFederation/oxAuth.git

Edit config-oxauth.properties:

Sample configuration:

config.oxauth.issuer=http://localhost:8080
config.oxauth.contextPath=http://localhost:8080
config.oxauth.appliance=@!1111!0002!0085
config.ldap.bindDN=cn=Directory Manager
config.ldap.bindPassword=GENERATED_PASSWD
config.ldap.servers=localhost:1389
config.ldap.maxConnections=3
config.ldap.useSSL=false
config.ldap.configurationEntryDN=ou=oxAuth,ou=configuration,o=@!1111,o=gluu
config.ldap.createLdapConfigurationEntryIfNotExist=true

Configure oxTrust

Clone https://github.com/GluuFederation/oxTrust.git using this command:

$ git clone https://github.com/GluuFederation/oxTrust.git

Edit config-oxtrust.properties using this command:

$ vim oxTrust/profiles/setup/config-oxtrust.properties

Sample configuration:

config.ldap.idp.bindPassword=GENERATED_PASSWD
config.ldap.idp.servers=localhost\:1389
config.ldap.central.bindPassword=GENERATED_PASSWD
config.ldap.central.servers=localhost\:1389
config.appliance.svn_base64_encoded_password=GENERATED_PASSWD
config.host.idp_name=localhost:8080
config.host.idp_mysql_base64_encoded_password=GENERATED_PASSWD
config.host.idp.ldap_base64_encoded_password=GENERATED_PASSWD
config.host.vds.ldap_base64_encoded_password=GENERATED_PASSWD
config.host.keystore_password=GENERATED_PASSWD

Configure Install Script

Clone https://github.com/GluuFederation/install.git using this command:

$ git clone https://github.com/GluuFederation/install.git

Edit install/setup.properties

Set these variables:

platform=unix

dsType=opendj

ldapPW=Password for cn=Directory Manager

dsHome=full path of opendj base install dir [default is /opt/opendj]

oxAuthHome=full path of oxAuth git clone

oxTrustHome=full path of oxTrust git clone

tomcatHome=full path of tomcat base install dir [default is /opt/tomcat]

Start openDj server:

$ opendj/bin/start-ds

Run setup:

$ cd install && python setup.py 2>&1 | tee /tmp/gluu_install.log

Test ox in web browser by loading this URL:

http://localhost:8080/oxTrust

Advanced Install Script Configuration

Install script performs a few step which are well described in setup.properties file:

Generates ldap schema

Generates ldap date

Configures directory server (in this document we stick to OpenDJ)

Build OX Products (oxAuth, oxTrust or any other product). This step can be configured (e.g. to build only oxAuth and skip oxTrust.)

Deploy OX Products to Web Container (Tomcat).

Start Web Container

Please check setup.properties for more details.

Build Project

Install script builds OX Products with "setup" Maven profile:

mvn clean install -Dmaven.test.skip=true -Dcfg=setup

setup.properties

Location: https://github.com/GluuFederation/install/blob/master/setup.properties

##############################
###### Control flow
# Script runs sequentially steps:
# 1. generates LDAP schema;
# 2. generates LDAP data required for correct running of OX products;
# 3. configures Directory Server (with LDAP schema and LDAP data generated in step 1 and 2).
# 4. Builds OX products (e.g. oxAuth, oxTrust)
# 5. Deploy OX products to Application Container(e.g. oxAuth, oxTrust to Tomcat)
# 6. Starts Application Container (Tomcat)
#
# ATTENTION: It's possible to switch on/off each step in setup script.
# However you need to be aware that there is dependencies between steps.
##############################

# Generates LDAP schema for Directory server. Later it's used for Directory server configuration
generateSchema=true

# Generates LDAP data as LDIF. Later is used to import into Directory server.
generateLdapDataLdif=true

# Configures Directory server with LDAP schema and LDAP data generated in previous step.
configureDS=true

# Builds OX products, e.g. oxAuth, oxTrust
buildOX=true

# Deploy OX products
deployOX=true

# Start application container (tomcat)
startContainer=true

##############################
###### Environment and Directory Server configuration
##############################

# Platform, possible values: windows, unix
platform=windows

# Directory server name, possible values: opendj, opends, openldap, apacheds
# ATTENTION : currently ONLY opendj and opends is supported
dsType=opendj

# Directory server home directory
dsHome=/opt/opendj
ldapHost=localhost
ldapPort=1389
ldapDN=cn=directory manager
ldapPW=pw

##############################
###### Schema generation
##############################
schemaFN=101-ox.ldif
userSchemaFN=100-user.ldif
userSchemaTemplateFN=100-user-template.ldif

##############################
###### LDAP Data generation
##############################
dataTemplateFile=template.ldif
dataGeneratedFile=generated-data.ldif
orgInum=@!1111
orgPass=changeit
orgInumNoDelimiters=1111
suffix=o=gluu
orgName=YOUR ORGANIZATION NAME HERE
orgShortName=yourname
l=NOWHERE
givenName=First
sn=Last
uid=you
mail=you@yoursmtp.any
password=changeit
personInum=@!1111!0000
applianceInum=@!1111!0002
groupInum=@!1111!0003
attributeInum=@!1111!0005
applianceQuad=0085
groupQuad=20A0
personQuad=C975

# manager group inum -> used to assign user to manager group, without it oxTrust will not represents complete UI for configuration
managerGroupInum=@!1111!0003!B2C6

# ATTENTION : Client is restricted to localhost ONLY
oxTrustClientId=@!1111!0008!1234!1234

# ATTENTION : Client is restricted to localhost ONLY
# Encoded 12345678-1234-1234-1234-123456789012
oxTrustClientSecret=HdUJNbcCCEuZVGC3SjE6imo5fzDeQTV5HdUJNbcCCEs8n8r/51LyJA==

##############################
###### Build process
# To successfully build OX make sure your Maven is properly configured.
# If you don't have Maven installed, please install it and configure
# as described here: http://maven.apache.org/download.cgi
##############################

# Path to oxAuth directory with sources.
# If you don't have sources please download them from here: https://svn.gluu.info/repository/openxdi/oxAuth/
oxAuthHome=/git/checkout/oxAuth

# Path to oxTrust directory with sources.
# If you don't have sources please download them from here: https://svn.gluu.info/repository/openxdi/oxTrust/
oxTrustHome=/git/checkout/oxTrust

##############################
###### Deploy process
# To successfully deploy OX products make sure your Tomcat is properly configured.
# If you don't have Tomcat installed, please install it and configure
# as described here: http://tomcat.apache.org/download-60.cgi
##############################

# Tomcat home directory
tomcatHome=/opt/tomcat

# Java runtime options used when the "start", "stop", or "run" command is executed of Tomcat catalina.
tomcatJavaOpts=-Xms228M -Xmx1512M -XX:MaxPermSize=292M


text:
module Api
  class PromisesController < ApiController

    def index
      rel = Promise.by_date.includes(:categories)
      rel = rel.random if params[:random]
      rel = rel.with_parliament_period(params[:parliament_period]) if params[:parliament_period]
      rel = rel.page(params[:page] || 1).per(10)
      rel = rel.where(id: params[:ids].split(',')) if params[:ids]

      respond_with rel, random: params[:random], parliament_period: params[:parliament_period]
    end

    def show
      respond_with Promise.includes(:categories).find(params[:id])
    end

  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
 <tileset name="Lucian Room" firstgid="1" tilewidth="16" tileheight="16">
<image source="Lucian Room.png" trans="000000"/>
</tileset>


text:
<?xml version="1.0" encoding="UTF-8"?>

<document xmlns="http://maven.apache.org/XDOC/2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/XDOC/2.0 http://maven.apache.org/xsd/xdoc-2.0.xsd">

  <properties>
    <title>MyBatis 3 | Statement Builders</title>
    <author email="clinton.begin@gmail.com">Clinton Begin</author>
    <author email="eduardo.macarron@gmail.com">Eduardo Macarron</author>
  </properties>

  <subsection name="El Problema">

Una de las cosas más tediosas que un programador Java puede llegar a tener que hacer es incluir código SQL en código Java. Normalmente esto se hace cuando es necesario generar dinámicamente el SQL – de otra forma podrías externalizar el código en un fichero o un procedimiento almacenado. Como ya has visto, MyBatis tiene una respuesta potente a la generación dinámica de SQL mediante las capacidades del mapeo XML. Sin embargo, en ocasiones se hace necesario construir una sentencia SQL dentro del código Java. En este caso, MyBatis tiene una funcionalidad más para ayudarte en ello, antes de que comiences con el típico lío de signos de suma, comillas, líneas nuevas, problemas de formato y condicionales anidados para tratar con las comas extra y las conjunciones AND… Realmente, generar código dinámico en java, puede ser una verdadera pesadilla. Por ejemplo:

<source><![CDATA[
String sql = "SELECT P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME, "
"P.LAST_NAME,P.CREATED_ON, P.UPDATED_ON " +
"FROM PERSON P, ACCOUNT A " +
"INNER JOIN DEPARTMENT D on D.ID = P.DEPARTMENT_ID " +
"INNER JOIN COMPANY C on D.COMPANY_ID = C.ID " +
"WHERE (P.ID = A.ID AND P.FIRST_NAME like ?) " +
"OR (P.LAST_NAME like ?) " +
"GROUP BY P.ID " +
"HAVING (P.LAST_NAME like ?) " +
"OR (P.FIRST_NAME like ?) " +
"ORDER BY P.ID, P.FULL_NAME";
]]></source>
  </subsection>

  <subsection name="La Solución">

MyBatis 3 introduce un concepto un tanto distinto para tratar con el problema.
    Con la clase SQL, puecdes crear una sentencia SQL en un sólo paso invocando a sus métodos.
    El ejemplo anterior tendría este aspecto si se rescribe con la clase SQL:

      <source><![CDATA[
private String selectPersonSql() {
  return new SQL() {{
    SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME");
    SELECT("P.LAST_NAME, P.CREATED_ON, P.UPDATED_ON");
    FROM("PERSON P");
    FROM("ACCOUNT A");
    INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID");
    INNER_JOIN("COMPANY C on D.COMPANY_ID = C.ID");
    WHERE("P.ID = A.ID");
    WHERE("P.FIRST_NAME like ?");
    OR();
    WHERE("P.LAST_NAME like ?");
    GROUP_BY("P.ID");
    HAVING("P.LAST_NAME like ?");
    OR();
    HAVING("P.FIRST_NAME like ?");
    ORDER_BY("P.ID");
    ORDER_BY("P.FULL_NAME");
  }}.toString();
}
]]></source>

¿Qué hay de especial en este ejemplo?
      Bien, si lo miras detenidamente, verás que no hay que preocuparse de duplicar "AND"s, o elegir entre "WHERE" o "AND", o ninguno de ambos!
      La clase SQL se ocupa de colocar el "WHERE" donde debe de ir, si debe usarse "AND" o no y de realizar todas las concatenaciones de Strings.

    </subsection>
      <subsection name="La clase SQL">

Aqui van algunos ejemplos:

        <source><![CDATA[
// Anonymous inner class
public String deletePersonSql() {
  return new SQL() {{
    DELETE_FROM("PERSON");
    WHERE("ID = #{id}");
  }}.toString();
}

// Builder / Fluent style
public String insertPersonSql() {
  String sql = new SQL()
    .INSERT_INTO("PERSON")
    .VALUES("ID, FIRST_NAME", "#{id}, #{firstName}")
    .VALUES("LAST_NAME", "#{lastName}")
    .toString();
  return sql;
}

// With conditionals (note the final parameters, required for the anonymous inner class to access them)
public String selectPersonLike(final String id, final String firstName, final String lastName) {
  return new SQL() {{
    SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FIRST_NAME, P.LAST_NAME");
    FROM("PERSON P");
    if (id != null) {
      WHERE("P.ID like #{id}");
    }
    if (firstName != null) {
      WHERE("P.FIRST_NAME like #{firstName}");
    }
    if (lastName != null) {
      WHERE("P.LAST_NAME like #{lastName}");
    }
    ORDER_BY("P.LAST_NAME");
  }}.toString();
}

public String deletePersonSql() {
  return new SQL() {{
    DELETE_FROM("PERSON");
    WHERE("ID = #{id}");
  }}.toString();
}

public String insertPersonSql() {
  return new SQL() {{
    INSERT_INTO("PERSON");
    VALUES("ID, FIRST_NAME", "#{id}, #{firstName}");
    VALUES("LAST_NAME", "#{lastName}");
  }}.toString();
}

public String updatePersonSql() {
  return new SQL() {{
    UPDATE("PERSON");
    SET("FIRST_NAME = #{firstName}");
    WHERE("ID = #{id}");
  }}.toString();
}
]]></source>

              Metodo
              Descripción

          SELECT(String)

          SELECT(String...)

    Comienza o añade a una sentencia SELECT. Se puede invocar más de una vez y los parámetros se irán añadiendo a la sentencia SELECT. Los parámetros son normalmente una lista de columnas o alias separados por comas, pero puede ser cualquier cosa que acepte el driver de base de datos.

          SELECT_DISTINCT(String)

          SELECT_DISTINCT(String...)

    Comienza o añade a una sentencia SELECT, también añade la palabra clave "DISTINCT" a la sentencia generada. Se puede invocar más de una vez y los parámetros se irán añadiendo a la sentencia SELECT. Los parámetros son normalmente una lista de columnas o alias separados por comas, pero puede ser cualquier cosa que acepte el driver de base de datos.

          FROM(String)

          FROM(String...)

    Comienza o añade a una cláusula FROM. Se puede invocar más de una vez y los parámetros se irán añadiendo a la clausula FROM. Los parámetros son normalmente un nombre de tabla o alias o cualquier cosa que acepte el driver de base de datos.

          JOIN(String)

          JOIN(String...)

          INNER_JOIN(String)

          INNER_JOIN(String...)

          LEFT_OUTER_JOIN(String)

          LEFT_OUTER_JOIN(String...)

          RIGHT_OUTER_JOIN(String)

          RIGHT_OUTER_JOIN(String...)

    Añade una nueva clausula JOIN del tipo apropiado, dependiendo al método que se haya llamado. El parámetro puede incluir un join estándar que consiste en las columnas y las condiciones sobre las que hacer la join.

          WHERE(String)

          WHERE(String...)

    Añade una nueva condición a la clausula WHERE concatenada con un AND. Puede llamarse más de una vez, lo cual hará que se añadan más condiciones todas ellas concatenadas con un AND. O usa OR() para partirlas con un OR().

      OR()

    Parte las condiciones actuales de la WHERE con un OR. Puede llamarse más de una vez, pero llamarlas más de una vez en la misma línea puede producir sentencias incorrectas.

      AND()

    Parte las condiciones actuales de la WHERE con un AND. Puede llamarse más de una vez, pero llamarlas más de una vez en la misma línea puede producir sentencias incorrectas.  Dado que WHERE y HAVING concatenan automáticamente el AND, es muy infrecuente que sea necesario invocar a este método y se incluye realmente por completitud.

          GROUP_BY(String)

          GROUP_BY(String...)

    Añade una nueva clausula GROUP BY grupo, concatenada con una coma. Se le puede llamar más de una vez, lo cual hará que se concatenen nuevas condiciones separadas también por coma.

          HAVING(String)

          HAVING(String...)

    Añade una nueva clausula HAVING, concatenada con un AND. Se le puede llamar más de una vez, lo cual hará que se concatenen nuevas condiciones separadas también por AND. Usa OR() para dividirlas por OR.

          ORDER_BY(String)

          ORDER_BY(String...)

    Añade un Nuevo elemento a la clausula ORDER BY concatenado por coma. Se le puede llamar más de una vez, lo cual hará que se concatenen nuevas condiciones separadas también por coma.

      DELETE_FROM(String)

    Comienza una sentencia delete y especifica la tabla donde borrar. Generalmente suele ir seguida de una clausula WHERE!

      INSERT_INTO(String)

    Comienza una sentencia insert y especifica al tabla en la que insertar. Suele ir seguida de una o más llamadas a VALUES().

          SET(String)

          SET(String...)

    Añade a la lista "set" de una update.

      UPDATE(String)

    Comienza una sentencia update y especifica la tabla que modificar Suele ir seguida de una o más llamadas a SET() y normalmente de una llamada a WHERE().

      VALUES(String, String)

    Añade a una sentencia insert. El primer parámetro es el nombre de columna y el Segundo el valor(es).

      </subsection>

      <subsection name="SqlBuilder y SelectBuilder (DEPRECADAS)">

          En versiones anteriores a la 3.2 optamos por una solución distinta, usando una variable ThreadLocal para
          resolver algunas limitaciones de las que hacen los DSLs Java algo incomodos. Sin embargo, esta solución está ahora
          desprecada porque los frameworks actuales están mas orientados a usar patrones builder-type y clases anónimas
          interas para este tipo de cosas. Por lo tanto las clases SelectBuilder y SqlBuilder están ahora deprecadas.

          Los siguientes métodos aplican solo a las clases deprecadas SqlBuilder y SelectBuilder.

            Método
            Descripción

      BEGIN() / RESET()

    Estos métodos limpian estado guardad en el ThreadLocal de la clase SelectBuilder, y la preparan para construir una nueva sentencia. BEGIN() se lee mejor cuando se está creando una sentencia. RESET() se lee mejor cuando se está borrando lo hecho anteriormente en medio de una ejecución (quizá porque la lógica necesita una sentencia completamente distinta según las condiciones).

      SQL()

    Devuelve la SQL generada y restablece el estado del SelectBuilder (como si se hubiera llamado a un BEGIN() o a un RESET()). Por tanto este método solo se puede llamar una vez!

La clase SelectBuilder no es mágica, pero es importante que conozcas cómo funcionan.
  SelectBuilder y SqlBuilder usan una combinación de imports estáticos y una variable ThreadLocal para permitir una sintaxis más limpia más fácilmente usabe con condicionales.
  Para usarlas debes importar estáticamente métodos de las siguientes clases (uno u otro, no ambos):

        <source>import static org.apache.ibatis.jdbc.SelectBuilder.*;</source>
        <source>import static org.apache.ibatis.jdbc.SqlBuilder.*;</source>

De esta forma podrás crear métodos como estos:

        <source><![CDATA[
/* DEPRECATED */
public String selectBlogsSql() {
  BEGIN(); // Clears ThreadLocal variable
  SELECT("*");
  FROM("BLOG");
  return SQL();
}
        ]]></source>

        <source><![CDATA[
/* DEPRECATED */
private String selectPersonSql() {
  BEGIN(); // Clears ThreadLocal variable
  SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME");
  SELECT("P.LAST_NAME, P.CREATED_ON, P.UPDATED_ON");
  FROM("PERSON P");
  FROM("ACCOUNT A");
  INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID");
  INNER_JOIN("COMPANY C on D.COMPANY_ID = C.ID");
  WHERE("P.ID = A.ID");
  WHERE("P.FIRST_NAME like ?");
  OR();
  WHERE("P.LAST_NAME like ?");
  GROUP_BY("P.ID");
  HAVING("P.LAST_NAME like ?");
  OR();
  HAVING("P.FIRST_NAME like ?");
  ORDER_BY("P.ID");
  ORDER_BY("P.FULL_NAME");
  return SQL();
}
        ]]></source>

      </subsection>

</document>


text:
/**
 * Test case for resolver.
 * Runs with mocha.
 */
'use strict'

const resolver = require('../lib/resolver.js')
const assert = require('assert')
const co = require('co')

describe('resolver', function () {
  this.timeout(3000)

  before(() => co(function * () {

  }))

  after(() => co(function * () {

  }))

  it('Resolver', () => co(function * () {
    let defined = resolver({
      captions: {
        USER_LIST: 'List of users'
      }
    })
    assert.equal(
      defined('captions.USER_LIST'),
      'List of users'
    )
    assert.deepEqual(
      defined({ foo: 'captions.USER_LIST' }),
      { foo: 'List of users' }
    )
  }))

  it('Define multiple resolver', () => co(function * () {
    let defined = resolver.combine({
      en: {
        captions: {
          USER_LIST: 'List of users'
        }
      }
    })
    assert.equal(
      defined.en('captions.USER_LIST'),
      'List of users'
    )
  }))
})

/* global describe, before, after, it */


text:
using System;
using System.Runtime.CompilerServices;
public class BringUpTest
{
    const int Pass = 100;
    const int Fail = -1;

    [MethodImplAttribute(MethodImplOptions.NoInlining)]
    public static int AsgOr1(int x) { x |= 0xa; return x; }

    public static int Main()
    {
        if (AsgOr1(4) == 0xe) return Pass;
        else return Fail;
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Vevo;
using Vevo.Domain;
using Vevo.Domain.DataInterfaces;
using Vevo.Domain.Marketing;
using Vevo.Domain.Orders;
using Vevo.Domain.Products;
using Vevo.Domain.Stores;
using Vevo.Shared.Utilities;
using Vevo.WebUI;
using Vevo.Base.Domain;
using Vevo.Deluxe.Domain.Products;

public partial class Admin_Components_ProductKitProductList : AdminAdvancedBaseListControl
{
    #region Private
    private const int ProductIDColumnIndex = 1;
    private const int StockColumnIndex = 5;
    private const int RetailColumnIndex = 7;

    public Culture CurrentCulture
    {
        get
        {
            if (ViewState["CurrentCulture"] == null)
                return new Culture();
            else
                return (Culture) ViewState["CurrentCulture"];
        }
        set
        {
            ViewState["CurrentCulture"] = value;
            RefreshGrid();
        }

    }

    public string ProductKitGroupID
    {
        get
        {
            if (ViewState["ProductKitGroupID"] == null)
                return "0";
            else
                return ViewState["ProductKitGroupID"].ToString();
        }
        set
        {
            ViewState["ProductKitGroupID"] = value;
        }

    }

    private string SelectedStoreID
    {
        get
        {
            if (MainContext.QueryString["StoreID"] == null)
                return Store.RegularStoreID;
            else
                return MainContext.QueryString["StoreID"];
        }
    }

    private string RootCategoryValue
    {
        get
        {
            if (!KeyUtilities.IsMultistoreLicense())
                return DataAccessContext.Configurations.GetValue(
                    "RootCategory",
                    DataAccessContext.StoreRepository.GetOne( Store.RegularStoreID ) );
            else
                return uxCategoryFilterDrop.SelectedRootValue;
        }
    }

    private void SetUpSearchFilter()
    {
        IList<TableSchemaItem> list = DataAccessContext.ProductRepository.GetTableSchema();
        uxSearchFilter.SetUpSchema( list, "UrlName",
            "UseDefaultMetaKeyword", "UseDefaultMetaDescription",
            "UseDefaultPrice", "UseDefaultRetailPrice",
            "UseDefaultWholeSalePrice", "UseDefaultWholeSalePrice2", "UseDefaultWholeSalePrice3" );
    }

    private void PopulateControls()
    {
        if (!MainContext.IsPostBack)
        {
            RefreshGrid();
        }

        if (uxGridProduct.Rows.Count > 0)
        {
            uxPagingControl.Visible = true;
        }
        else
        {
            uxPagingControl.Visible = false;
        }
    }

    private bool IsAnyOptionOutOfStock( string productID )
    {
        Product product = DataAccessContext.ProductRepository.GetOne(
            CurrentCulture, productID, new StoreRetriever().GetCurrentStoreID() );
        return product.IsOutOfStock();
    }

    private bool TaxIncludeVisibility()
    {
        return DataAccessContext.Configurations.GetBoolValue( "TaxIncludedInPrice" );
    }

    private void SetUpGridSupportControls()
    {
        if (!MainContext.IsPostBack)
        {
            uxPagingControl.ItemsPerPages = AdminConfig.ProductItemsPerPage;
            SetUpSearchFilter();
            uxCategoryFilterDrop.CultureID = CurrentCulture.CultureID;
            uxCurrencyControl.StoreID = SelectedStoreID;
        }

        RegisterGridView( uxGridProduct, "ProductID" );

        RegisterSearchFilter( uxSearchFilter );
        RegisterPagingControl( uxPagingControl );
        RegisterCategoryFilterDrop( uxCategoryFilterDrop );
        RegisterCurrencyFilterDrop( uxCurrencyControl );

        uxSearchFilter.BubbleEvent += new EventHandler( uxSearchFilter_BubbleEvent );
        uxPagingControl.BubbleEvent += new EventHandler( uxPagingControl_BubbleEvent );
        uxCategoryFilterDrop.BubbleEvent += new EventHandler( uxCategoryFilterDrop_BubbleEvent );
        uxCurrencyControl.BubbleEvent += new EventHandler( uxCurrencyControl_BubbleEvent );
    }

    #endregion

    protected void Page_Load( object sender, EventArgs e )
    {
        SetUpGridSupportControls();
        DataAccessContext.SetStoreRetriever( new StoreRetriever( SelectedStoreID ) );
    }

    protected void Page_PreRender( object sender, EventArgs e )
    {
        if (!MainContext.IsPostBack)
        {
            uxCurrencyControl.StoreID = SelectedStoreID;

            uxCategoryFilterDrop.CultureID = CurrentCulture.CultureID;
            uxCategoryFilterDrop.RefreshCategoryDropList(
            "0" );

            StoreContext.ClearCheckoutSession();
        }

        uxCurrencyControl.StoreID = SelectedStoreID;
        PopulateControls();
    }

    protected void uxGridProduct_RowDataBound( object sender, GridViewRowEventArgs e )
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string productID = e.Row.Cells[ProductIDColumnIndex].Text.Trim();
            int result;
            if (DataAccessContext.Configurations.GetBoolValue( "UseStockControl" ))
            {
                if (int.TryParse( productID, out result ))
                {
                    if (IsAnyOptionOutOfStock( productID ))
                    {
                        foreach (TableCell cell in e.Row.Cells)
                        {
                            cell.Style.Add( "color", "#ff0000" );
                        }
                    }
                }
            }

            if (e.Row.RowIndex > -1)
            {
                if ((e.Row.RowIndex % 2) == 0)
                {
                    // Even
                    e.Row.Attributes.Add( "onmouseover", "this.className='DefaultGridRowStyleHover'" );
                    e.Row.Attributes.Add( "onmouseout", "this.className='DefaultGridRowStyle'" );
                }
                else
                {
                    // Odd
                    e.Row.Attributes.Add( "onmouseover", "this.className='DefaultGridRowStyleHover'" );
                    e.Row.Attributes.Add( "onmouseout", "this.className='DefaultGridAlternatingRowStyle'" );
                }
            }
        }
    }

    protected string GetStockText( string sumStock, object isGiftCertificate, object useInventory )
    {
        if (!ConvertUtilities.ToBoolean( useInventory ))
            return "-";
        else
            return sumStock;
    }

    protected string GetPrice( object productID )
    {
        Product product = DataAccessContext.ProductRepository.GetOne( CurrentCulture, (string) productID, SelectedStoreID );

        decimal price;
        if (!product.IsCustomPrice)
            price = product.GetDisplayedPrice( StoreContext.WholesaleStatus, SelectedStoreID );
        else
            price = product.ProductCustomPrice.DefaultPrice;

        return uxCurrencyControl.CurrentCurrency.FormatPrice( price );

    }

    protected string GetRetailPrice( object productID )
    {
        Product product = DataAccessContext.ProductRepository.GetOne( CurrentCulture, (string) productID, SelectedStoreID );
        ProductPrice productPrice = product.GetProductPrice( SelectedStoreID );
        return uxCurrencyControl.CurrentCurrency.FormatPrice( productPrice.RetailPrice );
    }

    protected override void RefreshGrid()
    {
        int totalItems;

        uxGridProduct.DataSource = DataAccessContext.ProductRepository.SearchProduct(
            CurrentCulture,
            uxCategoryFilterDrop.SelectedValue,
            GridHelper.GetFullSortText(),
            uxSearchFilter.SearchFilterObj,
            uxPagingControl.StartIndex,
            uxPagingControl.EndIndex,
            out totalItems,
            SelectedStoreID,
            RootCategoryValue );
        uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages );

        uxGridProduct.DataBind();
    }

    protected string GetName( object cartItem )
    {
        return ((CartItem) cartItem).GetName( CurrentCulture, uxCurrencyControl.CurrentCurrency );
    }

    protected string GetTooltipText( object cartItem )
    {
        string mainText;
        return ((CartItem) cartItem).GetPreCheckoutTooltip(
            uxCurrencyControl.CurrentCurrency,
            StoreContext.WholesaleStatus,
            "Recurring Billing",
            "This product requires recurring payments, which will be charged from your credit card regularly.",
            "*Price above does not include discount, tax and shipping price.",
            SelectedStoreID,
            out mainText ).Replace( "<br/>", "\n" );
    }

    protected bool IsRecurringTooltipVisible( object cartItem )
    {
        return ((CartItem) cartItem).IsRecurring;
    }

    protected string GetUnitPriceText( object cartItem )
    {
        return uxCurrencyControl.CurrentCurrency.FormatPrice( ((CartItem) cartItem).GetShoppingCartUnitPrice(
            StoreContext.WholesaleStatus ) );
    }

    protected string GetSubtotalText( object cartItem )
    {
        CartItem item = ((CartItem) cartItem);

        return uxCurrencyControl.CurrentCurrency.FormatPrice(
            item.GetShoppingCartUnitPrice( StoreContext.WholesaleStatus )
            * item.Quantity );
    }

    private bool IsOptionProduct( string productID )
    {
        Product product = DataAccessContext.ProductRepository.GetOne( CurrentCulture, productID, StoreContext.CurrentStore.StoreID );
        if (product.ProductOptionGroups.Count > 0)
            return true;
        else
            return false;
    }

    private bool IsDuplicateItems( IList<ProductKitItem> productKitItems, ProductKitItem newKitItem )
    {
        foreach (ProductKitItem productKitItem in productKitItems)
        {
            if (productKitItem.ProductID == newKitItem.ProductID)
            {
                return true;
            }
        }
        return false;
    }

    private IList<ProductKitItem> UpdateItemDefault( IList<ProductKitItem> productKitItems, ProductKitItem newKitItem )
    {
        IList<ProductKitItem> newList = new List<ProductKitItem>();
        if (newKitItem.IsDefault)
        {
            foreach (ProductKitItem productKitItem in productKitItems)
            {
                if (productKitItem.ProductID != newKitItem.ProductID)
                {
                    productKitItem.IsDefault = false;
                }
                newList.Add( productKitItem );
            }
        }
        else
        {
            newList = productKitItems;
        }

        return newList;
    }

    private void DisplayErrorAndPopup( string message )
    {
        uxProductKitProductDetails.DisplayError( message );
        uxAddItemButtonModalPopup.Show();
    }

    private bool IsProductValid( Product product )
    {
        bool result = true;

        ProductSubscription subscriptionItem = new ProductSubscription( product.ProductID );

        if (subscriptionItem.IsSubscriptionProduct())
        {
            uxMessage.DisplayError( "Cannot Add Subscription Product." );
            result = false;
        }
        else if (product.IsProductKit)
        {
            uxMessage.DisplayError( "Cannot Add Product that already a Kit." );
            result = false;
        }
        else if (product.ProductOptionGroups.Count > 0)
        {
            uxMessage.DisplayError( "Cannot Add Product with Product Option." );
            result = false;
        }
        else if (product.IsDownloadable)
        {
            uxMessage.DisplayError( "Cannot Add Downloable Product." );
            result = false;
        }
        else if (product.IsRecurring)
        {
            uxMessage.DisplayError( "Cannot Add Recurring Product." );
            result = false;
        }
        else if (product.IsGiftCertificate)
        {
            uxMessage.DisplayError( "Cannot Add Gift Certificate product." );
            result = false;
        }

        return result;
    }

    protected void uxAddItemButton_Click( object sender, EventArgs e )
    {
        string errMeg = String.Empty;
        try
        {
            ProductKitGroup productKitGroup = DataAccessContext.ProductKitGroupRepository.GetOne( CurrentCulture, ProductKitGroupID );

            ProductKitItem productKitItem = new ProductKitItem();
            productKitItem.ProductID = uxProductKitProductDetails.ProductID;
            productKitItem.ProductKitGroupID = ProductKitGroupID;
            productKitItem.Quantity = uxProductKitProductDetails.Quantity;
            productKitItem.IsDefault = uxProductKitProductDetails.IsDefault;
            productKitItem.IsUserDefinedQuantity = uxProductKitProductDetails.IsUserDefinedQuantity;

            if (!IsDuplicateItems( productKitGroup.ProductKitItems, productKitItem ))
            {
                productKitGroup.ProductKitItems.Add( productKitItem );
                productKitGroup.ProductKitItems = UpdateItemDefault( productKitGroup.ProductKitItems, productKitItem );
                DataAccessContext.ProductKitGroupRepository.Save( productKitGroup );
                uxMessage.DisplayMessage( Resources.ProductKitGroupItemMessages.ItemAddSuccess );
                OnBubbleEvent( e );
                uxProductKitProductDetails.ClearCheckBox();
            }
            else
            {
                uxMessage.DisplayError( "Product already exist in this Group" );
            }
        }
        catch (Exception ex)
        {
            MessageControl.DisplayError( ex.ToString() );
        }
    }

    protected void uxAddItemButton_Command( object sender, CommandEventArgs e )
    {
        uxProductKitProductDetails.ClearCheckBox();

        string productID = e.CommandArgument.ToString();
        Product product = DataAccessContext.ProductRepository.GetOne(
            CurrentCulture, productID, SelectedStoreID );

        if (IsProductValid( product ))
        {
            uxProductKitProductDetails.StoreID = SelectedStoreID;
            uxProductKitProductDetails.CultureID = CurrentCulture.CultureID;
            uxProductKitProductDetails.ProductID = productID;
            uxProductKitProductDetails.CurrencyCode = uxCurrencyControl.CurrentCurrencyCode;
            uxProductKitProductDetails.PopulateControls();
            uxAddItemPanel.Visible = true;
            uxAddItemButton.Visible = true;
            uxAddItemButtonModalPopup.Show();
        }
    }

    public void UpdateCategoryLanguage()
    {
        uxCategoryFilterDrop.CultureID = CurrentCulture.CultureID;
        RefreshGrid();
    }
}