text:
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import numpy as np
np.set_printoptions(threshold=np.nan)
import tensorflow as tf
import time
from PIL import Image as im

def convolve_inner_layers(x, W, b):
    x = tf.nn.conv2d(x, W, strides = [1,1,1,1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    return tf.nn.tanh(x)

def convolve_ouput_layer(x, W, b):
    x = tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    return x

def conv_net(x, W, b):
    conv1 = convolve_inner_layers(x, W['weights1'], b['bias1'])
    conv2 = convolve_inner_layers(conv1, W['weights2'], b['bias2'])
    conv3 = convolve_inner_layers(conv2, W['weights3'], b['bias3'])
    conv4 = convolve_inner_layers(conv3, W['weights4'], b['bias4'])
    output = convolve_ouput_layer(conv4, W['weights_out'], b['bias_out'])
    return output

def get_batch(x, y, n):
    batch_indices = np.arange(x.shape[0])
    np.random.shuffle(batch_indices)
    x_batch = []
    y_batch = []
    for i in batch_indices[:n]:
        x_batch.append(x[i])
        y_batch.append(y[i])
    return [x_batch, y_batch]

def main():
    print("--------------------------------------------------")
    print("initializing variables ...")
    weights = {
        'weights1': tf.get_variable('weights1', shape=[11,11,2,30], initializer=tf.contrib.layers.variance_scaling_initializer(factor=1,mode='FAN_IN')),
        'weights2': tf.get_variable('weights2', shape=[11,11,30,15], initializer=tf.contrib.layers.variance_scaling_initializer(factor=1,mode='FAN_IN')),
        'weights3': tf.get_variable('weights3', shape=[11,11,15,7], initializer=tf.contrib.layers.variance_scaling_initializer(factor=1,mode='FAN_IN')),
        'weights4': tf.get_variable('weights4', shape=[11,11,7,3], initializer=tf.contrib.layers.variance_scaling_initializer(factor=1,mode='FAN_IN')),
        'weights_out': tf.get_variable('weights_out', shape=[11,11,3,1], initializer=tf.contrib.layers.variance_scaling_initializer(factor=1,mode='FAN_IN'))
    }
    biases = {
        'bias1': tf.get_variable('bias1', shape=[30], initializer=tf.contrib.layers.variance_scaling_initializer(factor=1,mode='FAN_IN')),
        'bias2': tf.get_variable('bias2', shape=[15], initializer=tf.contrib.layers.variance_scaling_initializer(factor=1,mode='FAN_IN')),
        'bias3': tf.get_variable('bias3', shape=[7], initializer=tf.contrib.layers.variance_scaling_initializer(factor=1,mode='FAN_IN')),
        'bias4': tf.get_variable('bias4', shape=[3], initializer=tf.contrib.layers.variance_scaling_initializer(factor=1,mode='FAN_IN')),
        'bias_out': tf.get_variable('bias_out', shape=[1], initializer=tf.contrib.layers.variance_scaling_initializer(factor=1,mode='FAN_IN'))
    }

    # tf Graph input
    x = tf.placeholder(tf.float32, [None, 96, 96, 2])
    y = tf.placeholder(tf.float32, [None, 96, 96, 1])

    # data
    print("loading data ...")
    original_images_train = np.loadtxt('../../../data/sample_data/orig_50.txt')
    reconstructed_images_train = np.loadtxt('../../../data/sample_data/recon_50.txt')
    comparison_images_train = np.loadtxt('../../../data/sample_data/comp_50.txt')
    original_images_test = np.loadtxt('../../../data/sample_data/orig_15.txt')
    reconstructed_images_test = np.loadtxt('../../../data/sample_data/recon_15.txt')
    comparison_images_test = np.loadtxt('../../../data/sample_data/comp_15.txt')

    # get size of training and testing set
    train_size = original_images_train.shape[0]
    test_size = original_images_test.shape[0]

    # reshaping the result data to --- (num pics), 96, 96, 1
    comparison_images_train = np.reshape(comparison_images_train, [train_size, 96, 96, 1])
    comparison_images_test = np.reshape(comparison_images_test, [test_size, 96, 96, 1])

    # zipping data
    input_combined_train = []
    for i in range(train_size):
        for j in range(96*96):
            input_combined_train.append([original_images_train[i][j], reconstructed_images_train[i][j]])
    input_combined_train = np.asarray(input_combined_train, dtype=np.float32)
    input_combined_train = np.reshape(input_combined_train, [train_size, 96,96, 2])
    input_combined_test = []
    for i in range(test_size):
        for j in range(96*96):
            input_combined_test.append([original_images_test[i][j], reconstructed_images_test[i][j]])
    input_combined_test = np.asarray(input_combined_test, dtype=np.float32)
    input_combined_test = np.reshape(input_combined_test, [test_size, 96,96, 2])
    test = input_combined_train[0]
    image1 = np.asarray(test[0], dtype='uint8')
    image2 = np.asarray(test[1], dtype='uint8')
    image3 = np.asarray(np.reshape(comparison_images_train[0],[96,96]), dtype='uint8')
    image_view = im.fromarray(image1, 'L')
    image_view.show()
    image_view = im.fromarray(image2, 'L')
    image_view.show()
    image_view = im.fromarray(image3, 'L')
    image_view.show()

    # paramaters
    learning_rate = .0001
    training_iterations = 10000

    # model
    prediction = conv_net(x, weights, biases)

    # saving state
    saver = tf.train.Saver()

    # loss and optimization
    cost = tf.reduce_mean(tf.square(tf.subtract(prediction, y)))
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

    # evaluation
    error = tf.reduce_mean(tf.square(tf.subtract(prediction, y)))

    init = tf.global_variables_initializer()
    with open('../../../data/results/loss_lr{}_trn{}_tst{}.csv'.format(learning_rate, train_size, test_size), mode='w') as write_file:
        with tf.Session() as sess:
            sess.run(init)
            step = 0
            start_time = time.time()
            print("starting training ... ")
            write_file.write('step, error\n')
            while step < training_iterations:
                x_data_train, y_data_train = [input_combined_train[0]], [comparison_images_train[0]]
                sess.run(optimizer, feed_dict={x : x_data_train, y : y_data_train})
                loss = sess.run(error, feed_dict={x : x_data_train, y : y_data_train})
                print("training step {}. current error: {}. ".format(step, loss))
                write_file.write(str(step)+', '+str(loss)+'\n')
                step += 1
            print("optimization finished!")
            print("--------------------------------------------------")
            print("testing accuracy")
            x_data_test, y_data_test = [input_combined_test[0]], [comparison_images_test[0]]
            final_error = sess.run(error, feed_dict={x: x_data_test, y: y_data_test})
            print("the average pixel difference on the test set is {}.".format(final_error))
            print("--------------------------------------------------")
            print('training took {} seconds'.format(time.time()- start_time))
    write_file.close()

if __name__ == '__main__':
    main()


text:
<fieldset class="b_clearfix">
	<legend>$r.translate("condition.editable.title")</legend>
	$r.contextHelpWithWrapper("org.olat.presentation.course.editor","ced-cal-acc-rw.html","help.hover.cal.acc.rw")
	$r.render("editCondition")
</fieldset>
<fieldset class="b_clearfix">
	<legend>$r.translate("condition.accessibility.title")</legend>
	$r.contextHelpWithWrapper("org.olat.presentation.course.editor","ced-acc.html","help.hover.cal.acc")
	$r.render("readerCondition")
</fieldset>

redpajama_set_name: RedPajamaGithub


text:
package rpc

import (
	"io"
	"os"

	boshlog "github.com/cloudfoundry/bosh-utils/logger"

	"github.com/cloudfoundry/bosh-cpi-go/apiv1"
)

type Factory struct {
	logger boshlog.Logger
}

func NewFactory(logger boshlog.Logger) Factory {
	return Factory{logger}
}

func (f Factory) NewCLI(cpiFactory apiv1.CPIFactory) CLI {
	return f.NewCLIWithInOut(os.Stdin, os.Stdout, cpiFactory)
}

func (f Factory) NewCLIWithInOut(in io.Reader, out io.Writer, cpiFactory apiv1.CPIFactory) CLI {
	actionFactory := apiv1.NewActionFactory(cpiFactory)
	caller := NewJSONCaller()
	disp := NewJSONDispatcher(actionFactory, caller, f.logger)
	return NewCLI(in, out, disp, f.logger)
}


text:
/*

---------------------------------------------------------------------------------

                                               oooo
                                               `888
                oooo d8b  .ooooo.  oooo    ooo  888  oooo  oooo
                `888""8P d88' `88b  `88b..8P'   888  `888  `888
                 888     888   888    Y888'     888   888   888
                 888     888   888  .o8"'88b    888   888   888
                d888b    `Y8bod8P' o88'   888o o888o  `V88V"V8P'

                                                  www.roxlu.com
                                             www.apollomedia.nl
                                          www.twitter.com/roxlu

---------------------------------------------------------------------------------

   # AudioEncoderMP3

   Encodes raw audio data using liblamemp3. We can either ingest
   interleaved float or interleaved signed shorts.

   ````c++
   AudioEncoderMP3 ae;

   my_settings.samplerate = AV_AUDIO_SAMPLERATE_44100;
   my_settings.mode = AV_AUDIO_MODE_STEREO;
   my_settings.bitsize = AV_AUDIO_BITSIZE_S16;
   my_settings.bitrate = 96; // 96 kbps
   my_settings.quality = 6;
   my_settings.in_bitsize = AV_AUDIO_BITSIZE_F32;
   my_settings.in_interleaved = true.

   ae.setup(my_settings);
   ae.initialize();

   for(int i = 0; i < 50; ++i) {
      ...
      ae.encodePacket(some_packet, tag);
      ...
   }
   ````

 */

#ifndef ROXLU_AUDIO_ENCODER_MP3_H
#define ROXLU_AUDIO_ENCODER_MP3_H

#include <stdint.h>

extern "C" {
#  include <lame/lame.h>
#  include <uv.h>
}

#include <fstream>
#include <streamer/flv/FLVTypes.h>
#include <streamer/core/EncoderTypes.h>
#include <streamer/core/AudioEncoder.h>

#define AUDIO_ENCODER_BUFFER_SIZE 168384

class AudioEncoderMP3 : public AudioEncoder {
 public:
  AudioEncoderMP3();
  ~AudioEncoderMP3();
  bool setup(AudioSettings settings);
  bool initialize();
  bool encodePacket(AVPacket* p, FLVTag& result);
  bool shutdown();
 private:
  int nchannels;
  AudioSettings settings;
  int samplerate;
  MPEG_mode mode;
  lame_global_flags* lame_flags;
  uint8_t mp3_buffer[AUDIO_ENCODER_BUFFER_SIZE];

  /* used to monitor bitrate */
  uint64_t bitrate_time_started; /* when we started with encoding, in nanosec. we've put this in setup() because we don't want to add a check in encodePacket(), this result in a bit less accurate value for the first run. */
  uint64_t bitrate_timeout;  /* when we should calculate the current bitrate again */
  uint64_t bitrate_delay; /* the time between bitrate measurements, in nanosec */
  double bitrate_in_kbps; /* the current bitrate we measured last delay */
  double bitrate_nbytes; /* the total amount of transferred bytes */

};

#endif


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../libc/constant.GENL_NAMSIZ.html">

Redirecting to ../../../../libc/constant.GENL_NAMSIZ.html...


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.ui.modelutil;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import android.view.View;

import androidx.annotation.Nullable;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLooper;

import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.ui.modelutil.PropertyModel.WritableBooleanPropertyKey;
import org.chromium.ui.modelutil.PropertyModel.WritableIntPropertyKey;
import org.chromium.ui.modelutil.PropertyModel.WritableObjectPropertyKey;
import org.chromium.ui.modelutil.PropertyModelChangeProcessor.ViewBinder;
import org.chromium.ui.test.util.modelutil.FakeViewProvider;

/**
 * Unit tests for LazyConstructionPropertyMcp.
 */
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class LazyConstructionPropertyMcpTest {
    private static final WritableBooleanPropertyKey VISIBILITY = new WritableBooleanPropertyKey();
    private static final WritableObjectPropertyKey<String> STRING_PROPERTY =
            new WritableObjectPropertyKey<>();
    private static final WritableIntPropertyKey INT_PROPERTY = new WritableIntPropertyKey();
    private static final PropertyKey[] ALL_PROPERTIES =
            new PropertyKey[] {VISIBILITY, STRING_PROPERTY, INT_PROPERTY};
    private PropertyModel mModel;
    private FakeViewProvider<View> mViewProvider;
    private @Nullable PropertyObservable.PropertyObserver<PropertyKey> mModelObserver;

    @Mock
    private View mView;
    @Mock
    private ViewBinder<PropertyModel, View, PropertyKey> mViewBinder;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        mModel = new PropertyModel(ALL_PROPERTIES);
        mModel.set(VISIBILITY, false);
        mViewProvider = new FakeViewProvider<>();
        mModel.addObserver((source, propertyKey) -> {
            // Forward model changes to the model observer if it exists. It's important for the test
            // that the observer is notified before the LazyConstructionPropertyMcp.
            if (mModelObserver != null) mModelObserver.onPropertyChanged(source, propertyKey);
        });
    }

    @Test
    public void testInitialConstruction() {
        LazyConstructionPropertyMcp.create(mModel, VISIBILITY, mViewProvider, mViewBinder);
        assertFalse(mViewProvider.inflationHasStarted());

        mModel.set(VISIBILITY, true);

        assertTrue(mViewProvider.inflationHasStarted());
        mViewProvider.finishInflation(mView);
        ShadowLooper.idleMainLooper();

        verifyBind(VISIBILITY);
    }

    @Test
    public void testUpdatesBeforeInflation() {
        LazyConstructionPropertyMcp.create(mModel, VISIBILITY, mViewProvider, mViewBinder);
        mModel.set(STRING_PROPERTY, "foo");
        mModel.set(VISIBILITY, true);
        assertTrue(mViewProvider.inflationHasStarted());
        mViewProvider.finishInflation(mView);
        ShadowLooper.idleMainLooper();
        verifyBind(STRING_PROPERTY, VISIBILITY);
    }

    @Test
    public void testUpdatesWhileVisible() {
        LazyConstructionPropertyMcp.create(mModel, VISIBILITY, mViewProvider, mViewBinder);

        // Show the view and pump the looper to do the initial bind.
        mModel.set(VISIBILITY, true);
        assertTrue(mViewProvider.inflationHasStarted());
        mViewProvider.finishInflation(mView);
        ShadowLooper.idleMainLooper();
        verifyBind(VISIBILITY);
        Mockito.<ViewBinder>reset(mViewBinder);

        mModel.set(INT_PROPERTY, 42);
        verifyBind(INT_PROPERTY);

        mModel.set(VISIBILITY, false);
        verifyBind(VISIBILITY);
    }

    @Test
    public void testUpdatesWhileHidden() {
        LazyConstructionPropertyMcp.create(mModel, VISIBILITY, mViewProvider, mViewBinder);

        // Show the view and pump the looper to do the initial bind, then hide the view again.
        mModel.set(VISIBILITY, true);
        assertTrue(mViewProvider.inflationHasStarted());
        mViewProvider.finishInflation(mView);
        ShadowLooper.idleMainLooper();
        verifyBind(VISIBILITY);

        mModel.set(VISIBILITY, false);
        verify(mViewBinder, times(2)).bind(eq(mModel), eq(mView), eq(VISIBILITY));
        Mockito.<ViewBinder>reset(mViewBinder);

        // While the view is hidden, the binder should not be invoked.
        mModel.set(STRING_PROPERTY, "foo");
        mModel.set(STRING_PROPERTY, "bar");
        verify(mViewBinder, never())
                .bind(any(PropertyModel.class), any(View.class), any(PropertyKey.class));

        // When the view is shown, all pending updates should be dispatched, coalescing updates to
        // the same property.
        mModel.set(VISIBILITY, true);
        verifyBind(VISIBILITY, STRING_PROPERTY);
    }

    @Test
    public void testReentrantUpdates() {
        mModel.set(INT_PROPERTY, 0);
        LazyConstructionPropertyMcp.create(mModel, VISIBILITY, mViewProvider, mViewBinder);

        // Increase INT_PROPERTY any time visibility changes.
        mModelObserver = (source, propertyKey) -> {
            if (propertyKey != VISIBILITY) return;
            mModel.set(INT_PROPERTY, mModel.get(INT_PROPERTY) + 1);
        };

        mModel.set(VISIBILITY, true);
        mViewProvider.finishInflation(mView);
        ShadowLooper.idleMainLooper();
        verifyBind(VISIBILITY, INT_PROPERTY);
        assertThat(mModel.get(INT_PROPERTY), is(1));
        Mockito.<ViewBinder>reset(mViewBinder);

        mModel.set(VISIBILITY, false);
        verifyBind(INT_PROPERTY, VISIBILITY);
        assertThat(mModel.get(INT_PROPERTY), is(2));
    }

    private void verifyBind(PropertyKey... properties) {
        for (PropertyKey key : properties) {
            verify(mViewBinder).bind(mModel, mView, key);
        }
    }
}


text:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'ldapcfg.php';
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="favicon.ico">

    <title>Richtlinien für Propaganda des FSR</title>

    <link href="vendor/bootstrap-3.3.5-dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/style.css" rel="stylesheet">

    <link rel="stylesheet" href="vendor/font-awesome-4.7.0/css/font-awesome.min.css">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
        Propagandasystem
des iFSR

            <?php
            echo '
Antrag
';
            echo '
Meine Anträge
';
            if (in_array($username, $memberarray)) {
                echo '
Register

Infoscreen

Archiv

Richtlinien
';
            }
            echo '

Logout
';
            ?>

Richtlinien für Propaganda des FSR

Statusfarben im Register:

          grün : erledigte Propaganda-Anträge

          gelb : unfertige Propaganda-Anträge

          rot : neue, unangefasste Propaganda-Anträge

Zurückweisungen:

          Das Zurückweisen von Propaganda auf einzelnen Kanälen kann über das System erfolgen. Der Antragsteller sollte darüber in Kentnis gesetzt werden (bestenfalls mit einer Begründung). Dies erfolgt nicht automatisch!

Propagandakanäle:

          Mittels Tooltip kann bei den Checkboxen der Zeitpunkt der letzten Änderung angezeigt werden.

Archivieren vs. Löschen:

          Jeder Propaganda-Antrag sollte im Normalfall archiviert werden, sobald das Ende der Kampagne erreicht ist oder alle Punkte abgeschlossen sind. Gelöscht werden sollten Einträge nur bei Duplikaten, Fehlern oder auf Wunsch des Antragstellers.


text:
require 'spec_helper'

RSpec.describe '#throws?' do
  it { expect(throws?(StandardError) { fail }).to be true }
  it { expect(throws?(NameError) { fail NameError }).to be true }
  it { expect(throws?(NoMethodError) { fail NameError }).to be false }
  it { expect(throws?(StandardError) { nil }).to be false }
end


text:
<?php namespace DMA\Friends\Commands;

use Log;
use RainLab\User\Models\User;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Helper\ProgressBar;
use DMA\Friends\Facades\MailChimpIntegration;
use Illuminate\Console\Command;

/**
 * Synchronize Friends users to a MailChip list
 *
 * @package DMA\Friends\Commands
 * @author Kristen Arnold, Carlos Arroyo
 */
class SyncFriendsToMailChimp extends Command
{
    /**
     * @var string The console command name.
     */
    protected $name = 'friends:sync-friends-mailchimp';

    /**
     * @var string The console command description.
     */
    protected $description = 'Syncronize Friends users data into MailChimp';

    /**
     * @return void
     */
    public function fire()
    {
          $this->synchronizeUser();
    }

    protected function synchronizeUser()
    {
        $alwaysUpdate = $this->option('force-update');

        $this->progressbar = $this->getHelperSet()->get('progress');
        $this->progressbar->start($this->output, User::count());

        User::chunk(500, function($users) use ($alwaysUpdate) {
            foreach($users as $user) {
                $this->progressbar->advance();

                $email = $user->email;

                MailChimpIntegration::syncMemberToMailChimp($email, $user, false);
            }
        });

       $$this->progressbar->finish();
    }

    /**
     * Get the console command options.
     * @return array
     */
    protected function getOptions()
    {
        return [
                ['force-update', 'u', InputOption::VALUE_NONE, 'Always update member in the list with Friends member data', null],
        ];
    }

}


text:
package org.magicdgs.readtools.utils.read.transformer.trimming;

import org.magicdgs.readtools.RTHelpConstants;
import org.magicdgs.readtools.utils.trimming.TrimmingUtil;

import org.broadinstitute.barclay.help.DocumentedFeature;
import org.broadinstitute.hellbender.utils.read.GATKRead;

/**
 * Trims trailing Ns (unknown bases) in the read sequence, in one or both sides.
 *
 * @author Daniel Gomez-Sanchez (magicDGS)
 * @ReadTools.warning If a previous trimmer left the read starting/ending with Ns, the read will not
 * be trimmed by the TrailingNtrimmer.
 */
@DocumentedFeature(groupName = RTHelpConstants.DOC_CAT_TRIMMERS, groupSummary = RTHelpConstants.DOC_CAT_TRIMMERS_SUMMARY, summary = "Trims the end of the read containing unknown bases.")
public final class TrailingNtrimmer extends TrimmingFunction {
    private static final long serialVersionUID = 1L;

    /**
     * {@inheritDoc}
     *
     * @see TrimmingUtil#trimPointsTrailingNs(byte[])
     */
    @Override
    protected void fillTrimPoints(final GATKRead read, final int[] toFill) {
        // this should be safe, because the bases are not modified in the method
        final int[] points = TrimmingUtil.trimPointsTrailingNs(read.getBasesNoCopy());
        toFill[0] = points[0];
        toFill[1] = points[1];
    }
}


text:
package iso20022

// Set of elements used to provide information on the charges related to the payment transaction.
type ChargesInformation5 struct {

	// Transaction charges to be paid by the charge bearer.
	Amount *ActiveOrHistoricCurrencyAndAmount `xml:"Amt"`

	// Party that takes the transaction charges or to which the transaction charges are due.
	Party *BranchAndFinancialInstitutionIdentification4 `xml:"Pty"`
}

func (c *ChargesInformation5) SetAmount(value, currency string) {
	c.Amount = NewActiveOrHistoricCurrencyAndAmount(value, currency)
}

func (c *ChargesInformation5) AddParty() *BranchAndFinancialInstitutionIdentification4 {
	c.Party = new(BranchAndFinancialInstitutionIdentification4)
	return c.Party
}


text:
"use strict";

var eth_sign = require("../wrappers/eth").sign;

/**
 * Check to see if the provided account is unlocked for the connected node.
 */
function isUnlocked(account, callback) {
  return function (dispatch) {
    dispatch(eth_sign([account, "0x00000000000000000000000000000000000000000000000000000000000f69b5"], function (err) {
      if (err) {
        console.warn("eth_sign failed during ethrpc.isUnlocked:", err);
        return callback(null, false);
      }
      callback(null, true);
    }));
  };
}

module.exports = isUnlocked;


text:
package controllers;

import java.util.List;

import models.BusinessPartner;
import models.BusinessYear;
import models.Company;
import models.Permission;
import models.User;
import play.Logger;
import play.mvc.Controller;

public class BusinessPartners extends Controller {

	public static void show(String mode) {
		if(!Application.authorize("viewBusinessPartners")){
			render("errors/401.html");
		}
		List<BusinessPartner> partners = BusinessPartner.findAll();
		List<Company> companies = Company.findAll();
		if (mode == null || mode.equals(""))
			mode = "edit";
		render(partners, companies, mode);
	}

	public static void create(BusinessPartner businesspartner) {
		checkAuthenticity();
		if(!Application.authorize("createBusinessPartner")){
			render("errors/401.html");
		}
		validation.required("name", businesspartner.name);
		validation.required("kind", businesspartner.kind);
		validation.required("account", businesspartner.account);

		if (validation.hasErrors()) {
			params.flash();
			validation.keep();
		} else {
			BusinessPartner bp = businesspartner.save();
			Application.logToFile("2_1", bp.id, " - account : "+businesspartner.account);
		}

		show("add");
	}

	public static void edit(BusinessPartner businesspartner) {
		checkAuthenticity();
		if(!Application.authorize("editBusinessPartner")){
			render("errors/401.html");
		}
		validation.required("name", businesspartner.name);
		validation.required("kind", businesspartner.kind);
		validation.required("account", businesspartner.account);

		if (validation.hasErrors()) {
			params.flash();
			validation.keep();
		} else {
			Application.logToFile("2_2", businesspartner.id, " - account : "+businesspartner.account);
			businesspartner.save();
		}

		show("edit");
	}

	public static void filter(BusinessPartner businesspartner) {
		checkAuthenticity();
		List<BusinessPartner> partners = BusinessPartner.find("name = ? or address = ? or kind = ? or "
															+ "mobile = ? or email = ? or account = ?",
															businesspartner.name,
															businesspartner.address,
															businesspartner.kind,
															businesspartner.mobile,
															businesspartner.email,
															businesspartner.account).fetch();
		renderTemplate("BusinessPartners/show.html", "edit", partners);
	}

	public static void delete(Long id) {
		if(!Application.authorize("deleteBusinessPartner")){
			render("errors/401.html");
		}
		if (id != null) {
			BusinessPartner partners = BusinessPartner.findById(id);
			partners.delete();
			Application.logToFile("2_3", id, "");
		}
		show("edit");
	}
}


text:
package net.violet.mynabaztag.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.violet.mynabaztag.form.MySrvTwitterForm;
import net.violet.platform.applications.GmailTwitterHandler;
import net.violet.platform.applications.SubscriptionManager;
import net.violet.platform.datamodel.Application;
import net.violet.platform.datamodel.Lang;
import net.violet.platform.datamodel.User;
import net.violet.platform.datamodel.VObject;
import net.violet.platform.datamodel.factories.Factories;
import net.violet.platform.dataobjects.SubscriptionData;
import net.violet.platform.dataobjects.TtsLangData;
import net.violet.platform.dataobjects.VObjectData;
import net.violet.platform.struts.DispatchActionForLoggedUserWithObject;
import net.violet.platform.util.DicoTools;
import net.violet.platform.util.SessionTools;
import net.violet.platform.util.StringShop;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class MySrvTwitterAction extends DispatchActionForLoggedUserWithObject {

	private static final Logger LOGGER = Logger.getLogger(MySrvTwitterAction.class);

	// Affichage de la page
	public ActionForward load(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) {
		final HttpSession session = request.getSession(true);
		final User user = SessionTools.getUserFromSession(request);
		final VObject object = SessionTools.getRabbitFromSession(session);
		final Lang lang = SessionTools.getLangFromSession(session, request);
		final MySrvTwitterForm myForm = (MySrvTwitterForm) form;

		myForm.setLangList(TtsLangData.findAll(user));

		final List<SubscriptionData> theSubscriptions = SubscriptionData.findByApplicationAndObject(Application.NativeApplication.TWITTER.getApplication(), object);

		if (!theSubscriptions.isEmpty()) {
			final SubscriptionData theSubscription = theSubscriptions.get(0);
			final Map<String, Object> theSettings = theSubscription.getSettings();
			myForm.setLogin(theSettings.get(GmailTwitterHandler.LOGIN).toString());
			myForm.setPassword(StringShop.EMPTY_STRING);
			final Lang theLang = Factories.LANG.findByIsoCode(theSettings.get(GmailTwitterHandler.LANGUAGE).toString());
			myForm.setTwitterLang(theLang.getId().intValue());
		} else {
			myForm.setLogin(StringShop.EMPTY_STRING);
			myForm.setPassword(StringShop.EMPTY_STRING);
			myForm.setTwitterLang(lang.getId().intValue());
		}

		return mapping.getInputForward();
	}

	// Activate the service for a user
	public ActionForward activate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		final HttpSession session = request.getSession(true);
		final VObject object = SessionTools.getRabbitFromSession(session);
		final Lang lang = SessionTools.getLangFromSession(session, request);
		final MySrvTwitterForm myForm = (MySrvTwitterForm) form;
		final ActionMessages errors = new ActionMessages();

		final String login = myForm.getLogin();
		final String password = myForm.getPassword();

		try {
			GmailTwitterHandler.createOrUpdateSubscription(null, VObjectData.getData(object), login, password, Factories.LANG.find(myForm.getTwitterLang()), false);
		} catch (final Exception e) {
			MySrvTwitterAction.LOGGER.fatal(e, e);
			errors.add("scenarioNotCreated", new ActionMessage("errors.addTwitter", DicoTools.dico(lang, "srv_podcast/scenario_not_created")));
			saveErrors(request, errors);
			return load(mapping, form, request, response);
		}

		errors.add("registerSucceed", new ActionMessage("errors.addTwitter", DicoTools.dico(lang, "srv_podcast/subscription_succeed")));
		saveErrors(request, errors);
		return load(mapping, form, request, response);
	}

	// Update a registred user
	public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		final HttpSession session = request.getSession(true);
		final VObject object = SessionTools.getRabbitFromSession(session);
		final Lang lang = SessionTools.getLangFromSession(session, request);
		final MySrvTwitterForm myForm = (MySrvTwitterForm) form;
		final ActionMessages errors = new ActionMessages();

		final String login = myForm.getLogin();
		final String password = myForm.getPassword();

		final List<SubscriptionData> theSubscriptions = SubscriptionData.findByApplicationAndObject(Application.NativeApplication.TWITTER.getApplication(), object);

		if (!theSubscriptions.isEmpty()) {
			try {
				GmailTwitterHandler.createOrUpdateSubscription(theSubscriptions.get(0), VObjectData.getData(object), login, password, Factories.LANG.find(myForm.getTwitterLang()), false);
			} catch (final Exception e) {
				MySrvTwitterAction.LOGGER.fatal(e, e);
				errors.add("scenarioNotCreated", new ActionMessage("errors.addTwitter", DicoTools.dico(lang, "srv_podcast/scenario_not_created")));
				saveErrors(request, errors);
				return load(mapping, form, request, response);
			}
		}

		return load(mapping, form, request, response);
	}

	// Unregistred a user
	public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		final HttpSession session = request.getSession(true);
		final VObject object = SessionTools.getRabbitFromSession(session);
		final Lang lang = SessionTools.getLangFromSession(session, request);

		final ActionMessages errors = new ActionMessages();

		for (final SubscriptionData aSubscription : SubscriptionData.findByApplicationAndObject(Application.NativeApplication.TWITTER.getApplication(), object)) {
			try {
				SubscriptionManager.deleteSubscription(aSubscription);
			} catch (final Exception e) {
				MySrvTwitterAction.LOGGER.fatal(e, e);
			}
		}

		errors.add("registerSucceed", new ActionMessage("errors.deleteRssUser", DicoTools.dico(lang, "srv_podcast/subscription_succeed")));
		saveErrors(request, errors);

		return load(mapping, form, request, response);
	}

}


text:
#pragma once
#include <aws/connect/Connect_EXPORTS.h>
#include <aws/connect/ConnectRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Connect
{
namespace Model
{

  /**
   */
  class AWS_CONNECT_API UpdateRoutingProfileNameRequest : public ConnectRequest
  {
  public:
    UpdateRoutingProfileNameRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateRoutingProfileName"; }

    Aws::String SerializePayload() const override;

    /**
     *
The identifier of the Amazon Connect instance.

     */
    inline const Aws::String& GetInstanceId() const{ return m_instanceId; }

    /**
     *
The identifier of the Amazon Connect instance.

     */
    inline bool InstanceIdHasBeenSet() const { return m_instanceIdHasBeenSet; }

    /**
     *
The identifier of the Amazon Connect instance.

     */
    inline void SetInstanceId(const Aws::String& value) { m_instanceIdHasBeenSet = true; m_instanceId = value; }

    /**
     *
The identifier of the Amazon Connect instance.

     */
    inline void SetInstanceId(Aws::String&& value) { m_instanceIdHasBeenSet = true; m_instanceId = std::move(value); }

    /**
     *
The identifier of the Amazon Connect instance.

     */
    inline void SetInstanceId(const char* value) { m_instanceIdHasBeenSet = true; m_instanceId.assign(value); }

    /**
     *
The identifier of the Amazon Connect instance.

     */
    inline UpdateRoutingProfileNameRequest& WithInstanceId(const Aws::String& value) { SetInstanceId(value); return *this;}

    /**
     *
The identifier of the Amazon Connect instance.

     */
    inline UpdateRoutingProfileNameRequest& WithInstanceId(Aws::String&& value) { SetInstanceId(std::move(value)); return *this;}

    /**
     *
The identifier of the Amazon Connect instance.

     */
    inline UpdateRoutingProfileNameRequest& WithInstanceId(const char* value) { SetInstanceId(value); return *this;}

    /**
     *
The identifier of the routing profile.

     */
    inline const Aws::String& GetRoutingProfileId() const{ return m_routingProfileId; }

    /**
     *
The identifier of the routing profile.

     */
    inline bool RoutingProfileIdHasBeenSet() const { return m_routingProfileIdHasBeenSet; }

    /**
     *
The identifier of the routing profile.

     */
    inline void SetRoutingProfileId(const Aws::String& value) { m_routingProfileIdHasBeenSet = true; m_routingProfileId = value; }

    /**
     *
The identifier of the routing profile.

     */
    inline void SetRoutingProfileId(Aws::String&& value) { m_routingProfileIdHasBeenSet = true; m_routingProfileId = std::move(value); }

    /**
     *
The identifier of the routing profile.

     */
    inline void SetRoutingProfileId(const char* value) { m_routingProfileIdHasBeenSet = true; m_routingProfileId.assign(value); }

    /**
     *
The identifier of the routing profile.

     */
    inline UpdateRoutingProfileNameRequest& WithRoutingProfileId(const Aws::String& value) { SetRoutingProfileId(value); return *this;}

    /**
     *
The identifier of the routing profile.

     */
    inline UpdateRoutingProfileNameRequest& WithRoutingProfileId(Aws::String&& value) { SetRoutingProfileId(std::move(value)); return *this;}

    /**
     *
The identifier of the routing profile.

     */
    inline UpdateRoutingProfileNameRequest& WithRoutingProfileId(const char* value) { SetRoutingProfileId(value); return *this;}

    /**
     *
The name of the routing profile. Must not be more than 127 characters.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
The name of the routing profile. Must not be more than 127 characters.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
The name of the routing profile. Must not be more than 127 characters.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The name of the routing profile. Must not be more than 127 characters.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The name of the routing profile. Must not be more than 127 characters.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
The name of the routing profile. Must not be more than 127 characters.

     */
    inline UpdateRoutingProfileNameRequest& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
The name of the routing profile. Must not be more than 127 characters.

     */
    inline UpdateRoutingProfileNameRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The name of the routing profile. Must not be more than 127 characters.

     */
    inline UpdateRoutingProfileNameRequest& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
The description of the routing profile. Must not be more than 250
     * characters.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
The description of the routing profile. Must not be more than 250
     * characters.

     */
    inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }

    /**
     *
The description of the routing profile. Must not be more than 250
     * characters.

     */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /**
     *
The description of the routing profile. Must not be more than 250
     * characters.

     */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }

    /**
     *
The description of the routing profile. Must not be more than 250
     * characters.

     */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /**
     *
The description of the routing profile. Must not be more than 250
     * characters.

     */
    inline UpdateRoutingProfileNameRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
The description of the routing profile. Must not be more than 250
     * characters.

     */
    inline UpdateRoutingProfileNameRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
The description of the routing profile. Must not be more than 250
     * characters.

     */
    inline UpdateRoutingProfileNameRequest& WithDescription(const char* value) { SetDescription(value); return *this;}

  private:

    Aws::String m_instanceId;
    bool m_instanceIdHasBeenSet;

    Aws::String m_routingProfileId;
    bool m_routingProfileIdHasBeenSet;

    Aws::String m_name;
    bool m_nameHasBeenSet;

    Aws::String m_description;
    bool m_descriptionHasBeenSet;
  };

} // namespace Model
} // namespace Connect
} // namespace Aws


text:
<!DOCTYPE html>
<meta charset="utf-8">

<body>

  <div id="chart" class='with-3d-shadow with-transitions'>
    <svg style="height: 500px;"></svg>
  </div>

<script src="../lib/d3.v3.js"></script>
<script src="../nv.d3.js"></script>
<script src="../src/tooltip.js"></script>
<script src="../src/utils.js"></script>
<script src="../src/models/legend.js"></script>
<script src="../src/models/axis.js"></script>
<script src="../src/models/scatter.js"></script>
<script src="../src/models/line.js"></script>
<script src="../src/models/lineWithFocusChart.js"></script>
<script src="stream_layers.js"></script>


text:
import {
  LocalStateForm,
  SimpleValidation
} from 'immutable-react-form';

import Form from './form';
import validation from './validation';
import {GetData,UpdateData} from './data';

export default LocalStateForm(
  props => (GetData()),
  validation,
  submit
)(Form);

async function submit(model,props){
  await UpdateData(model);
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>cds: cds::gc::HRC Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

cds
    1.4.0

Main Page

Modules

Namespaces

Data Structures

Files

Data Structures

Class Hierarchy

Data Fields

cds

gc

HRC

Data Structures |
Public Types |
Public Member Functions |
Static Public Member Functions

cds::gc::HRC Class Reference
Garbage collectors

Gidenstam's garbage collector.
 More...

#include <cds/gc/hrc.h>

Data Structures

class  	atomic_marked_ptr

 	Atomic marked pointer.  More...

class  	atomic_ref

 	Atomic reference.  More...

class  	Guard

 	HRC guard.  More...

class  	GuardArray

 	Array of guards.  More...

class  	thread_gc

 	Wrapper for hrc::ThreadGC class.  More...

Public Types

typedef hrc::ThreadGC 	thread_gc_impl

 	Thread GC implementation for internal usage.

typedef hrc::ContainerNode 	container_node

 	Base for container node.

typedef container_node * 	guarded_pointer

 	Native hazard pointer type.

Public Member Functions

 	HRC (size_t nHazardPtrCount=0, size_t nMaxThreadCount=0, size_t nMaxNodeLinkCount=0, size_t nMaxTransientLinks=0)

 	Initializes hrc::GarbageCollector singleton.  More...

 	~HRC ()

 	Terminates hrc::GarbageCollector singleton.  More...

Static Public Member Functions

static bool 	check_available_guards (size_t nCountNeeded, bool bRaiseException=true)

 	Checks if count of hazard pointer is no less than nCountNeeded.  More...

template<typename T >

static void 	retire (T *p, void(*pFunc)(T *))

 	Retire pointer p with function pFunc.  More...

template<class Disposer , typename T >

static void 	retire (T *p)

 	Retire pointer p with functor of type Disposer.  More...

static bool 	isUsed ()

 	Checks if HRC GC is constructed and may be used.

static void 	scan ()

 	Forced GC cycle call for current thread.  More...

static void 	force_dispose ()

Detailed Description

Gidenstam's garbage collector.

This class is a wrapper for Gidenstam's memory reclamation schema (HRC - Hazard pointer + Reference Counting) internal implementation.

Sources:

[2006] A.Gidenstam "Algorithms for synchronization and consistency
    in concurrent system services", Chapter 5 "Lock-Free Memory Reclamation" Thesis for the degree of Doctor of Philosophy

[2005] Anders Gidenstam, Marina Papatriantafilou and Philippas Tsigas "Allocating
    memory in a lock-free manner", Proceedings of the 13th Annual European Symposium on Algorithms (ESA 2005), Lecture Notes in Computer Science Vol. 3669, pages 229 – 242, Springer-Verlag, 2005

Note that HRC schema does not support cyclic references that significantly limits the applicability of this GC.

Usage

In your main function you declare a object of class cds::gc::HRC. This declaration initializes internal hrc::GarbageCollector singleton.

#include <cds/init.h>       // for cds::Initialize and cds::Terminate

#include <cds/gc/hrc.h>

int main(int argc, char** argv)

{

    // Initialize libcds

    cds::Initialize() ;

    {

        // Initialize HRC singleton

        cds::gc::HRC hpGC() ;

        // Some useful work

        ...

    }

    // Terminate libcds

    cds::Terminate()    ;

}

Each thread that uses cds::gc::HRC -based containers must be attached to HRC singleton. To make attachment you should declare a object of class HRC::thread_gc:

#include <cds/gc/hrc.h>

int myThreadEntryPoint()

{

    // Attach the thread to HRC singleton

    cds::gc::HRC::thread_gc myThreadGC()    ;

    // Do some work

    ...

    // The destructor of myThreadGC object detaches the thread from HRC singleton

}

In some cases, you should work in a external thread. For example, your application is a plug-in for a server that calls your code in the threads that has been created by server. In this case, you may use persistent mode of HRC::thread_gc. In this mode, the thread attaches to the HRC singleton only if it is not yet attached and never call detaching:

#include <cds/gc/hrc.h>

int myThreadEntryPoint()

{

// Attach the thread in persistent mode

cds::gc::HRC::thread_gc myThreadGC( true )    ;

// Do some work

...

// The destructor of myThreadGC object does NOT detach the thread from HRC singleton

}

Constructor & Destructor Documentation

          cds::gc::HRC::HRC
          (
          size_t
          nHazardPtrCount = 0,

          size_t
          nMaxThreadCount = 0,

          size_t
          nMaxNodeLinkCount = 0,

          size_t
          nMaxTransientLinks = 0

          )

inline

Initializes hrc::GarbageCollector singleton.

The constructor calls hrc::GarbageCollector::Construct with passed parameters. See hrc::GarbageCollector::Construct for explanation of parameters meaning.

Parameters

nHazardPtrCount	number of hazard pointers

nMaxThreadCount	max threads count

nMaxNodeLinkCount	max number of links a hrc::ContainerNode can contain

nMaxTransientLinks	max number of links in live nodes that may transiently point to a deleted node

          cds::gc::HRC::~HRC
          (
          	)

inline

Terminates hrc::GarbageCollector singleton.

The destructor calls

hrc::GarbageCollector::Destruct()

Member Function Documentation

          static bool cds::gc::HRC::check_available_guards
          (
          size_t
          nCountNeeded,

          bool
          bRaiseException = true

          )

inlinestatic

Checks if count of hazard pointer is no less than nCountNeeded.

If bRaiseException is true (that is the default), the function raises an exception gc::too_little_hazard_pointers if nCountNeeded is more than the count of hazard pointer per thread.

template<typename T >

          static void cds::gc::HRC::retire
          (
          T *
          p,

          void(*)(T *)
          pFunc

          )

static

Retire pointer p with function pFunc.

The function places pointer p to array of pointers ready for removing. (so called retired pointer array). The pointer can be safely removed when no guarded pointer points to it. Deleting the pointer is the function pFunc call.

template<class Disposer , typename T >

          static void cds::gc::HRC::retire
          (
          T *
          p	)

static

Retire pointer p with functor of type Disposer.

The function places pointer p to array of pointers ready for removing. (so called retired pointer array). The pointer can be safely removed when no guard points to it.

See gc::HP::retire for Disposer requirements.

          static void cds::gc::HRC::scan
          (
          	)

static

Forced GC cycle call for current thread.

Usually, this function should not be called directly.

The documentation for this class was generated from the following file:

cds/gc/hrc_decl.h

			cds 1.4.0
			Developed by Maxim Khiszinsky aka khizmax 2007 - 2012

			Autogenerated Mon May 20 2013 00:37:58 by Doxygen 1.8.3.1


text:
/*
 * @author Michael Holub
 * @author Valentin Simonov / http://va.lent.in/
 */

using System;
using System.Collections.Generic;
using TouchScript.Pointers;
using TouchScript.Utils;
using UnityEngine;
using UnityEngine.Profiling;

namespace TouchScript.InputSources.InputHandlers
{
    /// <summary>
    /// Unity touch handling implementation which can be embedded and controlled from other (input) classes.
    /// </summary>
    public class TouchHandler : IInputSource, IDisposable
    {
        #region Public properties

        /// <inheritdoc />
        public ICoordinatesRemapper CoordinatesRemapper { get; set; }

        /// <summary>
        /// Gets a value indicating whether there any active pointers.
        /// </summary>
        /// <value> <c>true</c> if this instance has active pointers; otherwise, <c>false</c>. </value>
        public bool HasPointers
        {
            get { return pointersNum > 0; }
        }

        #endregion

        #region Private variables

        private PointerDelegate addPointer;
        private PointerDelegate updatePointer;
        private PointerDelegate pressPointer;
        private PointerDelegate releasePointer;
        private PointerDelegate removePointer;
        private PointerDelegate cancelPointer;

        private ObjectPool<TouchPointer> touchPool;
        // Unity fingerId -> TouchScript touch info
        private Dictionary<int, TouchState> systemToInternalId = new Dictionary<int, TouchState>(10);
        private int pointersNum;

		private CustomSampler updateSampler;

        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="TouchHandler" /> class.
        /// </summary>
        /// <param name="addPointer">A function called when a new pointer is detected.</param>
        /// <param name="updatePointer">A function called when a pointer is moved or its parameter is updated.</param>
        /// <param name="pressPointer">A function called when a pointer touches the surface.</param>
        /// <param name="releasePointer">A function called when a pointer is lifted off.</param>
        /// <param name="removePointer">A function called when a pointer is removed.</param>
        /// <param name="cancelPointer">A function called when a pointer is cancelled.</param>
        public TouchHandler(PointerDelegate addPointer, PointerDelegate updatePointer, PointerDelegate pressPointer, PointerDelegate releasePointer, PointerDelegate removePointer, PointerDelegate cancelPointer)
        {
            this.addPointer = addPointer;
            this.updatePointer = updatePointer;
            this.pressPointer = pressPointer;
            this.releasePointer = releasePointer;
            this.removePointer = removePointer;
            this.cancelPointer = cancelPointer;

            touchPool = new ObjectPool<TouchPointer>(10, () => new TouchPointer(this), null, resetPointer);
            touchPool.Name = "Touch";

			updateSampler = CustomSampler.Create("[TouchScript] Update touch");
        }

        #region Public methods

        /// <inheritdoc />
        public bool UpdateInput()
        {
			updateSampler.Begin();

            for (var i = 0; i < Input.touchCount; ++i)
            {
                var t = Input.GetTouch(i);

                TouchState touchState;
                switch (t.phase)
                {
                    case TouchPhase.Began:
                        if (systemToInternalId.TryGetValue(t.fingerId, out touchState) && touchState.Phase != TouchPhase.Canceled)
                        {
                            // Ending previous touch (missed a frame)
                            internalRemovePointer(touchState.Pointer);
                            systemToInternalId[t.fingerId] = new TouchState(internalAddPointer(t.position));
                        }
                        else
                        {
                            systemToInternalId.Add(t.fingerId, new TouchState(internalAddPointer(t.position)));
                        }
                        break;
                    case TouchPhase.Moved:
                        if (systemToInternalId.TryGetValue(t.fingerId, out touchState))
                        {
                            if (touchState.Phase != TouchPhase.Canceled)
                            {
                                touchState.Pointer.Position = t.position;
                                updatePointer(touchState.Pointer);
                            }
                        }
                        else
                        {
                            // Missed began phase
                            systemToInternalId.Add(t.fingerId, new TouchState(internalAddPointer(t.position)));
                        }
                        break;
                    // NOTE: Unity touch on Windows reports Cancelled as Ended
                    // when a touch goes out of display boundary
                    case TouchPhase.Ended:
                        if (systemToInternalId.TryGetValue(t.fingerId, out touchState))
                        {
                            systemToInternalId.Remove(t.fingerId);
                            if (touchState.Phase != TouchPhase.Canceled) internalRemovePointer(touchState.Pointer);
                        }
                        else
                        {
                            // Missed one finger begin-end transition
                            var pointer = internalAddPointer(t.position);
                            internalRemovePointer(pointer);
                        }
                        break;
                    case TouchPhase.Canceled:
                        if (systemToInternalId.TryGetValue(t.fingerId, out touchState))
                        {
                            systemToInternalId.Remove(t.fingerId);
                            if (touchState.Phase != TouchPhase.Canceled) internalCancelPointer(touchState.Pointer);
                        }
                        else
                        {
                            // Missed one finger begin-end transition
                            var pointer = internalAddPointer(t.position);
                            internalCancelPointer(pointer);
                        }
                        break;
                    case TouchPhase.Stationary:
                        if (systemToInternalId.TryGetValue(t.fingerId, out touchState)) {}
                        else
                        {
                            // Missed begin phase
                            systemToInternalId.Add(t.fingerId, new TouchState(internalAddPointer(t.position)));
                        }
                        break;
                }
            }

			updateSampler.End();

            return Input.touchCount > 0;
        }

        /// <inheritdoc />
        public void UpdateResolution() {}

        /// <inheritdoc />
        public bool CancelPointer(Pointer pointer, bool shouldReturn)
        {
            var touch = pointer as TouchPointer;
            if (touch == null) return false;

            int fingerId = -1;
            foreach (var touchState in systemToInternalId)
            {
                if (touchState.Value.Pointer == touch && touchState.Value.Phase != TouchPhase.Canceled)
                {
                    fingerId = touchState.Key;
                    break;
                }
            }
            if (fingerId > -1)
            {
                internalCancelPointer(touch);
                if (shouldReturn) systemToInternalId[fingerId] = new TouchState(internalReturnPointer(touch));
                else systemToInternalId[fingerId] = new TouchState(touch, TouchPhase.Canceled);
                return true;
            }
            return false;
        }

        /// <summary>
        /// Releases resources.
        /// </summary>
        public void Dispose()
        {
            foreach (var touchState in systemToInternalId)
            {
                if (touchState.Value.Phase != TouchPhase.Canceled) internalCancelPointer(touchState.Value.Pointer);
            }
            systemToInternalId.Clear();
        }

        #endregion

        #region Internal methods

        /// <inheritdoc />
        public void INTERNAL_DiscardPointer(Pointer pointer)
        {
            var p = pointer as TouchPointer;
            if (p == null) return;

            touchPool.Release(p);
        }

        #endregion

        #region Private functions

        private Pointer internalAddPointer(Vector2 position)
        {
            pointersNum++;
            var pointer = touchPool.Get();
            pointer.Position = remapCoordinates(position);
            pointer.Buttons |= Pointer.PointerButtonState.FirstButtonDown | Pointer.PointerButtonState.FirstButtonPressed;
            addPointer(pointer);
            pressPointer(pointer);
            return pointer;
        }

        private TouchPointer internalReturnPointer(TouchPointer pointer)
        {
            pointersNum++;
            var newPointer = touchPool.Get();
            newPointer.CopyFrom(pointer);
            pointer.Buttons |= Pointer.PointerButtonState.FirstButtonDown | Pointer.PointerButtonState.FirstButtonPressed;
            newPointer.Flags |= Pointer.FLAG_RETURNED;
            addPointer(newPointer);
            pressPointer(newPointer);
            return newPointer;
        }

        private void internalRemovePointer(Pointer pointer)
        {
            pointersNum--;
            pointer.Buttons &= ~Pointer.PointerButtonState.FirstButtonPressed;
            pointer.Buttons |= Pointer.PointerButtonState.FirstButtonUp;
            releasePointer(pointer);
            removePointer(pointer);
        }

        private void internalCancelPointer(Pointer pointer)
        {
            pointersNum--;
            cancelPointer(pointer);
        }

        private Vector2 remapCoordinates(Vector2 position)
        {
            if (CoordinatesRemapper != null) return CoordinatesRemapper.Remap(position);
            return position;
        }

        private void resetPointer(Pointer p)
        {
            p.INTERNAL_Reset();
        }

        #endregion

        private struct TouchState
        {
            public Pointer Pointer;
            public TouchPhase Phase;

            public TouchState(Pointer pointer, TouchPhase phase = TouchPhase.Began)
            {
                Pointer = pointer;
                Phase = phase;
            }
        }
    }
}