text:
package com.xeiam.xchange.btccentral;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;

import org.junit.Test;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.btccentral.dto.marketdata.BTCCentralMarketDepth;
import com.xeiam.xchange.btccentral.dto.marketdata.BTCCentralTicker;
import com.xeiam.xchange.btccentral.dto.marketdata.BTCCentralTrade;
import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.dto.marketdata.OrderBook;
import com.xeiam.xchange.dto.marketdata.Ticker;
import com.xeiam.xchange.dto.marketdata.Trades;

/**
 * @author ObsessiveOrange
 */
public class AdaptersTest {

  @Test
  public void testBTCCentralTickerRequest() throws JsonParseException, JsonMappingException, IOException {

    // Read in the JSON from the example resources
    InputStream is = AdaptersTest.class.getResourceAsStream("/Example_TickerData.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    BTCCentralTicker btcCentralTicker = mapper.readValue(is, BTCCentralTicker.class);

    Ticker genericTicker = BTCCentralAdapters.adaptTicker(btcCentralTicker, CurrencyPair.BTC_EUR);

    assertEquals(genericTicker.getAsk(), new BigDecimal("20.4"));
    assertEquals(genericTicker.getBid(), new BigDecimal("20.1"));
    assertEquals(genericTicker.getHigh(), new BigDecimal("20.74"));
    assertEquals(genericTicker.getLow(), new BigDecimal("20.2"));
    assertEquals(genericTicker.getLast(), new BigDecimal("20.2"));
    assertEquals(genericTicker.getVolume(), new BigDecimal("148.80193218"));

  }

  @Test
  public void testBTCCentralDepthRequest() throws JsonParseException, JsonMappingException, IOException {

    // Read in the JSON from the example resources
    InputStream is = AdaptersTest.class.getResourceAsStream("/Example_DepthData.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    BTCCentralMarketDepth btcCentralMarketDepth = mapper.readValue(is, BTCCentralMarketDepth.class);

    OrderBook genericOrderBook = BTCCentralAdapters.adaptMarketDepth(btcCentralMarketDepth, CurrencyPair.BTC_EUR);

    assertEquals(genericOrderBook.getAsks().get(0).getTradableAmount(), new BigDecimal("0.48762"));
    assertEquals(genericOrderBook.getAsks().get(0).getLimitPrice(), new BigDecimal("24.48996"));
    assertEquals(genericOrderBook.getBids().get(0).getTradableAmount(), new BigDecimal("0.40491093"));
    assertEquals(genericOrderBook.getBids().get(0).getLimitPrice(), new BigDecimal("24.001"));

  }

  @Test
  public void testBTCCentralTradesRequest() throws JsonParseException, JsonMappingException, IOException {

    // Read in the JSON from the example resources
    InputStream is = AdaptersTest.class.getResourceAsStream("/Example_TradesData.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    BTCCentralTrade[] btcCentralTrades = mapper.readValue(is, BTCCentralTrade[].class);

    Trades genericTrades = BTCCentralAdapters.adaptTrade(btcCentralTrades, CurrencyPair.BTC_EUR);

    assertEquals(genericTrades.getTrades().get(0).getPrice(), new BigDecimal("5.0"));
    assertEquals(genericTrades.getTrades().get(0).getTradableAmount(), new BigDecimal("980.0"));

  }

}


text:
local ui = require "tek.ui"

local Group = ui.Group
local Text = ui.Text

local window = require "dash1090.ui.stats"
local tally = require "dash1090.tally"
local exec = require "tek.lib.exec"
local _d = require "tek.lib.debug"

-- Application Messages

-- * QUIT: Exits the Program
-- * MSG: An undecoded basestation (SBS1) formatted message
-- *

function handleSignals(self)
    _d.info("Main task signals: " .. (exec.getsignals() or "No Signals"))
end

local setup = function(self)
    ui.Application.setup(self)
    tally:load()
    self:addInputHandler(ui.MSG_USER, tally, tally.process)
    self:addInputHandler(ui.MSG_SIGNAL, self, handleSignals)
end

local cleanup = function(self)
    _d.trace("Cleanup")
    ui.Application.cleanup(self)
    self:remInputHandler(ui.MSG_USER, tally, tally.process)
    tally:unload()
    self:remInputHandler(ui.MSG_SIGNAL, self, handleAbort)
end

local app = ui.Application:new{ setup = setup, cleanup = cleanup}

app.tally = tally

window(ui, app)

return app

redpajama_set_name: RedPajamaGithub


text:
.. _usage:

=====
Usage
=====

This document covers the usage of django-user-accounts. It assumes you've
read :ref:`installation`.

django-user-accounts has very good default behavior when handling user
accounts. It has been designed to be customizable in many aspects. By default
this app will:

* enable username authentication
* provide default views and forms for sign up, log in, password reset and
  account management
* handle log out with POST
* require unique email addresses globally
* require email verification for performing password resets

The rest of this document will cover how you can tweak the default behavior
of django-user-accounts.

Customizing the sign up process
===============================

In many cases you need to tweak the sign up process to do some domain specific
tasks. Perhaps you need to update a profile for the new user or something else.
The built-in ``SignupView`` has hooks to enable just about any sort of
customization during sign up. Here's an example of a custom ``SignupView``
defined in your project::

    import account.views

    class SignupView(account.views.SignupView):

        def after_signup(self, form):
            self.update_profile(form)
            super(SignupView, self).after_signup(form)

        def update_profile(self, form):
            profile = self.created_user.get_profile()
            profile.some_attr = "some value"
            profile.save()

This example assumes you had a receiver hooked up to the `post_save` signal for
the sender, `User` like so::

    from django.dispatch import receiver
    from django.db.models.signals import post_save

    from django.contrib.auth.models import User

    from mysite.profiles.models import UserProfile

    @receiver(post_save, sender=User)
    def handle_user_save(sender, instance, created, **kwargs):
        if created:
            UserProfile.objects.create(user=instance)

You can define your own form class to add fields to the sign up process::

    # forms.py

    from django import forms
    from django.forms.extras.widgets import SelectDateWidget

    import account.forms

    class SignupForm(account.forms.SignupForm):

        birthdate = forms.DateField(widget=SelectDateWidget(years=range(1910, 1991)))

    # views.py

    import account.views

    import myproject.forms

    class SignupView(account.views.SignupView):

       form_class = myproject.forms.SignupForm

       def after_signup(self, form):
           self.create_profile(form)
           super(SignupView, self).after_signup(form)

       def create_profile(self, form):
           profile = self.created_user.get_profile()
           profile.birthdate = form.cleaned_data["birthdate"]
           profile.save()

To hook this up for your project you need to override the URL for sign up::

    from django.conf.urls import patterns, include, url

    import myproject.views

    urlpatterns = patterns("",
        url(r"^account/signup/$", myproject.views.SignupView.as_view(), name="account_signup"),
        url(r"^account/", include("account.urls")),
    )

.. note::

    Make sure your ``url`` for ``/account/signup/`` comes *before* the
    ``include`` of ``account.urls``. Django will short-circuit on yours.

Using email address for authentication
======================================

django-user-accounts allows you to use email addresses for authentication
instead of usernames. You still have the option to continue using usernames
or get rid of them entirely.

To enable email authentication do the following:

1. check your settings for the following values::

       ACCOUNT_EMAIL_UNIQUE = True
       ACCOUNT_EMAIL_CONFIRMATION_REQUIRED = True

   .. note::

       If you need to change the value of ``ACCOUNT_EMAIL_UNIQUE`` make sure your
       database schema is modified to support a unique email column in
       ``account_emailaddress``.

   ``ACCOUNT_EMAIL_CONFIRMATION_REQUIRED`` is optional, but highly
   recommended to be ``True``.

2. define your own ``LoginView`` in your project::

       import account.forms
       import account.views

       class LoginView(account.views.LoginView):

           form_class = account.forms.LoginEmailForm

3. ensure ``"account.auth_backends.EmailAuthenticationBackend"`` is in ``AUTHENTICATION_BACKENDS``

If you want to get rid of username you'll need to do some extra work:

1. define your own ``SignupForm`` and ``SignupView`` in your project::

       # forms.py

       import account.forms

       class SignupForm(account.forms.SignupForm):

           def __init__(self, *args, **kwargs):
               super(SignupForm, self).__init__(*args, **kwargs)
               del self.fields["username"]

       # views.py

       import account.views

       import myproject.forms

       class SignupView(account.views.SignupView):

           form_class = myproject.forms.SignupForm

           def generate_username(self, form):
               # do something to generate a unique username (required by the
               # Django User model, unfortunately)
               username = "<magic>"
               return username

2. many places will rely on a username for a User instance.
   django-user-accounts provides a mechanism to add a level of indirection
   when representing the user in the user interface. Keep in mind not
   everything you include in your project will do what you expect when
   removing usernames entirely.

   Set ``ACCOUNT_USER_DISPLAY`` in settings to a callable suitable for your
   site::

       ACCOUNT_USER_DISPLAY = lambda user: user.email

   Your Python code can use ``user_display`` to handle user representation::

       from account.utils import user_display
       user_display(user)

   Your templates can use ``{% user_display request.user %}``::

       {% load account_tags %}
       {% user_display request.user %}

Allow non-unique email addresses
================================

If your site requires that you support non-unique email addresses globally
you can tweak the behavior to allow this.

Set ``ACCOUNT_EMAIL_UNIQUE`` to ``False``. If you have already setup the
tables for django-user-accounts you will need to migrate the
``account_emailaddress`` table::

   ALTER TABLE "account_emailaddress" ADD CONSTRAINT "account_emailaddress_user_id_email_key" UNIQUE ("user_id", "email");
   ALTER TABLE "account_emailaddress" DROP CONSTRAINT "account_emailaddress_email_key";

``ACCOUNT_EMAIL_UNIQUE = False`` will allow duplicate email addresses per
user, but not across users.


text:
package net.nemerosa.ontrack.service.support;

import net.nemerosa.ontrack.job.*;
import net.nemerosa.ontrack.model.support.ApplicationLogService;
import net.nemerosa.ontrack.model.support.JobProvider;
import net.nemerosa.ontrack.model.support.OntrackConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;

@Component
public class ApplicationLogCleanupJobProvider implements JobProvider, Job {

    private final OntrackConfigProperties configProperties;
    private final ApplicationLogService service;

    @Autowired
    public ApplicationLogCleanupJobProvider(OntrackConfigProperties configProperties, ApplicationLogService service) {
        this.configProperties = configProperties;
        this.service = service;
    }

    @Override
    public Collection<JobRegistration> getStartingJobs() {
        return Collections.singleton(
                JobRegistration.of(this).withSchedule(Schedule.EVERY_DAY)
        );
    }

    @Override
    public JobKey getKey() {
        return JobCategory.CORE.getType("application-log-cleanup").withName("Application log cleanup")
                .getKey("main");
    }

    @Override
    public JobRun getTask() {
        return runListener -> service.cleanup(configProperties.getApplicationLogRetentionDays());
    }

    @Override
    public String getDescription() {
        return "Cleanup of application logs after a given retention period";
    }

    @Override
    public boolean isDisabled() {
        return false;
    }
}


text:
package com.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.orm.Medinfo;
import com.orm.Supplier;
import com.orm.SystemUser;
import com.service.MedicineService;
import com.service.SupplierService;
import com.service.UserService;

@SuppressWarnings("serial")
public class MedicineAction extends ActionSupport {

   private Medinfo medicineinfo;
   private String supid;
   @Autowired
   MedicineService medicineservice;
   @Autowired
   SupplierService supplierservice;
	@Override
    public String execute() throws Exception {
        return ERROR;
    }
	public String ListAll() throws Exception {
        return "ListAll";
    }
	public String List() throws Exception {
        return "List";
    }
	public String addmedicine() throws Exception {
        //添加用户
//		Date makedate=medicineinfo.getMaketime();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		medicineinfo.setMaketime(format.parse(format.format(medicineinfo.getMaketime())));
		medicineinfo.setUserfultime((format.parse(format.format(medicineinfo.getUserfultime()))));
		medicineinfo.setSupplier(supplierservice.findSupplierByid(getSupid()));
        boolean flag=medicineservice.saveOrUpdate(medicineinfo);
        if (flag) {
            return "addSuccess";
        }
        return ERROR;
    }
	public String modmedicine() throws Exception {
        //添加用户
		HttpServletRequest request = ServletActionContext.getRequest();
		Medinfo Medinfo=medicineservice.findMedicineByid(request.getParameter("id"));
        if (Medinfo!=null) {
        	setMedicineinfo(Medinfo);
            return "modpage";
        }
        return ERROR;
    }
	public String delmedicine() throws Exception {
        //添加用户
		HttpServletRequest request = ServletActionContext.getRequest();
		boolean flag=medicineservice.deleteMedicineByid(request.getParameter("id"));
        if (flag) {
            return "ListAll";
        }
        return ERROR;
    }
    public String exit() {
        ActionContext.getContext().getSession().clear();
        return "exit";
    }
	public Medinfo getMedicineinfo() {
		return medicineinfo;
	}
	public void setMedicineinfo(Medinfo medicineinfo) {
		this.medicineinfo = medicineinfo;
	}
	public String getSupid() {
		return supid;
	}
	public void setSupid(String supid) {
		this.supid = supid;
	}

}


text:
var command = require('shell/command'),
    returnMeta = require('misc').returnMeta,
    autocomplete = require('shell/autocomplete').autocomplete;

/**
 * Message processor.
 *
 * Reads messages and executes them, and routes back results.
 */
var workerProcessor = exports.processor = function (inStream, outStream) {
  // Set up stream callbacks.
  var that = this;
  inStream.on('data', function (data) { that.data(data); });
  inStream.on('end', function () { });
  this.outStream = outStream;

  this.buffer = '';
  this.views = {};
  this.config = {};
};

exports.processor.prototype = {
  // Process zero-delimited framing.
  data: function (data) {
    this.buffer += data;
    while (this.buffer.indexOf("\u0000") >= 0) {
      var chunk = this.buffer.split("\u0000").shift();
      this.receive(chunk);
      this.buffer = this.buffer.substring(chunk.length + 1);
    }
  },

  // Reply with message.
  send: function (message) {
    var data = JSON.stringify(message);
    this.outStream.write(data + "\u0000");
  },

  // Parse JSON command.
  receive: function (data) {
    try {
      var message = JSON.parse(data), view;
      if (typeof message == 'object') {
        var that = this,
            exit, returned;

        // Find handler.
        var handler = workerProcessor.handlers[message.method];

        // Create callbacks for query answers.
        if (typeof message.query == 'number') {
          // Define convenient exit callback.
          exit = function (success, object, meta) {

            if (!returned) {
              // Format return value.
              meta = meta || {};
              meta.success = success;

              meta.answer = message.query;
              meta.args = object;

              // Send answer back.
              that.send(meta);

              // Only return once.
              returned = true;
            }
          };

        }

        if (typeof message.answer == 'number') {
          // Unsupported. worker can't make queries.
          return;
        }

        // Handle internal events.
        if (handler) {
          handler.call(this, message.args, exit);
        }
        // Dispatch to process viewIn.
        else if (args.view && (view = this.views[args.view])) {
          view.emit(message);
        }
      }
    }
    catch (e) {
    }
  },

  // Establish a view stream.
  attach: function (view) {
    this.views[view.id] = view;
  },

  // Drop a view stream.
  detach: function (view) {
    delete this.views[view.id];
  },

  // Invoke an asynchronous method.
  notify: function (method, args) {
    var message = {
      method: method,
      args: args,
    };
    this.send(message);
  },

  // Store command status in environment.
  status: function (success, object) {
    this._status = { success: success, data: object };
  },

  // Return the environment.
  environment: function () {
    return {
      cwd: process.cwd(),
      home: process.env.HOME,
      user: process.env.USER,
      uid: process.getuid(),
      gid: process.getgid(),
      path: process.env.PATH.split(':'),
      manPath: process.env.MANPATH,
      defaultShell: process.env.SHELL,
      command: this._status,
    };
  },
};

workerProcessor.handlers = {

  /**
   * Set/update worker configuration.
   */
  "shell.config": function (args, exit) {
    process.stderr.write('config @' + JSON.stringify(args) + '@');
    this.config = args;
  },

  /**
   * Return environment state/variables.
   */
  "shell.environment": function (args, exit) {
    exit(true, this.environment());
  },

  /**
   * Autocomplete the command line.
   */
  "shell.autocomplete": function (args, exit) {
    var tokens = args.tokens,
        offset = args.offset,
        cwd = args.cwd,
        ignoreCase = !!args.ignoreCase;

    if (offset >= tokens.length) return exit(false);

    var auto = new autocomplete(),
        path = process.env.PATH.split(':');

    auto.process(cwd, path, tokens, offset, function (matches) {
      exit(true, { matches: matches });
    }, ignoreCase);

  },

  /**
   * Run a shell command.
   */
  "shell.run": function (args, exit) {
    var that = this,
        tokens = args.tokens,
        rel = args.rel;

    // Wrap exit callback to pass back updated environment.
    var shellExit = function (success, object, meta) {
      that.status(success, object);

      meta = meta || {};
      meta.environment = that.environment();
      exit(success, object, meta);
    };

    try {
      var list = new command.commandList(this, tokens, shellExit, rel);
      list.go();
    }
    catch (e) {
      var out = ['exception ' + e];
      for (i in e) out.push(i +': ' + e[i]);
      out.push('');
      out.push('');
      process.stderr.write(out.join("\n"));
      exit(false);
    };
  },

};


text:
package org.apache.camel.examples;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Version;

/**
 * @version
 */
@Entity
@NamedQuery(name = "findAllCustomersWithName",
query = "SELECT c FROM Customer c WHERE c.name LIKE :custName ")
public class Customer {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @OneToOne(cascade = CascadeType.ALL)
    private Address address;
    private int orderCount;

    @Version
    private Long version;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public int getOrderCount() {
        return orderCount;
    }

    public void setOrderCount(int orderCount) {
        this.orderCount = orderCount;
    }

    @Override
    public String toString() {
        // OpenJPA warns about fields being accessed directly in methods if NOT using the corresponding getters.
        return "Customer[id: " + getId() + ", version: " + version + ", name: " + getName() + ", address: " + getAddress() + "]";
    }

}


text:
package com.teletalk.jserver.property;

import java.util.Map;

/**
 *
 *
 * @author Tobias Löfstrand
 *
 * @since 2.1 (20050513)
 */
public class NullPropertyStorage implements PersistentPropertyStorage
{
   /**
    *
    */
   public void setPersistentPropertyStorageFile(String propertiesFileName)
   {
   }

   /**
    *
    */
   public void init(PropertyManager pm)
   {
   }

   /**
    *
    */
   public void readProperties()
   {
   }

   /**
    *
    */
   public boolean writeProperies(Map properties)
   {
      return false;
   }
}


text:
/**
 * @mainpage
 *
 * utf8proc is a free/open-source (MIT/expat licensed) C library
 * providing Unicode normalization, case-folding, and other operations
 * for strings in the UTF-8 encoding, supporting Unicode version
 * 8.0.0.  See the utf8proc home page (http://julialang.org/utf8proc/)
 * for downloads and other information, or the source code on github
 * (https://github.com/JuliaLang/utf8proc).
 *
 * For the utf8proc API documentation, see: @ref utf8proc.h
 *
 * The features of utf8proc include:
 *
 * - Transformation of strings (@ref utf8proc_map) to:
 *    - decompose (@ref UTF8PROC_DECOMPOSE) or compose (@ref UTF8PROC_COMPOSE) Unicode combining characters (http://en.wikipedia.org/wiki/Combining_character)
 *    - canonicalize Unicode compatibility characters (@ref UTF8PROC_COMPAT)
 *    - strip "ignorable" (@ref UTF8PROC_IGNORE) characters, control characters (@ref UTF8PROC_STRIPCC), or combining characters such as accents (@ref UTF8PROC_STRIPMARK)
 *    - case-folding (@ref UTF8PROC_CASEFOLD)
 * - Unicode normalization: @ref utf8proc_NFD, @ref utf8proc_NFC, @ref utf8proc_NFKD, @ref utf8proc_NFKC
 * - Detecting grapheme boundaries (@ref utf8proc_grapheme_break and @ref UTF8PROC_CHARBOUND)
 * - Character-width computation: @ref utf8proc_charwidth
 * - Classification of characters by Unicode category: @ref utf8proc_category and @ref utf8proc_category_string
 * - Encode (@ref utf8proc_encode_char) and decode (@ref utf8proc_iterate) Unicode codepoints to/from UTF-8.
 */

/** @file */

#ifndef UTF8PROC_H
#define UTF8PROC_H

/** @name API version
 *
 * The utf8proc API version MAJOR.MINOR.PATCH, following
 * semantic-versioning rules (http://semver.org) based on API
 * compatibility.
 *
 * This is also returned at runtime by @ref utf8proc_version; however, the
 * runtime version may append a string like "-dev" to the version number
 * for prerelease versions.
 *
 * @note The shared-library version number in the Makefile
 *       (and CMakeLists.txt, and MANIFEST) may be different,
 *       being based on ABI compatibility rather than API compatibility.
 */
/** @{ */
/** The MAJOR version number (increased when backwards API compatibility is broken). */
#define UTF8PROC_VERSION_MAJOR 2
/** The MINOR version number (increased when new functionality is added in a backwards-compatible manner). */
#define UTF8PROC_VERSION_MINOR 1
/** The PATCH version (increased for fixes that do not change the API). */
#define UTF8PROC_VERSION_PATCH 0
/** @} */

#include <stdlib.h>
#include <sys/types.h>
#if defined(_MSC_VER) && _MSC_VER < 1800
// MSVC prior to 2013 lacked stdbool.h and inttypes.h
typedef signed char utf8proc_int8_t;
typedef unsigned char utf8proc_uint8_t;
typedef short utf8proc_int16_t;
typedef unsigned short utf8proc_uint16_t;
typedef int utf8proc_int32_t;
typedef unsigned int utf8proc_uint32_t;
#  ifdef _WIN64
typedef __int64 utf8proc_ssize_t;
typedef unsigned __int64 utf8proc_size_t;
#  else
typedef int utf8proc_ssize_t;
typedef unsigned int utf8proc_size_t;
#  endif
#  ifndef __cplusplus
// emulate C99 bool
typedef unsigned char utf8proc_bool;
#    ifndef __bool_true_false_are_defined
#      define false 0
#      define true 1
#      define __bool_true_false_are_defined 1
#    endif
#  else
typedef bool utf8proc_bool;
#  endif
#else
#  include <stddef.h>
#  include <stdbool.h>
#  include <inttypes.h>
typedef int8_t utf8proc_int8_t;
typedef uint8_t utf8proc_uint8_t;
typedef int16_t utf8proc_int16_t;
typedef uint16_t utf8proc_uint16_t;
typedef int32_t utf8proc_int32_t;
typedef uint32_t utf8proc_uint32_t;
typedef size_t utf8proc_size_t;
typedef ptrdiff_t utf8proc_ssize_t;
typedef bool utf8proc_bool;
#endif
#include <limits.h>

#ifdef _WIN32
#  ifdef UTF8PROC_EXPORTS
#    define UTF8PROC_DLLEXPORT __declspec(dllexport)
#  else
#    define UTF8PROC_DLLEXPORT
//#    define UTF8PROC_DLLEXPORT __declspec(dllimport)
#  endif
#elif __GNUC__ >= 4
#  define UTF8PROC_DLLEXPORT __attribute__ ((visibility("default")))
#else
#  define UTF8PROC_DLLEXPORT
#endif

#ifdef __cplusplus
extern "C" {
#endif

#ifndef SSIZE_MAX
#define SSIZE_MAX ((size_t)SIZE_MAX/2)
#endif

#ifndef UINT16_MAX
#  define UINT16_MAX 65535U
#endif

/**
 * Option flags used by several functions in the library.
 */
typedef enum {
  /** The given UTF-8 input is NULL terminated. */
  UTF8PROC_NULLTERM  = (1<<0),
  /** Unicode Versioning Stability has to be respected. */
  UTF8PROC_STABLE    = (1<<1),
  /** Compatibility decomposition (i.e. formatting information is lost). */
  UTF8PROC_COMPAT    = (1<<2),
  /** Return a result with decomposed characters. */
  UTF8PROC_COMPOSE   = (1<<3),
  /** Return a result with decomposed characters. */
  UTF8PROC_DECOMPOSE = (1<<4),
  /** Strip "default ignorable characters" such as SOFT-HYPHEN or ZERO-WIDTH-SPACE. */
  UTF8PROC_IGNORE    = (1<<5),
  /** Return an error, if the input contains unassigned codepoints. */
  UTF8PROC_REJECTNA  = (1<<6),
  /**
   * Indicating that NLF-sequences (LF, CRLF, CR, NEL) are representing a
   * line break, and should be converted to the codepoint for line
   * separation (LS).
   */
  UTF8PROC_NLF2LS    = (1<<7),
  /**
   * Indicating that NLF-sequences are representing a paragraph break, and
   * should be converted to the codepoint for paragraph separation
   * (PS).
   */
  UTF8PROC_NLF2PS    = (1<<8),
  /** Indicating that the meaning of NLF-sequences is unknown. */
  UTF8PROC_NLF2LF    = (UTF8PROC_NLF2LS | UTF8PROC_NLF2PS),
  /** Strips and/or convers control characters.
   *
   * NLF-sequences are transformed into space, except if one of the
   * NLF2LS/PS/LF options is given. HorizontalTab (HT) and FormFeed (FF)
   * are treated as a NLF-sequence in this case.  All other control
   * characters are simply removed.
   */
  UTF8PROC_STRIPCC   = (1<<9),
  /**
   * Performs unicode case folding, to be able to do a case-insensitive
   * string comparison.
   */
  UTF8PROC_CASEFOLD  = (1<<10),
  /**
   * Inserts 0xFF bytes at the beginning of each sequence which is
   * representing a single grapheme cluster (see UAX#29).
   */
  UTF8PROC_CHARBOUND = (1<<11),
  /** Lumps certain characters together.
   *
   * E.g. HYPHEN U+2010 and MINUS U+2212 to ASCII "-". See lump.md for details.
   *
   * If NLF2LF is set, this includes a transformation of paragraph and
   * line separators to ASCII line-feed (LF).
   */
  UTF8PROC_LUMP      = (1<<12),
  /** Strips all character markings.
   *
   * This includes non-spacing, spacing and enclosing (i.e. accents).
   * @note This option works only with @ref UTF8PROC_COMPOSE or
   *       @ref UTF8PROC_DECOMPOSE
   */
  UTF8PROC_STRIPMARK = (1<<13),
} utf8proc_option_t;

/** @name Error codes
 * Error codes being returned by almost all functions.
 */
/** @{ */
/** Memory could not be allocated. */
#define UTF8PROC_ERROR_NOMEM -1
/** The given string is too long to be processed. */
#define UTF8PROC_ERROR_OVERFLOW -2
/** The given string is not a legal UTF-8 string. */
#define UTF8PROC_ERROR_INVALIDUTF8 -3
/** The @ref UTF8PROC_REJECTNA flag was set and an unassigned codepoint was found. */
#define UTF8PROC_ERROR_NOTASSIGNED -4
/** Invalid options have been used. */
#define UTF8PROC_ERROR_INVALIDOPTS -5
/** @} */

/* @name Types */

/** Holds the value of a property. */
typedef utf8proc_int16_t utf8proc_propval_t;

/** Struct containing information about a codepoint. */
typedef struct utf8proc_property_struct {
  /**
   * Unicode category.
   * @see utf8proc_category_t.
   */
  utf8proc_propval_t category;
  utf8proc_propval_t combining_class;
  /**
   * Bidirectional class.
   * @see utf8proc_bidi_class_t.
   */
  utf8proc_propval_t bidi_class;
  /**
   * @anchor Decomposition type.
   * @see utf8proc_decomp_type_t.
   */
  utf8proc_propval_t decomp_type;
  utf8proc_uint16_t decomp_seqindex;
  utf8proc_uint16_t casefold_seqindex;
  utf8proc_uint16_t uppercase_seqindex;
  utf8proc_uint16_t lowercase_seqindex;
  utf8proc_uint16_t titlecase_seqindex;
  utf8proc_uint16_t comb_index;
  unsigned bidi_mirrored:1;
  unsigned comp_exclusion:1;
  /**
   * Can this codepoint be ignored?
   *
   * Used by @ref utf8proc_decompose_char when @ref UTF8PROC_IGNORE is
   * passed as an option.
   */
  unsigned ignorable:1;
  unsigned control_boundary:1;
  /** The width of the codepoint. */
  unsigned charwidth:2;
  unsigned pad:2;
  /**
   * Boundclass.
   * @see utf8proc_boundclass_t.
   */
  unsigned boundclass:8;
} utf8proc_property_t;

/** Unicode categories. */
typedef enum {
  UTF8PROC_CATEGORY_CN  = 0, /**< Other, not assigned */
  UTF8PROC_CATEGORY_LU  = 1, /**< Letter, uppercase */
  UTF8PROC_CATEGORY_LL  = 2, /**< Letter, lowercase */
  UTF8PROC_CATEGORY_LT  = 3, /**< Letter, titlecase */
  UTF8PROC_CATEGORY_LM  = 4, /**< Letter, modifier */
  UTF8PROC_CATEGORY_LO  = 5, /**< Letter, other */
  UTF8PROC_CATEGORY_MN  = 6, /**< Mark, nonspacing */
  UTF8PROC_CATEGORY_MC  = 7, /**< Mark, spacing combining */
  UTF8PROC_CATEGORY_ME  = 8, /**< Mark, enclosing */
  UTF8PROC_CATEGORY_ND  = 9, /**< Number, decimal digit */
  UTF8PROC_CATEGORY_NL = 10, /**< Number, letter */
  UTF8PROC_CATEGORY_NO = 11, /**< Number, other */
  UTF8PROC_CATEGORY_PC = 12, /**< Punctuation, connector */
  UTF8PROC_CATEGORY_PD = 13, /**< Punctuation, dash */
  UTF8PROC_CATEGORY_PS = 14, /**< Punctuation, open */
  UTF8PROC_CATEGORY_PE = 15, /**< Punctuation, close */
  UTF8PROC_CATEGORY_PI = 16, /**< Punctuation, initial quote */
  UTF8PROC_CATEGORY_PF = 17, /**< Punctuation, final quote */
  UTF8PROC_CATEGORY_PO = 18, /**< Punctuation, other */
  UTF8PROC_CATEGORY_SM = 19, /**< Symbol, math */
  UTF8PROC_CATEGORY_SC = 20, /**< Symbol, currency */
  UTF8PROC_CATEGORY_SK = 21, /**< Symbol, modifier */
  UTF8PROC_CATEGORY_SO = 22, /**< Symbol, other */
  UTF8PROC_CATEGORY_ZS = 23, /**< Separator, space */
  UTF8PROC_CATEGORY_ZL = 24, /**< Separator, line */
  UTF8PROC_CATEGORY_ZP = 25, /**< Separator, paragraph */
  UTF8PROC_CATEGORY_CC = 26, /**< Other, control */
  UTF8PROC_CATEGORY_CF = 27, /**< Other, format */
  UTF8PROC_CATEGORY_CS = 28, /**< Other, surrogate */
  UTF8PROC_CATEGORY_CO = 29, /**< Other, private use */
} utf8proc_category_t;

/** Bidirectional character classes. */
typedef enum {
  UTF8PROC_BIDI_CLASS_L     = 1, /**< Left-to-Right */
  UTF8PROC_BIDI_CLASS_LRE   = 2, /**< Left-to-Right Embedding */
  UTF8PROC_BIDI_CLASS_LRO   = 3, /**< Left-to-Right Override */
  UTF8PROC_BIDI_CLASS_R     = 4, /**< Right-to-Left */
  UTF8PROC_BIDI_CLASS_AL    = 5, /**< Right-to-Left Arabic */
  UTF8PROC_BIDI_CLASS_RLE   = 6, /**< Right-to-Left Embedding */
  UTF8PROC_BIDI_CLASS_RLO   = 7, /**< Right-to-Left Override */
  UTF8PROC_BIDI_CLASS_PDF   = 8, /**< Pop Directional Format */
  UTF8PROC_BIDI_CLASS_EN    = 9, /**< European Number */
  UTF8PROC_BIDI_CLASS_ES   = 10, /**< European Separator */
  UTF8PROC_BIDI_CLASS_ET   = 11, /**< European Number Terminator */
  UTF8PROC_BIDI_CLASS_AN   = 12, /**< Arabic Number */
  UTF8PROC_BIDI_CLASS_CS   = 13, /**< Common Number Separator */
  UTF8PROC_BIDI_CLASS_NSM  = 14, /**< Nonspacing Mark */
  UTF8PROC_BIDI_CLASS_BN   = 15, /**< Boundary Neutral */
  UTF8PROC_BIDI_CLASS_B    = 16, /**< Paragraph Separator */
  UTF8PROC_BIDI_CLASS_S    = 17, /**< Segment Separator */
  UTF8PROC_BIDI_CLASS_WS   = 18, /**< Whitespace */
  UTF8PROC_BIDI_CLASS_ON   = 19, /**< Other Neutrals */
  UTF8PROC_BIDI_CLASS_LRI  = 20, /**< Left-to-Right Isolate */
  UTF8PROC_BIDI_CLASS_RLI  = 21, /**< Right-to-Left Isolate */
  UTF8PROC_BIDI_CLASS_FSI  = 22, /**< First Strong Isolate */
  UTF8PROC_BIDI_CLASS_PDI  = 23, /**< Pop Directional Isolate */
} utf8proc_bidi_class_t;

/** Decomposition type. */
typedef enum {
  UTF8PROC_DECOMP_TYPE_FONT      = 1, /**< Font */
  UTF8PROC_DECOMP_TYPE_NOBREAK   = 2, /**< Nobreak */
  UTF8PROC_DECOMP_TYPE_INITIAL   = 3, /**< Initial */
  UTF8PROC_DECOMP_TYPE_MEDIAL    = 4, /**< Medial */
  UTF8PROC_DECOMP_TYPE_FINAL     = 5, /**< Final */
  UTF8PROC_DECOMP_TYPE_ISOLATED  = 6, /**< Isolated */
  UTF8PROC_DECOMP_TYPE_CIRCLE    = 7, /**< Circle */
  UTF8PROC_DECOMP_TYPE_SUPER     = 8, /**< Super */
  UTF8PROC_DECOMP_TYPE_SUB       = 9, /**< Sub */
  UTF8PROC_DECOMP_TYPE_VERTICAL = 10, /**< Vertical */
  UTF8PROC_DECOMP_TYPE_WIDE     = 11, /**< Wide */
  UTF8PROC_DECOMP_TYPE_NARROW   = 12, /**< Narrow */
  UTF8PROC_DECOMP_TYPE_SMALL    = 13, /**< Small */
  UTF8PROC_DECOMP_TYPE_SQUARE   = 14, /**< Square */
  UTF8PROC_DECOMP_TYPE_FRACTION = 15, /**< Fraction */
  UTF8PROC_DECOMP_TYPE_COMPAT   = 16, /**< Compat */
} utf8proc_decomp_type_t;

/** Boundclass property. (TR29) */
typedef enum {
  UTF8PROC_BOUNDCLASS_START              =  0, /**< Start */
  UTF8PROC_BOUNDCLASS_OTHER              =  1, /**< Other */
  UTF8PROC_BOUNDCLASS_CR                 =  2, /**< Cr */
  UTF8PROC_BOUNDCLASS_LF                 =  3, /**< Lf */
  UTF8PROC_BOUNDCLASS_CONTROL            =  4, /**< Control */
  UTF8PROC_BOUNDCLASS_EXTEND             =  5, /**< Extend */
  UTF8PROC_BOUNDCLASS_L                  =  6, /**< L */
  UTF8PROC_BOUNDCLASS_V                  =  7, /**< V */
  UTF8PROC_BOUNDCLASS_T                  =  8, /**< T */
  UTF8PROC_BOUNDCLASS_LV                 =  9, /**< Lv */
  UTF8PROC_BOUNDCLASS_LVT                = 10, /**< Lvt */
  UTF8PROC_BOUNDCLASS_REGIONAL_INDICATOR = 11, /**< Regional indicator */
  UTF8PROC_BOUNDCLASS_SPACINGMARK        = 12, /**< Spacingmark */
  UTF8PROC_BOUNDCLASS_PREPEND            = 13, /**< Prepend */
  UTF8PROC_BOUNDCLASS_ZWJ                = 14, /**< Zero Width Joiner */
  UTF8PROC_BOUNDCLASS_E_BASE             = 15, /**< Emoji Base */
  UTF8PROC_BOUNDCLASS_E_MODIFIER         = 16, /**< Emoji Modifier */
  UTF8PROC_BOUNDCLASS_GLUE_AFTER_ZWJ     = 17, /**< Glue_After_ZWJ */
  UTF8PROC_BOUNDCLASS_E_BASE_GAZ         = 18, /**< E_BASE + GLUE_AFTER_ZJW */
} utf8proc_boundclass_t;

/**
 * Function pointer type passed to @ref utf8proc_map_custom and
 * @ref utf8proc_decompose_custom, which is used to specify a user-defined
 * mapping of codepoints to be applied in conjunction with other mappings.
 */
typedef utf8proc_int32_t (*utf8proc_custom_func)(utf8proc_int32_t codepoint, void *data);

/**
 * Array containing the byte lengths of a UTF-8 encoded codepoint based
 * on the first byte.
 */
UTF8PROC_DLLEXPORT extern const utf8proc_int8_t utf8proc_utf8class[256];

/**
 * Returns the utf8proc API version as a string MAJOR.MINOR.PATCH
 * (http://semver.org format), possibly with a "-dev" suffix for
 * development versions.
 */
UTF8PROC_DLLEXPORT const char *utf8proc_version(void);

/**
 * Returns an informative error string for the given utf8proc error code
 * (e.g. the error codes returned by @ref utf8proc_map).
 */
UTF8PROC_DLLEXPORT const char *utf8proc_errmsg(utf8proc_ssize_t errcode);

/**
 * Reads a single codepoint from the UTF-8 sequence being pointed to by `str`.
 * The maximum number of bytes read is `strlen`, unless `strlen` is
 * negative (in which case up to 4 bytes are read).
 *
 * If a valid codepoint could be read, it is stored in the variable
 * pointed to by `codepoint_ref`, otherwise that variable will be set to -1.
 * In case of success, the number of bytes read is returned; otherwise, a
 * negative error code is returned.
 */
UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_iterate(const utf8proc_uint8_t *str, utf8proc_ssize_t strlen, utf8proc_int32_t *codepoint_ref);

/**
 * Check if a codepoint is valid (regardless of whether it has been
 * assigned a value by the current Unicode standard).
 *
 * @return 1 if the given `codepoint` is valid and otherwise return 0.
 */
UTF8PROC_DLLEXPORT utf8proc_bool utf8proc_codepoint_valid(utf8proc_int32_t codepoint);

/**
 * Encodes the codepoint as an UTF-8 string in the byte array pointed
 * to by `dst`. This array must be at least 4 bytes long.
 *
 * In case of success the number of bytes written is returned, and
 * otherwise 0 is returned.
 *
 * This function does not check whether `codepoint` is valid Unicode.
 */
UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_encode_char(utf8proc_int32_t codepoint, utf8proc_uint8_t *dst);

/**
 * Look up the properties for a given codepoint.
 *
 * @param codepoint The Unicode codepoint.
 *
 * @returns
 * A pointer to a (constant) struct containing information about
 * the codepoint.
 * @par
 * If the codepoint is unassigned or invalid, a pointer to a special struct is
 * returned in which `category` is 0 (@ref UTF8PROC_CATEGORY_CN).
 */
UTF8PROC_DLLEXPORT const utf8proc_property_t *utf8proc_get_property(utf8proc_int32_t codepoint);

/** Decompose a codepoint into an array of codepoints.
 *
 * @param codepoint the codepoint.
 * @param dst the destination buffer.
 * @param bufsize the size of the destination buffer.
 * @param options one or more of the following flags:
 * - @ref UTF8PROC_REJECTNA  - return an error `codepoint` is unassigned
 * - @ref UTF8PROC_IGNORE    - strip "default ignorable" codepoints
 * - @ref UTF8PROC_CASEFOLD  - apply Unicode casefolding
 * - @ref UTF8PROC_COMPAT    - replace certain codepoints with their
 *                             compatibility decomposition
 * - @ref UTF8PROC_CHARBOUND - insert 0xFF bytes before each grapheme cluster
 * - @ref UTF8PROC_LUMP      - lump certain different codepoints together
 * - @ref UTF8PROC_STRIPMARK - remove all character marks
 * @param last_boundclass
 * Pointer to an integer variable containing
 * the previous codepoint's boundary class if the @ref UTF8PROC_CHARBOUND
 * option is used.  Otherwise, this parameter is ignored.
 *
 * @return
 * In case of success, the number of codepoints written is returned; in case
 * of an error, a negative error code is returned (@ref utf8proc_errmsg).
 * @par
 * If the number of written codepoints would be bigger than `bufsize`, the
 * required buffer size is returned, while the buffer will be overwritten with
 * undefined data.
 */
UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_decompose_char(
  utf8proc_int32_t codepoint, utf8proc_int32_t *dst, utf8proc_ssize_t bufsize,
  utf8proc_option_t options, int *last_boundclass
);

/**
 * The same as @ref utf8proc_decompose_char, but acts on a whole UTF-8
 * string and orders the decomposed sequences correctly.
 *
 * If the @ref UTF8PROC_NULLTERM flag in `options` is set, processing
 * will be stopped, when a NULL byte is encounted, otherwise `strlen`
 * bytes are processed.  The result (in the form of 32-bit unicode
 * codepoints) is written into the buffer being pointed to by
 * `buffer` (which must contain at least `bufsize` entries).  In case of
 * success, the number of codepoints written is returned; in case of an
 * error, a negative error code is returned (@ref utf8proc_errmsg).
 * See @ref utf8proc_decompose_custom to supply additional transformations.
 *
 * If the number of written codepoints would be bigger than `bufsize`, the
 * required buffer size is returned, while the buffer will be overwritten with
 * undefined data.
 */
UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_decompose(
  const utf8proc_uint8_t *str, utf8proc_ssize_t strlen,
  utf8proc_int32_t *buffer, utf8proc_ssize_t bufsize, utf8proc_option_t options
);

/**
 * The same as @ref utf8proc_decompose, but also takes a `custom_func` mapping function
 * that is called on each codepoint in `str` before any other transformations
 * (along with a `custom_data` pointer that is passed through to `custom_func`).
 * The `custom_func` argument is ignored if it is `NULL`.  See also @ref utf8proc_map_custom.
 */
UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_decompose_custom(
  const utf8proc_uint8_t *str, utf8proc_ssize_t strlen,
  utf8proc_int32_t *buffer, utf8proc_ssize_t bufsize, utf8proc_option_t options,
  utf8proc_custom_func custom_func, void *custom_data
);

/**
 * Normalizes the sequence of `length` codepoints pointed to by `buffer`
 * in-place (i.e., the result is also stored in `buffer`).
 *
 * @param buffer the (native-endian UTF-32) unicode codepoints to re-encode.
 * @param length the length (in codepoints) of the buffer.
 * @param options a bitwise or (`|`) of one or more of the following flags:
 * - @ref UTF8PROC_NLF2LS  - convert LF, CRLF, CR and NEL into LS
 * - @ref UTF8PROC_NLF2PS  - convert LF, CRLF, CR and NEL into PS
 * - @ref UTF8PROC_NLF2LF  - convert LF, CRLF, CR and NEL into LF
 * - @ref UTF8PROC_STRIPCC - strip or convert all non-affected control characters
 * - @ref UTF8PROC_COMPOSE - try to combine decomposed codepoints into composite
 *                           codepoints
 * - @ref UTF8PROC_STABLE  - prohibit combining characters that would violate
 *                           the unicode versioning stability
 *
 * @return
 * In case of success, the length (in codepoints) of the normalized UTF-32 string is
 * returned; otherwise, a negative error code is returned (@ref utf8proc_errmsg).
 *
 * @warning The entries of the array pointed to by `str` have to be in the
 *          range `0x0000` to `0x10FFFF`. Otherwise, the program might crash!
 */
UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_normalize_utf32(utf8proc_int32_t *buffer, utf8proc_ssize_t length, utf8proc_option_t options);

/**
 * Reencodes the sequence of `length` codepoints pointed to by `buffer`
 * UTF-8 data in-place (i.e., the result is also stored in `buffer`).
 * Can optionally normalize the UTF-32 sequence prior to UTF-8 conversion.
 *
 * @param buffer the (native-endian UTF-32) unicode codepoints to re-encode.
 * @param length the length (in codepoints) of the buffer.
 * @param options a bitwise or (`|`) of one or more of the following flags:
 * - @ref UTF8PROC_NLF2LS  - convert LF, CRLF, CR and NEL into LS
 * - @ref UTF8PROC_NLF2PS  - convert LF, CRLF, CR and NEL into PS
 * - @ref UTF8PROC_NLF2LF  - convert LF, CRLF, CR and NEL into LF
 * - @ref UTF8PROC_STRIPCC - strip or convert all non-affected control characters
 * - @ref UTF8PROC_COMPOSE - try to combine decomposed codepoints into composite
 *                           codepoints
 * - @ref UTF8PROC_STABLE  - prohibit combining characters that would violate
 *                           the unicode versioning stability
 * - @ref UTF8PROC_CHARBOUND - insert 0xFF bytes before each grapheme cluster
 *
 * @return
 * In case of success, the length (in bytes) of the resulting nul-terminated
 * UTF-8 string is returned; otherwise, a negative error code is returned
 * (@ref utf8proc_errmsg).
 *
 * @warning The amount of free space pointed to by `buffer` must
 *          exceed the amount of the input data by one byte, and the
 *          entries of the array pointed to by `str` have to be in the
 *          range `0x0000` to `0x10FFFF`. Otherwise, the program might crash!
 */
UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_reencode(utf8proc_int32_t *buffer, utf8proc_ssize_t length, utf8proc_option_t options);

/**
 * Given a pair of consecutive codepoints, return whether a grapheme break is
 * permitted between them (as defined by the extended grapheme clusters in UAX#29).
 *
 * @param state Beginning with Version 29 (Unicode 9.0.0), this algorithm requires
 *              state to break graphemes. This state can be passed in as a pointer
 *              in the `state` argument and should initially be set to 0. If the
 *              state is not passed in (i.e. a null pointer is passed), UAX#29 rules
 *              GB10/12/13 which require this state will not be applied, essentially
 *              matching the rules in Unicode 8.0.0.
 *
 * @warning If the state parameter is used, `utf8proc_grapheme_break_stateful` must
 *          be called IN ORDER on ALL potential breaks in a string.
 */
UTF8PROC_DLLEXPORT utf8proc_bool utf8proc_grapheme_break_stateful(
    utf8proc_int32_t codepoint1, utf8proc_int32_t codepoint2, utf8proc_int32_t *state);

/**
 * Same as @ref utf8proc_grapheme_break_stateful, except without support for the
 * Unicode 9 additions to the algorithm. Supported for legacy reasons.
 */
UTF8PROC_DLLEXPORT utf8proc_bool utf8proc_grapheme_break(
    utf8proc_int32_t codepoint1, utf8proc_int32_t codepoint2);

/**
 * Given a codepoint `c`, return the codepoint of the corresponding
 * lower-case character, if any; otherwise (if there is no lower-case
 * variant, or if `c` is not a valid codepoint) return `c`.
 */
UTF8PROC_DLLEXPORT utf8proc_int32_t utf8proc_tolower(utf8proc_int32_t c);

/**
 * Given a codepoint `c`, return the codepoint of the corresponding
 * upper-case character, if any; otherwise (if there is no upper-case
 * variant, or if `c` is not a valid codepoint) return `c`.
 */
UTF8PROC_DLLEXPORT utf8proc_int32_t utf8proc_toupper(utf8proc_int32_t c);

/**
 * Given a codepoint `c`, return the codepoint of the corresponding
 * title-case character, if any; otherwise (if there is no title-case
 * variant, or if `c` is not a valid codepoint) return `c`.
 */
UTF8PROC_DLLEXPORT utf8proc_int32_t utf8proc_totitle(utf8proc_int32_t c);

/**
 * Given a codepoint, return a character width analogous to `wcwidth(codepoint)`,
 * except that a width of 0 is returned for non-printable codepoints
 * instead of -1 as in `wcwidth`.
 *
 * @note
 * If you want to check for particular types of non-printable characters,
 * (analogous to `isprint` or `iscntrl`), use @ref utf8proc_category. */
UTF8PROC_DLLEXPORT int utf8proc_charwidth(utf8proc_int32_t codepoint);

/**
 * Return the Unicode category for the codepoint (one of the
 * @ref utf8proc_category_t constants.)
 */
UTF8PROC_DLLEXPORT utf8proc_category_t utf8proc_category(utf8proc_int32_t codepoint);

/**
 * Return the two-letter (nul-terminated) Unicode category string for
 * the codepoint (e.g. `"Lu"` or `"Co"`).
 */
UTF8PROC_DLLEXPORT const char *utf8proc_category_string(utf8proc_int32_t codepoint);

/**
 * Maps the given UTF-8 string pointed to by `str` to a new UTF-8
 * string, allocated dynamically by `malloc` and returned via `dstptr`.
 *
 * If the @ref UTF8PROC_NULLTERM flag in the `options` field is set,
 * the length is determined by a NULL terminator, otherwise the
 * parameter `strlen` is evaluated to determine the string length, but
 * in any case the result will be NULL terminated (though it might
 * contain NULL characters with the string if `str` contained NULL
 * characters). Other flags in the `options` field are passed to the
 * functions defined above, and regarded as described.  See also
 * @ref utfproc_map_custom to supply a custom codepoint transformation.
 *
 * In case of success the length of the new string is returned,
 * otherwise a negative error code is returned.
 *
 * @note The memory of the new UTF-8 string will have been allocated
 * with `malloc`, and should therefore be deallocated with `free`.
 */
UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_map(
  const utf8proc_uint8_t *str, utf8proc_ssize_t strlen, utf8proc_uint8_t **dstptr, utf8proc_option_t options
);

/**
 * Like @ref utf8proc_map, but also takes a `custom_func` mapping function
 * that is called on each codepoint in `str` before any other transformations
 * (along with a `custom_data` pointer that is passed through to `custom_func`).
 * The `custom_func` argument is ignored if it is `NULL`.
 */
UTF8PROC_DLLEXPORT utf8proc_ssize_t utf8proc_map_custom(
  const utf8proc_uint8_t *str, utf8proc_ssize_t strlen, utf8proc_uint8_t **dstptr, utf8proc_option_t options,
  utf8proc_custom_func custom_func, void *custom_data
);

/** @name Unicode normalization
 *
 * Returns a pointer to newly allocated memory of a NFD, NFC, NFKD or NFKC
 * normalized version of the null-terminated string `str`.  These
 * are shortcuts to calling @ref utf8proc_map with @ref UTF8PROC_NULLTERM
 * combined with @ref UTF8PROC_STABLE and flags indicating the normalization.
 */
/** @{ */
/** NFD normalization (@ref UTF8PROC_DECOMPOSE). */
UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFD(const utf8proc_uint8_t *str);
/** NFC normalization (@ref UTF8PROC_COMPOSE). */
UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFC(const utf8proc_uint8_t *str);
/** NFKD normalization (@ref UTF8PROC_DECOMPOSE and @ref UTF8PROC_COMPAT). */
UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKD(const utf8proc_uint8_t *str);
/** NFKC normalization (@ref UTF8PROC_COMPOSE and @ref UTF8PROC_COMPAT). */
UTF8PROC_DLLEXPORT utf8proc_uint8_t *utf8proc_NFKC(const utf8proc_uint8_t *str);
/** @} */

#ifdef __cplusplus
}
#endif

#endif


text:
package it.backbox.bean;

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

import com.google.api.client.util.Key;

public class Configuration {

	public static final String DEFAULT_DB_FILENAME = "backbox.db";

	@Key
	private String pwdDigest;
	@Key
	private String salt;

	@Key
	private int defaultUploadSpeed;
	@Key
	private int defaultDownloadSpeed;
	@Key
	private int chunkSize;
	@Key
	private String rootFolderID;

	@Key
	private List<Folder> backupFolders;
	@Key
	private ProxyConfiguration proxyConfiguration;

	@Key
	private boolean autoUploadConf;
	@Key
	private String dbFileID;
	@Key
	private String dbFilename;
	@Key
	private String confFileID;

	private boolean modified = false;

	public String getPwdDigest() {
		return pwdDigest;
	}

	public void setPwdDigest(String pwdDigest) {
		this.pwdDigest = pwdDigest;
		modified = true;
	}

	public String getSalt() {
		return salt;
	}

	public void setSalt(String salt) {
		this.salt = salt;
		modified = true;
	}

	public int getDefaultUploadSpeed() {
		return defaultUploadSpeed;
	}

	public void setDefaultUploadSpeed(int defaultUploadSpeed) {
		this.defaultUploadSpeed = defaultUploadSpeed;
		modified = true;
	}

	public int getDefaultDownloadSpeed() {
		return defaultDownloadSpeed;
	}

	public void setDefaultDownloadSpeed(int defaultDownloadSpeed) {
		this.defaultDownloadSpeed = defaultDownloadSpeed;
		modified = true;
	}

	public int getChunkSize() {
		return chunkSize;
	}

	public void setChunkSize(int chunkSize) {
		this.chunkSize = chunkSize;
		modified = true;
	}

	public String getRootFolderID() {
		return rootFolderID;
	}

	public void setRootFolderID(String rootFolderID) {
		this.rootFolderID = rootFolderID;
		modified = true;
	}

	public List<Folder> getBackupFolders() {
		if (backupFolders == null)
			backupFolders = new ArrayList<>();
		return backupFolders;
	}

	public void setBackupFolders(List<Folder> backupFolders) {
		this.backupFolders = backupFolders;
		modified = true;
	}

	public ProxyConfiguration getProxyConfiguration() {
		if (proxyConfiguration == null)
			proxyConfiguration = new ProxyConfiguration(false, null, 0);
		return proxyConfiguration;
	}

	public void setProxyConfiguration(ProxyConfiguration proxyConfiguration) {
		this.proxyConfiguration = proxyConfiguration;
		modified = true;
	}

	public boolean isEmpty() {
		return (pwdDigest == null) || pwdDigest.isEmpty();
	}

	public boolean isAutoUploadConf() {
		return autoUploadConf;
	}

	public void setAutoUploadConf(boolean autoUploadConf) {
		this.autoUploadConf = autoUploadConf;
		modified = true;
	}

	public String getDbFileID() {
		return dbFileID;
	}

	public void setDbFileID(String dbFileID) {
		this.dbFileID = dbFileID;
		modified = true;
	}

	public String getConfFileID() {
		return confFileID;
	}

	public void setConfFileID(String confFileID) {
		this.confFileID = confFileID;
		modified = true;
	}

	public boolean isModified() {
		return modified;
	}

	public String getDbFilename() {
		if ((dbFilename == null) || dbFilename.isEmpty())
			dbFilename = DEFAULT_DB_FILENAME;
		return dbFilename;
	}

	public void setDbFilename(String dbFilename) {
		this.dbFilename = dbFilename;
	}

}


text:
namespace trace_event_internal {

const unsigned long long kNoId = 0;

template <typename... Args>
void Ignore(Args&&... args) {}

struct IgnoredValue {
  template <typename... Args>
  IgnoredValue(Args&&... args) {}
};

}  // namespace trace_event_internal

#define INTERNAL_TRACE_IGNORE(...) \
  (false ? trace_event_internal::Ignore(__VA_ARGS__) : (void)0)

#define INTERNAL_TRACE_EVENT_ADD(...) INTERNAL_TRACE_IGNORE(__VA_ARGS__)
#define INTERNAL_TRACE_EVENT_ADD_SCOPED(...) INTERNAL_TRACE_IGNORE(__VA_ARGS__)
#define INTERNAL_TRACE_EVENT_ADD_WITH_ID(...) INTERNAL_TRACE_IGNORE(__VA_ARGS__)
#define INTERNAL_TRACE_LOG_MESSAGE(...) INTERNAL_TRACE_IGNORE(__VA_ARGS__)
#define INTERNAL_TRACE_EVENT_ADD_SCOPED_WITH_FLOW(...) \
  INTERNAL_TRACE_IGNORE(__VA_ARGS__)
#define INTERNAL_TRACE_EVENT_ADD_WITH_ID_TID_AND_TIMESTAMP(...) \
  INTERNAL_TRACE_IGNORE(__VA_ARGS__)
#define INTERNAL_TRACE_EVENT_ADD_WITH_ID_TID_AND_TIMESTAMPS(...) \
  INTERNAL_TRACE_IGNORE(__VA_ARGS__)

// Defined in application_state_proto_android.h
#define TRACE_APPLICATION_STATE(...) INTERNAL_TRACE_IGNORE(__VA_ARGS__)

#define TRACE_HEAP_PROFILER_API_SCOPED_TASK_EXECUTION \
  trace_event_internal::IgnoredValue

#define TRACE_ID_MANGLE(val) (val)

#define INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(cat) INTERNAL_TRACE_IGNORE(cat);
#define INTERNAL_TRACE_EVENT_CATEGORY_GROUP_ENABLED_FOR_RECORDING_MODE() false

#define TRACE_EVENT_API_CURRENT_THREAD_ID 0

// Typed macros. For these, we have to erase the extra args entirely, as they
// may include a lambda that refers to protozero message types (which aren't
// available in the stub). This may trigger "unused variable" errors at the
// callsite, which have to be addressed at the callsite (e.g. via
// [[maybe_unused]]).
#define TRACE_EVENT_BEGIN(category, name, ...) \
  INTERNAL_TRACE_IGNORE(category, name)
#define TRACE_EVENT_END(category, ...) INTERNAL_TRACE_IGNORE(category)
#define TRACE_EVENT(category, name, ...) INTERNAL_TRACE_IGNORE(category, name)
#define TRACE_EVENT_INSTANT(category, name, ...) \
  INTERNAL_TRACE_IGNORE(category, name)
#define PERFETTO_INTERNAL_ADD_EMPTY_EVENT() INTERNAL_TRACE_IGNORE()

namespace base {
namespace trace_event {

class BASE_EXPORT ConvertableToTraceFormat {
 public:
  ConvertableToTraceFormat() = default;
  ConvertableToTraceFormat(const ConvertableToTraceFormat&) = delete;
  ConvertableToTraceFormat& operator=(const ConvertableToTraceFormat&) = delete;
  virtual ~ConvertableToTraceFormat();

  // Append the class info to the provided |out| string. The appended
  // data must be a valid JSON object. Strings must be properly quoted, and
  // escaped. There is no processing applied to the content after it is
  // appended.
  virtual void AppendAsTraceFormat(std::string* out) const = 0;
};

class BASE_EXPORT TracedValue : public ConvertableToTraceFormat {
 public:
  explicit TracedValue(size_t capacity = 0) {}

  void EndDictionary() {}
  void EndArray() {}

  void SetInteger(const char* name, int value) {}
  void SetDouble(const char* name, double value) {}
  void SetBoolean(const char* name, bool value) {}
  void SetString(const char* name, base::StringPiece value) {}
  void SetValue(const char* name, TracedValue* value) {}
  void BeginDictionary(const char* name) {}
  void BeginArray(const char* name) {}

  void SetIntegerWithCopiedName(base::StringPiece name, int value) {}
  void SetDoubleWithCopiedName(base::StringPiece name, double value) {}
  void SetBooleanWithCopiedName(base::StringPiece name, bool value) {}
  void SetStringWithCopiedName(base::StringPiece name,
                               base::StringPiece value) {}
  void SetValueWithCopiedName(base::StringPiece name, TracedValue* value) {}
  void BeginDictionaryWithCopiedName(base::StringPiece name) {}
  void BeginArrayWithCopiedName(base::StringPiece name) {}

  void AppendInteger(int) {}
  void AppendDouble(double) {}
  void AppendBoolean(bool) {}
  void AppendString(base::StringPiece) {}
  void BeginArray() {}
  void BeginDictionary() {}

  void AppendAsTraceFormat(std::string* out) const override;
};

class BASE_EXPORT TracedValueJSON : public TracedValue {
 public:
  explicit TracedValueJSON(size_t capacity = 0) : TracedValue(capacity) {}

  std::unique_ptr<base::Value> ToBaseValue() const { return nullptr; }
  std::string ToJSON() const { return ""; }
  std::string ToFormattedJSON() const { return ""; }
};

struct MemoryDumpArgs;
class ProcessMemoryDump;

class BASE_EXPORT MemoryDumpProvider {
 public:
  MemoryDumpProvider(const MemoryDumpProvider&) = delete;
  MemoryDumpProvider& operator=(const MemoryDumpProvider&) = delete;
  virtual ~MemoryDumpProvider();

  virtual bool OnMemoryDump(const MemoryDumpArgs& args,
                            ProcessMemoryDump* pmd) = 0;

 protected:
  MemoryDumpProvider() = default;
};

class BASE_EXPORT MemoryDumpManager {
 public:
  static constexpr const char* const kTraceCategory =
      TRACE_DISABLED_BY_DEFAULT("memory-infra");
};

}  // namespace trace_event
}  // namespace base

// Stub implementation for
// perfetto::StaticString/ThreadTrack/TracedValue/TracedDictionary/TracedArray.
namespace perfetto {

class TracedArray;
class TracedDictionary;
class EventContext;

class StaticString {
 public:
  template <typename T>
  StaticString(T) {}
};

class DynamicString {
 public:
  template <typename T>
  explicit DynamicString(T) {}
};

class TracedValue {
 public:
  void WriteInt64(int64_t) && {}
  void WriteUInt64(uint64_t) && {}
  void WriteDouble(double) && {}
  void WriteBoolean(bool) && {}
  void WriteString(const char*) && {}
  void WriteString(const char*, size_t) && {}
  void WriteString(const std::string&) && {}
  void WritePointer(const void*) && {}

  TracedDictionary WriteDictionary() &&;
  TracedArray WriteArray() &&;
};

class TracedDictionary {
 public:
  TracedValue AddItem(StaticString) { return TracedValue(); }
  TracedValue AddItem(DynamicString) { return TracedValue(); }

  template <typename T>
  void Add(StaticString, T&&) {}
  template <typename T>
  void Add(DynamicString, T&&) {}

  TracedDictionary AddDictionary(StaticString);
  TracedDictionary AddDictionary(DynamicString);
  TracedArray AddArray(StaticString);
  TracedArray AddArray(DynamicString);
};

class TracedArray {
 public:
  TracedValue AppendItem() { return TracedValue(); }

  template <typename T>
  void Append(T&&) {}

  TracedDictionary AppendDictionary();
  TracedArray AppendArray();
};

template <class T>
void WriteIntoTracedValue(TracedValue, T&&) {}

}  // namespace perfetto

#endif  // BASE_TRACE_EVENT_TRACE_EVENT_STUB_H_


text:
package ee.telekom.workflow.facade;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import ee.telekom.workflow.TestApplicationContexts;
import ee.telekom.workflow.core.common.WorkflowEngineConfiguration;
import ee.telekom.workflow.core.node.NodeService;
import ee.telekom.workflow.core.workflowinstance.WorkflowInstanceStatus;
import ee.telekom.workflow.executor.GraphEngineFactory;
import ee.telekom.workflow.executor.WorkflowExecutor;
import ee.telekom.workflow.facade.model.CreateWorkflowInstance;
import ee.telekom.workflow.facade.model.ExecutionErrorState;
import ee.telekom.workflow.facade.model.WorkItemState;
import ee.telekom.workflow.facade.model.WorkflowInstanceState;
import ee.telekom.workflow.graph.Graph;
import ee.telekom.workflow.graph.Node;
import ee.telekom.workflow.graph.WorkItemStatus;
import ee.telekom.workflow.graph.core.GraphImpl;
import ee.telekom.workflow.graph.core.TransitionImpl;
import ee.telekom.workflow.graph.node.activity.BeanAsyncCallActivity;
import ee.telekom.workflow.graph.node.activity.HumanTaskActivity;
import ee.telekom.workflow.graph.node.event.CatchSignal;
import ee.telekom.workflow.graph.node.event.CatchTimer;
import ee.telekom.workflow.graph.node.gateway.AndFork;
import ee.telekom.workflow.graph.node.gateway.AndJoin;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = TestApplicationContexts.DEFAULT)
@DirtiesContext
public class WorkflowEngineFacadeIT extends TestApplicationContexts{

    @Autowired
    private WorkflowEngineFacade facade;

    @Autowired
    private WorkflowExecutor executor;
    @Autowired
    private GraphEngineFactory engineFactory;
    @Autowired
    private NodeService nodeService;
    @Autowired
    private WorkflowEngineConfiguration config;

    private static final String NAME1 = "name1";
    private static final int VERSION1 = 1;
    private static final String NAME2 = "name2";
    private static final int VERSION2 = 5;
    private static final String UNKNOWN = "unknown";

    private static final String SIGNAL = "go";
    private static final int TIMER_MS = 600000;
    private static final String BEAN = "bean1";
    private static final String METHOD = "method1";
    private static final String ROLE = "role1";
    private static final String USER = "user1";

    private static final Graph GRAPH1 = createTestGraph( NAME1, VERSION1 );
    private static final Graph GRAPH2 = createTestGraph( NAME2, VERSION2 );

    @Test
    @DirtiesContext
    public void testDeployedAndKnownWorkflowNames(){
        engineFactory.getSingletonInstance().getRepository().addGraph( GRAPH1 );
        engineFactory.getSingletonInstance().getRepository().addGraph( GRAPH2 );
        facade.createWorkflowInstance( createRequest( UNKNOWN, null, null, null ) );

        Set<String> deployedWorkflowNames = facade.getDeployedWorkflowNames();
        Assert.assertEquals( 2, deployedWorkflowNames.size() );
        Assert.assertTrue( deployedWorkflowNames.contains( NAME1 ) );
        Assert.assertTrue( deployedWorkflowNames.contains( NAME2 ) );

        Set<String> knownWorkflowNames = facade.getKnownWorkflowNames();
        Assert.assertEquals( 3, knownWorkflowNames.size() );
        Assert.assertTrue( knownWorkflowNames.contains( NAME1 ) );
        Assert.assertTrue( knownWorkflowNames.contains( NAME2 ) );
        Assert.assertTrue( knownWorkflowNames.contains( UNKNOWN ) );
    }

    @Test
    @DirtiesContext
    public void manageWorkflowIntstance(){
        engineFactory.getSingletonInstance().getRepository().addGraph( GRAPH1 );

        // test createWorkflowInstance
        CreateWorkflowInstance request = createRequest( NAME1, null, "label1", "label2" );
        facade.createWorkflowInstance( request );
        Assert.assertEquals( 1, (long)request.getRefNum() );

        // test findWorkflowInstance
        WorkflowInstanceState woin = facade.findWorkflowInstance( 1, null );
        assertInstance( woin, 1, NAME1, null, "label1", "label2", WorkflowInstanceStatus.NEW );

        woin = facade.findWorkflowInstance( 1, true );
        assertInstance( woin, 1, NAME1, null, "label1", "label2", WorkflowInstanceStatus.NEW );

        woin = facade.findWorkflowInstance( 1, false );
        Assert.assertNull( woin );

        // test suspendWorkflowInstance
        executor.startWorkflow( 1 );
        woin = facade.findWorkflowInstance( 1, null );
        assertInstance( woin, 1, NAME1, VERSION1, "label1", "label2", WorkflowInstanceStatus.EXECUTING );

        facade.suspendWorkflowInstance( 1 );
        woin = facade.findWorkflowInstance( 1, true );
        assertInstance( woin, 1, NAME1, VERSION1, "label1", "label2", WorkflowInstanceStatus.SUSPENDED );

        // test resumeWorkflowInstance
        facade.resumeWorkflowInstance( 1 );
        woin = facade.findWorkflowInstance( 1, true );
        assertInstance( woin, 1, NAME1, VERSION1, "label1", "label2", WorkflowInstanceStatus.EXECUTING );

        // test findWorkItems
        List<WorkItemState> woits = facade.findWorkItems( 1, true );
        Assert.assertEquals( 4, woits.size() );
        assertSignal( woits.get( 3 ), 1, 1, 2, WorkItemStatus.NEW, SIGNAL );
        assertTimer( woits.get( 2 ), 2, 1, 3, WorkItemStatus.NEW, false );
        assertTask( woits.get( 1 ), 3, 1, 4, WorkItemStatus.NEW, BEAN, METHOD );
        assertHumanTask( woits.get( 0 ), 4, 1, 5, WorkItemStatus.NEW, ROLE, null );

        // test findWorkItem
        WorkItemState woit1 = facade.findWorkItem( 1, true );
        assertSignal( woit1, 1, 1, 2, WorkItemStatus.NEW, SIGNAL );
        WorkItemState woit2 = facade.findWorkItem( 2, true );
        assertTimer( woit2, 2, 1, 3, WorkItemStatus.NEW, false );
        WorkItemState woit3 = facade.findWorkItem( 3, true );
        assertTask( woit3, 3, 1, 4, WorkItemStatus.NEW, BEAN, METHOD );
        WorkItemState woit4 = facade.findWorkItem( 4, true );
        assertHumanTask( woit4, 4, 1, 5, WorkItemStatus.NEW, ROLE, null );

        // test findActiveWorkItemByTokenId
        woit1 = facade.findActiveWorkItemByTokenId( 1, 2 );
        assertSignal( woit1, 1, 1, 2, WorkItemStatus.NEW, SIGNAL );
        woit2 = facade.findActiveWorkItemByTokenId( 1, 3 );
        assertTimer( woit2, 2, 1, 3, WorkItemStatus.NEW, false );
        woit3 = facade.findActiveWorkItemByTokenId( 1, 4 );
        assertTask( woit3, 3, 1, 4, WorkItemStatus.NEW, BEAN, METHOD );
        woit4 = facade.findActiveWorkItemByTokenId( 1, 5 );
        assertHumanTask( woit4, 4, 1, 5, WorkItemStatus.NEW, ROLE, null );

        // test findActiveHumanTasksByRoleAndUser
        List<WorkItemState> humanTasks = facade.findActiveHumanTasksByRoleAndUser( ROLE, null );
        Assert.assertEquals( 1, humanTasks.size() );
        assertHumanTask( humanTasks.get( 0 ), 4, 1, 5, WorkItemStatus.NEW, ROLE, null );

        // test findActiveHumanTasksByRole
        humanTasks = facade.findActiveHumanTasksByRole( ROLE );
        Assert.assertEquals( 1, humanTasks.size() );
        assertHumanTask( humanTasks.get( 0 ), 4, 1, 5, WorkItemStatus.NEW, ROLE, null );

        // test findActiveHumanTasksByUser
        humanTasks = facade.findActiveHumanTasksByUser( USER );
        Assert.assertEquals( 0, humanTasks.size() );

        // test sendSignalToWorkflowInstance()
        facade.sendSignalToWorkflowInstance( 1, SIGNAL, null );
        woit1 = facade.findWorkItem( 1, null );
        assertSignal( woit1, 1, 1, 2, WorkItemStatus.EXECUTED, SIGNAL );

        // test skipTimer()
        facade.skipTimer( 2 );
        woit2 = facade.findWorkItem( 2, null );
        assertTimer( woit2, 2, 1, 3, WorkItemStatus.NEW, true );

        // test findExecutionError
        executor.executeTask( 1, 3 );
        ExecutionErrorState error = facade.findExecutionError( 1 );
        Assert.assertNotNull( error );
        Assert.assertEquals( 1, (long)error.getWoinRefNum() );
        Assert.assertEquals( 3, (long)error.getWoitRefNum() );
        woin = facade.findWorkflowInstance( 1, true );
        assertInstance( woin, 1, NAME1, VERSION1, "label1", "label2", WorkflowInstanceStatus.EXECUTING_ERROR );

        // test retryWorkflowInstance
        facade.retryWorkflowInstance( 1 );
        error = facade.findExecutionError( 1 );
        Assert.assertNull( error );
        woin = facade.findWorkflowInstance( 1, true );
        assertInstance( woin, 1, NAME1, VERSION1, "label1", "label2", WorkflowInstanceStatus.EXECUTING );

        // test submitTask
        facade.submitTask( 3, null );
        woit3 = facade.findWorkItem( 3, null );
        assertTask( woit3, 3, 1, 4, WorkItemStatus.EXECUTED, BEAN, METHOD );

        // test assignHumanTask
        facade.assignHumanTask( 4, USER );
        woit4 = facade.findWorkItem( 4, null );
        assertHumanTask( woit4, 4, 1, 5, WorkItemStatus.NEW, ROLE, USER );

        facade.assignHumanTask( 4, null );
        woit4 = facade.findWorkItem( 4, null );
        assertHumanTask( woit4, 4, 1, 5, WorkItemStatus.NEW, ROLE, null );

        facade.assignHumanTask( 4, USER );

        // test again findActiveHumanTasksByRoleAndUser
        humanTasks = facade.findActiveHumanTasksByRoleAndUser( ROLE, USER );
        Assert.assertEquals( 1, humanTasks.size() );
        assertHumanTask( humanTasks.get( 0 ), 4, 1, 5, WorkItemStatus.NEW, ROLE, USER );

        // test again findActiveHumanTasksByRole
        humanTasks = facade.findActiveHumanTasksByRole( ROLE );
        Assert.assertEquals( 1, humanTasks.size() );
        assertHumanTask( humanTasks.get( 0 ), 4, 1, 5, WorkItemStatus.NEW, ROLE, USER );

        // test again findActiveHumanTasksByUser
        humanTasks = facade.findActiveHumanTasksByUser( USER );
        Assert.assertEquals( 1, humanTasks.size() );
        assertHumanTask( humanTasks.get( 0 ), 4, 1, 5, WorkItemStatus.NEW, ROLE, USER );

        // test submitHumanTask
        facade.submitHumanTask( 4, null );
        woit4 = facade.findWorkItem( 4, null );
        assertHumanTask( woit4, 4, 1, 5, WorkItemStatus.EXECUTED, ROLE, USER );

        humanTasks = facade.findActiveHumanTasksByRoleAndUser( ROLE, USER );
        Assert.assertEquals( 0, humanTasks.size() );

        humanTasks = facade.findActiveHumanTasksByRole( ROLE );
        Assert.assertEquals( 0, humanTasks.size() );

        humanTasks = facade.findActiveHumanTasksByUser( USER );
        Assert.assertEquals( 0, humanTasks.size() );

        // Testing abortWorkflowInstance
        facade.abortWorkflowInstance( 1 );
        woin = facade.findWorkflowInstance( 1, true );
        assertInstance( woin, 1, NAME1, VERSION1, "label1", "label2", WorkflowInstanceStatus.ABORT );
        executor.abortWorkflow( 1 );
        woin = facade.findWorkflowInstance( 1, false );
        assertInstance( woin, 1, NAME1, VERSION1, "label1", "label2", WorkflowInstanceStatus.ABORTED );

        // test again findActiveWorkItemByTokenId
        Assert.assertNull( facade.findActiveWorkItemByTokenId( 1, 2 ) );
        Assert.assertNull( facade.findActiveWorkItemByTokenId( 1, 3 ) );
        Assert.assertNull( facade.findActiveWorkItemByTokenId( 1, 4 ) );
        Assert.assertNull( facade.findActiveWorkItemByTokenId( 1, 5 ) );
    }

    @Test
    @DirtiesContext
    public void testSendSignals(){
        engineFactory.getSingletonInstance().getRepository().addGraph( GRAPH1 );
        engineFactory.getSingletonInstance().getRepository().addGraph( GRAPH2 );

        CreateWorkflowInstance request1 = createRequest( NAME1, null, "1", null );
        CreateWorkflowInstance request2 = createRequest( NAME1, VERSION1, "1", null );
        CreateWorkflowInstance request3 = createRequest( NAME2, null, "2", null );

        // test createWorkflowInstances
        facade.createWorkflowInstances( Arrays.asList( request1, request2, request3 ) );
        Assert.assertEquals( 1, (long)request1.getRefNum() );
        Assert.assertEquals( 2, (long)request2.getRefNum() );
        Assert.assertEquals( 3, (long)request3.getRefNum() );
        assertInstance( facade.findWorkflowInstance( 1, true ), 1, NAME1, null, "1", null, WorkflowInstanceStatus.NEW );
        assertInstance( facade.findWorkflowInstance( 2, true ), 2, NAME1, VERSION1, "1", null, WorkflowInstanceStatus.NEW );
        assertInstance( facade.findWorkflowInstance( 3, true ), 3, NAME2, null, "2", null, WorkflowInstanceStatus.NEW );

        // test sendSignalToWorkItem
        executor.startWorkflow( 1 );
        assertInstance( facade.findWorkflowInstance( 1, true ), 1, NAME1, VERSION1, "1", null, WorkflowInstanceStatus.EXECUTING );
        assertSignal( facade.findWorkItem( 1, true ), 1, 1, 2, WorkItemStatus.NEW, SIGNAL );
        facade.sendSignalToWorkItem( 1, SIGNAL, null );
        assertSignal( facade.findWorkItem( 1, true ), 1, 1, 2, WorkItemStatus.EXECUTED, SIGNAL );

        // test sendSignalByLabel1
        executor.startWorkflow( 2 );
        assertInstance( facade.findWorkflowInstance( 2, true ), 2, NAME1, VERSION1, "1", null, WorkflowInstanceStatus.EXECUTING );
        assertSignal( facade.findWorkItem( 5, true ), 5, 2, 2, WorkItemStatus.NEW, SIGNAL );
        facade.sendSignalByLabel1( "1", SIGNAL, null );
        assertSignal( facade.findWorkItem( 5, true ), 5, 2, 2, WorkItemStatus.EXECUTED, SIGNAL );

        // test sendSignalByLabels
        executor.startWorkflow( 3 );
        assertInstance( facade.findWorkflowInstance( 3, true ), 3, NAME2, VERSION2, "2", null, WorkflowInstanceStatus.EXECUTING );
        assertSignal( facade.findWorkItem( 9, true ), 9, 3, 2, WorkItemStatus.NEW, SIGNAL );
        facade.sendSignalByLabels( "2", null, SIGNAL, null );
        assertSignal( facade.findWorkItem( 9, true ), 9, 3, 2, WorkItemStatus.EXECUTED, SIGNAL );
        facade.sendSignalByLabels( "x", "y", SIGNAL, null );
    }

    @Test
    @DirtiesContext
    public void testCreateWorkflowInstancesAndFindByLabel(){
        CreateWorkflowInstance request1 = createRequest( NAME1, null, "1", null );
        CreateWorkflowInstance request2 = createRequest( NAME1, VERSION1, "1", null );
        CreateWorkflowInstance request3 = createRequest( NAME2, null, "2", null );
        CreateWorkflowInstance request4 = createRequest( NAME2, VERSION2, "2", null );
        CreateWorkflowInstance request5 = createRequest( UNKNOWN, null, "3", null );

        // test createWorkflowInstances
        facade.createWorkflowInstances( Arrays.asList( request1, request2, request3, request4, request5 ) );
        Assert.assertEquals( 1, (long)request1.getRefNum() );
        Assert.assertEquals( 2, (long)request2.getRefNum() );
        Assert.assertEquals( 3, (long)request3.getRefNum() );
        Assert.assertEquals( 4, (long)request4.getRefNum() );
        Assert.assertEquals( 5, (long)request5.getRefNum() );
        assertInstance( facade.findWorkflowInstance( 1, true ), 1, NAME1, null, "1", null, WorkflowInstanceStatus.NEW );
        assertInstance( facade.findWorkflowInstance( 2, true ), 2, NAME1, VERSION1, "1", null, WorkflowInstanceStatus.NEW );
        assertInstance( facade.findWorkflowInstance( 3, true ), 3, NAME2, null, "2", null, WorkflowInstanceStatus.NEW );
        assertInstance( facade.findWorkflowInstance( 4, true ), 4, NAME2, VERSION2, "2", null, WorkflowInstanceStatus.NEW );
        assertInstance( facade.findWorkflowInstance( 5, true ), 5, UNKNOWN, null, "3", null, WorkflowInstanceStatus.NEW );

        // test findWorkflowInstancesByLabels
        Assert.assertEquals( 2, facade.findWorkflowInstancesByLabels( "1", null, false ).size() );
        Assert.assertEquals( 2, facade.findWorkflowInstancesByLabels( "1", null, false ).size() );
        Assert.assertEquals( 2, facade.findWorkflowInstancesByLabel1( "1", false ).size() );
        Assert.assertEquals( 2, facade.findWorkflowInstancesByLabel1( "1", false ).size() );

        // test abortWorkflowInstance
        facade.abortWorkflowInstance( 5 );
        executor.abortWorkflow( 5 );
        Assert.assertEquals( 1, facade.findWorkflowInstancesByLabels( "3", null, false ).size() );
        Assert.assertEquals( 0, facade.findWorkflowInstancesByLabels( "3", null, true ).size() );
    }

    @Test
    @DirtiesContext
    public void testNextActiveTimerDueDates(){
        engineFactory.getSingletonInstance().getRepository().addGraph( GRAPH1 );

        facade.createWorkflowInstance( createRequest( NAME1, null, "1", null ) );
        Assert.assertEquals( 0, facade.getNextActiveTimerDueDates( Collections.singletonList( 1l ) ).size() );

        executor.startWorkflow( 1 );
        Assert.assertEquals( 1, facade.getNextActiveTimerDueDates( Collections.singletonList( 1l ) ).size() );

        facade.skipTimer( 2 );
        Assert.assertEquals( 1, facade.getNextActiveTimerDueDates( Collections.singletonList( 1l ) ).size() );

        executor.completeWorkItem( 1, 2 );
        Assert.assertEquals( 0, facade.getNextActiveTimerDueDates( Collections.singletonList( 1l ) ).size() );
    }

    @Test
    @DirtiesContext
    public void testWorkflowInstancesWithHumanTasks(){
        engineFactory.getSingletonInstance().getRepository().addGraph( GRAPH1 );

        facade.createWorkflowInstance( createRequest( NAME1, null, "1", null ) );
        debug();
        Assert.assertEquals( 0, facade.getWorkflowInstancesWithActiveHumanTask( Collections.singletonList( 1l ) ).size() );

        executor.startWorkflow( 1 );
        debug();
        Assert.assertEquals( 1, facade.getWorkflowInstancesWithActiveHumanTask( Collections.singletonList( 1l ) ).size() );

        facade.submitHumanTask( 4, null );
        debug();
        Assert.assertEquals( 0, facade.getWorkflowInstancesWithActiveHumanTask( Collections.singletonList( 1l ) ).size() );

        executor.completeWorkItem( 1, 4 );
        debug();
        Assert.assertEquals( 0, facade.getWorkflowInstancesWithActiveHumanTask( Collections.singletonList( 1l ) ).size() );
    }

    private void debug(){
        System.out.println( "===============================================" );
        for( WorkItemState woit : facade.findWorkItems( 1, true ) ){
            System.out.println( ToStringBuilder.reflectionToString( woit ) );
        }
    }

    /**
     * <pre>
     *     +--[signal]--+
     * [AND]--[timer]---[AND]
     *     +--[task]----+
     *     +--[htask]---+
     * </pre>
     */
    private static Graph createTestGraph( String name, int version ){
        GraphImpl graph = new GraphImpl( name, version );

        Node fork = new AndFork( 1 );
        Node signal = new CatchSignal( 2, SIGNAL );
        Node timer = new CatchTimer( 3, TIMER_MS );
        Node task = new BeanAsyncCallActivity( 4, BEAN, METHOD, null, null );
        Node htask = new HumanTaskActivity( 5, ROLE, null, null, null );
        Node join = new AndJoin( -1 );

        graph.setStartNode( fork );
        graph.addNode( signal );
        graph.addNode( timer );
        graph.addNode( task );
        graph.addNode( htask );
        graph.addNode( join );
        graph.addTransition( new TransitionImpl( "1_2", fork, signal ) );
        graph.addTransition( new TransitionImpl( "1_3", fork, timer ) );
        graph.addTransition( new TransitionImpl( "1_4", fork, task ) );
        graph.addTransition( new TransitionImpl( "1_5", fork, htask ) );
        graph.addTransition( new TransitionImpl( signal, join ) );
        graph.addTransition( new TransitionImpl( timer, join ) );
        graph.addTransition( new TransitionImpl( task, join ) );
        graph.addTransition( new TransitionImpl( htask, join ) );

        return graph;
    }

    private CreateWorkflowInstance createRequest( String name, Integer version, String label1, String label2 ){
        CreateWorkflowInstance request = new CreateWorkflowInstance();
        request.setWorkflowName( name );
        request.setWorkflowVersion( version );
        request.setLabel1( label1 );
        request.setLabel2( label2 );
        return request;
    }

    private void assertInstance( WorkflowInstanceState woin,
                                 long refNum,
                                 String name,
                                 Integer version,
                                 String label1,
                                 String label2,
                                 WorkflowInstanceStatus status ){
        Assert.assertEquals( refNum, (long)woin.getRefNum() );
        Assert.assertEquals( name, woin.getWorkflowName() );
        Assert.assertEquals( version, woin.getWorkflowVersion() );
        Assert.assertEquals( label1, woin.getLabel1() );
        Assert.assertEquals( label2, woin.getLabel2() );
        Assert.assertEquals( status.name(), woin.getStatus() );
    }

    private void assertSignal( WorkItemState woit, long refNum, long woinRefNum, int tokenId, WorkItemStatus status, String signal ){
        assertCommon( woit, refNum, woinRefNum, tokenId, status );
        Assert.assertEquals( signal, woit.getSignal() );
    }

    private void assertTimer( WorkItemState woit, long refNum, long woinRefNum, int tokenId, WorkItemStatus status, boolean isDue ){
        assertCommon( woit, refNum, woinRefNum, tokenId, status );
        Assert.assertEquals( isDue, woit.getDueDate().getTime() - System.currentTimeMillis() <= 0 );
    }

    private void assertTask( WorkItemState woit, long refNum, long woinRefNum, int tokenId, WorkItemStatus status, String bean, String method ){
        assertCommon( woit, refNum, woinRefNum, tokenId, status );
        Assert.assertEquals( bean, woit.getBean() );
        Assert.assertEquals( method, woit.getMethod() );
    }

    private void assertHumanTask( WorkItemState woit, long refNum, long woinRefNum, int tokenId, WorkItemStatus status, String role, String user ){
        assertCommon( woit, refNum, woinRefNum, tokenId, status );
        Assert.assertEquals( role, woit.getRole() );
        Assert.assertEquals( user, woit.getUserName() );
    }

    private void assertCommon( WorkItemState woit, long refNum, long woinRefNum, int tokenId, WorkItemStatus status ){
        Assert.assertEquals( refNum, (long)woit.getRefNum() );
        Assert.assertEquals( woinRefNum, (long)woit.getWoinRefNum() );
        Assert.assertEquals( tokenId, woit.getTokenId() );
        Assert.assertEquals( status.name(), woit.getStatus() );
    }

    @Before
    public void prepareTest(){
        nodeService.findOrCreateByName( config.getNodeName() );
    }

}


text:
package org.extremecomponents.table.callback;

import java.util.Collection;

import org.extremecomponents.table.core.TableModel;

public interface RetrieveRowsCallback {
    public Collection retrieveRows(TableModel model) throws Exception;
}


text:
/**
 * CreateSliceTask.java
 * (C) 2013,2015, Hitachi, Ltd.
 */
package org.o3project.mlo.server.impl.logic;

import org.o3project.mlo.server.dto.RestifRequestDto;
import org.o3project.mlo.server.dto.RestifResponseDto;
import org.o3project.mlo.server.logic.EquipmentConfigurator;

/**
 * This is the implementation class to create slice in {@link SliceManager} class.
 */
public class CreateSliceTask extends SliceOperationBaseTask {

	/* (non-Javadoc)
	 * @see java.util.concurrent.Callable#call()
	 */
	@Override
	public RestifResponseDto call() throws Exception {
		RestifRequestDto reqDto = getRequestDto();
		EquipmentConfigurator equConf =
				equipmentConfiguratorFactory.getConfigurator(
						reqDto.common.srcComponent.name);
		synchronized (sliceManager) {
			return sliceManager.createSlice(reqDto, equConf);
		}
	}
}