text:
package com.jakewharton.rxbinding3.widget;

import android.app.Instrumentation;
import android.widget.SeekBar;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import com.jakewharton.rxbinding3.RecordingObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import static android.view.MotionEvent.ACTION_DOWN;
import static android.view.MotionEvent.ACTION_MOVE;
import static android.view.MotionEvent.ACTION_UP;
import static com.jakewharton.rxbinding3.MotionEventUtil.motionEventAtPosition;
import static org.junit.Assert.assertEquals;

public final class RxSeekBarTest {
  @Rule public final ActivityTestRule<RxSeekBarTestActivity> activityRule =
      new ActivityTestRule<>(RxSeekBarTestActivity.class);

  private final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();

  SeekBar seekBar;

  @Before public void setUp() {
    seekBar = activityRule.getActivity().seekBar;
  }

  @Test public void changes() {
    RecordingObserver<Integer> o = new RecordingObserver<>();
    RxSeekBar.changes(seekBar) //
        .subscribeOn(AndroidSchedulers.mainThread()) //
        .subscribe(o);
    assertEquals(0, o.takeNext().intValue());

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_DOWN, 0, 50));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 100, 50));
    instrumentation.waitForIdleSync();
    assertEquals(100, o.takeNext().intValue());

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 0, 50));
    instrumentation.waitForIdleSync();
    assertEquals(0, o.takeNext().intValue());

    instrumentation.runOnMainSync(() -> seekBar.setProgress(85));
    instrumentation.waitForIdleSync();
    assertEquals(85, o.takeNext().intValue());

    o.dispose();

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 100, 50));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();

    instrumentation.runOnMainSync(() -> seekBar.setProgress(85));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();
  }

  @Test public void systemChanges() {
    RecordingObserver<Integer> o = new RecordingObserver<>();
    RxSeekBar.systemChanges(seekBar) //
            .subscribeOn(AndroidSchedulers.mainThread()) //
            .subscribe(o);
    assertEquals(0, o.takeNext().intValue());

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 100, 50));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();

    instrumentation.runOnMainSync(() -> seekBar.setProgress(85));
    instrumentation.waitForIdleSync();
    assertEquals(85, o.takeNext().intValue());

    o.dispose();

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 100, 50));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();

    instrumentation.runOnMainSync(() -> seekBar.setProgress(85));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();
  }

  @Test public void userChanges() {
    RecordingObserver<Integer> o = new RecordingObserver<>();
    RxSeekBar.userChanges(seekBar) //
            .subscribeOn(AndroidSchedulers.mainThread()) //
            .subscribe(o);
    assertEquals(0, o.takeNext().intValue());

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_DOWN, 0, 50));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 100, 50));
    instrumentation.waitForIdleSync();
    assertEquals(100, o.takeNext().intValue());

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 0, 50));
    instrumentation.waitForIdleSync();
    assertEquals(0, o.takeNext().intValue());

    instrumentation.runOnMainSync(() -> seekBar.setProgress(85));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();

    o.dispose();

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 100, 50));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();

    instrumentation.runOnMainSync(() -> seekBar.setProgress(85));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();
  }

  @Test public void changeEvents() {
    RecordingObserver<SeekBarChangeEvent> o = new RecordingObserver<>();
    RxSeekBar.changeEvents(seekBar) //
        .subscribeOn(AndroidSchedulers.mainThread()) //
        .subscribe(o);
    assertEquals(new SeekBarProgressChangeEvent(seekBar, 0, false), o.takeNext());

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_DOWN, 0, 50));
    instrumentation.waitForIdleSync();
    assertEquals(new SeekBarStartChangeEvent(seekBar), o.takeNext());

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_MOVE, 100, 50));
    instrumentation.waitForIdleSync();
    assertEquals(new SeekBarProgressChangeEvent(seekBar, 100, true), o.takeNext());

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_UP, 100, 50));
    instrumentation.waitForIdleSync();
    assertEquals(new SeekBarStopChangeEvent(seekBar), o.takeNext());

    instrumentation.runOnMainSync(() -> seekBar.setProgress(0));
    instrumentation.waitForIdleSync();
    assertEquals(new SeekBarProgressChangeEvent(seekBar, 0, false), o.takeNext());

    o.dispose();

    instrumentation.sendPointerSync(motionEventAtPosition(seekBar, ACTION_DOWN, 0, 50));
    instrumentation.waitForIdleSync();
    o.assertNoMoreEvents();
  }
}


text:
% pop_signalstat() - Computes and plots statistical characteristics of a signal,
%                    including the data histogram, a fitted normal distribution,
%                    a normal ditribution fitted on trimmed data, a boxplot, and
%                    the QQ-plot. The estimates value are printed in a panel and
%                    can be read as output. See SIGNALSTAT.
% Usage:
%   >>  OUTEEG = pop_signalstat( EEG, type ); % pops up
%   >>  [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_signalstat( EEG, type, cnum );
%   >>  [M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh] = pop_signalstat( EEG, type, cnum, percent );
%
% Inputs:
%   EEG   - input EEG dataset
%   type  - type of processing
%           1: process the raw  data; 0: the ICA components
%   cnum  - selected channel or component
%
% Outputs:
%   OUTEEG  - output dataset
%
% Author: Luca Finelli, CNL / Salk Institute - SCCN, 2 August 2002
%
% See also:
%   SIGNALSTAT,  EEGLAB

% Copyright (C) 2002 Luca Finelli, Salk/SCCN, La Jolla, CA
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function varargout = pop_signalstat( EEG, typeproc, cnum, percent );

% the command output is a hidden output that does not have to
% be described in the header

com = ''; % this initialization ensure that the function will return something
          % if the user press the cancel button
varargout{1} = '';

% display help if not enough arguments
% ------------------------------------
if nargin < 2
	help pop_signalstat;
	return;
end;
popup=0;
if nargin < 3
	popup = 1;
end;
if nargin < 4
	percent=5;
end;

% pop up window
% -------------
if (nargin < 3 & typeproc==1)
	promptstr    = { 'Channel number:'; 'Trim percentage (each end):' };
	inistr       = { '1';'5' };
	result       = inputdlg2( promptstr, 'Plot signal statistics -- pop_signalstat()', 1,  inistr, 'signalstat');
	if length( result ) == 0 return; end;
	cnum   	     = eval( [ '[' result{1} ']' ] ); % the brackets allow processing Matlab arrays
	percent      = eval( [ '[' result{2} ']' ] );
elseif (nargin < 3 & typeproc==0)
	promptstr    = { 'Component number:'; 'Trim percentage (each end):' };
	inistr       = { '1'; '5' };
	result       = inputdlg2( promptstr, 'Plot signal statistics -- pop_signalstat()', 1,  inistr, 'signalstat');
	if length( result ) == 0 return; end;
	cnum    	 = eval( [ '[' result{1} ']' ] ); % the brackets allow processing Matlab arrays
    percent      = eval( [ '[' result{2} ']' ] );
end;

if length(cnum) ~= 1 | (cnum-floor(cnum)) ~= 0
	error('pop_signalstat(): Channel/component number must be a single integer');
end

if cnum < 1 | cnum > EEG.nbchan
   error('pop_signalstat(): Channel/component number out of range');
end;

% call function signalstat() either on raw data or ICA data
% ---------------------------------------------------------
if typeproc == 1
	tmpsig=EEG.data(cnum,:);
%	[M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh]=signalstat( EEG.data(cnum,:),1,[], percent);
	dlabel=[];
	dlabel2=['Channel ' num2str(cnum)];
	map = cnum;
else
	if ~isempty( EEG.icasphere )
        tmpsig = eeg_getdatact(EEG, 'component', cnum);
        tmpsig = tmpsig(:,:);
	%	[M,SD,sk,k,med,zlow,zhi,tM,tSD,tndx,ksh]=signalstat( tmpsig,1,'Component Activity',percent);
		dlabel='Component Activity';
		dlabel2=['Component ' num2str(cnum)];
		map = EEG.icawinv(:,cnum);
	else
		error('You must run ICA first');
	end;
end;

% outputs
% -------
outstr = '';
if ~popup
    for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;
    if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;
end;

% return the string command
% -------------------------
%fprintf('Pop_signalstat: computing statistics...\n');
varargout{1} = sprintf('pop_signalstat( %s, %d, %d );', inputname(1), typeproc, cnum);

plotloc = 0;
if ~isempty(EEG.chanlocs)
    if isfield(EEG.chanlocs, 'theta')
        if ~isempty(EEG.chanlocs(cnum).theta)
            plotloc = 1;
        end;
    end;
end;
if plotloc
    if typeproc == 1
        com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2, map, EEG.chanlocs );', outstr);
    else
        com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2, map, EEG.chanlocs(EEG.icachansind) );', outstr);
    end;
else
    com = sprintf('%s signalstat( tmpsig, 1, dlabel, percent, dlabel2);', outstr);
end;

eval(com)
try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;

return;

redpajama_set_name: RedPajamaGithub


text:
package dinamica.http;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
 * A class encapsulating an HTTP query string.
 */
public final class QueryString implements Serializable
{
  private String mQueryString;
  private String mCharacterEncoding;
  private Map<String, List<Parameter>> mParameterMap;
  private List<Parameter> mParameterList;
  private List<String> mParameterNames;
  private String mFragment;

  /**
   * Construct a QueryString from a pre-encoded string.
   */
  public QueryString(String queryString, String characterEncoding)
  {
    // We only work on regular QueryStrings not strictXhtml QueryStrings
    mQueryString = queryString.replace("&", "&");
    mCharacterEncoding = characterEncoding;
  }

  /**
   * Makes a copy of an existing QueryString.
   */
  public QueryString(QueryString source)
  {
    mQueryString = source.mQueryString;
    mCharacterEncoding = source.mCharacterEncoding;
    if (source.mParameterList != null)
    {
      mParameterList = new ArrayList<Parameter>(source.mParameterList);
    }
  }

  /**
   * Constructs an empty query string (parameters may be added later).
   */
  public QueryString(String characterEncoding)
  {
    mCharacterEncoding = characterEncoding;
  }

  /**
   * Constructs a query string from an old-fashioned array of PRE-ENCODED name-value pairs
   */
  public QueryString(String[][] args, String characterEncoding)
  {
    this(characterEncoding);
    for (String[] element : args)
    {
      addParameter(element[0], element[1], true);
    }
  }

  /**
   * Constructs a query string from a list of PRE-ENCODED name-value pairs
   */
  public QueryString(List<String[]> params, String characterEncoding)
  {
    this(characterEncoding);

    for (String[] pair : params)
    {
      // -= Simon Lessard =-
      // FIXME: Add if (pair == null) check
      addParameter(pair[0], pair[1], true);
    }
  }

  /**
   * Converts this object into an encoded query string.
   */
  @Override
  public String toString()
  {
    // Use appendTo to concatenate the parameters together
    if (mQueryString == null)
    {
      appendTo(new StringBuilder(200));
    }
    return mQueryString;
  }

  /**
   * Appends the contents of this object to the given buffer in encoded query string form.
   *
   * @param buff
   *          the buffer to append to
   */
  public void appendTo(StringBuilder buff)
  {
    if (mQueryString == null)
    {
      // If we don't have a cached query string yet, generate it
      if (mParameterList == null || mParameterList.isEmpty())
      {
        // If we don't have any parameters at all, cache the empty string
        mQueryString = "";
      }
      else
      {
        // Remember the start position in the buffer, so that we can also
        // cache the concatenated string in mQueryString
        int startPos = buff.length();

        Iterator<Parameter> iter = mParameterList.iterator();
        Parameter param = iter.next();
        buff.append(param.getEncodedName()).append('=').append(param.getEncodedValue());

        while (iter.hasNext())
        {
          param = iter.next();
          buff.append('&').append(param.getEncodedName()).append('=')
            .append(param.getEncodedValue());
        }

        mQueryString = buff.substring(startPos);
      }

      if (mFragment != null)
      {
        mQueryString += mFragment;
      }
    }
    else
    {
      // If we have a cached query string, reuse it
      buff.append(mQueryString);
    }
  }

  public Enumeration<String> getParameterNames()
  {
    initParameterMap();
    return Collections.enumeration(mParameterNames);
  }

  public Map getParameterMap()
  {
    initParameterMap();
    return mParameterMap;
  }

  public int numParameters()
  {
    return (mParameterMap != null) ? mParameterMap.size() : 0;
  }

  public String getParameter(String name)
  {
    initParameterMap();
    List<Parameter> values = mParameterMap.get(name);
    return values == null ? null : values.get(0).getValue();
  }

  public Enumeration<String> getParameterValues(String name)
  {
    initParameterMap();
    List<Parameter> params = mParameterMap.get(name);
    if (params == null || params.isEmpty())
    {
      List<String> temp = Collections.emptyList();
      return Collections.enumeration(temp);
    }

    List<String> values = new ArrayList<String>(params.size());
    for (Parameter param : params)
    {
      values.add(param.getValue());
    }

    return Collections.enumeration(values);
  }

  public void addParameter(String name, String value)
  {
    addParameter(name, value, false);
  }

  public void addParameter(String name, String value, boolean isEncoded)
  {
    if (value == null)
    {
      return;
    }
    initParameterList();

    // Invalidate the query string
    mQueryString = null;

    // Update the parameter list
    Parameter param = new Parameter(name, value, isEncoded);
    mParameterList.add(param);

    // Update the parameter map if it is initialized
    if (mParameterMap != null)
    {
      String decodedName = param.getName();
      List<Parameter> values = mParameterMap.get(decodedName);
      if (values == null)
      {
        createParameterList(param);
      }
      else
      {
        values.add(param);
      }
    }
  }

  public void setParameter(String name, String value)
  {
    setParameter(name, value, false);
  }

  public void setParameter(String name, String value, boolean isEncoded)
  {
    if (value == null)
    {
      removeParameter(name, isEncoded);
      return;
    }
    initParameterMap();

    // Invalidate the query string
    mQueryString = null;

    // Update the map
    Parameter param = new Parameter(name, value, isEncoded);
    String decodedName = param.getName();
    List<Parameter> values = mParameterMap.get(decodedName);
    if (values == null)
    {
      createParameterList(param);
      mParameterList.add(param);
    }
    else
    {
      values.clear();

      // First, replace the existing occurence of the parameter
      int i = mParameterList.indexOf(param);
      mParameterList.set(i, param);

      // Now, remove any subsequent occurrences
      int j;
      while ((j = mParameterList.lastIndexOf(param)) > i)
      {
        mParameterList.remove(j);
      }

      values.add(param);
    }
  }

  public String removeParameter(String name)
  {
    return removeParameter(name, false);
  }

  public String removeParameter(String name, boolean isEncoded)
  {
    initParameterList();

    // Invalidate the query string
    mQueryString = null;

    // Create a template parameter for comparisons, so that we can avoid
    // decoding all parameter names in the list
    Parameter templateParam = new Parameter(name, "", isEncoded);

    // Update the parameter list
    Iterator<Parameter> i = mParameterList.iterator();
    Parameter firstParam = null;
    while (i.hasNext())
    {
      Parameter param = i.next();
      // Compare the parameter with our template (only the template name
      // will be encoded / decoded if necessary)
      if (templateParam.equals(param))
      {
        if (firstParam == null)
        {
          firstParam = param;
        }

        i.remove();
      }
    }

    if (firstParam == null)
    {
      return null;
    }

    // Update the map, if it is initialized and we found a parameter
    if (mParameterMap != null)
    {
      String decodedName = templateParam.getName();
      List<Parameter> values = mParameterMap.remove(decodedName);
      if (values != null)
      {
        mParameterNames.remove(decodedName);
      }
    }

    return isEncoded ? firstParam.getEncodedValue() : firstParam.getValue();
  }

  private void createParameterList(Parameter param)
  {
    String decodedName = param.getName();

    List<Parameter> values = new ArrayList<Parameter>(4);
    mParameterMap.put(decodedName, values);

    // Only add UNIQUE parameter names (preserving order)
    mParameterNames.add(decodedName);

    values.add(param);
  }

  private void initParameterMap()
  {
    if (mParameterMap == null)
    {
      initParameterList();

      // TODO: Constants
      mParameterMap = new HashMap<String, List<Parameter>>(30);
      mParameterNames = new ArrayList<String>(30);
      if (mParameterList.isEmpty())
      {
        return;
      }

      String decodedName;

      for (Parameter param : mParameterList)
      {
        decodedName = param.getName();
        List<Parameter> values = mParameterMap.get(decodedName);
        if (values == null)
        {
          createParameterList(param);
        }
        else
        {
          values.add(param);
        }
      }
    }
  }

  private void initParameterList()
  {
    if (mParameterList == null)
    {
      // remove/deal with a fragment hanging on the end
      initFragment();

      // TODO: Constant
      mParameterList = new ArrayList<Parameter>(30);
      int length;
      if (mQueryString == null || (length = mQueryString.length()) == 0)
      {
        return;
      }
      Parameter param;
      int lastPos = 0, nextPos, sepPos;
      do
      {
        nextPos = mQueryString.indexOf('&', lastPos);
        if (nextPos == -1)
        {
          nextPos = length;
        }
        sepPos = mQueryString.indexOf('=', lastPos);
        if (sepPos != -1 && sepPos < nextPos)
        {
          param = new Parameter(mQueryString.substring(lastPos, sepPos),
                                mQueryString.substring(sepPos + 1, nextPos), true);
        }
        else
        {
          param = new Parameter(mQueryString.substring(lastPos, nextPos), "", true);
        }
        mParameterList.add(param);
        lastPos = nextPos + 1;
      } while (nextPos < length);
    }
  }

  private void initFragment()
  {
    if (mQueryString != null)
    {
      int i = mQueryString.indexOf('#');
      if (i == 0)
      {
        mFragment = mQueryString;
        mQueryString = "";
      }
      else if (i > 0)
      {
        mFragment = mQueryString.substring(i);
        mQueryString = mQueryString.substring(0, i);
      }
    }
  }

  private class Parameter implements Serializable
  {
    private String mName;
    private String mEncodedName;

    private String mValue;
    private String mEncodedValue;

    public Parameter(String name, String value, boolean encoded)
    {
	      if (encoded)
	      {
	        mEncodedName = name;
	        mEncodedValue = value;
	      }
	      else
	      {
	        mName = name;
	        mValue = value;
	      }
	    }

	    public String getName()
	    {
	      if (mName == null)
	      {
	        try
	        {
	          mName = URLDecoder.decode(mEncodedName, mCharacterEncoding);
	        }
	        catch (UnsupportedEncodingException uee)
	        {
	          handleUnsupportedEncoding();
	        }
	      }
	      return mName;
	    }

	    public String getEncodedName()
	    {
	      if (mEncodedName == null)
	      {
	        try
	        {
	          mEncodedName = URLEncoder.encode(mName, mCharacterEncoding);
	        }
	        catch (UnsupportedEncodingException uee)
	        {
	          handleUnsupportedEncoding();
	        }
	      }
	      return mEncodedName;
	    }

	    public String getValue()
	    {
	      if (mValue == null)
	      {
	        try
	        {
	          mValue = URLEncoder.encode(mEncodedValue, mCharacterEncoding);
	        }
	        catch (UnsupportedEncodingException uee)
	        {
	          handleUnsupportedEncoding();
	        }
	      }
	      return mValue;
	    }

	    public String getEncodedValue()
	    {
	      if (mEncodedValue == null)
	      {
	        try
	        {
	          mEncodedValue = URLEncoder.encode(mValue, mCharacterEncoding);
	        }
	        catch (UnsupportedEncodingException uee)
	        {
	          handleUnsupportedEncoding();
	        }
	      }
	      return mEncodedValue;
	    }

	    /**
	     * Compares two parameters for name equality.
	     *
	     * Attempts not to invoke any lazy encoding or decoding in the passed in parameter - only in
	     * this one.
	     */
	    @Override
	    public boolean equals(Object o)
	    {
	      if (o == null || !(o instanceof Parameter))
	      {
	        return false;
	      }
	      Parameter p1 = (Parameter) o;
	      return p1.mName != null && getName().equals(p1.mName) || p1.mEncodedName != null
	             && getEncodedName().equals(p1.mEncodedName);
	    }
  }

  private void handleUnsupportedEncoding()
  {
    throw new IllegalArgumentException(
           new StringBuilder(100)
           .append( "Unrecognized character encoding \"")
           .append(mCharacterEncoding)
           .append('"').toString());
  }

	public static void main(String[] args) throws URISyntaxException {
		QueryString q=new QueryString("/forum/article.jsp?id=2");
		q.addParameter("user", "fff");
		//System.out.println(q.toString());
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Verrucaria fischeri Müll. Arg.

### Remarks
null


text:
"""adhoc filters

Revision ID: bddc498dd179
Revises: afb7730f6a9c
Create Date: 2018-06-13 14:54:47.086507

"""

# revision identifiers, used by Alembic.
revision = "bddc498dd179"
down_revision = "80a67c5192fa"

import json
import uuid
from collections import defaultdict

from alembic import op
from sqlalchemy import Column, Integer, Text
from sqlalchemy.ext.declarative import declarative_base

from superset import db
from superset.utils.core import (
    convert_legacy_filters_into_adhoc,
    split_adhoc_filters_into_base_filters,
)

Base = declarative_base()

class Slice(Base):
    __tablename__ = "slices"

    id = Column(Integer, primary_key=True)
    params = Column(Text)

def upgrade():
    bind = op.get_bind()
    session = db.Session(bind=bind)

    for slc in session.query(Slice).all():
        try:
            params = json.loads(slc.params)
            convert_legacy_filters_into_adhoc(params)
            slc.params = json.dumps(params, sort_keys=True)
        except Exception:
            pass

    session.commit()
    session.close()

def downgrade():
    bind = op.get_bind()
    session = db.Session(bind=bind)

    for slc in session.query(Slice).all():
        try:
            params = json.loads(slc.params)
            split_adhoc_filters_into_base_filters(params)

            if "adhoc_filters" in params:
                del params["adhoc_filters"]

            slc.params = json.dumps(params, sort_keys=True)
        except Exception:
            pass

    session.commit()
    session.close()


text: require 'wordify_djungst2'


text:
/* 3DLocation implementation */

#include "sles_allinclusive.h"

static SLresult I3DLocation_SetLocationCartesian(SL3DLocationItf self, const SLVec3D *pLocation)
{
    SL_ENTER_INTERFACE

    if (NULL == pLocation) {
        result = SL_RESULT_PARAMETER_INVALID;
    } else {
        I3DLocation *this = (I3DLocation *) self;
        SLVec3D locationCartesian = *pLocation;
        interface_lock_exclusive(this);
        this->mLocationCartesian = locationCartesian;
        this->mLocationActive = CARTESIAN_SET_SPHERICAL_UNKNOWN;
        interface_unlock_exclusive(this);
        result = SL_RESULT_SUCCESS;
    }

    SL_LEAVE_INTERFACE
}

static SLresult I3DLocation_SetLocationSpherical(SL3DLocationItf self,
    SLmillidegree azimuth, SLmillidegree elevation, SLmillimeter distance)
{
    SL_ENTER_INTERFACE

    if (!((-360000 <= azimuth) && (azimuth <= 360000) &&
        (-90000 <= elevation) && (elevation <= 90000) &&
        (0 <= distance) && (distance <= SL_MILLIMETER_MAX))) {
        result = SL_RESULT_PARAMETER_INVALID;
    } else {
        I3DLocation *this = (I3DLocation *) self;
        interface_lock_exclusive(this);
        this->mLocationSpherical.mAzimuth = azimuth;
        this->mLocationSpherical.mElevation = elevation;
        this->mLocationSpherical.mDistance = distance;
        this->mLocationActive = CARTESIAN_UNKNOWN_SPHERICAL_SET;
        interface_unlock_exclusive(this);
        result = SL_RESULT_SUCCESS;
    }

    SL_LEAVE_INTERFACE
}

static SLresult I3DLocation_Move(SL3DLocationItf self, const SLVec3D *pMovement)
{
    SL_ENTER_INTERFACE

    if (NULL == pMovement) {
        result = SL_RESULT_PARAMETER_INVALID;
    } else {
        I3DLocation *this = (I3DLocation *) self;
        SLVec3D movementCartesian = *pMovement;
        interface_lock_exclusive(this);
        for (;;) {
            enum CartesianSphericalActive locationActive = this->mLocationActive;
            switch (locationActive) {
            case CARTESIAN_COMPUTED_SPHERICAL_SET:
            case CARTESIAN_SET_SPHERICAL_COMPUTED:  // not in 1.0.1
            case CARTESIAN_SET_SPHERICAL_REQUESTED: // not in 1.0.1
            case CARTESIAN_SET_SPHERICAL_UNKNOWN:
                this->mLocationCartesian.x += movementCartesian.x;
                this->mLocationCartesian.y += movementCartesian.y;
                this->mLocationCartesian.z += movementCartesian.z;
                this->mLocationActive = CARTESIAN_SET_SPHERICAL_UNKNOWN;
                break;
            case CARTESIAN_UNKNOWN_SPHERICAL_SET:
                this->mLocationActive = CARTESIAN_REQUESTED_SPHERICAL_SET;
                // fall through
            case CARTESIAN_REQUESTED_SPHERICAL_SET:
                // matched by cond_broadcast in case multiple requesters
#if 0
                interface_cond_wait(this);
#else
                this->mLocationActive = CARTESIAN_COMPUTED_SPHERICAL_SET;
#endif
                continue;
            default:
                assert(SL_BOOLEAN_FALSE);
                break;
            }
            break;
        }
        interface_unlock_exclusive(this);
        result = SL_RESULT_SUCCESS;
    }

    SL_LEAVE_INTERFACE
}

static SLresult I3DLocation_GetLocationCartesian(SL3DLocationItf self, SLVec3D *pLocation)
{
    SL_ENTER_INTERFACE

    if (NULL == pLocation) {
        result = SL_RESULT_PARAMETER_INVALID;
    } else {
        I3DLocation *this = (I3DLocation *) self;
        interface_lock_exclusive(this);
        for (;;) {
            enum CartesianSphericalActive locationActive = this->mLocationActive;
            switch (locationActive) {
            case CARTESIAN_COMPUTED_SPHERICAL_SET:
            case CARTESIAN_SET_SPHERICAL_COMPUTED:  // not in 1.0.1
            case CARTESIAN_SET_SPHERICAL_REQUESTED: // not in 1.0.1
            case CARTESIAN_SET_SPHERICAL_UNKNOWN:
                {
                SLVec3D locationCartesian = this->mLocationCartesian;
                interface_unlock_exclusive(this);
                *pLocation = locationCartesian;
                }
                break;
            case CARTESIAN_UNKNOWN_SPHERICAL_SET:
                this->mLocationActive = CARTESIAN_REQUESTED_SPHERICAL_SET;
                // fall through
            case CARTESIAN_REQUESTED_SPHERICAL_SET:
                // matched by cond_broadcast in case multiple requesters
#if 0
                interface_cond_wait(this);
#else
                this->mLocationActive = CARTESIAN_COMPUTED_SPHERICAL_SET;
#endif
                continue;
            default:
                assert(SL_BOOLEAN_FALSE);
                interface_unlock_exclusive(this);
                pLocation->x = 0;
                pLocation->y = 0;
                pLocation->z = 0;
                break;
            }
            break;
        }
        result = SL_RESULT_SUCCESS;
    }

    SL_LEAVE_INTERFACE
}

static SLresult I3DLocation_SetOrientationVectors(SL3DLocationItf self,
    const SLVec3D *pFront, const SLVec3D *pAbove)
{
    SL_ENTER_INTERFACE

    if (NULL == pFront || NULL == pAbove) {
        result = SL_RESULT_PARAMETER_INVALID;
    } else {
        SLVec3D front = *pFront;
        SLVec3D above = *pAbove;
        // NTH Check for vectors close to zero or close to parallel
        I3DLocation *this = (I3DLocation *) self;
        interface_lock_exclusive(this);
        this->mOrientationVectors.mFront = front;
        this->mOrientationVectors.mAbove = above;
        this->mOrientationActive = ANGLES_UNKNOWN_VECTORS_SET;
        this->mRotatePending = SL_BOOLEAN_FALSE;
        interface_unlock_exclusive(this);
        result = SL_RESULT_SUCCESS;
    }

    SL_LEAVE_INTERFACE
}

static SLresult I3DLocation_SetOrientationAngles(SL3DLocationItf self,
    SLmillidegree heading, SLmillidegree pitch, SLmillidegree roll)
{
    SL_ENTER_INTERFACE

    if (!((-360000 <= heading) && (heading <= 360000) &&
        (-90000 <= pitch) && (pitch <= 90000) &&
        (-360000 <= roll) && (roll <= 360000))) {
        result = SL_RESULT_PARAMETER_INVALID;
    } else {
        I3DLocation *this = (I3DLocation *) self;
        interface_lock_exclusive(this);
        this->mOrientationAngles.mHeading = heading;
        this->mOrientationAngles.mPitch = pitch;
        this->mOrientationAngles.mRoll = roll;
        this->mOrientationActive = ANGLES_SET_VECTORS_UNKNOWN;
        this->mRotatePending = SL_BOOLEAN_FALSE;
        interface_unlock_exclusive(this);
        result = SL_RESULT_SUCCESS;
    }

    SL_LEAVE_INTERFACE
}

static SLresult I3DLocation_Rotate(SL3DLocationItf self, SLmillidegree theta, const SLVec3D *pAxis)
{
    SL_ENTER_INTERFACE

    if (!((-360000 <= theta) && (theta <= 360000)) || (NULL == pAxis)) {
        result = SL_RESULT_PARAMETER_INVALID;
    } else {
        SLVec3D axis = *pAxis;
        // NTH Check that axis is not (close to) zero vector, length does not matter
        I3DLocation *this = (I3DLocation *) self;
        interface_lock_exclusive(this);
        while (this->mRotatePending)
#if 0
            interface_cond_wait(this);
#else
            break;
#endif
        this->mTheta = theta;
        this->mAxis = axis;
        this->mRotatePending = SL_BOOLEAN_TRUE;
        interface_unlock_exclusive(this);
        result = SL_RESULT_SUCCESS;
    }

    SL_LEAVE_INTERFACE
}

static SLresult I3DLocation_GetOrientationVectors(SL3DLocationItf self,
    SLVec3D *pFront, SLVec3D *pUp)
{
    SL_ENTER_INTERFACE

    if (NULL == pFront || NULL == pUp) {
        result = SL_RESULT_PARAMETER_INVALID;
    } else {
        I3DLocation *this = (I3DLocation *) self;
        interface_lock_shared(this);
        SLVec3D front = this->mOrientationVectors.mFront;
        SLVec3D up = this->mOrientationVectors.mUp;
        interface_unlock_shared(this);
        *pFront = front;
        *pUp = up;
        result = SL_RESULT_SUCCESS;
    }

    SL_LEAVE_INTERFACE
}

static const struct SL3DLocationItf_ I3DLocation_Itf = {
    I3DLocation_SetLocationCartesian,
    I3DLocation_SetLocationSpherical,
    I3DLocation_Move,
    I3DLocation_GetLocationCartesian,
    I3DLocation_SetOrientationVectors,
    I3DLocation_SetOrientationAngles,
    I3DLocation_Rotate,
    I3DLocation_GetOrientationVectors
};

void I3DLocation_init(void *self)
{
    I3DLocation *this = (I3DLocation *) self;
    this->mItf = &I3DLocation_Itf;
    this->mLocationCartesian.x = 0;
    this->mLocationCartesian.y = 0;
    this->mLocationCartesian.z = 0;
    memset(&this->mLocationSpherical, 0x55, sizeof(this->mLocationSpherical));
    this->mLocationActive = CARTESIAN_SET_SPHERICAL_UNKNOWN;
    this->mOrientationAngles.mHeading = 0;
    this->mOrientationAngles.mPitch = 0;
    this->mOrientationAngles.mRoll = 0;
    memset(&this->mOrientationVectors, 0x55, sizeof(this->mOrientationVectors));
    this->mOrientationActive = ANGLES_SET_VECTORS_UNKNOWN;
    this->mTheta = 0x55555555;
    this->mAxis.x = 0x55555555;
    this->mAxis.y = 0x55555555;
    this->mAxis.z = 0x55555555;
    this->mRotatePending = SL_BOOLEAN_FALSE;
}


text:
package org.estatio.module.capex.app.orderinvoice;

import java.math.BigDecimal;

import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.Nature;

import org.estatio.module.capex.dom.order.OrderItem;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@DomainObject(
        nature = Nature.VIEW_MODEL,
        objectType = "org.estatio.capex.dom.orderinvoice.viewmodel.LinkedOrderItemViewModel")
@Getter @Setter
@AllArgsConstructor
@NoArgsConstructor
public class LinkedOrderItemViewModel {

    private OrderItem orderItem;

    private BigDecimal netAmount;

    private BigDecimal netAmountInvoiced;

}


text:
var FastClick = (function() {

	// Determine whether touch handling is supported
	var touchSupport = 'ontouchstart' in window;

	return function(layer) {
		if (!(layer instanceof HTMLElement)) {
			throw new TypeError('Layer must be instance of HTMLElement');
		}

		// Set up event handlers as required
		if (touchSupport) {
			layer.addEventListener('touchstart', onTouchStart, true);
			layer.addEventListener('touchmove', onTouchMove, true);
			layer.addEventListener('touchend', onTouchEnd, true);
			layer.addEventListener('touchcancel', onTouchCancel, true);
		}
		layer.addEventListener('click', onClick, true);

		// If a handler is already declared in the element's onclick attribute, it will be fired before
		// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
		// adding it as listener.
		if (layer.onclick instanceof Function) {
			layer.addEventListener('click', layer.onclick, false);
			layer.onclick = '';
		}

		// Define touch-handling variables
		var clickStart = { x: 0, y: 0, scroll: 0 }, trackingClick = false;

		// On touch start, record the position and scroll offset.
		function onTouchStart(event) {
			trackingClick = true;
			clickStart.x = event.targetTouches[0].clientX;
			clickStart.y = event.targetTouches[0].clientY;
			clickStart.scroll = window.pageYOffset;

			return true;
		}

		// If the touch moves more than a small amount, cancel any derived clicks.
		function onTouchMove(event) {
			if (trackingClick) {
				if (Math.abs(event.targetTouches[0].clientX - clickStart.x) > 10 || Math.abs(event.targetTouches[0].clientY - clickStart.y) > 10) {
					trackingClick = false;
				}
			}

			return true;
		}

		// On touch end, determine whether to send a click event at once.
		function onTouchEnd(event) {
			var targetElement, clickEvent;

			// If the touch was cancelled (eg due to movement), or if the page has scrolled in the meantime, return.
			if (!trackingClick || Math.abs(window.pageYOffset - clickStart.scroll) > 5) {
				return true;
			}

			// Derive the element to click as a result of the touch.
			targetElement = document.elementFromPoint(clickStart.x, clickStart.y);

			// If the targeted node is a text node, target the parent instead.
			if (targetElement.nodeType === Node.TEXT_NODE) {
				targetElement = targetElement.parentNode;
			}

			// Unless the element is marked as only requiring a non-programmatic click, synthesise a click
			// event, with an extra attribute so it can be tracked.
			if (!(targetElement.className.indexOf('clickevent') !== -1 && targetElement.className.indexOf('touchandclickevent') === -1)) {
				clickEvent = document.createEvent('MouseEvents');
				clickEvent.initMouseEvent('click', true, true, window, 1, 0, 0, clickStart.x, clickStart.y, false, false, false, false, 0, null);
				clickEvent.forwardedTouchEvent = true;
				targetElement.dispatchEvent(clickEvent);
			}

			// Prevent the actual click from going though - unless the target node is marked as requiring
			// real clicks or if it is a SELECT, in which case only non-programmatic clicks are permitted
			// to open the options list and so the original event is required.
			if (!(targetElement instanceof HTMLSelectElement) &&
				targetElement.className.indexOf('clickevent') === -1) {
				event.preventDefault();
			} else {
				return false;
			}
		}

		function onTouchCancel(event) {
			trackingClick = false;
		}

		// On actual clicks, determine whether this is a touch-generated click, a click action occurring
		// naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
		// an actual click which should be permitted.
		function onClick(event) {
			if (!window.event) {
				return true;
			}

			var allowClick = true;
			var targetElement;
			var forwardedTouchEvent = window.event.forwardedTouchEvent;

			// For devices with touch support, derive and check the target element to see whether the
			// click needs to be permitted; unless explicitly enabled, prevent non-touch click events
			// from triggering actions, to prevent ghost/doubleclicks.
			if (touchSupport) {
				targetElement = document.elementFromPoint(clickStart.x, clickStart.y);
				if (!targetElement ||
					(!forwardedTouchEvent && targetElement.className.indexOf('clickevent') == -1)) {
					allowClick = false;
				}
			}

			// If clicks are permitted, return true for the action to go through.
			if (allowClick) {
				return true;
			}

			// Otherwise cancel the event
			event.stopPropagation();
			event.preventDefault();

			// Prevent any user-added listeners declared on FastClick element from being fired.
			event.stopImmediatePropagation();

			return false;
		}
	}

})();


text:
import React, { PropTypes, classSet } from 'react';
import classNames from 'classnames';
import './Background.css';
window.$ = window.jQuery = require('../../jquery-2.1.4.js');

export default class Background extends React.Component {
  constructor(props, context) {
    super(props, context);

    if(this.props.animate) {
      this.tick = this.tick.bind(this);
    }
    this.state = {bubbleCount: 0, width: 0, height: 0};
    this.updateDimensions = this.updateDimensions.bind(this);
  }

  tick() {
    var maxBubbleSize = 80;
    var minBubbleSize = 10;

    var maxNumBubbles = 25;
    var bubbleGroupSize = 5;

    var maxBubbleDur = 10;
    var minBubbleDur = 1.5;

    var minBubbleOpacity = 0.2;
    var maxBubbleOpacity = 0.8;

    if(this.state.bubbleCount < maxNumBubbles) {
      for (var i=0; i < bubbleGroupSize; i++) {
        var bubble = document.createElement("div");
        $(bubble).addClass("Background-bubble");
        var randX = 100 * Math.random();
        $(bubble).css( "left", randX + "%");
        $(bubble).css( "z-index", 1);

        var randSize = (maxBubbleSize-minBubbleSize) * Math.random() + minBubbleSize;
        $(bubble).css( "width", randSize+"px");
        $(bubble).css( "height", randSize+"px");

        var randOpacity = (maxBubbleOpacity - minBubbleOpacity) * Math.random() + minBubbleOpacity;
        $(bubble).css( "opacity", randOpacity);

        var randDur = (maxBubbleDur-minBubbleDur) * Math.random() + minBubbleDur;
        $(bubble).css("-webkit-animation-duration", randDur + "s");
        $("div.Background-bubble-container")[0].appendChild(bubble);
        this.state.bubbleCount = this.state.bubbleCount + 1;
      }
    }
  }

  updateDimensions() {
    this.setState({width: window.innerWidth, height: window.innerHeight});
  }

  componentDidMount() {
    if(this.props.animate) {
      this.interval = setInterval(this.tick, 1000);
    }
    window.addEventListener('resize', this.updateDimensions);
    this.updateDimensions();
  }

  componentWillUnmount() {
    clearInterval(this.interval);
    window.removeEventListener("resize", this.updateDimensions);
  }

  render() {
    const contentStyle = {
      height: this.state.height + 'px',
    }

    return (

        {this.props.children}

    );
  }
}

Background.propTypes = {animate: React.PropTypes.bool, maxBubbleCount: React.PropTypes.number};
Background.defaultProps = {animate: true, maxBubbleCount: 25};


text:
//
//  FFWeekHeaderCell.m
//  FFCalendar
//
//  Created by Fernanda G. Geraissate on 2/26/14.
//  Copyright (c) 2014 Fernanda G. Geraissate. All rights reserved.
//
//  http://fernandasportfolio.tumblr.com
//

#import "FFWeekHeaderCell.h"
#import "FFImportantFilesForCalendar.h"

@implementation FFWeekHeaderCell

@synthesize label;
@synthesize imageView;
@synthesize date;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0., 0., self.frame.size.width, self.frame.size.height)];
        [imageView setAutoresizingMask:AR_LEFT_RIGHT];
        [imageView setContentMode:UIViewContentModeCenter];
        [self addSubview:imageView];

        label = [[UILabel alloc] initWithFrame:CGRectMake(0., 0., self.frame.size.width, self.frame.size.height)];
        [label setAutoresizingMask:AR_LEFT_RIGHT];
        [label setTextAlignment:NSTextAlignmentCenter];
        [self addSubview:label];
    }
    return self;
}

- (void)cleanCell {

    [imageView setImage:nil];
    [label setText:@""];
    [label setTextColor:[UIColor blackColor]];
    date = nil;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end


text:
Dir[File.join File.dirname(__FILE__), '*_examples.rb'].each do |file|
  require file
end # end each


text:
/* globals AFRAME THREE */
AFRAME.registerComponent('ui', {
  schema: {
    brightness: { default: 1.0, max: 1.0, min: 0.0 },
    opacity: { default: 0 }
  },
  dependencies: ['ui-raycaster'],

  init: function () {
    var el = this.el;
    var uiEl = this.uiEl = document.createElement('a-entity');
    var rayEl = this.rayEl = document.createElement('a-entity');
    this.closed = true;
    this.isTooltipPaused = false;
    this.colorStack = ['#272727', '#727272', '#FFFFFF', '#24CAFF', '#249F90', '#F2E646', '#EF2D5E'];
    this.bindMethods();
    this.colorHasChanged = true;
    this.highlightMaterials = {};
    this.intersectedObjects = [];
    this.hoveredOffObjects = [];
    this.hoveredOnObjects = [];
    this.pressedObjects = {};
    this.selectedObjects = {};
    this.unpressedObjects = {};
    this.brushButtonsMapping = {};
    this.brushRegexp = /^(?!.*(fg|bg)$)brush[0-9]+/;
    this.colorHistoryRegexp = /^(?!.*(fg|bg)$)colorhistory[0-9]+$/;
    this.hsv = { h: 0.0, s: 0.0, v: 1.0 };
    this.rayAngle = 45;
    this.rayDistance = 0.2;

    // The cursor is centered in 0,0 to allow scale it easily
    // This is the offset to put it back in its original position on the slider
    this.cursorOffset = new THREE.Vector3(0.06409, 0.01419, -0.10242);

    // UI entity setup
    uiEl.setAttribute('material', {
      color: '#ffffff',
      flatShading: true,
      shader: 'flat',
      transparent: true,
      fog: false,
      src: '#uinormal'
    });
    uiEl.setAttribute('obj-model', 'obj:#uiobj');
    uiEl.setAttribute('position', '0 0.04 -0.15');

    uiEl.setAttribute('scale', '0 0 0');
    uiEl.setAttribute('visible', false);
    uiEl.classList.add('apainter-ui');
    el.appendChild(uiEl);

    // Ray entity setup
    rayEl.setAttribute('line', '');

    //rayEl.setAttribute('visible', false);
    el.appendChild(rayEl);

    // Raycaster setup
    el.setAttribute('ui-raycaster', {
      far: this.rayDistance,
      objects: '.apainter-ui',
      rotation: -this.rayAngle
    });

    this.controller = null;

    var self = this;

    el.addEventListener('controllerconnected', function (evt) {
      var controllerName = evt.detail.name;
      self.tooltips = Utils.getTooltips(controllerName);
      self.controller = {
        name: controllerName,
        hand: evt.detail.component.data.hand
      }

      if (controllerName === 'oculus-touch-controls') {
        self.uiEl.setAttribute('rotation', '45 0 0');
        uiEl.setAttribute('position', '0 0.13 -0.08');
        self.rayAngle = 0;
        el.setAttribute('ui-raycaster', {
          rotation: 0
        });
      } else if (controllerName === 'windows-motion-controls') {
        self.rayAngle = 25;
        self.rayDistance = 1;
        el.setAttribute('ui-raycaster', {
          rotation: -30,
          far: self.rayDistance
        });
      }

      if (self.el.isPlaying) {
        self.addToggleEvent();
      }
    });
  },

  initColorWheel: function () {
    var colorWheel = this.objects.hueWheel;

    var vertexShader = '\
      varying vec2 vUv;\
      void main() {\
        vUv = uv;\
        vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);\
        gl_Position = projectionMatrix * mvPosition;\
      }\
      ';

    var fragmentShader = '\
      #define M_PI2 6.28318530718\n \
      uniform float brightness;\
      varying vec2 vUv;\
      vec3 hsb2rgb(in vec3 c){\
          vec3 rgb = clamp(abs(mod(c.x * 6.0 + vec3(0.0, 4.0, 2.0), 6.0) - 3.0) - 1.0, \
                           0.0, \
                           1.0 );\
          rgb = rgb * rgb * (3.0 - 2.0 * rgb);\
          return c.z * mix( vec3(1.0), rgb, c.y);\
      }\
      \
      void main() {\
        vec2 toCenter = vec2(0.5) - vUv;\
        float angle = atan(toCenter.y, toCenter.x);\
        float radius = length(toCenter) * 2.0;\
        vec3 color = hsb2rgb(vec3((angle / M_PI2) + 0.5, radius, brightness));\
        gl_FragColor = vec4(color, 1.0);\
      }\
      ';

    var material = new THREE.ShaderMaterial({
      uniforms: { brightness: { type: 'f', value: this.hsv.v } },
      vertexShader: vertexShader,
      fragmentShader: fragmentShader
    });
    colorWheel.material = material;
  },

  bindMethods: function () {
    this.onComponentChanged = this.onComponentChanged.bind(this);
    this.onTriggerChanged = this.onTriggerChanged.bind(this);
    this.onIntersection = this.onIntersection.bind(this);
    this.onIntersected = this.onIntersected.bind(this);
    this.onIntersectionCleared = this.onIntersectionCleared.bind(this);
    this.onIntersectedCleared = this.onIntersectedCleared.bind(this);
    this.onModelLoaded = this.onModelLoaded.bind(this);
    this.onStrokeStarted = this.onStrokeStarted.bind(this);
    this.toggleMenu = this.toggleMenu.bind(this);
    this.open = this.open.bind(this);
    this.close = this.close.bind(this);
  },

  tick: function () {
    if (!this.closed && this.handEl) {
      this.updateIntersections();
      this.handleHover();
      this.handlePressedButtons();
    }
  },

  update: function () {
    if (this.messagesMaterial) {
      this.messagesMaterial.opacity = this.data.opacity;
    }
  },

  onTriggerChanged: function (evt) {
    var triggerValue = evt.detail.value;
    this.lastTriggerValue = triggerValue;
    if (evt.detail.value >= 0.25) {
      this.triggeredPressed = true;
    } else {
      this.triggeredPressed = false;
      this.handleButtonUp();
    }
  },

  handleButtonDown: function (object, position) {
    var name = object.name;
    if (this.activeWidget && this.activeWidget !== name) { return; }
    this.activeWidget = name;
    switch (true) {
      case name === 'brightness': {
        this.onBrightnessDown(position);
        break;
      }
      case name === 'brushnext': {
        if (!this.pressedObjects[name]) {
          this.nextPage();
        }
        break;
      }
      case name === 'brushprev': {
        if (!this.pressedObjects[name]) {
          this.previousPage();
        }
        break;
      }
      case name === 'clear': {
        if (!this.pressedObjects[name]) {
          this.el.sceneEl.systems.brush.clear();
          this.playSound('ui_click1');
        }
        break;
      }
      case name === 'copy': {
        if (!this.pressedObjects[name]) {
          this.copyBrush();
          this.playSound('ui_click1');
        }
        break;
      }
      case name === 'hue': {
        this.onHueDown(position);
        break;
      }
      case name === 'save': {
        if (!this.pressedObjects[name]) {
          this.el.sceneEl.systems.painter.upload();
          this.playSound('ui_click1');
        }
        break;
      }
      case name === 'sizebg': {
        this.onBrushSizeBackgroundDown(position);
        break;
      }
      case this.brushRegexp.test(name): {
        this.onBrushDown(name);
        break;
      }
      case this.colorHistoryRegexp.test(name): {
        this.onColorHistoryButtonDown(object);
        break;
      }
      default: {
        this.activeWidget = undefined;
      }
    }
    this.pressedObjects[name] = object;
  },

  copyBrush: function () {
    var brush = this.el.getAttribute('brush');
    this.handEl.setAttribute('brush', 'brush', brush.brush);
    this.handEl.setAttribute('brush', 'color', brush.color);
    this.handEl.setAttribute('brush', 'size', brush.size);
    this.colorHasChanged = true;
  },

  handleButtonUp: function () {
    var pressedObjects = this.pressedObjects;
    var unpressedObjects = this.unpressedObjects;
    this.activeWidget = undefined;
    Object.keys(pressedObjects).forEach(function (key) {
      var buttonName = pressedObjects[key].name;
      switch (true) {
        case buttonName === 'size': {
          // self.onBrushSizeUp();
          break;
        }
        default: {
          break;
        }
      }
      unpressedObjects[buttonName] = pressedObjects[buttonName];
      delete pressedObjects[buttonName];
    });
  },

  handlePressedButtons: function () {
    var self = this;
    if (!this.triggeredPressed) { return; }
    this.hoveredOnObjects.forEach(function triggerAction (button) {
      self.handleButtonDown(button.object, button.point);
    });
  },

  onColorHistoryButtonDown: function (object) {
    var color = object.material.color.getHexString();
    this.handEl.setAttribute('brush', 'color', '#' + color);
    this.playSound('ui_click0', object.name);
  },

  onBrushDown: function (name) {
    var brushName = this.brushButtonsMapping[name];
    if (!brushName) { return; }
    this.selectBrushButton(name);
    this.handEl.setAttribute('brush', 'brush', brushName.toLowerCase());
  },

  selectBrushButton: function (brushName) {
    var object = this.uiEl.getObject3D('mesh').getObjectByName(brushName + 'bg');
    var selectedObjects = this.selectedObjects;
    var selectedBrush = this.selectedBrush;
    if (selectedBrush) {
      if (!this.highlightMaterials[selectedBrush.name]) {
        this.initHighlightMaterial(object);
      }
      selectedBrush.material = this.highlightMaterials[selectedBrush.name].normal;
      delete selectedObjects[selectedBrush.name];
    }
    selectedObjects[object.name] = object;
    this.selectedBrush = object;
    this.playSound('ui_click1', brushName);
  },

  onHueDown: function (position) {
    var hueWheel = this.objects.hueWheel;
    var polarPosition;
    var radius = this.colorWheelSize;
    hueWheel.updateMatrixWorld();
    hueWheel.worldToLocal(position);
    this.objects.hueCursor.position.copy(position);

    polarPosition = {
      r: Math.sqrt(position.x * position.x + position.z * position.z),
      theta: Math.PI + Math.atan2(-position.z, position.x)
    };
    var angle = ((polarPosition.theta * (180 / Math.PI)) + 180) % 360;
    this.hsv.h = angle / 360;
    this.hsv.s = polarPosition.r / radius;
    this.updateColor();
    this.playSound('ui_click0', 'hue');
  },

  updateColor: function () {
    var rgb = this.hsv2rgb(this.hsv);
    var color = 'rgb(' + rgb.r + ', ' + rgb.g + ', ' + rgb.b + ')';
    this.handEl.setAttribute('brush', 'color', color);
    this.colorHasChanged = true;
  },

  hsv2rgb: function (hsv) {
    var r, g, b, i, f, p, q, t;
    var h = THREE.Math.clamp(hsv.h, 0, 1);
    var s = THREE.Math.clamp(hsv.s, 0, 1);
    var v = hsv.v;

    i = Math.floor(h * 6);
    f = h * 6 - i;
    p = v * (1 - s);
    q = v * (1 - f * s);
    t = v * (1 - (1 - f) * s);
    switch (i % 6) {
      case 0: r = v; g = t; b = p; break;
      case 1: r = q; g = v; b = p; break;
      case 2: r = p; g = v; b = t; break;
      case 3: r = p; g = q; b = v; break;
      case 4: r = t; g = p; b = v; break;
      case 5: r = v; g = p; b = q; break;
    }
    return {
      r: Math.round(r * 255),
      g: Math.round(g * 255),
      b: Math.round(b * 255)
    };
  },

  rgb2hsv: function (r, g, b) {
    var max = Math.max(r, g, b);
    var min = Math.min(r, g, b);
    var d = max - min;
    var h;
    var s = (max === 0 ? 0 : d / max);
    var v = max;

    if (arguments.length === 1) { g = r.g; b = r.b; r = r.r; }

    switch (max) {
      case min: h = 0; break;
      case r: h = (g - b) + d * (g < b ? 6 : 0); h /= 6 * d; break;
      case g: h = (b - r) + d * 2; h /= 6 * d; break;
      case b: h = (r - g) + d * 4; h /= 6 * d; break;
    }
    return {h: h, s: s, v: v};
  },

  onBrightnessDown: function (position) {
    var slider = this.objects.brightnessSlider;
    var sliderBoundingBox = slider.geometry.boundingBox;
    var sliderHeight = sliderBoundingBox.max.z - sliderBoundingBox.min.z;
    slider.updateMatrixWorld();
    slider.worldToLocal(position);
    var brightness = 1.0 - (position.z - sliderBoundingBox.min.z) / sliderHeight;
    // remove object border padding
    brightness = THREE.Math.clamp(brightness * 1.29 - 0.12, 0.0, 1.0);
    this.objects.hueWheel.material.uniforms['brightness'].value = brightness;
    this.objects.brightnessCursor.rotation.y = brightness * 1.5 - 1.5;
    this.hsv.v = brightness;
    this.updateColor();
    this.playSound('ui_click0', 'brightness');
  },

  onBrushSizeBackgroundDown: function (position) {
    var slider = this.objects.sizeSlider;
    var sliderBoundingBox = slider.geometry.boundingBox;
    var sliderWidth = sliderBoundingBox.max.x - sliderBoundingBox.min.x;
    slider.updateMatrixWorld();
    slider.worldToLocal(position);
    var brushSize = (position.x - sliderBoundingBox.min.x) / sliderWidth;
    brushSize = brushSize * AFRAME.components.brush.schema.size.max;
    this.handEl.setAttribute('brush', 'size', brushSize);
    this.playSound('ui_click0', 'sizebg');
  },

  handleHover: function () {
    this.updateHoverObjects();
    this.updateMaterials();
  },

  updateHoverObjects: function () {
    var intersectedObjects = this.intersectedObjects;
    intersectedObjects = intersectedObjects.filter(function (obj) {
      return obj.object.name !== 'bb' && obj.object.name !== 'msg_save';
    });
    this.hoveredOffObjects = this.hoveredOnObjects.filter(function (obj) {
      return intersectedObjects.indexOf(obj) === -1;
    });
    this.hoveredOnObjects = intersectedObjects;
  },

  updateMaterials: (function () {
    var point = new THREE.Vector3();
    return function () {
      var self = this;
      var pressedObjects = this.pressedObjects;
      var unpressedObjects = this.unpressedObjects;
      var selectedObjects = this.selectedObjects;
      // Remove hover highlights
      this.hoveredOffObjects.forEach(function (obj) {
        var object = obj.object;
        object.material = self.highlightMaterials[object.name].normal;
      });
      // Add highlight to newly intersected objects
      this.hoveredOnObjects.forEach(function (obj) {
        var object = obj.object;
        point.copy(obj.point);
        if (!self.highlightMaterials[object.name]) {
          self.initHighlightMaterial(object);
        }
        // Update ray
        self.handRayEl.object3D.worldToLocal(point);
        self.handRayEl.setAttribute('line', 'end', point);
        object.material = self.highlightMaterials[object.name].hover;
      });
      // Pressed Material
      Object.keys(pressedObjects).forEach(function (key) {
        var object = pressedObjects[key];
        var materials = self.highlightMaterials[object.name];
        object.material = materials.pressed || object.material;
      });
      // Unpressed Material
      Object.keys(unpressedObjects).forEach(function (key) {
        var object = unpressedObjects[key];
        var materials = self.highlightMaterials[object.name];
        object.material = materials.normal;
        delete unpressedObjects[key];
      });
      // Selected material
      Object.keys(selectedObjects).forEach(function (key) {
        var object = selectedObjects[key];
        var materials = self.highlightMaterials[object.name];
        if (!materials) { return; }
        object.material = materials.selected;
      });
    };
  })(),

  addToggleEvent: function () {
    this.el.addEventListener('toggleMenu', this.toggleMenu);
  },

  removeToggleEvent: function () {
    this.el.removeEventListener('toggleMenu', this.toggleMenu);
  },

  play: function () {
    var el = this.el;
    var handEl = this.handEl;
    if (this.controller) {
      this.addToggleEvent();
    }

    el.addEventListener('model-loaded', this.onModelLoaded);
    el.addEventListener('raycaster-intersection', this.onIntersection);
    el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
    el.addEventListener('raycaster-intersected', this.onIntersected);
    el.addEventListener('raycaster-intersected-cleared', this.onIntersectedCleared);
    if (!handEl) { return; }
    this.addHandListeners();
  },

  pause: function () {
    var el = this.el;
    var handEl = this.handEl;

    if (this.controller) {
      this.removeToggleEvent();
    }

    el.removeEventListener('raycaster-intersection', this.onIntersection);
    el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
    el.removeEventListener('raycaster-intersected', this.onIntersected);
    el.removeEventListener('raycaster-intersected-cleared', this.onIntersectedCleared);
    if (!handEl) { return; }
    this.removeHandListeners();
  },

  onModelLoaded: function (evt) {
    var uiEl = this.uiEl;
    var model = uiEl.getObject3D('mesh');
    model = evt.detail.model;
    if (evt.detail.format !== 'obj' || !model.getObjectByName('brightnesscursor')) { return; }

    this.objects = {};
    this.objects.brightnessCursor = model.getObjectByName('brightnesscursor');
    this.objects.brightnessSlider = model.getObjectByName('brightness');
    this.objects.brightnessSlider.geometry.computeBoundingBox();
    this.objects.previousPage = model.getObjectByName('brushprev');
    this.objects.nextPage = model.getObjectByName('brushnext');

    this.objects.hueCursor = model.getObjectByName('huecursor');
    this.objects.hueWheel = model.getObjectByName('hue');
    this.objects.hueWheel.geometry.computeBoundingSphere();
    this.colorWheelSize = this.objects.hueWheel.geometry.boundingSphere.radius;

    this.objects.sizeCursor = model.getObjectByName('size');
    this.objects.sizeCursor.position.copy(this.cursorOffset);
    this.objects.colorHistory = [];
    for (var i = 0; i < 7; i++) {
      this.objects.colorHistory[i] = model.getObjectByName('colorhistory' + i);
    }
    this.objects.currentColor = model.getObjectByName('currentcolor');
    this.objects.sizeSlider = model.getObjectByName('sizebg');
    this.objects.sizeSlider.geometry.computeBoundingBox();
    // Hide bounding box
    model.getObjectByName('bb').material = new THREE.MeshBasicMaterial(
      { color: 0x248f24, alphaTest: 0, visible: false });
    // Hide objects
    var self = this;

    this.messagesMaterial = new THREE.MeshBasicMaterial({ map: null, transparent: true, opacity: 0.0 });
    this.objects.messageSave = model.getObjectByName('msg_save');
    this.objects.messageSave.material = this.messagesMaterial;
    this.objects.messageSave.visible = false;
    this.objects.messageError = model.getObjectByName('msg_error');
    this.objects.messageError.visible = false;
    this.objects.messageError.material = this.messagesMaterial;

    var messagesImageUrl = 'assets/images/messages.png';

    this.el.sceneEl.systems.material.loadTexture(messagesImageUrl, {src: messagesImageUrl}, function (texture) {
      var material = self.messagesMaterial;
      material.map = texture;
      material.needsUpdate = true;
    });

    this.el.setAttribute('animation__showmessage', { dur: 500, property: 'ui.opacity', from: 0, to: 1, startEvents: 'showmessage' });
    this.el.setAttribute('animation__hidemessage', { dur: 500, delay: 3000, property: 'ui.opacity', from: 1, to: 0, startEvents: 'animationcomplete__showmessage' });
    function showMessage (msgObject) {
      msgObject.visible = true;
      self.el.emit('showmessage');
    }

    this.el.sceneEl.addEventListener('drawing-upload-completed', function (event) {
      showMessage(self.objects.messageSave);
    });
    this.el.sceneEl.addEventListener('drawing-upload-error', function (event) {
      showMessage(self.objects.messageError);
    });

    this.initColorWheel();
    this.initColorHistory();
    this.initBrushesMenu();
    this.setCursorTransparency();
    this.updateColorUI(this.el.getAttribute('brush').color);
    this.updateSizeSlider(this.el.getAttribute('brush').size);
  },

  initBrushesMenu: function () {
    var previousPage = this.objects.previousPage;
    var nextPage = this.objects.nextPage;
    var brushes = Object.keys(AFRAME.BRUSHES);
    this.initHighlightMaterial(nextPage);
    this.initHighlightMaterial(previousPage);
    previousPage.visible = false;
    nextPage.visible = false;
    this.brushesPerPage = 15;
    this.brushesPagesNum = Math.ceil(brushes.length / this.brushesPerPage);
    this.brushesPage = 0;
    this.loadBrushes(this.brushesPage, this.brushesPerPage);
  },

  setCursorTransparency: function () {
    var hueCursor = this.objects.hueCursor;
    var brightnessCursor = this.objects.brightnessCursor;
    var sizeCursor = this.objects.sizeCursor;
    sizeCursor.material.alphaTest = 0.5;
    hueCursor.material.alphaTest = 0.5;
    brightnessCursor.material.alphaTest = 0.5;
    sizeCursor.material.transparent = true;
    hueCursor.material.transparent = true;
    brightnessCursor.material.transparent = true;
  },

  loadBrushes: (function () {
    var brushesMaterials = {};
    return function (page, pageSize) {
      var brush;
      var brushNum = 0;
      var uiEl = this.uiEl.getObject3D('mesh');
      var brushes = Object.keys(AFRAME.BRUSHES);
      var thumbnail;
      var brushIndex;
      var self = this;
      var i;
      if (page < 0 || page >= this.brushesPagesNum) { return; }
      if (page === 0) {
        this.objects.previousPage.visible = false;
      } else {
        this.objects.previousPage.visible = true;
      }
      if (page === this.brushesPagesNum - 1) {
        this.objects.nextPage.visible = false;
      } else {
        this.objects.nextPage.visible = true;
      }
      for (i = 0; i < pageSize; i++) {
        brushIndex = page * pageSize + i;
        brush = brushes[brushIndex];
        thumbnail = brush && AFRAME.BRUSHES[brush].prototype.options.thumbnail;
        loadBrush(brush, brushNum, thumbnail);
        brushNum += 1;
      }
      function loadBrush (name, id, thumbnailUrl) {
        var brushName = !name ? undefined : (name.charAt(0).toUpperCase() + name.slice(1)).toLowerCase();
        if (thumbnailUrl && !brushesMaterials[brushName]) {
          self.el.sceneEl.systems.material.loadTexture(thumbnailUrl, {src: thumbnailUrl}, onLoadThumbnail);
          return;
        }
        onLoadThumbnail();
        function onLoadThumbnail (texture) {
          var button = uiEl.getObjectByName('brush' + id);
          self.brushButtonsMapping['brush' + id] = brushName;
          setBrushThumbnail(texture, button);
        }
      }
      function setBrushThumbnail (texture, button) {
        var brushName = self.brushButtonsMapping[button.name];
        var material = brushesMaterials[brushName] || new THREE.MeshBasicMaterial();
        if (texture) {
          material.map = texture;
          material.alphaTest = 0.5;
          material.transparent = true;
        } else if (!brushesMaterials[brushName]) {
          material.visible = false;
        }
        brushesMaterials[brushName] = material;
        self.highlightMaterials[button.name] = {
          normal: material,
          hover: material,
          pressed: material,
          selected: material
        };
        button.material = material;
      }
    };
  })(),

  nextPage: function () {
    if (this.brushesPage >= this.brushesPagesNum - 1) { return; }
    this.brushesPage++;
    this.loadBrushes(this.brushesPage, this.brushesPerPage);
    this.playSound('ui_click1');
  },

  previousPage: function () {
    if (this.brushesPage === 0) { return; }
    this.brushesPage--;
    this.loadBrushes(this.brushesPage, this.brushesPerPage);
    this.playSound('ui_click1')
  },

  initHighlightMaterial: function (object) {
    var buttonName = object.name;
    var isBrushButton = this.brushRegexp.test(buttonName);
    var isHistory = buttonName.indexOf('history') !== -1;
    var isHue = buttonName === 'hue' || buttonName === 'huecursor';
    var materials = {
      normal: object.material,
      hover: object.material,
      pressed: object.material,
      selected: object.material
    };
    if (!isBrushButton && !isHistory && !isHue) {
      materials.normal = object.material;
      materials.hover = object.material.clone();
      materials.hover.map = this.system.hoverTexture;
      materials.selected = object.material.clone();
      materials.selected.map = this.system.pressedTexture;
      materials.pressed = object.material.clone();
      materials.pressed.map = this.system.pressedTexture;
    }
    this.highlightMaterials[buttonName] = materials;
  },

  toggleMenu: function (evt) {
    if (this.closed) {
      this.system.closeAll();
      this.open();
      this.system.opened = this.el;
    } else {
      this.close();
      this.system.opened = undefined;
    }
  },

  open: function () {
    var uiEl = this.uiEl;
    if (!this.closed) { return; }
    this.uiEl.setAttribute('visible', true);

    this.uiEl.setAttribute('animation', { dur: 100, easing: 'easeOutExpo', property: 'scale', from: { x: 0, y: 0, z: 0 }, to: { x: 1, y: 1, z: 1 } });

    this.el.setAttribute('brush', 'enabled', false);
    this.rayEl.setAttribute('visible', false);
    this.closed = false;

    if (!!this.tooltips) {
      var self = this;
      this.tooltips.forEach(function (tooltip) {
        if (tooltip.getAttribute('visible') && uiEl.parentEl.id !== tooltip.parentEl.id) {
          self.isTooltipPaused = true;
          tooltip.setAttribute('visible', false);
        }
      });
    }
    this.playSound('ui_menu');
  },

  updateIntersections: (function () {
    var raycaster = this.raycaster = new THREE.Raycaster();
    return function (evt) {
      this.updateRaycaster(raycaster);
      this.intersectedObjects = raycaster.intersectObjects(this.menuEls, true);
    };
  })(),

  onIntersection: function (evt) {
    var visible = this.closed && this.system.opened;
    if (this.el.components.brush.active) { return; }
    this.rayEl.setAttribute('visible', !!visible);
    this.el.setAttribute('brush', 'enabled', false);
  },

  onIntersected: function (evt) {
    var handEl = evt.detail.el;
    // Remove listeners of previous hand
    if (this.handEl) { this.removeHandListeners(); }
    this.handEl = handEl;
    this.handRayEl = this.handEl.components.ui.rayEl;
    this.menuEls = this.uiEl.object3D.children;
    this.syncUI();
    this.addHandListeners();
  },

  addHandListeners: function () {
    var handEl = this.handEl;
    handEl.addEventListener('componentchanged', this.onComponentChanged);
    handEl.addEventListener('stroke-started', this.onStrokeStarted);
    handEl.addEventListener('triggerchanged', this.onTriggerChanged);
  },

  removeHandListeners: function () {
    var handEl = this.handEl;
    handEl.removeEventListener('componentchanged', this.onComponentChanged);
    handEl.removeEventListener('stroke-started', this.onStrokeStarted);
    handEl.removeEventListener('triggerchanged', this.onTriggerChanged);
  },

  onComponentChanged: function (evt) {
    if (evt.detail.name === 'brush') { this.syncUI(); }
  },

  syncUI: function () {
    var brush;
    if (!this.handEl || !this.objects) { return; }
    brush = this.handEl.getAttribute('brush');
    this.updateSizeSlider(brush.size);
    this.updateColorUI(brush.color);
    this.updateColorHistory();
    // this.updateBrushSelector(brush.brush);
  },

  initColorHistory: function () {
    var colorHistoryObject;
    var currentColor = this.objects.currentColor;
    for (var i = 0; i < this.objects.colorHistory.length; i++) {
      colorHistoryObject = this.objects.colorHistory[i];
      colorHistoryObject.material = colorHistoryObject.material.clone();
      colorHistoryObject.material.map = this.system.selectedTexture;
    }
    currentColor.material = currentColor.material.clone();
    currentColor.material.map = this.system.selectedTexture;
    this.updateColorHistory();
  },

  updateColorHistory: function () {
    var color = this.handEl && this.handEl.getAttribute('brush').color;
    var colorStack = this.colorStack;
    if (!color) { color = this.el.components.brush.schema.color.default; }
    this.objects.currentColor.material.color.set(color);
    for (var i = 0; i < colorStack.length; i++) {
      color = colorStack[colorStack.length - i - 1];
      this.objects.colorHistory[i].material.color.set(color);
    }
  },

  updateSizeSlider: function (size) {
    var slider = this.objects.sizeSlider;
    var sliderBoundingBox = slider.geometry.boundingBox;
    var cursor = this.objects.sizeCursor;
    var sliderWidth = sliderBoundingBox.max.x - sliderBoundingBox.min.x;
    var normalizedSize = size / AFRAME.components.brush.schema.size.max;
    var positionX = normalizedSize * sliderWidth;
    cursor.position.setX(positionX - this.cursorOffset.x);

    var scale = normalizedSize + 0.3;
    cursor.scale.set(scale, 1, scale);
  },

  updateColorUI: function (color) {
    var colorRGB = new THREE.Color(color);
    var hsv = this.hsv = this.rgb2hsv(colorRGB.r, colorRGB.g, colorRGB.b);
    // Update color wheel
    var angle = hsv.h * 2 * Math.PI;
    var radius = hsv.s * this.colorWheelSize;
    var x = radius * Math.cos(angle);
    var y = radius * Math.sin(angle);
    this.objects.hueCursor.position.setX(x);
    this.objects.hueCursor.position.setZ(-y);

    // Update color brightness
    this.objects.hueWheel.material.uniforms['brightness'].value = this.hsv.v;
    this.objects.brightnessCursor.rotation.y = this.hsv.v * 1.5 - 1.5;
  },

  updateBrushSelector: function (brush) {
    var self = this;
    var buttons = Object.keys(this.brushButtonsMapping);
    var brushButtonsMapping = this.brushButtonsMapping;
    buttons.forEach(function (id) {
      if (brushButtonsMapping[id] !== brush) { return; }
      self.selectBrushButton(id);
    });
  },

  onIntersectionCleared: function () {
    this.checkMenuIntersections = false;
    this.rayEl.setAttribute('visible', false);
    this.el.setAttribute('brush', 'enabled', true);
  },

  onIntersectedCleared: function (evt) {
    if (!this.handEl) { return; }
    this.handEl.removeEventListener('triggerchanged', this.onTriggerChanged);
  },

  onStrokeStarted: function () {
    var color;
    var colorStack = this.colorStack;
    if (!this.colorHasChanged) { return; }
    color = this.handEl.getAttribute('brush').color;
    this.colorHasChanged = false;
    if (colorStack.length === 7) { colorStack.shift(); }
    colorStack.push(color);
    this.syncUI();
  },

  updateRaycaster: (function () {
    var direction = new THREE.Vector3();
    var directionHelper = new THREE.Quaternion();
    var scaleDummy = new THREE.Vector3();
    var originVec3 = new THREE.Vector3();

    // Closure to make quaternion/vector3 objects private.
    return function (raycaster) {
      var object3D = this.handEl.object3D;

      // Update matrix world.
      object3D.updateMatrixWorld();
      // Grab the position and rotation.
      object3D.matrixWorld.decompose(originVec3, directionHelper, scaleDummy);
      // Apply rotation to a 0, 0, -1 vector.
      direction.set(0, 0, -1);
      direction.applyAxisAngle(new THREE.Vector3(1, 0, 0), -(this.rayAngle / 360) * 2 * Math.PI);
      direction.applyQuaternion(directionHelper);
      raycaster.far = this.rayDistance;
      raycaster.set(originVec3, direction);
    };
  })(),

  close: function () {
    if (this.closed) { return; }

    this.uiEl.setAttribute('animation', { dur: 100, easing: 'easeOutExpo', property: 'scale', from: { x: 1, y: 1, z: 1 }, to: { x: 0, y: 0, z: 0 } });
    this.el.setAttribute('brush', 'enabled', true);
    this.closed = true;

    if (!!this.tooltips && this.isTooltipPaused) {
      this.isTooltipPaused = false;
      this.tooltips.forEach(function (tooltip) {
        tooltip.setAttribute('visible', true);
      });
    }
    this.playSound('ui_menu');
  },

  playSound: function (sound, objName) {
    if (objName === undefined || !this.pressedObjects[objName]) {
      document.getElementById(sound).play();
    }
  }
});


text:
package org.slc.sli.ingestion.transformation.normalization.did;

/**
 *
 * @author npandey
 *
 */

public class DidNaturalKey {

    String naturalKeyName;
    boolean isOptional;

    public String getNaturalKeyName() {
        return naturalKeyName;
    }

    public void setNaturalKeyName(String naturalKeyName) {
        this.naturalKeyName = naturalKeyName;
    }

    public boolean isOptional() {
        return isOptional;
    }

    public void setOptional(boolean isOptional) {
        this.isOptional = isOptional;
    }
}


text:
package org.dominokit.domino.gwt.client.slots;

import elemental2.dom.CustomEvent;
import elemental2.dom.Event;
import elemental2.dom.EventListener;
import elemental2.dom.HTMLElement;
import jsinterop.base.Js;
import org.dominokit.domino.api.client.mvp.slots.IsSlot;

public abstract class ElementSlot implements IsSlot<HTMLElement>, EventListener {

  @Override
  public void handleEvent(Event evt) {
    CustomEvent slotEvent = Js.uncheckedCast(evt);
    HTMLElement view = Js.uncheckedCast(slotEvent.detail);
    updateContent(view);
  }
}