text:
"""Code for reformatting supervised learning targets."""
from operator import mul

import numpy as np
from theano.compat.six.moves import reduce
import theano.sparse
if theano.sparse.enable_sparse:
    scipy_available = True
    import scipy.sparse
else:
    scipy_available = False
from theano import tensor, config
from pylearn2.utils.exc import reraise_as

class OneHotFormatter(object):
    """
    A target formatter that transforms labels from integers in both single
    and batch mode.

    Parameters
    ----------
    max_labels : int
        The number of possible classes/labels. This means that all labels
        should be < max_labels. Example: For MNIST there are 10 numbers
        and hence max_labels = 10.
    dtype : dtype, optional
        The desired dtype for the converted one-hot vectors. Defaults to
        `config.floatX` if not given.
    """
    def __init__(self, max_labels, dtype=None):
        """
        Initializes the formatter given the number of max labels.
        """
        try:
            np.empty(max_labels)
        except (ValueError, TypeError):
            reraise_as(ValueError("%s got bad max_labels argument '%s'" %
                                  (self.__class__.__name__, str(max_labels))))
        self._max_labels = max_labels
        if dtype is None:
            self._dtype = config.floatX
        else:
            try:
                np.dtype(dtype)
            except TypeError:
                reraise_as(TypeError("%s got bad dtype identifier %s" %
                                     (self.__class__.__name__, str(dtype))))
            self._dtype = dtype

    def format(self, targets, mode='stack', sparse=False):
        """
        Formats a given array of target labels into a one-hot
        vector. If labels appear multiple times, their value
        in the one-hot vector is incremented.

        Parameters
        ----------
        targets : ndarray
            A 1D array of targets, or a batch (2D array) where
            each row is a list of targets.
        mode : string
            The way in which to convert the labels to arrays. Takes
            three different options:

              - "concatenate" : concatenates the one-hot vectors from
                multiple labels
              - "stack" : returns a matrix where each row is the
                one-hot vector of a label
              - "merge" : merges the one-hot vectors together to
                form a vector where the elements are
                the result of an indicator function
                NB: As the result of an indicator function
                the result is the same in case a label
                is duplicated in the input.
        sparse : bool
            If true then the return value is sparse matrix. Note that
            if sparse is True, then mode cannot be 'stack' because
            sparse matrices need to be 2D

        Returns
        -------
        one_hot : a NumPy array (can be 1D-3D depending on settings)
            where normally the first axis are the different batch items,
            the second axis the labels, the third axis the one_hot
            vectors. Can be dense or sparse.
        """
        if mode not in ('concatenate', 'stack', 'merge'):
            raise ValueError("%s got bad mode argument '%s'" %
                             (self.__class__.__name__, str(self._max_labels)))
        elif mode == 'stack' and sparse:
            raise ValueError("Sparse matrices need to be 2D, hence they"
                             "cannot be stacked")
        if targets.ndim > 2:
            raise ValueError("Targets needs to be 1D or 2D, but received %d "
                             "dimensions" % targets.ndim)
        if 'int' not in str(targets.dtype):
            raise TypeError("need an integer array for targets")
        if sparse:
            if not scipy_available:
                raise RuntimeError("The converting of indices to a sparse "
                                   "one-hot vector requires scipy to be "
                                   "installed")
            if mode == 'concatenate':
                one_hot = scipy.sparse.csr_matrix(
                    (np.ones(targets.size, dtype=self._dtype),
                     (targets.flatten() + np.arange(targets.size)
                      * self._max_labels)
                     % (self._max_labels * targets.shape[1]),
                     np.arange(targets.shape[0] + 1) * targets.shape[1]),
                    (targets.shape[0], self._max_labels * targets.shape[1])
                )
            elif mode == 'merge':
                one_hot = scipy.sparse.csr_matrix(
                    (np.ones(targets.size), targets.flatten(),
                     np.arange(targets.shape[0] + 1) * targets.shape[1]),
                    (targets.shape[0], self._max_labels)
                )
        else:
            one_hot = np.zeros(targets.shape + (self._max_labels,),
                               dtype=self._dtype)
            shape = (np.prod(one_hot.shape[:-1]), one_hot.shape[-1])
            one_hot.reshape(shape)[np.arange(shape[0]), targets.flatten()] = 1
            if mode == 'concatenate':
                shape = one_hot.shape[-3:-2] + (reduce(mul,
                                                       one_hot.shape[-2:], 1),)
                one_hot = one_hot.reshape(shape)
            elif mode == 'merge':
                one_hot = np.minimum(one_hot.sum(axis=one_hot.ndim - 2), 1)
        return one_hot

    def theano_expr(self, targets, mode='stack', sparse=False):
        """
        Return the one-hot transformation as a symbolic expression.
        If labels appear multiple times, their value in the one-hot
        vector is incremented.

        Parameters
        ----------
        targets : tensor_like, 1- or 2-dimensional, integer dtype
            A symbolic tensor representing labels as integers
            between 0 and `max_labels` - 1, `max_labels` supplied
            at formatter construction.
        mode : string
            The way in which to convert the labels to arrays. Takes
            three different options:

              - "concatenate" : concatenates the one-hot vectors from
                multiple labels
              - "stack" : returns a matrix where each row is the
                one-hot vector of a label
              - "merge" : merges the one-hot vectors together to
                form a vector where the elements are
                the result of an indicator function
                NB: As the result of an indicator function
                the result is the same in case a label
                is duplicated in the input.
        sparse : bool
            If true then the return value is sparse matrix. Note that
            if sparse is True, then mode cannot be 'stack' because
            sparse matrices need to be 2D

        Returns
        -------
        one_hot : TensorVariable, 1, 2 or 3-dimensional, sparse or dense
            A symbolic tensor representing a one-hot encoding of the
            supplied labels.
        """
        if mode not in ('concatenate', 'stack', 'merge'):
            raise ValueError("%s got bad mode argument '%s'" %
                             (self.__class__.__name__, str(self._max_labels)))
        elif mode == 'stack' and sparse:
            raise ValueError("Sparse matrices need to be 2D, hence they"
                             "cannot be stacked")
        squeeze_required = False
        if targets.ndim != 2:
            if targets.ndim == 1:
                squeeze_required = True
                targets = targets.dimshuffle('x', 0)
            else:
                raise ValueError("targets tensor must be 1 or 2-dimensional")
        if 'int' not in str(targets.dtype):
            raise TypeError("need an integer tensor for targets")
        if sparse:
            if mode == 'concatenate':
                one_hot = theano.sparse.CSR(
                    tensor.ones_like(targets, dtype=self._dtype).flatten(),
                    (targets.flatten() + tensor.arange(targets.size) *
                     self._max_labels) % (self._max_labels * targets.shape[1]),
                    tensor.arange(targets.shape[0] + 1) * targets.shape[1],
                    tensor.stack(targets.shape[0],
                                 self._max_labels * targets.shape[1])
                )
            else:
                one_hot = theano.sparse.CSR(
                    tensor.ones_like(targets, dtype=self._dtype).flatten(),
                    targets.flatten(),
                    tensor.arange(targets.shape[0] + 1) * targets.shape[1],
                    tensor.stack(targets.shape[0], self._max_labels)
                )
        else:
            if mode == 'concatenate':
                one_hot = tensor.zeros((targets.shape[0] * targets.shape[1],
                                        self._max_labels))
                one_hot = tensor.set_subtensor(
                    one_hot[tensor.arange(targets.size),
                            targets.flatten()], 1)
                one_hot = one_hot.reshape(
                    (targets.shape[0], targets.shape[1] * self._max_labels)
                )
            elif mode == 'merge':
                one_hot = tensor.zeros((targets.shape[0], self._max_labels))
                one_hot = tensor.set_subtensor(
                    one_hot[tensor.arange(targets.size) % targets.shape[0],
                            targets.T.flatten()], 1)
            else:
                one_hot = tensor.zeros((targets.shape[0], targets.shape[1],
                                        self._max_labels))
                one_hot = tensor.set_subtensor(one_hot[
                    tensor.arange(targets.shape[0]).reshape((targets.shape[0],
                                                             1)),
                    tensor.arange(targets.shape[1]),
                    targets
                ], 1)
            if squeeze_required:
                if one_hot.ndim == 2:
                    one_hot = one_hot.reshape((one_hot.shape[1],))
                if one_hot.ndim == 3:
                    one_hot = one_hot.reshape((one_hot.shape[1],
                                               one_hot.shape[2]))
        return one_hot

def convert_to_one_hot(integer_vector, dtype=None, max_labels=None,
                       mode='stack', sparse=False):
    """
    Formats a given array of target labels into a one-hot
    vector.

    Parameters
    ----------
    max_labels : int, optional
        The number of possible classes/labels. This means that
        all labels should be < max_labels. Example: For MNIST
        there are 10 numbers and hence max_labels = 10. If not
        given it defaults to max(integer_vector) + 1.
    dtype : dtype, optional
        The desired dtype for the converted one-hot vectors.
        Defaults to config.floatX if not given.
    integer_vector : ndarray
        A 1D array of targets, or a batch (2D array) where
        each row is a list of targets.
    mode : string
        The way in which to convert the labels to arrays. Takes
        three different options:

          - "concatenate" : concatenates the one-hot vectors from
            multiple labels
          - "stack" : returns a matrix where each row is the
            one-hot vector of a label
          - "merge" : merges the one-hot vectors together to
            form a vector where the elements are
            the result of an indicator function
    sparse : bool
        If true then the return value is sparse matrix. Note that
        if sparse is True, then mode cannot be 'stack' because
        sparse matrices need to be 2D

    Returns
    -------
    one_hot : NumPy array
       Can be 1D-3D depending on settings. Normally, the first axis are
       the different batch items, the second axis the labels, the third
       axis the one_hot vectors. Can be dense or sparse.
    """
    if dtype is None:
        dtype = config.floatX
    if isinstance(integer_vector, list):
        integer_vector = np.array(integer_vector)
    assert np.min(integer_vector) >= 0
    assert integer_vector.ndim <= 2
    if max_labels is None:
        max_labels = max(integer_vector) + 1
    return OneHotFormatter(max_labels, dtype=dtype).format(
        integer_vector, mode=mode, sparse=sparse
    )

def _validate_labels(labels, ndim):
    """
    Validate that the passed label is in a right data type, and convert
    it into the desired shape.

    Parameters
    ----------
    labels : array_like, 1-dimensional (or 2-dimensional (nlabels, 1))
        The integer labels to use to construct the one hot matrix.
    ndim : int
        Number of dimensions the label have.

    Returns
    -------
    labels : ndarray, (nlabels, ) or (nlabels, )
        The resulting label vector.
    """
    labels = np.asarray(labels)
    if labels.dtype.kind not in ('u', 'i'):
        raise ValueError("labels must have int or uint dtype")
    if ndim == 1 and labels.ndim != 1:
        if labels.ndim == 2 and labels.shape[1] == 1:
            labels = labels.squeeze()
        else:
            raise ValueError("labels must be 1-dimensional")
    elif ndim == 2 and labels.ndim != 2:
        raise ValueError("labels must be 2-dimensional, no ragged "
                         "lists-of-lists")
    return labels

def compressed_one_hot(labels, dtype=None, out=None, simplify_binary=True,
                       mode='stack', sparse=False):
    """
    Construct a one-hot matrix from a vector of integer labels, but
    only including columns corresponding to integer labels that
    actually appear.

    Parameters
    ----------
    labels : array_like, 1-dimensional (or 2-dimensional (nlabels, 1))
        The integer labels to use to construct the one hot matrix.

    dtype : str or dtype object, optional
        The dtype you wish the returned array to have. Defaults
        to `labels.dtype` if not provided.

    out : ndarray, optional
        An array to use in lieu of allocating one. Must be the
        right shape, i.e. same first dimension as `labels` and
        second dimension greater than or equal to the number of
        unique values in `labels`.

    simplify_binary : bool, optional
        If `True`, if there are only two distinct labels, return
        an `(nlabels, 1)` matrix with 0 denoting the lesser integer
        label and 1 denoting the greater, instead of a redundant
        `(nlabels, 2)` matrix.
    mode : string
        The way in which to convert the labels to arrays. Takes
        three different options:

            - "concatenate" : concatenates the one-hot vectors from
              multiple labels
            - "stack" : returns a matrix where each row is the
              one-hot vector of a label
            - "merge" : merges the one-hot vectors together to
              form a vector where the elements are
              the result of an indicator function
              NB: As the result of an indicator function
              the result is the same in case a label
              is duplicated in the input.
    sparse : bool
        If true then the return value is sparse matrix. Note that
        if sparse is True, then mode cannot be 'stack' because
        sparse matrices need to be 2D

    Returns
    -------
    out : ndarray, (nlabels, max_label + 1) or (nlabels, 1)
        The resulting one-hot matrix.

    uniq : ndarray, 1-dimensional
        The array of unique values in `labels` in the order
        in which the corresponding columns appear in `out`.
    """
    labels = _validate_labels(labels, ndim=1)
    labels_ = labels.copy()
    uniq = np.unique(labels_)
    for i, e in enumerate(uniq):
        labels_[labels_ == e] = i
    if simplify_binary and len(uniq) == 2:
        return labels_.reshape((labels_.shape[0], 1)), uniq
    else:
        return OneHotFormatter(len(uniq), dtype=dtype).format(
            labels_, mode=mode, sparse=sparse), uniq


text:
<?php

namespace Google\AdsApi\AdManager\v202205;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class User extends \Google\AdsApi\AdManager\v202205\UserRecord
{

    /**
     * @var boolean $isActive
     */
    protected $isActive = null;

    /**
     * @var boolean $isEmailNotificationAllowed
     */
    protected $isEmailNotificationAllowed = null;

    /**
     * @var string $externalId
     */
    protected $externalId = null;

    /**
     * @var boolean $isServiceAccount
     */
    protected $isServiceAccount = null;

    /**
     * @var string $ordersUiLocalTimeZoneId
     */
    protected $ordersUiLocalTimeZoneId = null;

    /**
     * @param int $id
     * @param string $name
     * @param string $email
     * @param int $roleId
     * @param string $roleName
     * @param boolean $isActive
     * @param boolean $isEmailNotificationAllowed
     * @param string $externalId
     * @param boolean $isServiceAccount
     * @param string $ordersUiLocalTimeZoneId
     */
    public function __construct($id = null, $name = null, $email = null, $roleId = null, $roleName = null, $isActive = null, $isEmailNotificationAllowed = null, $externalId = null, $isServiceAccount = null, $ordersUiLocalTimeZoneId = null)
    {
      parent::__construct($id, $name, $email, $roleId, $roleName);
      $this->isActive = $isActive;
      $this->isEmailNotificationAllowed = $isEmailNotificationAllowed;
      $this->externalId = $externalId;
      $this->isServiceAccount = $isServiceAccount;
      $this->ordersUiLocalTimeZoneId = $ordersUiLocalTimeZoneId;
    }

    /**
     * @return boolean
     */
    public function getIsActive()
    {
      return $this->isActive;
    }

    /**
     * @param boolean $isActive
     * @return \Google\AdsApi\AdManager\v202205\User
     */
    public function setIsActive($isActive)
    {
      $this->isActive = $isActive;
      return $this;
    }

    /**
     * @return boolean
     */
    public function getIsEmailNotificationAllowed()
    {
      return $this->isEmailNotificationAllowed;
    }

    /**
     * @param boolean $isEmailNotificationAllowed
     * @return \Google\AdsApi\AdManager\v202205\User
     */
    public function setIsEmailNotificationAllowed($isEmailNotificationAllowed)
    {
      $this->isEmailNotificationAllowed = $isEmailNotificationAllowed;
      return $this;
    }

    /**
     * @return string
     */
    public function getExternalId()
    {
      return $this->externalId;
    }

    /**
     * @param string $externalId
     * @return \Google\AdsApi\AdManager\v202205\User
     */
    public function setExternalId($externalId)
    {
      $this->externalId = $externalId;
      return $this;
    }

    /**
     * @return boolean
     */
    public function getIsServiceAccount()
    {
      return $this->isServiceAccount;
    }

    /**
     * @param boolean $isServiceAccount
     * @return \Google\AdsApi\AdManager\v202205\User
     */
    public function setIsServiceAccount($isServiceAccount)
    {
      $this->isServiceAccount = $isServiceAccount;
      return $this;
    }

    /**
     * @return string
     */
    public function getOrdersUiLocalTimeZoneId()
    {
      return $this->ordersUiLocalTimeZoneId;
    }

    /**
     * @param string $ordersUiLocalTimeZoneId
     * @return \Google\AdsApi\AdManager\v202205\User
     */
    public function setOrdersUiLocalTimeZoneId($ordersUiLocalTimeZoneId)
    {
      $this->ordersUiLocalTimeZoneId = $ordersUiLocalTimeZoneId;
      return $this;
    }

}

redpajama_set_name: RedPajamaGithub


text:
.class public interface abstract Lcom/samsung/android/media/mediacapture/SemMediaCapture$OnRenderingStartedListener;
.super Ljava/lang/Object;
.source "SemMediaCapture.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/samsung/android/media/mediacapture/SemMediaCapture;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "OnRenderingStartedListener"
.end annotation

# virtual methods
.method public abstract onRenderingStarted(Lcom/samsung/android/media/mediacapture/SemMediaCapture;)V
.end method


text:
var baseCreate = require('./_baseCreate'),
    isPrototype = require('./_isPrototype');

/** Built-in value references. */
var getPrototypeOf = Object.getPrototypeOf;

/**
 * Initializes an object clone.
 *
 * @private
 * @param {Object} object The object to clone.
 * @returns {Object} Returns the initialized clone.
 */
function initCloneObject(object) {
  return (typeof object.constructor == 'function' && !isPrototype(object))
    ? baseCreate(getPrototypeOf(object))
    : {};
}

module.exports = initCloneObject;


text:
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Key;
import com.intellij.util.concurrency.EdtScheduledExecutorService;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class AnimatedIcon implements Icon {
  private static final Logger LOG = Logger.getInstance(AnimatedIcon.class);
  /**
   * This key is used to allow animated icons in lists, tables and trees.
   * If the corresponding client property is set to {@code true} the corresponding component
   * will be automatically repainted to update an animated icon painted by the renderer of the component.
   * Note, that animation may cause a performance problems and should not be used everywhere.
   *
   * @see UIUtil#putClientProperty
   */
  @ApiStatus.Internal
  public static final Key<Boolean> ANIMATION_IN_RENDERER_ALLOWED = Key.create("ANIMATION_IN_RENDERER_ALLOWED");
  @ApiStatus.Internal
  public static final Key<Runnable> REFRESH_DELEGATE = Key.create("REFRESH_DELEGATE");

  public interface Frame {
    @NotNull
    Icon getIcon();

    int getDelay();
  }

  public static class Default extends AnimatedIcon {

    public Default() {
      super(DELAY, ICONS.toArray(new Icon[0]));
    }

    public static final int DELAY = 130;
    public static final List<Icon> ICONS = List.of(
      AllIcons.Process.Step_1,
      AllIcons.Process.Step_2,
      AllIcons.Process.Step_3,
      AllIcons.Process.Step_4,
      AllIcons.Process.Step_5,
      AllIcons.Process.Step_6,
      AllIcons.Process.Step_7,
      AllIcons.Process.Step_8);

    public static final AnimatedIcon INSTANCE = new Default();
  }

  public static class Big extends AnimatedIcon {
    public Big() {
      super(DELAY, ICONS.toArray(new Icon[0]));
    }

    public static final int DELAY = 130;
    public static final List<Icon> ICONS = List.of(
      AllIcons.Process.Big.Step_1,
      AllIcons.Process.Big.Step_2,
      AllIcons.Process.Big.Step_3,
      AllIcons.Process.Big.Step_4,
      AllIcons.Process.Big.Step_5,
      AllIcons.Process.Big.Step_6,
      AllIcons.Process.Big.Step_7,
      AllIcons.Process.Big.Step_8);

    public static final AnimatedIcon INSTANCE = new Big();
  }

  public static final class Recording extends AnimatedIcon {
    public Recording() {
      super(DELAY, ICONS.toArray(new Icon[0]));
    }

    public static final int DELAY = 250;
    public static final List<Icon> ICONS = List.of(
      AllIcons.Ide.Macro.Recording_1,
      AllIcons.Ide.Macro.Recording_2,
      AllIcons.Ide.Macro.Recording_3,
      AllIcons.Ide.Macro.Recording_4);
  }

  @ApiStatus.Internal
  public static final class FS extends AnimatedIcon {
    public FS() {
      super(DELAY, ICONS.toArray(new Icon[0]));
    }

    public static final int DELAY = 50;
    public static final List<Icon> ICONS = List.of(
      AllIcons.Process.FS.Step_1,
      AllIcons.Process.FS.Step_2,
      AllIcons.Process.FS.Step_3,
      AllIcons.Process.FS.Step_4,
      AllIcons.Process.FS.Step_5,
      AllIcons.Process.FS.Step_6,
      AllIcons.Process.FS.Step_7,
      AllIcons.Process.FS.Step_8,
      AllIcons.Process.FS.Step_9,
      AllIcons.Process.FS.Step_10,
      AllIcons.Process.FS.Step_11,
      AllIcons.Process.FS.Step_12,
      AllIcons.Process.FS.Step_13,
      AllIcons.Process.FS.Step_14,
      AllIcons.Process.FS.Step_15,
      AllIcons.Process.FS.Step_16,
      AllIcons.Process.FS.Step_17,
      AllIcons.Process.FS.Step_18);
  }

  @ApiStatus.Internal
  public static final class Blinking extends AnimatedIcon {
    public Blinking(@NotNull Icon icon) {
      this(1000, icon);
    }

    public Blinking(int delay, @NotNull Icon icon) {
      super(delay, icon, IconLoader.getDisabledIcon(icon));
    }
  }

  @ApiStatus.Internal
  public static final class Fading extends AnimatedIcon {
    public Fading(@NotNull Icon icon) {
      this(1000, icon);
    }

    public Fading(int period, @NotNull Icon icon) {
      super(50, new Icon() {
        private final long time = System.currentTimeMillis();

        @Override
        public int getIconWidth() {
          return icon.getIconWidth();
        }

        @Override
        public int getIconHeight() {
          return icon.getIconHeight();
        }

        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
          assert period > 0 : "unexpected";
          long time = (System.currentTimeMillis() - this.time) % period;
          float alpha = (float)((Math.cos(2 * Math.PI * time / period) + 1) / 2);
          if (alpha > 0) {
            if (alpha < 1 && g instanceof Graphics2D) {
              Graphics2D g2d = (Graphics2D)g.create();
              try {
                g2d.setComposite(AlphaComposite.SrcAtop.derive(alpha));
                icon.paintIcon(c, g2d, x, y);
              }
              finally {
                g2d.dispose();
              }
            }
            else {
              icon.paintIcon(c, g, x, y);
            }
          }
        }
      });
    }
  }

  private final Frame[] frames;
  private final Set<Component> requested = Collections.newSetFromMap(new IdentityHashMap<>());
  private long time;
  private int index;

  public AnimatedIcon(int delay, Icon @NotNull ... icons) {
    this(getFrames(delay, icons));
  }

  public AnimatedIcon(Frame @NotNull ... frames) {
    this.frames = frames;
    assert frames.length > 0 : "empty array";
    for (Frame frame : frames) assert frame != null : "null animation frame";
    time = System.currentTimeMillis();
  }

  private static Frame[] getFrames(int delay, Icon @NotNull ... icons) {
    int length = icons.length;
    assert length > 0 : "empty array";
    Frame[] frames = new Frame[length];
    for (int i = 0; i < length; i++) {
      Icon icon = icons[i];
      assert icon != null : "null icon";
      frames[i] = new Frame() {
        @NotNull
        @Override
        public Icon getIcon() {
          return icon;
        }

        @Override
        public int getDelay() {
          return delay;
        }
      };
    }
    return frames;
  }

  private void updateFrameAt(long current) {
    int next = index + 1;
    index = next < frames.length ? next : 0;
    time = current;
  }

  @NotNull
  private Icon getUpdatedIcon() {
    int index = getCurrentIndex();
    return frames[index].getIcon();
  }

  private int getCurrentIndex() {
    long current = System.currentTimeMillis();
    Frame frame = frames[index];
    if (frame.getDelay() <= (current - time)) updateFrameAt(current);
    return index;
  }

  private void requestRefresh(@Nullable Component c) {
    if (c == null || requested.contains(c) || !canRefresh(c)) {
      return;
    }

    Frame frame = frames[index];
    int delay = frame.getDelay();
    if (delay > 0) {
      requested.add(c);
      EdtScheduledExecutorService.getInstance().schedule(() -> {
        requested.remove(c);
        if (canRefresh(c)) {
          doRefresh(c);
        }
      }, delay, TimeUnit.MILLISECONDS);
    }
    else {
      doRefresh(c);
    }
  }

  @Override
  public final void paintIcon(Component c, Graphics g, int x, int y) {
    Icon icon = getUpdatedIcon();
    if (EventQueue.isDispatchThread()) {
      CellRendererPane pane = ComponentUtil.getParentOfType(CellRendererPane.class, c);
      requestRefresh(pane == null ? c : getRendererOwner(pane.getParent()));
    }
    else if (LOG.isDebugEnabled()) {
      LOG.debug(new IllegalStateException("Unexpected thread " + Thread.currentThread().getName()));
    }
    icon.paintIcon(c, g, x, y);
  }

  @Override
  public final int getIconWidth() {
    return getUpdatedIcon().getIconWidth();
  }

  @Override
  public final int getIconHeight() {
    return getUpdatedIcon().getIconHeight();
  }

  protected boolean canRefresh(@NotNull Component component) {
    return component.isShowing();
  }

  protected void doRefresh(@NotNull Component component) {
    Runnable delegate = component instanceof JComponent ? (Runnable)((JComponent)component).getClientProperty(REFRESH_DELEGATE) : null;
    if (delegate == null) {
      component.repaint();
    }
    else {
      delegate.run();
    }
  }

  @Nullable
  protected Component getRendererOwner(@Nullable Component component) {
    return UIUtil.isClientPropertyTrue(component, ANIMATION_IN_RENDERER_ALLOWED) ? component : null;
  }
}


text:
using System.IO;

using Microsoft.VisualStudio.TestTools.UnitTesting;

using AM.IO;

namespace UnitTests.AM.IO
{
    [TestClass]
    public class InsistentFileTest
        : Common.CommonUnitTest
    {
        private string _GetReadFileName()
        {
            return Path.Combine(TestDataPath, "record.txt");
        }

        private string _GetWriteFileName()
        {
            return Path.GetTempFileName();
        }

        [TestMethod]
        public void InsistentFile_OpenForExclusiveRead_1()
        {
            string fileName = _GetReadFileName();
            using var stream = InsistentFile.OpenForExclusiveRead(fileName);
            byte[] content = new byte[10];
            int read = stream.Read(content, 0, content.Length);
            Assert.AreEqual(content.Length, read);
        }

        [TestMethod]
        public void InsistentFile_OpenForSharedRead_1()
        {
            string fileName = _GetReadFileName();
            using var stream = InsistentFile.OpenForSharedRead(fileName);
            byte[] content = new byte[10];
            int read = stream.Read(content, 0, content.Length);
            Assert.AreEqual(content.Length, read);
        }

        [TestMethod]
        public void InsistentFile_OpenForExclusiveWrite_1()
        {
            int expected = 10;
            string fileName = _GetWriteFileName();
            using (var stream = InsistentFile.OpenForExclusiveWrite(fileName))
            {
                byte[] content = new byte[expected];
                stream.Write(content, 0, expected);
            }
            int actual = (int)new FileInfo(fileName).Length;
            Assert.AreEqual(expected, actual);
        }

        [TestMethod]
        public void InsistentFile_OpenForSharedWrite_1()
        {
            int expected = 10;
            string fileName = _GetWriteFileName();
            using (var stream = InsistentFile.OpenForSharedWrite(fileName))
            {
                byte[] content = new byte[expected];
                stream.Write(content, 0, expected);
            }
            int actual = (int)new FileInfo(fileName).Length;
            Assert.AreEqual(expected, actual);
        }
    }
}


text:
typedef enum {
	CVDataTypeNewsDetail,
	CVDataTypeRelativeNewsList,
	CVDataTypeTodayNewsList,
	CVDataTypeHeadlineNewsList,
	CVDataTypeLatestNewsList,
	CVDataTypeMacroNewsList,
	CVDataTypeDiscretionaryNewsList,
	CVDataTypeStaplesNewsList,
	CVDataTypeFinancialsNewsList,
	CVDataTypeHealthCareNewsList,
	CVDataTypeIndustrialsNewsList,
	CVDataTypeMaterialsNewsList,
	CVDataTypeEnergyNewsList,
	CVDataTypeTelecomNewsList,
	CVDataTypeUtilitiesNewsList,
	CVDataTypeITNewsList,
	CVDataTypeIndustryNewsList,
	CVDataTypeStockNewsList,
	CVDataTypeCompositeIndexList,
	CVDataTypeCompositeIndexSummary,
	CVDataTypeStockCodeList,
	CVDataTypeEquityProfile,
	CVDataTypeIndexProfile,
	CVDataTypeIndexLatestPrice,
	CVDataTypeStockTopMovingSecurites,
	CVDataTypeStockInTheNews,
	CVDataTypeStockMostActive,
	CVDataTypeStockTopMarketCapital,
	CVDataTypeFundTopMovingSecurites,
	CVDataTypeBondTopMovingSecurites,
	CVDataTypeStockChart,
	CVDataTypeFundChart,
	CVDataTypeBondChart,
	CVDataTypeStockDetail,   //leon changed
	CVDataTypeFundDetail,
	CVDataTypeBondDetail,
	CVDataTypeSectorList,
	CVDataTypeSectorTopGainerDecliner,
	CVDataTypeSectorTurnover,
	CVDataTypeSectorVolume,
	CVDataTypeSectorTotalCap,
	CVDataTypeSectorTradableCap,
	CVDataTypeSectorSummary,
	CVDataTypeMacroData,
	CVDataTypeEquityBalanceSheet,
	CVDataTypeEquityIncomeStatement,
	CVDataTypeEquityCashFlow,
	CVDataTypeMostActivatedMarketCap,
	CVDataTypeBenchmarkTopAShare,
	CVDataTypeBenchmarkTopBlueChips,
	CVDataTypeInvalid
} CVDataType;

@interface CVDataAnalyzer : NSObject {

}

+ (id) analyze:(CVDataType)type data:(NSDictionary *)rawData;

@end


text:
@interface UIView ()
@property (nonatomic, readwrite, strong) NSMutableArray *layoutContainers;
@end

@implementation UIView (XMLLayout)

#pragma mark - properties

- (NSMutableArray *)layoutContainers
{
    NSMutableArray *_layoutContainers = objc_getAssociatedObject(self, @selector(layoutContainers));
    if (!_layoutContainers) [self setLayoutContainers:[NSMutableArray array]];
    return objc_getAssociatedObject(self, @selector(layoutContainers));
}

- (void)setLayoutContainers:(NSMutableArray *)layoutContainers
{
    objc_setAssociatedObject(self, @selector(layoutContainers), layoutContainers, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

#pragma mark - control container layout

- (void)applyLayoutContainer:(XMLLayoutContainer *)container
{
    [container removeFromSuperLayout];
    [self.layoutContainers addObject:container];
    [self addSubview:container.view];
    [container refresh];
}

- (void)applyLayoutContainers:(NSArray *)layoutContainers
{
    for (XMLLayoutContainer *container in layoutContainers) {
        [self applyLayoutContainer:container];
    }
}

- (void)removeLayoutContainer:(XMLLayoutContainer *)container
{
    if (![self.layoutContainers containsObject:container]) return;
    [self.layoutContainers removeObject:container];
    [container.view removeFromSuperview];
}

- (void)removeAllLayouts
{
    for (XMLLayoutContainer *container in self.layoutContainers) {
        [self removeLayoutContainer:container];
    }
}

#pragma mark - read xml file

- (void)loadXMLLayoutsWithResourceName:(NSString *)resourceName
{
    [self loadXMLLayoutsWithResourceName:resourceName completion:nil];
}

- (void)loadXMLLayoutsWithResourceName:(NSString *)resourceName completion:(void (^)(NSError *))completion
{
    [self loadXMLLayoutsWithResourceName:resourceName preset:nil completion:completion];
}

- (void)loadXMLLayoutsWithResourceName:(NSString *)resourceName preset:(void (^)(void))preset completion:(void (^)(NSError *))completion
{
    [XMLLayoutConverter convertXMLToLayoutsWithResourceName:resourceName completion:^(XMLLayoutConverter *converter, NSArray *layouts, NSError *error) {
        // get layout containers
        NSMutableArray *containers = [NSMutableArray array];
        for (XMLLayout *layout in layouts) {
            if (layout.isLayoutContainer) [containers addObject:layout];
        }
        // add container
        for (XMLLayoutContainer *container in containers) {
            [self.layoutContainers addObject:container];
            [self addSubview:container.view];
        }
        // refresh layouts
        if (preset) preset();
        if (completion) {
            for (XMLLayoutContainer *container in containers) [container refreshWithSynchronous:YES];
            completion(error);
        } else {
            for (XMLLayoutContainer *container in containers) [container refreshWithSynchronous:NO];
        }
    }];
}

#pragma mark - search view/layout with ID

- (UIView *)viewWithID:(NSInteger)id
{
    for (XMLLayoutContainer *layoutContainer in self.layoutContainers) {
        if (layoutContainer.id == id) return layoutContainer.view;
        if ([layoutContainer respondsToSelector:@selector(isLayoutContainer)] && layoutContainer.isLayoutContainer) {
            UIView *view = [layoutContainer viewWithID:id];
            if (view) return view;
        } else {
            NSLog(@"%s !! skip to search %@", __FUNCTION__, layoutContainer);
        }
    }
    return nil;
}

- (BOOL)findViewByID:(NSInteger)id work:(void (^)(UIView *view))work
{
    for (XMLLayoutContainer *layoutContainer in self.layoutContainers) {
        if (layoutContainer.id == id) {
            if (work) work(layoutContainer.view);
            return YES;
        }
        if ([layoutContainer respondsToSelector:@selector(isLayoutContainer)] && layoutContainer.isLayoutContainer) {
            if ([layoutContainer findViewByID:id work:work]) return YES;
        } else {
            NSLog(@"%s !! skip to search %@", __FUNCTION__, layoutContainer);
        }
    }
    return NO;
}

- (XMLLayout *)layoutWithID:(NSInteger)id
{
    for (XMLLayoutContainer *layoutContainer in self.layoutContainers) {
        if (layoutContainer.id == id) return layoutContainer;
        if ([layoutContainer respondsToSelector:@selector(isLayoutContainer)] && layoutContainer.isLayoutContainer) {
            XMLLayout *layout = [layoutContainer layoutWithID:id];
            if (layout) return layout;
        } else {
            NSLog(@"%s !! skip to search %@", __FUNCTION__, layoutContainer);
        }
    }
    return nil;
}

- (BOOL)findLayoutByID:(NSInteger)id work:(void (^)(XMLLayout *))work
{
    for (XMLLayoutContainer *layoutContainer in self.layoutContainers) {
        if (layoutContainer.id == id) {
            if (work) work(layoutContainer);
            return YES;
        };
        if ([layoutContainer respondsToSelector:@selector(isLayoutContainer)] && layoutContainer.isLayoutContainer) {
            if ([layoutContainer findLayoutByID:id work:work]) return YES;
        } else {
            NSLog(@"%s !! skip to search %@", __FUNCTION__, layoutContainer);
        }
    }
    return NO;
}

#pragma mark - refresh

- (void)refreshAllLayout
{
    for (XMLLayoutContainer *layoutContainer in self.layoutContainers) {
        [layoutContainer refreshWithSynchronous:NO];
    }
}

- (void)refreshAllLayoutWithSynchronous:(BOOL)synchronous {
    for (XMLLayoutContainer *layoutContainer in self.layoutContainers) {
        [layoutContainer refreshWithSynchronous:synchronous];
    }
}

- (CGSize)containerWrappedSize
{
    CGSize wrappedSize = CGSizeZero;
    for (XMLLayoutContainer *layoutContainer in self.layoutContainers) {
        CGSize size = layoutContainer.wrappedSize;
        wrappedSize = CGSizeMake(MAX(wrappedSize.width, size.width), MAX(wrappedSize.height, size.height));
    }
    return wrappedSize;
}

@end


text:
.. _maptools:

Map-making Tools
=================================

This broad class of operations include anything that generates pixel-space data products.

Distributed Pixel-space Data
--------------------------------

.. autoclass:: toast.map.OpLocalPixels
    :members:

.. autoclass:: toast.map.DistPixels
    :members:

Diagonal Noise Covariance
------------------------------

.. autoclass:: toast.map.OpAccumDiag
    :members:

.. autofunction:: toast.map.covariance_invert

.. autofunction:: toast.map.covariance_rcond

.. autofunction:: toast.map.covariance_multiply

.. autofunction:: toast.map.covariance_apply

Native Mapmaking
-----------------------

Using the distributed diagonal noise covariance tools, one can make a simple
binned map.  Porting the old TOAST map-maker to this version of TOAST is still
on the to-do list.

External Madam Interface
----------------------------------

If the MADAM library is installed and in your shared library search path, then
you can use it to make maps.

.. autoclass:: toast.map.OpMadam
    :members:


text:
using extension_function_test_utils::RunFunctionAndReturnError;
using extension_function_test_utils::RunFunctionAndReturnSingleResult;

namespace {

enum OriginSetMask {
  UNPROTECTED_WEB = BrowsingDataHelper::UNPROTECTED_WEB,
  PROTECTED_WEB = BrowsingDataHelper::PROTECTED_WEB,
  EXTENSION = BrowsingDataHelper::EXTENSION
};

const char kRemoveEverythingArguments[] = "[{\"since\": 1000}, {"
    "\"appcache\": true, \"cache\": true, \"cookies\": true, "
    "\"downloads\": true, \"fileSystems\": true, \"formData\": true, "
    "\"history\": true, \"indexedDB\": true, \"localStorage\": true, "
    "\"serverBoundCertificates\": true, \"passwords\": true, "
    "\"pluginData\": true, \"webSQL\": true"
    "}]";

class ExtensionBrowsingDataTest : public InProcessBrowserTest,
                                  public content::NotificationObserver {
 public:
  base::Time GetBeginTime() {
    return called_with_details_->removal_begin;
  }

  int GetRemovalMask() {
    return called_with_details_->removal_mask;
  }

  int GetOriginSetMask() {
    return called_with_details_->origin_set_mask;
  }

 protected:
  virtual void SetUpOnMainThread() OVERRIDE {
    called_with_details_.reset(new BrowsingDataRemover::NotificationDetails());
    registrar_.Add(this, chrome::NOTIFICATION_BROWSING_DATA_REMOVED,
                   content::Source<Profile>(browser()->profile()));
  }

  // content::NotificationObserver implementation.
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE {
    DCHECK_EQ(type, chrome::NOTIFICATION_BROWSING_DATA_REMOVED);

    // We're not taking ownership of the details object, but storing a copy of
    // it locally.
    called_with_details_.reset(new BrowsingDataRemover::NotificationDetails(
        *content::Details<BrowsingDataRemover::NotificationDetails>(
            details).ptr()));
  }

  int GetAsMask(const base::DictionaryValue* dict, std::string path,
                int mask_value) {
    bool result;
    EXPECT_TRUE(dict->GetBoolean(path, &result)) << "for " << path;
    return result ? mask_value : 0;
  }

  void RunRemoveBrowsingDataFunctionAndCompareRemovalMask(
      const std::string& data_types,
      int expected_mask) {
    scoped_refptr<RemoveBrowsingDataFunction> function =
        new RemoveBrowsingDataFunction();
    SCOPED_TRACE(data_types);
    EXPECT_EQ(NULL, RunFunctionAndReturnSingleResult(
        function.get(),
        std::string("[{\"since\": 1},") + data_types + "]",
        browser()));
    EXPECT_EQ(expected_mask, GetRemovalMask());
    EXPECT_EQ(UNPROTECTED_WEB, GetOriginSetMask());
  }

  void RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      const std::string& key,
      int expected_mask) {
    RunRemoveBrowsingDataFunctionAndCompareRemovalMask(
        std::string("{\"") + key + "\": true}", expected_mask);
  }

  void RunRemoveBrowsingDataFunctionAndCompareOriginSetMask(
      const std::string& protectedStr,
      int expected_mask) {
    scoped_refptr<RemoveBrowsingDataFunction> function =
        new RemoveBrowsingDataFunction();
    SCOPED_TRACE(protectedStr);
    EXPECT_EQ(NULL, RunFunctionAndReturnSingleResult(
        function.get(),
        "[{\"originTypes\": " + protectedStr + "}, {\"cookies\": true}]",
        browser()));
    EXPECT_EQ(expected_mask, GetOriginSetMask());
  }

  template<class ShortcutFunction>
  void RunAndCompareRemovalMask(int expected_mask) {
    scoped_refptr<ShortcutFunction> function =
        new ShortcutFunction();
    SCOPED_TRACE(ShortcutFunction::function_name());
    EXPECT_EQ(NULL, RunFunctionAndReturnSingleResult(
        function.get(),
        std::string("[{\"since\": 1}]"),
        browser()));
    EXPECT_EQ(expected_mask, GetRemovalMask());
    EXPECT_EQ(UNPROTECTED_WEB, GetOriginSetMask());
  }

  void SetSinceAndVerify(BrowsingDataRemover::TimePeriod since_pref) {
    PrefService* prefs = browser()->profile()->GetPrefs();
    prefs->SetInteger(prefs::kDeleteTimePeriod, since_pref);

    scoped_refptr<BrowsingDataSettingsFunction> function =
        new BrowsingDataSettingsFunction();
    SCOPED_TRACE("settings");
    scoped_ptr<base::Value> result_value(RunFunctionAndReturnSingleResult(
        function.get(), std::string("[]"), browser()));

    base::DictionaryValue* result;
    EXPECT_TRUE(result_value->GetAsDictionary(&result));
    base::DictionaryValue* options;
    EXPECT_TRUE(result->GetDictionary("options", &options));
    double since;
    EXPECT_TRUE(options->GetDouble("since", &since));

    double expected_since = 0;
    if (since_pref != BrowsingDataRemover::EVERYTHING) {
      base::Time time =
          BrowsingDataRemover::CalculateBeginDeleteTime(since_pref);
      expected_since = time.ToJsTime();
    }
    // Even a synchronous function takes nonzero time, but the difference
    // between when the function was called and now should be well under a
    // second, so we'll make sure the requested start time is within 10 seconds.
    // Since the smallest selectable period is an hour, that should be
    // sufficient.
    EXPECT_LE(expected_since, since + 10.0 * 1000.0);
  }

  void SetPrefsAndVerifySettings(int data_type_flags,
                                 int expected_origin_set_mask,
                                 int expected_removal_mask) {
    PrefService* prefs = browser()->profile()->GetPrefs();
    prefs->SetBoolean(prefs::kDeleteCache,
        !!(data_type_flags & BrowsingDataRemover::REMOVE_CACHE));
    prefs->SetBoolean(prefs::kDeleteCookies,
        !!(data_type_flags & BrowsingDataRemover::REMOVE_COOKIES));
    prefs->SetBoolean(prefs::kDeleteBrowsingHistory,
        !!(data_type_flags & BrowsingDataRemover::REMOVE_HISTORY));
    prefs->SetBoolean(prefs::kDeleteFormData,
        !!(data_type_flags & BrowsingDataRemover::REMOVE_FORM_DATA));
    prefs->SetBoolean(prefs::kDeleteDownloadHistory,
        !!(data_type_flags & BrowsingDataRemover::REMOVE_DOWNLOADS));
    prefs->SetBoolean(prefs::kDeleteHostedAppsData,
        !!(data_type_flags &
           BrowsingDataRemover::REMOVE_HOSTED_APP_DATA_TESTONLY));
    prefs->SetBoolean(prefs::kDeletePasswords,
        !!(data_type_flags & BrowsingDataRemover::REMOVE_PASSWORDS));
    prefs->SetBoolean(prefs::kClearPluginLSODataEnabled,
        !!(data_type_flags & BrowsingDataRemover::REMOVE_PLUGIN_DATA));

    scoped_refptr<BrowsingDataSettingsFunction> function =
        new BrowsingDataSettingsFunction();
    SCOPED_TRACE("settings");
    scoped_ptr<base::Value> result_value(RunFunctionAndReturnSingleResult(
        function.get(), std::string("[]"), browser()));

    base::DictionaryValue* result;
    EXPECT_TRUE(result_value->GetAsDictionary(&result));

    base::DictionaryValue* options;
    EXPECT_TRUE(result->GetDictionary("options", &options));
    base::DictionaryValue* origin_types;
    EXPECT_TRUE(options->GetDictionary("originTypes", &origin_types));
    int origin_set_mask = GetAsMask(origin_types, "unprotectedWeb",
                                    UNPROTECTED_WEB) |
                          GetAsMask(origin_types, "protectedWeb",
                                    PROTECTED_WEB) |
                          GetAsMask(origin_types, "extension", EXTENSION);
    EXPECT_EQ(expected_origin_set_mask, origin_set_mask);

    base::DictionaryValue* data_to_remove;
    EXPECT_TRUE(result->GetDictionary("dataToRemove", &data_to_remove));
    int removal_mask = GetAsMask(data_to_remove, "appcache",
                                 BrowsingDataRemover::REMOVE_APPCACHE) |
                       GetAsMask(data_to_remove, "cache",
                                 BrowsingDataRemover::REMOVE_CACHE) |
                       GetAsMask(data_to_remove, "cookies",
                                 BrowsingDataRemover::REMOVE_COOKIES) |
                       GetAsMask(data_to_remove, "downloads",
                                 BrowsingDataRemover::REMOVE_DOWNLOADS) |
                       GetAsMask(data_to_remove, "fileSystems",
                                 BrowsingDataRemover::REMOVE_FILE_SYSTEMS) |
                       GetAsMask(data_to_remove, "formData",
                                 BrowsingDataRemover::REMOVE_FORM_DATA) |
                       GetAsMask(data_to_remove, "history",
                                 BrowsingDataRemover::REMOVE_HISTORY) |
                       GetAsMask(data_to_remove, "indexedDB",
                                 BrowsingDataRemover::REMOVE_INDEXEDDB) |
                       GetAsMask(data_to_remove, "localStorage",
                                 BrowsingDataRemover::REMOVE_LOCAL_STORAGE) |
                       GetAsMask(data_to_remove, "pluginData",
                                 BrowsingDataRemover::REMOVE_PLUGIN_DATA) |
                       GetAsMask(data_to_remove, "passwords",
                                 BrowsingDataRemover::REMOVE_PASSWORDS) |
                       GetAsMask(data_to_remove, "webSQL",
                                 BrowsingDataRemover::REMOVE_WEBSQL) |
                       GetAsMask(data_to_remove, "serverBoundCertificates",
                           BrowsingDataRemover::REMOVE_SERVER_BOUND_CERTS);
    EXPECT_EQ(expected_removal_mask, removal_mask);
  }

  // The kAllowDeletingBrowserHistory pref must be set to false before this
  // is called.
  void CheckRemovalPermitted(const std::string& data_types, bool permitted) {
    scoped_refptr<RemoveBrowsingDataFunction> function =
        new RemoveBrowsingDataFunction();
    std::string args = "[{\"since\": 1}," + data_types + "]";

    if (permitted) {
      EXPECT_EQ(NULL, RunFunctionAndReturnSingleResult(
        function.get(), args, browser())) << " for " << args;
    } else {
      EXPECT_TRUE(MatchPattern(
          RunFunctionAndReturnError(function.get(), args, browser()),
          extension_browsing_data_api_constants::kDeleteProhibitedError))
          << " for " << args;
    }
  }

 private:
  scoped_ptr<BrowsingDataRemover::NotificationDetails> called_with_details_;
  content::NotificationRegistrar registrar_;
};

}  // namespace

IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, OneAtATime) {
  BrowsingDataRemover::set_removing(true);
  scoped_refptr<RemoveBrowsingDataFunction> function =
      new RemoveBrowsingDataFunction();
  EXPECT_TRUE(
      MatchPattern(RunFunctionAndReturnError(
                       function.get(), kRemoveEverythingArguments, browser()),
                   extension_browsing_data_api_constants::kOneAtATimeError));
  BrowsingDataRemover::set_removing(false);

  EXPECT_EQ(base::Time(), GetBeginTime());
  EXPECT_EQ(-1, GetRemovalMask());
}

IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, RemovalProhibited) {
  PrefService* prefs = browser()->profile()->GetPrefs();
  prefs->SetBoolean(prefs::kAllowDeletingBrowserHistory, false);

  CheckRemovalPermitted("{\"appcache\": true}", true);
  CheckRemovalPermitted("{\"cache\": true}", true);
  CheckRemovalPermitted("{\"cookies\": true}", true);
  CheckRemovalPermitted("{\"downloads\": true}", false);
  CheckRemovalPermitted("{\"fileSystems\": true}", true);
  CheckRemovalPermitted("{\"formData\": true}", true);
  CheckRemovalPermitted("{\"history\": true}", false);
  CheckRemovalPermitted("{\"indexedDB\": true}", true);
  CheckRemovalPermitted("{\"localStorage\": true}", true);
  CheckRemovalPermitted("{\"serverBoundCertificates\": true}", true);
  CheckRemovalPermitted("{\"passwords\": true}", true);
  CheckRemovalPermitted("{\"webSQL\": true}", true);

  // The entire removal is prohibited if any part is.
  CheckRemovalPermitted("{\"cache\": true, \"history\": true}", false);
  CheckRemovalPermitted("{\"cookies\": true, \"downloads\": true}", false);

  // If a prohibited type is not selected, the removal is OK.
  CheckRemovalPermitted("{\"history\": false}", true);
  CheckRemovalPermitted("{\"downloads\": false}", true);
  CheckRemovalPermitted("{\"cache\": true, \"history\": false}", true);
  CheckRemovalPermitted("{\"cookies\": true, \"downloads\": false}", true);
}

// Use-after-free, see http://crbug.com/116522
IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest,
                       DISABLED_RemoveBrowsingDataAll) {
  scoped_refptr<RemoveBrowsingDataFunction> function =
      new RemoveBrowsingDataFunction();
  EXPECT_EQ(NULL, RunFunctionAndReturnSingleResult(function.get(),
                                                   kRemoveEverythingArguments,
                                                   browser()));

  EXPECT_EQ(base::Time::FromDoubleT(1.0), GetBeginTime());
  EXPECT_EQ((BrowsingDataRemover::REMOVE_SITE_DATA |
      BrowsingDataRemover::REMOVE_CACHE |
      BrowsingDataRemover::REMOVE_DOWNLOADS |
      BrowsingDataRemover::REMOVE_FORM_DATA |
      BrowsingDataRemover::REMOVE_HISTORY |
      BrowsingDataRemover::REMOVE_PASSWORDS) &
      // We can't remove plugin data inside a test profile.
      ~BrowsingDataRemover::REMOVE_PLUGIN_DATA, GetRemovalMask());
}

IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, BrowsingDataOriginSetMask) {
  RunRemoveBrowsingDataFunctionAndCompareOriginSetMask("{}", 0);

  RunRemoveBrowsingDataFunctionAndCompareOriginSetMask(
      "{\"unprotectedWeb\": true}", UNPROTECTED_WEB);
  RunRemoveBrowsingDataFunctionAndCompareOriginSetMask(
      "{\"protectedWeb\": true}", PROTECTED_WEB);
  RunRemoveBrowsingDataFunctionAndCompareOriginSetMask(
      "{\"extension\": true}", EXTENSION);

  RunRemoveBrowsingDataFunctionAndCompareOriginSetMask(
      "{\"unprotectedWeb\": true, \"protectedWeb\": true}",
      UNPROTECTED_WEB | PROTECTED_WEB);
  RunRemoveBrowsingDataFunctionAndCompareOriginSetMask(
      "{\"unprotectedWeb\": true, \"extension\": true}",
      UNPROTECTED_WEB | EXTENSION);
  RunRemoveBrowsingDataFunctionAndCompareOriginSetMask(
      "{\"protectedWeb\": true, \"extension\": true}",
      PROTECTED_WEB | EXTENSION);

  RunRemoveBrowsingDataFunctionAndCompareOriginSetMask(
      ("{\"unprotectedWeb\": true, \"protectedWeb\": true, "
       "\"extension\": true}"),
      UNPROTECTED_WEB | PROTECTED_WEB | EXTENSION);
}

IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest,
                       FLAKY_BrowsingDataRemovalMask) {
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "appcache", BrowsingDataRemover::REMOVE_APPCACHE);
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "cache", BrowsingDataRemover::REMOVE_CACHE);
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "cookies", BrowsingDataRemover::REMOVE_COOKIES);
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "downloads", BrowsingDataRemover::REMOVE_DOWNLOADS);
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "fileSystems", BrowsingDataRemover::REMOVE_FILE_SYSTEMS);
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "formData", BrowsingDataRemover::REMOVE_FORM_DATA);
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "history", BrowsingDataRemover::REMOVE_HISTORY);
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "indexedDB", BrowsingDataRemover::REMOVE_INDEXEDDB);
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "localStorage", BrowsingDataRemover::REMOVE_LOCAL_STORAGE);
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "serverBoundCertificates",
      BrowsingDataRemover::REMOVE_SERVER_BOUND_CERTS);
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "passwords", BrowsingDataRemover::REMOVE_PASSWORDS);
  // We can't remove plugin data inside a test profile.
  RunRemoveBrowsingDataWithKeyAndCompareRemovalMask(
      "webSQL", BrowsingDataRemover::REMOVE_WEBSQL);
}

// Test an arbitrary combination of data types.
IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest,
                       BrowsingDataRemovalMaskCombination) {
  RunRemoveBrowsingDataFunctionAndCompareRemovalMask(
       "{\"appcache\": true, \"cookies\": true, \"history\": true}",
       BrowsingDataRemover::REMOVE_APPCACHE |
           BrowsingDataRemover::REMOVE_COOKIES |
           BrowsingDataRemover::REMOVE_HISTORY);
}

// Make sure the remove() function accepts the format produced by settings().
IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest,
                       BrowsingDataRemovalInputFromSettings) {
  PrefService* prefs = browser()->profile()->GetPrefs();
  prefs->SetBoolean(prefs::kDeleteCache, true);
  prefs->SetBoolean(prefs::kDeleteBrowsingHistory, true);
  prefs->SetBoolean(prefs::kDeleteDownloadHistory, true);
  prefs->SetBoolean(prefs::kDeleteCookies, false);
  prefs->SetBoolean(prefs::kDeleteFormData, false);
  prefs->SetBoolean(prefs::kDeleteHostedAppsData, false);
  prefs->SetBoolean(prefs::kDeletePasswords, false);
  prefs->SetBoolean(prefs::kClearPluginLSODataEnabled, false);
  int expected_mask = BrowsingDataRemover::REMOVE_CACHE |
        BrowsingDataRemover::REMOVE_DOWNLOADS |
        BrowsingDataRemover::REMOVE_HISTORY;
  std::string json;
  // Scoping for the traces.
  {
    scoped_refptr<BrowsingDataSettingsFunction> settings_function =
        new BrowsingDataSettingsFunction();
    SCOPED_TRACE("settings_json");
    scoped_ptr<base::Value> result_value(RunFunctionAndReturnSingleResult(
        settings_function.get(), std::string("[]"), browser()));

    base::DictionaryValue* result;
    EXPECT_TRUE(result_value->GetAsDictionary(&result));
    base::DictionaryValue* data_to_remove;
    EXPECT_TRUE(result->GetDictionary("dataToRemove", &data_to_remove));

    JSONStringValueSerializer serializer(&json);
    EXPECT_TRUE(serializer.Serialize(*data_to_remove));
  }
  {
    scoped_refptr<RemoveBrowsingDataFunction> remove_function =
        new RemoveBrowsingDataFunction();
    SCOPED_TRACE("remove_json");
    EXPECT_EQ(NULL, RunFunctionAndReturnSingleResult(
        remove_function.get(),
        std::string("[{\"since\": 1},") + json + "]",
        browser()));
    EXPECT_EQ(expected_mask, GetRemovalMask());
    EXPECT_EQ(UNPROTECTED_WEB, GetOriginSetMask());
  }
}

IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, ShortcutFunctionRemovalMask) {
  RunAndCompareRemovalMask<RemoveAppCacheFunction>(
      BrowsingDataRemover::REMOVE_APPCACHE);
  RunAndCompareRemovalMask<RemoveCacheFunction>(
      BrowsingDataRemover::REMOVE_CACHE);
  RunAndCompareRemovalMask<RemoveCookiesFunction>(
      BrowsingDataRemover::REMOVE_COOKIES |
      BrowsingDataRemover::REMOVE_SERVER_BOUND_CERTS);
  RunAndCompareRemovalMask<RemoveDownloadsFunction>(
      BrowsingDataRemover::REMOVE_DOWNLOADS);
  RunAndCompareRemovalMask<RemoveFileSystemsFunction>(
      BrowsingDataRemover::REMOVE_FILE_SYSTEMS);
  RunAndCompareRemovalMask<RemoveFormDataFunction>(
      BrowsingDataRemover::REMOVE_FORM_DATA);
  RunAndCompareRemovalMask<RemoveHistoryFunction>(
      BrowsingDataRemover::REMOVE_HISTORY);
  RunAndCompareRemovalMask<RemoveIndexedDBFunction>(
      BrowsingDataRemover::REMOVE_INDEXEDDB);
  RunAndCompareRemovalMask<RemoveLocalStorageFunction>(
      BrowsingDataRemover::REMOVE_LOCAL_STORAGE);
  // We can't remove plugin data inside a test profile.
  RunAndCompareRemovalMask<RemovePasswordsFunction>(
      BrowsingDataRemover::REMOVE_PASSWORDS);
  RunAndCompareRemovalMask<RemoveWebSQLFunction>(
      BrowsingDataRemover::REMOVE_WEBSQL);
}

// Test the processing of the 'delete since' preference.
IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionSince) {
  SetSinceAndVerify(BrowsingDataRemover::EVERYTHING);
  SetSinceAndVerify(BrowsingDataRemover::LAST_HOUR);
  SetSinceAndVerify(BrowsingDataRemover::LAST_DAY);
  SetSinceAndVerify(BrowsingDataRemover::LAST_WEEK);
  SetSinceAndVerify(BrowsingDataRemover::FOUR_WEEKS);
}

IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionEmpty) {
  SetPrefsAndVerifySettings(0, 0, 0);
}

// Test straightforward settings, mapped 1:1 to data types.
IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionSimple) {
  SetPrefsAndVerifySettings(BrowsingDataRemover::REMOVE_CACHE, 0,
                            BrowsingDataRemover::REMOVE_CACHE);
  SetPrefsAndVerifySettings(BrowsingDataRemover::REMOVE_HISTORY, 0,
                            BrowsingDataRemover::REMOVE_HISTORY);
  SetPrefsAndVerifySettings(BrowsingDataRemover::REMOVE_FORM_DATA, 0,
                            BrowsingDataRemover::REMOVE_FORM_DATA);
  SetPrefsAndVerifySettings(BrowsingDataRemover::REMOVE_DOWNLOADS, 0,
                            BrowsingDataRemover::REMOVE_DOWNLOADS);
  SetPrefsAndVerifySettings(BrowsingDataRemover::REMOVE_PASSWORDS, 0,
                            BrowsingDataRemover::REMOVE_PASSWORDS);
}

// Test cookie and app data settings.
IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionSiteData) {
  int site_data_no_plugins = BrowsingDataRemover::REMOVE_SITE_DATA &
      ~BrowsingDataRemover::REMOVE_PLUGIN_DATA;

  SetPrefsAndVerifySettings(BrowsingDataRemover::REMOVE_COOKIES,
                            UNPROTECTED_WEB,
                            site_data_no_plugins);
  SetPrefsAndVerifySettings(
      BrowsingDataRemover::REMOVE_HOSTED_APP_DATA_TESTONLY,
      PROTECTED_WEB,
      site_data_no_plugins);
  SetPrefsAndVerifySettings(
      BrowsingDataRemover::REMOVE_COOKIES |
          BrowsingDataRemover::REMOVE_HOSTED_APP_DATA_TESTONLY,
      PROTECTED_WEB | UNPROTECTED_WEB,
      site_data_no_plugins);
  SetPrefsAndVerifySettings(
      BrowsingDataRemover::REMOVE_COOKIES |
          BrowsingDataRemover::REMOVE_PLUGIN_DATA,
      UNPROTECTED_WEB,
      BrowsingDataRemover::REMOVE_SITE_DATA);
}

// Test an arbitrary assortment of settings.
IN_PROC_BROWSER_TEST_F(ExtensionBrowsingDataTest, SettingsFunctionAssorted) {
  int site_data_no_plugins = BrowsingDataRemover::REMOVE_SITE_DATA &
      ~BrowsingDataRemover::REMOVE_PLUGIN_DATA;

  SetPrefsAndVerifySettings(
      BrowsingDataRemover::REMOVE_COOKIES |
          BrowsingDataRemover::REMOVE_HISTORY |
          BrowsingDataRemover::REMOVE_DOWNLOADS,
    UNPROTECTED_WEB,
    site_data_no_plugins |
        BrowsingDataRemover::REMOVE_HISTORY |
        BrowsingDataRemover::REMOVE_DOWNLOADS);
}


text:
<?php

	require dirname(__FILE__)."/j-folder/php/csrf.php";
	$new_token = new CSRF('register');

?>
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Registration form</title>

	<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0" name="viewport">

	<link rel="stylesheet" href="j-folder/css/demo.css">
	<link rel="stylesheet" href="j-folder/css/font-awesome.min.css">
	<link rel="stylesheet" href="j-folder/css/j-forms.css">

		<form action="j-folder/php/action.php" method="post" class="j-forms" id="j-forms" novalidate>

					<?php echo $new_token->get_token();?>

							<input type="text" placeholder="first name" name="first_name">

							<input type="text" placeholder="last name" name="last_name">

						<select name="gender">
							<option value="" selected>select gender...</option>
							<option value="male">male</option>
							<option value="female">female</option>
							<option value="other">other</option>
						</select>

						<input type="text" id="username" name="username" placeholder="username">

						<input type="email" id="email" name="email" placeholder="email">

						<input type="password" id="password" name="password" placeholder="password">

				<button type="submit" class="primary-btn">Register</button>

		</form>


text:
package org.oscm.subscriptionservice.dao;

import java.math.BigInteger;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.interceptor.Interceptors;
import javax.persistence.Query;

import org.oscm.converter.ParameterizedTypes;
import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.Organization;
import org.oscm.interceptor.ExceptionMapper;
import org.oscm.internal.types.enumtypes.SubscriptionStatus;
import org.oscm.paginator.Filter;
import org.oscm.paginator.PaginationInt;
import org.oscm.paginator.PaginationSubForUser;
import org.oscm.paginator.TableColumns;

@Interceptors({ ExceptionMapper.class })
public class UserSubscriptionDao {

    private final DataService dataManager;

    public UserSubscriptionDao(DataService ds) {
        this.dataManager = ds;
    }

    private String paginatedQuery(String selectWhereQuery,
            PaginationInt pagination) {

        String queryOrderBy = " ORDER BY subscription.assigned DESC, subscription.subscriptionid ASC ";

        if (pagination.getSorting() != null) {
            queryOrderBy = createQueryOrderBy(pagination);
        }

        String queryFilter = "";
        if (pagination.getFilterSet() != null
                && pagination.getFilterSet().size() > 0) {
            queryFilter = createQueryFilter(pagination, queryFilter);
        }

        return selectWhereQuery + queryFilter + queryOrderBy;
    }

    private String paginatedQueryForCountSubs(String selectWhereQuery,
            PaginationInt pagination) {

        String queryFilter = "";
        if (pagination.getFilterSet() != null
                && pagination.getFilterSet().size() > 0) {
            queryFilter = createQueryFilter(pagination, queryFilter);
        }

        return selectWhereQuery + queryFilter;
    }

    private String createQueryOrderBy(PaginationInt pagination) {
        String queryOrderBy;

        String whenUserId = " WHEN '" + TableColumns.SUBSCRIPTION_ID.name()
                + "' THEN subscription.subscriptionid ";
        String whenFirstName = "WHEN '" + TableColumns.ROLE_IN_SUB.name()
                + "' THEN " + createQueryWithChangedRoles(pagination) + " ";

        queryOrderBy = " ORDER BY (CASE :sortColumn " + whenUserId
                + whenFirstName + " END) "
                + pagination.getSorting().getOrder().name();
        return queryOrderBy;
    }

    private String createQueryWithChangedRoles(PaginationInt pagination) {

        Map<String, String> changedRoles = ((PaginationSubForUser) pagination)
                .getChangedRoles();

        Map<String, Boolean> changedSelectedSubs = ((PaginationSubForUser) pagination)
                .getSelectedUsersIds();

        if (changedRoles.isEmpty() && changedSelectedSubs.isEmpty()) {
            return " subscription.displayedrole ";
        }
        String query = "";

        for (Entry<String, Boolean> selectedSub : changedSelectedSubs
                .entrySet()) {
            if (!selectedSub.getValue()) {
                query += " WHEN subscription.subscriptionid = '"
                        + selectedSub.getKey() + "' THEN null ";
            }
        }

        for (Entry<String, String> role : changedRoles.entrySet()) {
            query += " WHEN subscription.subscriptionid = '" + role.getKey()
                    + "' THEN '" + role.getValue() + "' ";
        }

        if (query.equals("")) {
            return " subscription.displayedrole ";
        }
        return " CASE " + query + " ELSE subscription.displayedrole END ";

    }

    private String createQueryFilter(PaginationInt pagination,
            String queryFilter) {

        Iterator<Filter> filterIterator = pagination.getFilterSet().iterator();
        StringBuilder queryFilterBuilder = new StringBuilder(queryFilter);

        queryFilterBuilder.append(" WHERE ");

        int i = 0;
        while (filterIterator.hasNext()) {
            if (i != 0) {
                queryFilterBuilder.append(" AND ");
            }
            Filter filter = filterIterator.next();
            addFilterColumn(pagination, queryFilterBuilder, filter);
            i++;
        }
        return queryFilterBuilder.toString();
    }

    private void addFilterColumn(PaginationInt pagination,
            StringBuilder queryFilterBuilder, Filter filter) {
        switch (filter.getColumn()) {
        case SUBSCRIPTION_ID:
            queryFilterBuilder.append(
                    " subscription.subscriptionid ILIKE :filterExpressionSubscriptionId");
            break;
        case ROLE_IN_SUB:
            queryFilterBuilder.append(createQueryWithChangedRoles(pagination)
                    + " ILIKE :filterExpressionRoleInSub ");
        default:
            break;
        }
    }

    private void setPaginationParameters(PaginationInt pagination,
            Query query) {
        setSortingParameter(query, pagination);
        setFilterParameters(query, pagination);

        query.setFirstResult(pagination.getOffset());
        query.setMaxResults(pagination.getLimit());
    }

    private void setSortingParameter(Query query, PaginationInt pagination) {
        if (pagination.getSorting() != null) {
            query.setParameter("sortColumn",
                    pagination.getSorting().getColumn().name());
        }
    }

    private void setFilterParameters(Query query, PaginationInt pagination) {
        if (pagination.getFilterSet() != null) {
            for (Filter filter : pagination.getFilterSet()) {
                setFilterParameter(query, filter);
            }
        }
    }

    private void setFilterParameter(Query query, Filter filter) {
        switch (filter.getColumn()) {
        case SUBSCRIPTION_ID:
            query.setParameter("filterExpressionSubscriptionId",
                    filter.getExpression() + "%");
            break;
        case ROLE_IN_SUB:
            query.setParameter("filterExpressionRoleInSub",
                    filter.getExpression() + "%");
            break;
        default:
            break;
        }
    }

    public List<Object[]> getUserAssignableSubscriptions(
            PaginationInt pagination, Organization owner, long userKey,
            Set<SubscriptionStatus> states) {

        String nativeQuery = getQueryUserAssignableSubscriptions(pagination);
        Query q = dataManager.createNativeQuery(nativeQuery);

        q.setParameter("locale", owner.getLocale());
        q.setParameter("orgKey", Long.valueOf(owner.getKey()));
        q.setParameter("userKey", Long.valueOf(userKey));
        q.setParameter("states", getSubscriptionStatesAsString(states));

        setPaginationParameters(pagination, q);
        return ParameterizedTypes.list(q.getResultList(), Object[].class);
    }

    public Long getCountUserAssignableSubscriptions(PaginationInt pagination,
            Organization owner, long userKey, Set<SubscriptionStatus> states) {

        String nativeQuery = getQueryCountUserAssignableSubscriptions(
                pagination);
        Query q = dataManager.createNativeQuery(nativeQuery);

        q.setParameter("locale", owner.getLocale());
        q.setParameter("orgKey", Long.valueOf(owner.getKey()));
        q.setParameter("userKey", Long.valueOf(userKey));
        q.setParameter("states", getSubscriptionStatesAsString(states));

        setPaginationParameters(pagination, q);
        BigInteger result = (BigInteger) q.getSingleResult();

        return result.longValue();
    }

    private String getQueryUserAssignableSubscriptions(
            PaginationInt pagination) {

        String query = "SELECT * FROM ("
                + "                     SELECT  sub.subscriptionid, "
                + "                             true as assigned, "
                + "                             roles.roleid, "
                + "                             (SELECT loc.value FROM localizedresource loc WHERE loc.objecttype = 'ROLE_DEF_NAME' AND loc.objectkey=roles.tkey AND loc.locale =:locale) as displayedrole, "
                + "                             license.tkey as key, "
                + "                             license.version as version"
                + "                     FROM subscription sub, usagelicense license"
                + "                     LEFT JOIN roledefinition roles"
                + "                     ON roles.tkey = license.roledefinition_tkey"
                + "                     WHERE license.subscription_tkey = sub.tkey "
                + "                             AND sub.status IN (:states) "
                + "                             AND sub.organizationKey =:orgKey "
                + "                             AND license.user_tkey =:userKey "
                + "                     UNION "
                + "                     SELECT  sub.subscriptionid, "
                + "                             false as assigned, "
                + "                             null as roleid, "
                + "                             null as displayedrole, "
                + "                             null as key, "
                + "                             null as version"
                + "                     FROM subscription sub"
                + "                     WHERE sub.tkey NOT IN (SELECT lic.subscription_tkey FROM usagelicense lic WHERE lic.user_tkey=:userKey)"
                + "                             AND sub.status IN (:states)"
                + "                             AND sub.organizationKey =:orgKey) AS subscription ";

        return paginatedQuery(query, pagination);
    }

    private String getQueryCountUserAssignableSubscriptions(
            PaginationInt pagination) {

        String query = "SELECT COUNT(*) FROM ("
                + "                     SELECT  sub.subscriptionid, "
                + "                             true as assigned, "
                + "                             roles.roleid, "
                + "                             (SELECT loc.value FROM localizedresource loc WHERE loc.objecttype = 'ROLE_DEF_NAME' AND loc.objectkey=roles.tkey AND loc.locale =:locale) as displayedrole, "
                + "                             license.tkey as key, "
                + "                             license.version as version"
                + "                     FROM subscription sub, usagelicense license"
                + "                     LEFT JOIN roledefinition roles"
                + "                     ON roles.tkey = license.roledefinition_tkey"
                + "                     WHERE license.subscription_tkey = sub.tkey "
                + "                             AND sub.status IN (:states) "
                + "                             AND sub.organizationKey =:orgKey "
                + "                             AND license.user_tkey =:userKey "
                + "                     UNION "
                + "                     SELECT  sub.subscriptionid, "
                + "                             false as assigned, "
                + "                             null as roleid, "
                + "                             null as displayedrole, "
                + "                             null as key, "
                + "                             null as version"
                + "                     FROM subscription sub"
                + "                     WHERE sub.tkey NOT IN (SELECT lic.subscription_tkey FROM usagelicense lic WHERE lic.user_tkey=:userKey)"
                + "                             AND sub.status IN (:states)"
                + "                             AND sub.organizationKey =:orgKey) AS subscription ";

        return paginatedQueryForCountSubs(query, pagination);
    }

    private Set<String> getSubscriptionStatesAsString(Set<SubscriptionStatus> states) {
        Set<String> statesAsString = new HashSet<String>();
        for (SubscriptionStatus s : states) {
            statesAsString.add(s.name());
        }
        return statesAsString;
    }

}


text:
void register_DefaultLogger_class();

#endif//DefaultLogger_hpp__pyplusplus_wrapper


text:
module 'mock'

--------------------------------------------------------------------
CLASS: SQNodeLog ( SQNode )
	:MODEL{
		Field 'text' :string();
	}

function SQNodeLog:__init()
	self.text = 'message'
end

function SQNodeLog:load( data )
	local args = data.args
	local text = false
	for i, arg in ipairs( data.args ) do
		if not text then
			text = arg
		else
			text = text .. '\n' .. arg
		end
	end
	self.text = text or ''
end

function SQNodeLog:enter( state, env )
	self:_log( self.text )
end

function SQNodeLog:getRichText()
	return string.format( '<cmd>LOG</cmd> <comment>%s</comment>', self.text )
end

--------------------------------------------------------------------
registerSQNode( 'log', SQNodeLog )