text:
<?php
namespace Travel\Form;
use Zend\InputFilter\InputFilter;
use Zend\Form\Element;
use Zend\InputFilter\Input;
use Admin\Validator\UniqueValueValidator;
use Zend\Validator\Regex;
use Zend\Validator\Date;
use AceLibrary\Form\AceForm;
use AceLibrary\Validator\DateRangeValidator;

/**
 * @author Laurynas Tretjakovas(n3ziniuka5) <laurynas.tretjakovas@gmail.com>
 *
 */
class SearchForm extends AceForm {

    protected $inputFilter;

    public function __construct($sm) {
        parent::__construct($sm, 'searchForm');

        $this->setInputFilter($this->getMyInputFilter());
        $this->setAttribute('method', 'post');

        $commenceDate = new Element\Text();
        $commenceDate->setName('commencing');
        $commenceDate->setAttribute('id', 'commenceDate');

        $nightsOptions = array();
        for($i = 1; $i <= 28; $i++) {
            $nightsOptions[$i] = $i;
        }
        $nightsSelect = new Element\Select();
        $nightsSelect->setName('nights');
        $nightsSelect->setAttribute('id', 'nightsSelect');
        $nightsSelect->setValueOptions($nightsOptions);
        $nightsSelect->setValue(2);

        $guestsOptions = array();
        for($i = 1; $i <= 20; $i++) {
        	$guestsOptions[$i] = $i;
        }
        $guestsSelect = new Element\Select();
        $guestsSelect->setName('guests');
        $guestsSelect->setAttribute('id', 'guestsSelect');
        $guestsSelect->setValueOptions($guestsOptions);
        $guestsSelect->setValue(2);

        $areaOptions = $this->getServiceManager()->get('Travel\Model\DestinationModel')->getSearchAreasOptionValues();
        $areaSelect = new Element\Select();
        $areaSelect->setName('area');
        $areaSelect->setAttribute('id', 'areaSelect');
        $areaSelect->setValueOptions($areaOptions);

        $submitButton = new Element\Submit();
        $submitButton->setName('submit-searchForm');
        $submitButton->setValue($this->getTranslator()->translate('Search Accommodation'));
        $submitButton->setAttribute('class', 'btn');

        $this->add($commenceDate)
             ->add($nightsSelect)
             ->add($guestsSelect)
             ->add($areaSelect)
             ->add($submitButton);
    }

    public function getMyInputFilter() {
        if(!$this->inputFilter) {
            $inputFilter = new InputFilter();

            $dateRangeValidator = new DateRangeValidator(array(
            	'min'	=> date('d M Y', time() + 60*60*24), //+24 hours
            ));
            $commenceDate = new Input('commencing');
            $commenceDate->setRequired(true);
            $commenceDate->getValidatorChain()
            	->addValidator(new Date(array('format' => 'd M Y')))
            	->addValidator($dateRangeValidator);

            $inputFilter->add($commenceDate);

            $this->inputFilter= $inputFilter;
        }
        return $this->inputFilter;
    }

}

redpajama_set_name: RedPajamaGithub


text:
:orphan:

# Release checklist

1. Make sure all tests pass.

   ```shell
   pytest -vv --disable-pytest-warnings
   ```

2. Create release candidate with `git flow`:

    ```shell
    new_version=0.0.0
    echo ${new_version}

    git flow release start ${new_version}
    ```

3. Update version in `genomepy/__about__.py`

4. Update the `CHANGELOG.md`

    * add the new version & date to the header
    * link to the diff in the footer
    * add & commit the changes, but do not push

5. Check if release works on pypi:

    ```shell
    python setup.py sdist bdist_wheel

    # twine must be up to date (3.3.0 works). System installed twine can interfere.
    twine upload --repository-url https://test.pypi.org/legacy/ dist/genomepy-${new_version}*

    python setup.py develop --uninstall

    # the \ is to escape the ==, so the variable ${new_version} can be called
    pip install --extra-index-url https://test.pypi.org/simple/ genomepy\==${new_version}

    # tests
    genomepy --version
    genomepy --help
    genomepy install --help
    genomepy clean
    genomepy search xenopus_tropicalis
    genomepy annotation hg38
    genomepy annotation GRCh38.p13
    genomepy install -af -p gencode GRCm39
    genomepy install -af -p ensembl TAIR10
    genomepy install -af -p ucsc sacCer3 --UCSC-annotation ensGene
    genomepy install -af -p ncbi ASM2732v1
    genomepy install -af -p url -l url_test https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/027/325/GCF_000027325.1_ASM2732v1/GCF_000027325.1_ASM2732v1_genomic.fna.gz --URL-to-annotation https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/027/325/GCF_000027325.1_ASM2732v1/GCF_000027325.1_ASM2732v1_genomic.gff.gz
    genomepy install -af -p local -l local_test ~/.local/share/genomes/TAIR10/TAIR10.fa --Local-path-to-annotation ~/.local/share/genomes/TAIR10/TAIR10.annotation.gtf
    ```

6. Finish the release:

    ```shell
    git flow release finish ${new_version}
   ```

7. Push everything to github, including tags:

   ```shell
   git push --follow-tags origin develop
   ```

8. Pull into master

9. Upload to pypi:

    ```shell
    python setup.py sdist bdist_wheel
    twine upload dist/genomepy-${new_version}*
    ```

10. Create release on github (if it not already exists)

    * Update release with CHANGELOG information from the latest version
    * Download the tarball from the github release (`.tar.gz`).
    * Attach downloaded tarball to release as binary (this way the download count get tracked).

11a. Update bioconda package

    * wait for the bioconda bot to create a PR
    * update dependencies in the bioconda recipe.yaml if needed
    * approve the PR
    * comment: @bioconda-bot please merge

11b. Update bioconda package

    * fork bioconda/bioconda-recipes
    * follow the steps in the [docs](https://bioconda.github.io/contributor/workflow.html)
    * get the hash from the downloaded tarbal using `sha256sum *genomepy-${new_version}.tar.gz`
    * update the [yaml file](https://github.com/bioconda/bioconda-recipes/blob/master/recipes/genomepy/meta.yaml) locally.
    * push to a new branch on the fork
    * start a PR


text:
================

The missing Async NodeJS Wrapper for SoundCloud API
soundcloudnodejs is a nodejs module to access [soundcloud](https://www.soundcloud.com) from NodeJS.

## Install
```bash
npm install --save soundcloudnodejs
```

## Register
Register your app http://soundcloud.com/you/apps/new

Example Code to get your Token Access from SoundCloud API
```
var soundcloudnodejs = require("soundcloudnodejs");
var options = {
    client_id: "your_client_id",
    client_secret: "your_client_secret",
    grant_type: "password",
    username: "your_username",
    password: "your_password",
    redirect_uri: "your_redirect_uri"
}
soundcloudnodejs.getToken(options).then(function (token, meta) {
    console.log(token.access_token)
});

```

* For usage see folder [soundcloudnodejs/example/](https://github.com/thomasmodeneis/soundcloudnodejs/tree/master/example) .
* For test cases and BDD scenarios see folder [soundcloudnodejs/test/](https://github.com/thomasmodeneis/soundcloudnodejs/tree/master/test) .
* Make sure to add your credentials to [credentials.js](https://github.com/thomasmodeneis/soundcloudnodejs/tree/master/example/credentials.js) and run `npm run token` before running the tests, otherwise tests will fail.

# DEBUG

To enable debug mode, run scripts with env variable SOUNDCLOUDJS_DEBUG=true

# License

```
The MIT License (MIT)

Copyright (c) 2018 Thomas Modeneis

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```

Disclaimer:
* I've done this module because SoundCloud does not offer a NodeJS wrapper for their APIs, other opensource modules where not working or not maintained when I started this SoundCloud saga back in 2016.
* This module is fully tested and functional, however if something does not work for you please feel free to open a ticket / pull request with a fix or new functionality.


text:
var reload = require("live-reload");
var other = require("./other");

// Keep a count of how many times this reloads.
if(typeof window.counter !== "number") window.counter = -1;
window.counter++;

reload(function(){
	console.log("All complete", window.counter);
});

reload("other", function(other){
	console.log("Other is now", other);
});

reload.dispose(function(){
	console.log("Doing some cleanup");
});


text:
package org.apache.cassandra.simulator.systems;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

import io.netty.util.concurrent.FastThreadLocal;
import org.apache.cassandra.concurrent.ExecutorPlus;
import org.apache.cassandra.concurrent.LocalAwareExecutorPlus;
import org.apache.cassandra.concurrent.LocalAwareSequentialExecutorPlus;
import org.apache.cassandra.concurrent.ScheduledExecutorPlus;
import org.apache.cassandra.concurrent.SequentialExecutorPlus;
import org.apache.cassandra.concurrent.SingleThreadExecutorPlus;
import org.apache.cassandra.concurrent.SyncFutureTask;
import org.apache.cassandra.concurrent.TaskFactory;
import org.apache.cassandra.config.CassandraRelevantProperties;
import org.apache.cassandra.simulator.OrderOn;
import org.apache.cassandra.simulator.OrderOn.OrderAppliesAfterScheduling;
import org.apache.cassandra.simulator.systems.NotifyThreadPaused.AwaitPaused;
import org.apache.cassandra.utils.Shared;
import org.apache.cassandra.utils.WithResources;
import org.apache.cassandra.utils.concurrent.Condition;
import org.apache.cassandra.utils.concurrent.Condition.Sync;
import org.apache.cassandra.utils.concurrent.Future;
import org.apache.cassandra.utils.concurrent.RunnableFuture;
import org.apache.cassandra.utils.concurrent.UncheckedInterruptedException;

import static java.util.Collections.newSetFromMap;
import static java.util.Collections.synchronizedSet;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static org.apache.cassandra.config.CassandraRelevantProperties.TEST_SIMULATOR_DEBUG;
import static org.apache.cassandra.simulator.systems.InterceptibleThread.runDeterministic;
import static org.apache.cassandra.simulator.systems.SimulatedAction.Kind.SCHEDULED_DAEMON;
import static org.apache.cassandra.simulator.systems.SimulatedAction.Kind.SCHEDULED_TASK;
import static org.apache.cassandra.simulator.systems.SimulatedAction.Kind.SCHEDULED_TIMEOUT;
import static org.apache.cassandra.simulator.systems.SimulatedExecution.callable;
import static org.apache.cassandra.simulator.systems.SimulatedTime.Global.absoluteToRelativeNanos;
import static org.apache.cassandra.simulator.systems.SimulatedTime.Global.localToGlobalNanos;
import static org.apache.cassandra.simulator.systems.SimulatedTime.Global.relativeToGlobalAbsoluteNanos;
import static org.apache.cassandra.utils.Shared.Recursive.INTERFACES;
import static org.apache.cassandra.utils.Shared.Scope.SIMULATION;
import static org.apache.commons.collections.MapUtils.synchronizedMap;

// An executor whose tasks we can intercept the execution of
@Shared(scope = SIMULATION, inner = INTERFACES)
public interface InterceptingExecutor extends OrderOn
{
    class ForbiddenExecutionException extends RejectedExecutionException
    {
    }

    interface InterceptingTaskFactory extends TaskFactory
    {
    }

    void addPending(Object task);
    void cancelPending(Object task);
    void submitUnmanaged(Runnable task);
    void submitAndAwaitPause(Runnable task, InterceptorOfConsequences interceptor);

    OrderOn orderAppliesAfterScheduling();

    static class InterceptedScheduledFutureTask<T> extends SyncFutureTask<T> implements ScheduledFuture<T>
    {
        final long delayNanos;
        Runnable onCancel;
        public InterceptedScheduledFutureTask(long delayNanos, Callable<T> call)
        {
            super(call);
            this.delayNanos = delayNanos;
        }

        @Override
        public long getDelay(TimeUnit unit)
        {
            return unit.convert(delayNanos, NANOSECONDS);
        }

        @Override
        public int compareTo(Delayed that)
        {
            return Long.compare(delayNanos, that.getDelay(NANOSECONDS));
        }

        void onCancel(Runnable onCancel)
        {
            this.onCancel = onCancel;
        }

        @Override
        public boolean cancel(boolean b)
        {
            if (onCancel != null)
            {
                onCancel.run();
                onCancel = null;
            }
            return super.cancel(b);
        }
    }

    @PerClassLoader
    abstract class AbstractInterceptingExecutor implements InterceptingExecutor, ExecutorPlus
    {
        private static final AtomicIntegerFieldUpdater<AbstractInterceptingExecutor> pendingUpdater = AtomicIntegerFieldUpdater.newUpdater(AbstractInterceptingExecutor.class, "pending");

        final OrderAppliesAfterScheduling orderAppliesAfterScheduling = new OrderAppliesAfterScheduling(this);

        final InterceptorOfExecution interceptorOfExecution;
        final InterceptingTaskFactory taskFactory;

        final Set<Object> debugPending = TEST_SIMULATOR_DEBUG.getBoolean() ? synchronizedSet(newSetFromMap(new IdentityHashMap<>())) : null;
        final Condition isTerminated = new Sync();
        volatile boolean isShutdown;
        volatile int pending;

        protected AbstractInterceptingExecutor(InterceptorOfExecution interceptorOfExecution, InterceptingTaskFactory taskFactory)
        {
            this.interceptorOfExecution = interceptorOfExecution;
            this.taskFactory = taskFactory;
        }

        @Override
        public void addPending(Object task)
        {
            if (isShutdown)
                throw new RejectedExecutionException();

            pendingUpdater.incrementAndGet(this);
            if (isShutdown)
            {
                if (0 == pendingUpdater.decrementAndGet(this))
                    terminate();
                throw new RejectedExecutionException();
            }

            if (debugPending != null && !debugPending.add(task))
                throw new AssertionError();
        }

        @Override
        public void cancelPending(Object task)
        {
            boolean shutdown = isShutdown;
            if (completePending(task) == 0 && shutdown)
                terminate();
        }

        @Override
        public OrderOn orderAppliesAfterScheduling()
        {
            return orderAppliesAfterScheduling;
        }

        public int completePending(Object task)
        {
            int remaining = pendingUpdater.decrementAndGet(this);
            if (debugPending != null && !debugPending.remove(task))
                throw new AssertionError();
            return remaining;
        }

        <V, T extends RunnableFuture<V>> T addTask(T task)
        {
            if (isShutdown)
                throw new RejectedExecutionException();

            return interceptorOfExecution.intercept().addTask(task, this);
        }

        public void maybeExecuteImmediately(Runnable command)
        {
            execute(command);
        }

        @Override
        public void execute(Runnable run)
        {
            addTask(taskFactory.toSubmit(run));
        }

        @Override
        public void execute(WithResources withResources, Runnable run)
        {
            addTask(taskFactory.toSubmit(withResources, run));
        }

        @Override
        public Future<?> submit(Runnable run)
        {
            return addTask(taskFactory.toSubmit(run));
        }

        @Override
        public <T> Future<T> submit(Runnable run, T result)
        {
            return addTask(taskFactory.toSubmit(run, result));
        }

        @Override
        public <T> Future<T> submit(Callable<T> call)
        {
            return addTask(taskFactory.toSubmit(call));
        }

        @Override
        public <T> Future<T> submit(WithResources withResources, Runnable run, T result)
        {
            return addTask(taskFactory.toSubmit(withResources, run, result));
        }

        @Override
        public Future<?> submit(WithResources withResources, Runnable run)
        {
            return addTask(taskFactory.toSubmit(withResources, run));
        }

        @Override
        public <T> Future<T> submit(WithResources withResources, Callable<T> call)
        {
            return addTask(taskFactory.toSubmit(withResources, call));
        }

        abstract void terminate();

        protected void onThreadTermination()
        {
            FastThreadLocal.removeAll();
        }

        public boolean isShutdown()
        {
            return isShutdown;
        }

        public boolean isTerminated()
        {
            return isTerminated.isSignalled();
        }

        public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException
        {
            return isTerminated.await(timeout, unit);
        }

        @Override
        public void setCorePoolSize(int newCorePoolSize)
        {
            throw new UnsupportedOperationException();
        }

        @Override
        public void setMaximumPoolSize(int newMaximumPoolSize)
        {
            throw new UnsupportedOperationException();
        }
    }

    @PerClassLoader
    class InterceptingPooledExecutor extends AbstractInterceptingExecutor implements InterceptingExecutor
    {
        enum State { RUNNING, TERMINATING, TERMINATED }

        private class WaitingThread
        {
            final InterceptibleThread thread;
            Runnable task;
            State state = State.RUNNING;

            WaitingThread(ThreadFactory factory)
            {
                this.thread = (InterceptibleThread) factory.newThread(() -> {
                    InterceptibleThread thread = (InterceptibleThread) Thread.currentThread();
                    try
                    {
                        while (true)
                        {
                            try
                            {
                                task.run();
                            }
                            catch (Throwable t)
                            {
                                try { thread.getUncaughtExceptionHandler().uncaughtException(thread, t); }
                                catch (Throwable ignore) {}
                            }

                            boolean shutdown = isShutdown;
                            int remaining = completePending(task);
                            if (shutdown && remaining < threads.size())
                            {
                                threads.remove(thread);
                                if (threads.isEmpty())
                                    isTerminated.signal(); // this has simulator side-effects, so try to perform before we interceptTermination
                                thread.interceptTermination(true);
                                return;
                            }

                            task = null;
                            waiting.add(this); // inverse order of waiting.add/isShutdown to ensure visibility vs shutdown()
                            thread.interceptTermination(false);
                            synchronized (this)
                            {
                                while (task == null)
                                {
                                    if (state == State.TERMINATING)
                                        return;

                                    try { wait(); }
                                    catch (InterruptedException | UncheckedInterruptedException ignore) { }
                                }
                            }
                        }
                    }
                    finally
                    {
                        try
                        {
                            runDeterministic(() -> {
                                if (null != threads.remove(thread))
                                {
                                    task = null;
                                    waiting.remove(this);
                                    thread.onTermination();
                                    if (isShutdown && threads.isEmpty() && waiting.isEmpty() && !isTerminated())
                                        isTerminated.signal();
                                }
                            });
                        }
                        finally
                        {
                            synchronized (this)
                            {
                                state = State.TERMINATED;
                                notify();
                            }
                        }
                    }
                });

                threads.put(thread, this);
            }

            synchronized void submit(Runnable task)
            {
                if (state != State.RUNNING)
                    throw new IllegalStateException();
                this.task = task;
                if (thread.isAlive()) notify();
                else thread.start();
            }

            synchronized void terminate()
            {
                if (state != State.TERMINATED)
                    state = State.TERMINATING;

                if (thread.isAlive()) notify();
                else thread.start();
                try
                {
                    while (state != State.TERMINATED)
                        wait();
                }
                catch (InterruptedException e)
                {
                    throw new UncheckedInterruptedException(e);
                }
            }
        }

        final Map<InterceptibleThread, WaitingThread> threads = synchronizedMap(new IdentityHashMap<>());
        final ThreadFactory threadFactory;
        final Queue<WaitingThread> waiting = new ConcurrentLinkedQueue<>();
        final int concurrency;

        InterceptingPooledExecutor(InterceptorOfExecution interceptorOfExecution, int concurrency, ThreadFactory threadFactory, InterceptingTaskFactory taskFactory)
        {
            super(interceptorOfExecution, taskFactory);
            this.threadFactory = threadFactory;
            this.concurrency = concurrency;
        }

        public void submitAndAwaitPause(Runnable task, InterceptorOfConsequences interceptor)
        {
            // we don't check isShutdown as we could have a task queued by simulation from prior to shutdown
            if (isTerminated()) throw new AssertionError();
            if (debugPending != null && !debugPending.contains(task)) throw new AssertionError();

            WaitingThread waiting = getWaiting();
            AwaitPaused done = new AwaitPaused(waiting);
            waiting.thread.beforeInvocation(interceptor, done);
            synchronized (waiting)
            {
                waiting.submit(task);
                done.awaitPause();
            }
        }

        public void submitUnmanaged(Runnable task)
        {
            if (isShutdown)
                throw new RejectedExecutionException();

            addPending(task);
            WaitingThread waiting = getWaiting();
            waiting.submit(task);
        }

        private WaitingThread getWaiting()
        {
            WaitingThread next = waiting.poll();
            if (next != null)
                return next;

            return new WaitingThread(threadFactory);
        }

        public synchronized void shutdown()
        {
            isShutdown = true;
            WaitingThread next;
            while (null != (next = waiting.poll()))
                next.terminate();
            if (pending == 0)
                terminate();
        }

        synchronized void terminate()
        {
            List<InterceptibleThread> snapshot = new ArrayList<>(threads.keySet());
            for (InterceptibleThread thread : snapshot)
            {
                WaitingThread terminate = threads.get(thread);
                if (terminate != null)
                    terminate.terminate();
            }
            runDeterministic(isTerminated::signal);
        }

        public synchronized List<Runnable> shutdownNow()
        {
            shutdown();
            threads.keySet().forEach(InterceptibleThread::interrupt);
            return Collections.emptyList();
        }

        @Override
        public boolean inExecutor()
        {
            return threads.containsKey(Thread.currentThread());
        }

        @Override
        public int getActiveTaskCount()
        {
            return threads.size() - waiting.size();
        }

        @Override
        public long getCompletedTaskCount()
        {
            return 0;
        }

        @Override
        public int getPendingTaskCount()
        {
            return 0;
        }

        @Override
        public int getCorePoolSize()
        {
            return concurrency;
        }

        @Override
        public int getMaximumPoolSize()
        {
            return concurrency;
        }

        public String toString()
        {
            return threadFactory.toString();
        }

        @Override
        public int concurrency()
        {
            return concurrency;
        }
    }

    // we might want different variants
    // (did consider a non-intercepting variant, or immediate executor, but we need to intercept the thread events)
    @PerClassLoader
    abstract class AbstractSingleThreadedExecutorPlus extends AbstractInterceptingExecutor implements SequentialExecutorPlus
    {
        static class AtLeastOnce extends SingleThreadExecutorPlus.AtLeastOnce
        {
            AtLeastOnce(SequentialExecutorPlus executor, Runnable run)
            {
                super(executor, run);
            }

            public boolean trigger()
            {
                boolean success;
                if (success = compareAndSet(false, true))
                    executor.execute(this);
                else
                    executor.execute(() -> {}); // submit a no-op, so we can still impose our causality orderings
                return success;
            }
        }

        enum ThreadState { WAITING, EXECUTING, TERMINATING, TERMINATED }

        final InterceptibleThread thread;
        final ArrayDeque<Runnable> queue = new ArrayDeque<>();
        volatile boolean executing;
        volatile boolean terminating;
        volatile boolean terminated;

        AbstractSingleThreadedExecutorPlus(InterceptorOfExecution interceptorOfExecution, ThreadFactory threadFactory, InterceptingTaskFactory taskFactory)
        {
            super(interceptorOfExecution, taskFactory);
            this.thread = (InterceptibleThread) threadFactory.newThread(() -> {
                InterceptibleThread thread = (InterceptibleThread) Thread.currentThread();
                try
                {
                    while (true)
                    {
                        Runnable task;
                        try
                        {
                            task = dequeue();
                            if (task == null)
                                return;
                        }
                        catch (InterruptedException | UncheckedInterruptedException ignore)
                        {
                            continue;
                        }

                        try
                        {
                            task.run();
                        }
                        catch (Throwable t)
                        {
                            try { thread.getUncaughtExceptionHandler().uncaughtException(thread, t); }
                            catch (Throwable ignore) {}
                        }

                        executing = false;
                        boolean shutdown = isShutdown;
                        if ((0 == completePending(task) && shutdown))
                        {
                            isTerminated.signal(); // this has simulator side-effects, so try to perform before we interceptTermination
                            thread.interceptTermination(true);
                            return;
                        }

                        thread.interceptTermination(false);
                    }
                }
                finally
                {
                    synchronized (this)
                    {
                        terminated = true;
                        notifyAll();
                    }
                    if (!isTerminated())
                    {
                        runDeterministic(() -> {
                            isTerminated.signal();
                            thread.interceptTermination(true);
                        });
                    }
                }
            });
            thread.start();
        }

        synchronized void terminate()
        {
            terminating = true;
            notifyAll();
            try
            {
                while (!terminated)
                    wait();
            }
            catch (InterruptedException e)
            {
                throw new UncheckedInterruptedException(e);
            }
        }

        public synchronized void shutdown()
        {
            if (isShutdown)
                return;

            isShutdown = true;
            if (pending == 0)
                terminate();
        }

        public synchronized List<Runnable> shutdownNow()
        {
            if (isShutdown)
                return Collections.emptyList();

            isShutdown = true;
            List<Runnable> cancelled = new ArrayList<>(queue);
            queue.clear();
            cancelled.forEach(super::cancelPending);
            if (pending > 0) thread.interrupt();
            else terminate();
            return cancelled;
        }

        synchronized void enqueue(Runnable runnable)
        {
            queue.add(runnable);
            notify();
        }

        synchronized Runnable dequeue() throws InterruptedException
        {
            while (queue.isEmpty() && !terminating)
                wait();
            return queue.poll();
        }

        public AtLeastOnce atLeastOnceTrigger(Runnable run)
        {
            return new AtLeastOnce(this, run);
        }

        @Override
        public boolean inExecutor()
        {
            return thread == Thread.currentThread();
        }

        @Override
        public int getCorePoolSize()
        {
            return 1;
        }

        @Override
        public int getMaximumPoolSize()
        {
            return 1;
        }

        public String toString()
        {
            return thread.toString();
        }
    }

    @PerClassLoader
    class InterceptingSequentialExecutor extends AbstractSingleThreadedExecutorPlus implements InterceptingExecutor, ScheduledExecutorPlus, OrderOn
    {
        InterceptingSequentialExecutor(InterceptorOfExecution interceptorOfExecution, ThreadFactory threadFactory, InterceptingTaskFactory taskFactory)
        {
            super(interceptorOfExecution, threadFactory, taskFactory);
        }

        public void submitAndAwaitPause(Runnable task, InterceptorOfConsequences interceptor)
        {
            synchronized (this)
            {
                // we don't check isShutdown as we could have a task queued by simulation from prior to shutdown
                if (isTerminated()) throw new AssertionError();
                if (executing) throw new AssertionError();
                if (debugPending != null && !debugPending.contains(task)) throw new AssertionError();
                executing = true;

                AwaitPaused done = new AwaitPaused(this);
                thread.beforeInvocation(interceptor, done);
                enqueue(task);
                done.awaitPause();
            }
        }

        public synchronized void submitUnmanaged(Runnable task)
        {
            addPending(task);
            enqueue(task);
        }

        @Override public int getActiveTaskCount()
        {
            return !queue.isEmpty() || executing ? 1 : 0;
        }

        @Override public long getCompletedTaskCount()
        {
            return 0;
        }

        @Override
        public int getPendingTaskCount()
        {
            return 0;
        }

        public ScheduledFuture<?> schedule(Runnable run, long delay, TimeUnit unit)
        {
            if (isShutdown)
                throw new RejectedExecutionException();

            long delayNanos = unit.toNanos(delay);
            return interceptorOfExecution.intercept().schedule(SCHEDULED_TASK, delayNanos, relativeToGlobalAbsoluteNanos(delayNanos), callable(run, null), this);
        }

        public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit)
        {
            if (isShutdown)
                throw new RejectedExecutionException();

            long delayNanos = unit.toNanos(delay);
            return interceptorOfExecution.intercept().schedule(SCHEDULED_TASK, delayNanos, relativeToGlobalAbsoluteNanos(delayNanos), callable, this);
        }

        public ScheduledFuture<?> scheduleTimeoutWithDelay(Runnable run, long delay, TimeUnit unit)
        {
            return scheduleTimeoutAt(run, relativeToGlobalAbsoluteNanos(unit.toNanos(delay)));
        }

        public ScheduledFuture<?> scheduleAt(Runnable run, long deadlineNanos)
        {
            if (isShutdown)
                throw new RejectedExecutionException();

            return interceptorOfExecution.intercept().schedule(SCHEDULED_TASK, absoluteToRelativeNanos(deadlineNanos), localToGlobalNanos(deadlineNanos), callable(run, null), this);
        }

        public ScheduledFuture<?> scheduleTimeoutAt(Runnable run, long deadlineNanos)
        {
            if (isShutdown)
                throw new RejectedExecutionException();

            return interceptorOfExecution.intercept().schedule(SCHEDULED_TIMEOUT, absoluteToRelativeNanos(deadlineNanos), localToGlobalNanos(deadlineNanos), callable(run, null), this);
        }

        public ScheduledFuture<?> scheduleSelfRecurring(Runnable run, long delay, TimeUnit unit)
        {
            if (isShutdown)
                throw new RejectedExecutionException();

            long delayNanos = unit.toNanos(delay);
            return interceptorOfExecution.intercept().schedule(SCHEDULED_DAEMON, delayNanos, relativeToGlobalAbsoluteNanos(delayNanos), callable(run, null), this);
        }

        public ScheduledFuture<?> scheduleAtFixedRate(Runnable run, long initialDelay, long period, TimeUnit unit)
        {
            if (isShutdown)
                throw new RejectedExecutionException();

            long delayNanos = unit.toNanos(initialDelay);
            return interceptorOfExecution.intercept().schedule(SCHEDULED_DAEMON, delayNanos, relativeToGlobalAbsoluteNanos(delayNanos), new Callable<Object>()
            {
                @Override
                public Object call()
                {
                    run.run();
                    scheduleAtFixedRate(run, period, period, unit);
                    return null;
                }

                @Override
                public String toString()
                {
                    return run.toString();
                }
            }, this);
        }

        public ScheduledFuture<?> scheduleWithFixedDelay(Runnable run, long initialDelay, long delay, TimeUnit unit)
        {
            return scheduleAtFixedRate(run, initialDelay, delay, unit);
        }

        public int concurrency()
        {
            return 1;
        }
    }

    @PerClassLoader
    class InterceptingPooledLocalAwareExecutor extends InterceptingPooledExecutor implements LocalAwareExecutorPlus
    {
        InterceptingPooledLocalAwareExecutor(InterceptorOfExecution interceptors, int concurrency, ThreadFactory threadFactory, InterceptingTaskFactory taskFactory)
        {
            super(interceptors, concurrency, threadFactory, taskFactory);
        }
    }

    @PerClassLoader
    class InterceptingLocalAwareSequentialExecutor extends InterceptingSequentialExecutor implements LocalAwareSequentialExecutorPlus
    {
        InterceptingLocalAwareSequentialExecutor(InterceptorOfExecution interceptorOfExecution, ThreadFactory threadFactory, InterceptingTaskFactory taskFactory)
        {
            super(interceptorOfExecution, threadFactory, taskFactory);
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface DWModalPresentationAnimation ()

@property (nonatomic, assign) BOOL animatorConfigured;

@end

@implementation DWModalPresentationAnimation

- (UIViewPropertyAnimator *)animatorForTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    UIViewPropertyAnimator *animator = self.animator;

    if (self.animatorConfigured) {
        return animator;
    }
    self.animatorConfigured = YES;

    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    NSParameterAssert(toView);

    UIViewController *toViewController =
        [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    NSParameterAssert(toViewController);

    const CGRect finalFrame = [transitionContext finalFrameForViewController:toViewController];

    const CGFloat heightOffset = self.style == DWModalAnimationStyle_Default
                                     ? CGRectGetHeight(finalFrame)
                                     : CGRectGetHeight([UIScreen mainScreen].bounds);

    toView.frame = CGRectOffset(finalFrame, 0.0, heightOffset);

    [animator addAnimations:^{
        toView.frame = finalFrame;
    }];

    [animator addCompletion:^(UIViewAnimatingPosition finalPosition) {
        [transitionContext completeTransition:!transitionContext.transitionWasCancelled];
    }];

    return animator;
}

@end

NS_ASSUME_NONNULL_END


text:
def readfq(fp): # this is a generator function
    last = None # this is a buffer keeping the last unprocessed line
    while True: # mimic closure; is it a bad idea?
        if not last: # the first record or a record following a fastq
            for l in fp: # search for the start of the next record
                if l[0] in '>@': # fasta/q header line
                    last = l[:-1] # save this line
                    break
        if not last: break
        name, seqs, last = last[1:].partition(" ")[0], [], None
        for l in fp: # read the sequence
            if l[0] in '@+>':
                last = l[:-1]
                break
            seqs.append(l[:-1])
        if not last or last[0] != '+': # this is a fasta record
            yield name, ''.join(seqs), None # yield a fasta record
            if not last: break
        else: # this is a fastq record
            seq, leng, seqs = ''.join(seqs), 0, []
            for l in fp: # read the quality
                seqs.append(l[:-1])
                leng += len(l) - 1
                if leng >= len(seq): # have read enough quality
                    last = None
                    yield name, seq, ''.join(seqs); # yield a fastq record
                    break
            if last: # reach EOF before reading enough quality
                yield name, seq, None # yield a fasta record instead
                break

if __name__ == "__main__":
    import sys
    n, slen, qlen = 0, 0, 0
    for name, seq, qual in readfq(sys.stdin):
        n += 1
        slen += len(seq)
        qlen += qual and len(qual) or 0
    print n, '\t', slen, '\t', qlen


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="Content-Language" content="en"/>

	<title>Emily Lewis - Web Standards Sherpa</title>
	<meta name="robots" content="index,follow,archive" />

	<meta name='description' content='Web Standards Sherpa’s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.' />
	<meta name='DC.description' content='Web Standards Sherpa’s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.' />
	<meta name='keywords' content='web standards,best practices,web design,web development' />
	<meta name='DC.subject' content='web standards,best practices,web design,web development' />

	<link rel="schema.DC" href="http://purl.org/dc/elements/1.1/" />
	<link rel="schema.DCTERMS" href="http://purl.org/dc/terms/" />
	<meta name="DC.title" content="Emily Lewis - Web Standards Sherpa" />
	<meta name="DC.creator" content="Web Standards Sherpa" />
	<meta name="DC.publisher" content="The Web Standards Project" />
	<meta name="DC.date.created" scheme="DCTERMS.W3CDTF" content="2015-12-07T14:44:17-05:00" />
	<meta name="DC.date.modified" scheme="DCTERMS.W3CDTF" content="1453-05-15T04:00:00-05:00" />
	<meta name="DC.date.valid" scheme="DCTERMS.W3CDTF" content="2015-12-13T16:44:17-05:00" />
	<meta name="DC.type" scheme="DCTERMS.DCMIType" content="Text" />
	<meta name="DC.rights" scheme="DCTERMS.URI" content="(cc) Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License">
	<meta name="Copyright" content="(cc) Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License"/>
	<meta name="DC.format" content="text/html" />
	<meta name="DC.identifier" scheme="DCTERMS.URI" content="http://webstandardssherpa.com/about/authors/emily-lewis" />
	<meta name="MSSmartTagsPreventParsing" content="true"/>
	<meta name="Rating" content="General"/>

	<meta name="viewport" content="width=device-width, initial-scale=1"/>
	<link rel="home" href="../../../index.html"/>
	<link rel="copyright" href="index.html#license"/>
	<link rel="shortcut icon" type="image/png" href="../../../favicon.png"/>
	<link rel="author" type="text/plain" href="../../../humans.txt.html"/>

		<link rel="stylesheet" type="text/css" href="../../../c/main.css" media="screen"/>

	<link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Reviews (Summary)" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Reviews-Summary"/>
	<link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Reviews (Full Text)" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Reviews"/>
	<link rel="alternate" type="application/rss+xml" title="Web Standards Sherpa Discussions" href="http://feeds.feedburner.com/Web-Standards-Sherpa-Discussions"/>

Web Standards Sherpa

Home

Reviews

Ask the Sherpas

About Us

Authors

Emily Lewis

Emily Lewis

Standardista

Emily is the owner of and lead developer for Bright Umbrella, a small web design and development studio. A standardista at heart, she is an expert in front-end development and specializes in semantics and structured data.  As part of her ongoing quest to spread the good word about standards, she is the author of Microformats Made Simple and a contributing author for HTML5 Cookbook.

In addition to loving all things web, Emily is passionate about community building and knowledge sharing. She is a co-host of the internationally-acclaimed CTRL+CLICK CAST, and she speaks at conferences and events all over the country.

Reviews by this author

(Issue No. 18)
 What’s Your CSS Style?

<time datetime="2012-02-16T11:00:25" pubdate="pubdate">16 February 2012</time>

Compatibility

CSS

Performance

Looking beyond class and id selectors, Emily explores how and when we can use attribute, child and sibling selectors in the real world through a reader-submitted portfolio, klvn.org.

(Issue No. 13)
 Making the Transition to HTML5

<time datetime="2011-08-18T15:38:01" pubdate="pubdate">18 August 2011</time>

Accessibility

Compatibility

Semantics

Interested in HTML5, but not sure where to go after changing the DOCTYPE? Emily details how a reader-submitted site, Pelizzoli World, can start using HTML5 today to add structure and semantics.

Ask the Sherpas by this author

Question About Choosing the Right CMS

			There are hundreds, if not thousands, of content management systems (CMS) and publishing tools that provide membership features. Some are out-of-the-box solutions and some must be customized per…

Question About Choosing a Structured Data Technology

			Answering this question is really about goals: your goals as a developer, your employer’s or client’s goals, and project goals. But before answering that question, let’s first talk about what&…

This Week

Issue No. 38

Sass for Big Sites, Part 2

by Jackie Balzer

In part 2 of our series on Sass for large sites and teams, Jackie shares how Behance maintains a living Style Guide and documents its code base.

Begin the climb

Topics

Accessibility

Business

Compatibility

Content

CSS

Design / UX

HTML

Javascript

Performance

Semantics

Usability

Workflow / Process

Follow us

Twitter

Facebook

Google+

RSS

  		<form style="display: none" id="search-form" method="post" action="../../../index.html"  >

<input type="hidden" name="ACT" value="6" />
<input type="hidden" name="XID" value="3e0d24668905e5d75c6172fb969fac94d8257421" />
<input type="hidden" name="RES" value="10" />
<input type="hidden" name="meta" value="vJed+IEhaFn3W7jNVVY8C6VK4KKB0doGerxtt+3TXJkJkrK5M3OFhLNfv7UrH+uJhVYy/SM2Y8CEBzxS9ZAY+5Ry234MoWdF0KwpptDKKX/rJJg1NP4Y7SntDPwMKWd0mrV/+nbWgdpLXyGAXHtWDd/W8QMHWePL8qfhqCpJzaK4pU2LxFEhOj26ZDN4P+8d8hXffYqEVMiMRDrkUYAlZAa+r08a/igafmWKpfXqcmFAHWq/qsh+zoaTz9V6wiUJl2MMAdfHTEZ76nZbWvE5NUZpcvtxRexke8gSzhsFUK46dJJ8pJfmOvPccKB8bfwmBU4cgAZ668OleVhPUZRHiYhGfX21C2DodUFydLdhuEPR2Upj1jdw5RfdVF8nWXwA5G5T4DRd4xKMtKvVvr1BpJKZ37Gid+DBZjiqIcAhYCY=" />
<input type="hidden" name="site_id" value="1" />

			Looking for something?
			<input type="search" name="keywords" id="query" value=""/>
			<button type="submit">Search</button>

	</form>

Sign up

Log in

Web Standards Sherpa’s experts provide helpful, pragmatic and up-to-date advice on best practices for web professionals everywhere.

More about us

Contact us

Participate

Submit a site

Submit a question

Sign upLog in

Learn

Reviews

Ask Sherpas

Authors

Glossary

We thank our sponsors

Web Standards Sherpa is an outreach effort by the Web Standards Project (WaSP).

The content of this site is licensed under Creative Commons.


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_Security_Cryptography_AsymmetricSi3580832979.h"

// System.Security.Cryptography.DSA
struct DSA_t903174880;

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// System.Security.Cryptography.DSASignatureDeformatter
struct  DSASignatureDeformatter_t2187578719  : public AsymmetricSignatureDeformatter_t3580832979
{
public:
	// System.Security.Cryptography.DSA System.Security.Cryptography.DSASignatureDeformatter::dsa
	DSA_t903174880 * ___dsa_0;

public:
	inline static int32_t get_offset_of_dsa_0() { return static_cast<int32_t>(offsetof(DSASignatureDeformatter_t2187578719, ___dsa_0)); }
	inline DSA_t903174880 * get_dsa_0() const { return ___dsa_0; }
	inline DSA_t903174880 ** get_address_of_dsa_0() { return &___dsa_0; }
	inline void set_dsa_0(DSA_t903174880 * value)
	{
		___dsa_0 = value;
		Il2CppCodeGenWriteBarrier(&___dsa_0, value);
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
function RangeController ($scope) {
  'ngInject';

  var vm = this;

  vm.startTimeOpen = false;
  vm.endTimeOpen = false;

  vm.openStartTime = () => {
    vm.startTimeOpen = true;
    vm.endTimeOpen = false;
  };

  vm.openEndTime = () => {
    vm.startTimeOpen = false;
    vm.endTimeOpen = true;
  };

  vm.done = () => {
    vm.close();
    $scope.onDone();
  };

  vm.close = () => {
    vm.startTimeOpen = false;
    vm.endTimeOpen = false;
  };

  let keydownListener = (event) => {
    if (event.keyCode !== 27) { return; }
    vm.close();
  };

  document.addEventListener('keydown', keydownListener);
  document.body.addEventListener('click', vm.close, false);

  $scope.$on('$destroy', () => {
    document.removeEventListener('keydown', keydownListener);
    document.body.removeEventListener('click', vm.close, false);
  });
}

angular.module(PKG.name+'.commons')
  .directive('myDatetimeRange', () => {
    return {
      restrict: 'E',
      scope: {
        dateRange: '=',
        onDone: '&'
      },
      controller: RangeController,
      controllerAs: 'RangeController',
      templateUrl: 'datetime-range/datetime-range.html'
    };
  });


text:
topic: sample
languages:
- js
products:
- windows
- windows-uwp
---

# Custom Capability sample

Shows the use of custom capabilities.

Note that the SCCD file included with this sample is not valid,
but it is included for instructional purposes.
If the PC is Developer Mode, the sample will deploy despite the invalid SCCD file.
When writing your own app, follow the instructions in
[Custom Capabilities for Universal Windows Platform apps](https://msdn.microsoft.com/windows/hardware/drivers/devapps/custom-capabilities-for-universal-windows-platform-apps)
to obtain a properly-signed SCCD file.

## Using a custom capability to connect to an NT service

The "Connect to an NT service" scenario uses a custom capability
to control access to an NT service.
For demonstration purposes, the service reads data from an imaginary device.

The scenario demonstrates the following:

- Declaring a custom capability "microsoft.hsaTestCustomCapability_q536wpkpf5cy2" in the manifest.
- Establishing an RPC connection to the NT service.
- Invoking methods over RPC to initiate data collection and alter the sampling period.
- Using an RPC callback to receive data from the imaginary device.

The service portion of this sample demonstrates the following:

- Converting the capability string to a SID using the `DeriveCapabilitySidsFromName` function.
- Using that SID to create the Security Descriptor for the RPC endpoint.

The following diagram summarizes the communication between the app and the NT service:

```sh
                  CLIENT                                   SERVER
         ------------------------                     -----------------
         |                      |                     |               |
         | CustomCapability.exe |                     | RpcServer.exe |
         |                      |                     |               |
         ------------------------                     -----------------
                    |                                         |
                    |                                         |
 Click Start button |-------------StartMetering-------------->|
                    |            [Blocking call]              |
                    |                                         |
                    |                                         |
 Updates Sample     |<------------MeteringData----------------|
 text box           |  [Sent at choosen sample period]        |
                    |                                         |
                    |                                         |
 Move the sample    |-----------SetSamplePeriod-------------->|
 period slider      |<-------SetSamplePeriod completes--------|
                    |                                         |
 Click Stop button  |-------------StopMetering--------------->|
                    |<--------StopMetering completes----------|
                    |                                         |
                    |<-------StartMetering completes----------|
                    |                                         |
```

Before you run this scenario, you must start the corresponding NT service.

* Build the NT service portion of the sample, which requires that the Windows SDK for Desktop C++ Apps be installed.
* Start the service from an elevated command prompt in one of two ways:
  * Install it as a service using `rpcserver.exe -install` and start it using `sc start hsaservice`.
  * Run the service in console mode: `rpcserver.exe -console`

## Using a custom capability to access a custom device

A series of scenarios demonstrate how to use a custom capability to access the
OSR USB FX-2 Learning Kit device.
The code for the OSR USB FX-2 driver can be found in the
[Microsoft Windows-driver-samples repo](https://github.com/Microsoft/Windows-driver-samples/)
under
[usb/umdf2_fx2/driver](https://github.com/Microsoft/Windows-driver-samples/tree/master/usb/umdf2_fx2/driver).
The driver must be built for Windows 10 version 1703 or higher in order to support
the custom capability used by this sample.

The "Connect to the OSR FX-2 device" scenario demonstrates the following:

- Declaring a custom capability "microsoft.hsaTestCustomCapability_q536wpkpf5cy2" in the manifest.
- Updating driver code or driver INF to enable access to driver interface using the custom capability
- Using a `DeviceWatcher` to enumerate OSR FX-2 devices by using its device interface GUID.
- Using the `CustomDevice.FromIdAsync` method to access a particular instance of the device.

The "Send IOCTLs to the device" scenario demonstrates the following:

- Sending an IOCTL to the device to set the 7 segment LED value.
- Sending an IOCTL to the device to get the 7 segment LED value.
  - The values and meanings of I/O control codes are defined by the device.

The "Handle asynchronous device events" scenario demonstrates the following:

- Sending an IOCTL that does not complete until the DIP switches change.
- Canceling the task which is waiting for the switches to change.
- Sending an IOCTL to read the current state of the switches.
  - The values and meanings of I/O control codes are defined by the device.

To use this scenario, click "Begin Receiving Switch Change Events" and then
change the DIP switches. The app displays the state of the switches when they
change. You can also click "Get Switch State" to read the switch state immediately.

The "Read and Write operations" scenario demonstrates the following:

- Writing data to the device's internal memory by writing to its OutputStream.
- Reading data from the device's internal memory by reading from its InputStream.

Each time you click "Write Block", a message is written to the device,
and each time you click "Read Block", a message is read from the device.
The OSR FX-2 has four message buffers.
When they are full, the next write operation will wait until a message is read,
thereby freeing up a message buffer.
When they are empty, the next read operation will wait until a message is written.

## Raising Custom System Event Trigger

Demonstrates how to register background task with the CustomSystemEventTrigger type and
raise a custom system event when an OSR FX-2 device is connected to a system. The code to
raise the event is part of the OSR FX-2 driver. This enables custom devices/NT services to raise a custom system event which triggers a background task.

The code for the OSR USB FX-2 driver can be found in the
[Microsoft Windows-driver-samples repo](https://github.com/Microsoft/Windows-driver-samples/)
under
[usb/kmdf_fx2/driver](https://github.com/Microsoft/Windows-driver-samples/tree/master/usb/kmdf_fx2).
The driver must be built for Windows 10 version 1803 or higher in order to support
the custom system event trigger used by this sample.

## Firmware access

Declaring the restricted capability `smbios` allows apps to read the SMBIOS.
Call the
[GetSystemFirmwareTable](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724379(v=vs.85).aspx)
and
[EnumSystemFirmwareTables](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724259(v=vs.85).aspx)
functions with the 'RSMB' (Raw SMBIOS) table provider.

The following custom capabilities can be used for accessing UEFI variables:

- `microsoft.firmwareRead_cw5n1h2txyewy`: Read UEFI variables using [GetFirmwareEnvironmentVariable](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724325(v=vs.85).aspx)
- `microsoft.firmwareWrite_cw5n1h2txyewy`: Read/Write UEFI variables using [SetFirmwareEnvironmentVariable](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724934(v=vs.85).aspx)

UEFI access also requires the app to declare 'protectedApp' restricted capability and enable [INTEGRITYCHECK](https://docs.microsoft.com/en-us/cpp/build/reference/integritycheck-require-signature-check) for the project. This would trigger necessary store signing for protected apps during store submission. Currently the [INTEGRITYCHECK](https://docs.microsoft.com/en-us/cpp/build/reference/integritycheck-require-signature-check) can only be enabled on C++ projects properties.

UEFI variables can be accessed only when the app is being used by a user belonging to Administrators group.

**Note** The Windows universal samples require Visual Studio 2017 to build and Windows 10 to execute.

To obtain information about Windows 10 development, go to the [Windows Dev Center](http://go.microsoft.com/fwlink/?LinkID=532421)

To obtain information about Microsoft Visual Studio and the tools for developing Windows apps, go to [Visual Studio](http://go.microsoft.com/fwlink/?LinkID=532422)

## Related topics

### Samples

* [IoT-GPIO](/Samples/IoT-GPIO)
* [IoT-I2C](/Samples/IoT-I2C)
* [IoT-SPI](/Samples/IoT-SPI)
* [Custom HID device access](/Samples/CustomHidDeviceAccess)
* [Custom serial device access](/Samples/CustomSerialDeviceAccess)
* [Custom USB device access](/Samples/CustomUsbDeviceAccess)

### Reference

* [Windows.Devices.Custom.CustomDevice runtime class](https://msdn.microsoft.com/library/windows/apps/windows.devices.custom.customdevice.aspx) class
* The [Custom driver access sample](https://code.msdn.microsoft.com/windowsapps/Custom-device-access-sample-43bde679)
  sample has been converted to a Windows 10 app.
* [How to use RPC callbacks](https://support.microsoft.com/kb/96781)
* [Custom Capabilities for Universal Windows Platform apps](https://msdn.microsoft.com/windows/hardware/drivers/devapps/custom-capabilities-for-universal-windows-platform-apps)
* [Hardware access for Universal Windows Platform apps](https://msdn.microsoft.com/windows/hardware/drivers/devapps/hardware-access-for-universal-windows-platform-apps)

## System requirements

**Client:** Windows 10 version 1703

**Server:** Windows Server 2016 Technical Preview

**Phone:** Windows 10 version 1703

## Build the sample

1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with the sample you want to build.
2. Start Microsoft Visual Studio 2017 and select **File** \> **Open** \> **Project/Solution**.
3. Starting in the folder where you unzipped the samples, go to the Samples subfolder, then the subfolder for this specific sample, then the subfolder for your preferred language (C++, C#, or JavaScript). Double-click the Visual Studio 2017 Solution (.sln) file.
4. Press Ctrl+Shift+B, or select **Build** \> **Build Solution**.

## Run the sample

The next steps depend on whether you just want to deploy the sample or you want to both deploy and run it.

### Deploying the sample

- Select Build > Deploy Solution.

### Deploying and running the sample

- To debug the sample and then run it, press F5 or select Debug >  Start Debugging. To run the sample without debugging, press Ctrl+F5 or select Debug > Start Without Debugging.
- To run the "Connect to an NT service" scenario, see additional instructions above.

### Modifying the sample

- If you modify the sample, make sure to [change the interface ID in `RpcInterface.idl`](Service/Interface/RpcInterface.idl#L15), because interface IDs must be unique.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Steamworks
{
    [TestClass]
    [DeploymentItem( "steam_api64.dll" )]
	[DeploymentItem( "steam_api.dll" )]
	public partial class ServerListTest
    {
        [TestMethod]
        public void IpAddressConversions()
        {
            var ipstr = "185.38.150.40";
            var ip = IPAddress.Parse( ipstr );

            var ip_int = Utility.IpToInt32( ip );

            var ip_back = Utility.Int32ToIp( ip_int );

            Console.WriteLine( "ipstr: " + ipstr );
            Console.WriteLine( "ip: " + ip );
            Console.WriteLine( "ip int: " + ip_int );
            Console.WriteLine( "ip_back: " + ip_back );
        }

        [TestMethod]
        public async Task ServerListInternetInterupted()
        {
			using ( var list = new ServerList.Internet() )
			{
				var task = list.RunQueryAsync();

				await Task.Delay( 1000 );

				Console.WriteLine( $"Querying.." );

				list.Cancel();

				foreach ( var s in list.Responsive )
				{
					Console.WriteLine( $"{s.Address} {s.Name}" );
				}

				Console.WriteLine( $"Found {list.Responsive.Count} Responsive Servers" );
				Console.WriteLine( $"Found {list.Unresponsive.Count} Unresponsive Servers" );
				Console.WriteLine( $"task.IsCompleted {task.IsCompleted}" );

			}
		}

		[TestMethod]
		public async Task ServerListInternet()
		{
			using ( var list = new ServerList.Internet() )
			{
				var success = await list.RunQueryAsync();

				Console.WriteLine( $"success {success}" );
				Console.WriteLine( $"Found {list.Responsive.Count} Responsive Servers" );
				Console.WriteLine( $"Found {list.Unresponsive.Count} Unresponsive Servers" );
			}
		}

		[TestMethod]
		public async Task SourceQuery()
		{
			using ( var list = new ServerList.Internet() )
			{
				var task = list.RunQueryAsync();
				await Task.Delay( 1000 );
				list.Cancel();

				foreach ( var s in list.Responsive.Take( 10 ).ToArray() )
				{
					Console.WriteLine( $"{s.Name} [{s.Address}]" );

					var rules = await s.QueryRulesAsync();
					Assert.IsNotNull( rules );

					foreach ( var rule in rules )
					{
						Console.WriteLine( $"	{rule.Key}  = {rule.Value}" );
					}
				}
			}
		}

		[TestMethod]
		public async Task ServerListLan()
		{
			using ( var list = new ServerList.LocalNetwork() )
			{
				var success = await list.RunQueryAsync();

				Console.WriteLine( $"success {success}" );
				Console.WriteLine( $"Found {list.Responsive.Count} Responsive Servers" );
				Console.WriteLine( $"Found {list.Unresponsive.Count} Unresponsive Servers" );
			}
		}

		[TestMethod]
		public async Task ServerListFavourites()
		{
			using ( var list = new ServerList.Favourites() )
			{
				var success = await list.RunQueryAsync();

				Console.WriteLine( $"success {success}" );
				Console.WriteLine( $"Found {list.Responsive.Count} Responsive Servers" );
				Console.WriteLine( $"Found {list.Unresponsive.Count} Unresponsive Servers" );
			}
		}

		[TestMethod]
		public async Task ServerListFriends()
		{
			using ( var list = new ServerList.Friends() )
			{
				var success = await list.RunQueryAsync();

				Console.WriteLine( $"success {success}" );
				Console.WriteLine( $"Found {list.Responsive.Count} Responsive Servers" );
				Console.WriteLine( $"Found {list.Unresponsive.Count} Unresponsive Servers" );
			}
		}

		[TestMethod]
		public async Task ServerListHistory()
		{
			using ( var list = new ServerList.History() )
			{
				var success = await list.RunQueryAsync();

				Console.WriteLine( $"success {success}" );
				Console.WriteLine( $"Found {list.Responsive.Count} Responsive Servers" );
				Console.WriteLine( $"Found {list.Unresponsive.Count} Unresponsive Servers" );
			}
		}

		[TestMethod]
		public async Task FilterByMap()
		{
			using ( var list = new ServerList.Internet() )
			{
				list.AddFilter( "map", "de_dust" );

				var success = await list.RunQueryAsync();

				Console.WriteLine( $"success {success}" );
				Console.WriteLine( $"Found {list.Responsive.Count} Responsive Servers" );
				Console.WriteLine( $"Found {list.Unresponsive.Count} Unresponsive Servers" );

				foreach ( var server in list.Responsive )
				{
					Assert.AreEqual( server.Map.ToLower(), "de_dust" );

					Console.WriteLine( $"[{server.Map}] - {server.Name}" );
				}
			}
		}

		[TestMethod]
		public async Task ServerListIps()
		{
			var ips = new string[]
			{
				"31.186.251.76",
				"31.186.251.76",
				"31.186.251.76",
				"31.186.251.76",
				"31.186.251.76",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"139.99.144.70",
				"139.99.144.70",
				"139.99.144.70",
				"139.99.144.70",
				"139.99.144.70",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"74.91.119.142",
				"95.172.92.176",
				"95.172.92.176",
				"95.172.92.176",
				"95.172.92.176",
				"95.172.92.176",
				"164.132.205.154",
				"164.132.205.154",
				"164.132.205.154",
				"164.132.205.154",
				"164.132.205.154",
			};

			using ( var list = new ServerList.IpList( ips ) )
			{
				var success = await list.RunQueryAsync();

				Console.WriteLine( $"success {success}" );
				Console.WriteLine( $"Found {list.Responsive.Count} Responsive Servers" );
				Console.WriteLine( $"Found {list.Unresponsive.Count} Unresponsive Servers" );

				Assert.AreNotEqual( list.Responsive.Count, 0 );

				foreach ( var server in list.Responsive )
				{
					Console.WriteLine( $"[{server.Address}:{server.ConnectionPort}] - {server.Name}" );
				}
			}
		}
	}
}


text:
'use strict';

/**
 * @ngdoc service
 * @name stockDogApp.CompanyService
 * @description
 * # CompanyService
 * Service in the stockDogApp.
 */
angular.module('stockDogApp')
  .service('CompanyService', function CompanyService($resource) {
    return $resource('companies.json');
  });


text:
"use strict";
var path_1 = require('path');
var Builder = require('systemjs-builder');
var config_1 = require('../config');
var BUNDLER_OPTIONS = {
    format: 'cjs',
    minify: true,
    mangle: false
};
module.exports = function bundles(gulp, plugins) {
    return function (done) {
        var builder = new Builder(config_1.SYSTEM_BUILDER_CONFIG);
        builder
            .buildStatic(path_1.join(config_1.TMP_DIR, config_1.BOOTSTRAP_MODULE), path_1.join(config_1.JS_DEST, config_1.JS_PROD_APP_BUNDLE), BUNDLER_OPTIONS)
            .then(function () { return done(); });
    };
};


text:
package de.jakop.mathetrainer.common.ui;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JPanel;

import de.jakop.mathetrainer.common.logic.Controller;
import de.jakop.mathetrainer.common.logic.Model;

public class ApplicationFrame extends JFrame {

	private static final long serialVersionUID = 3549123919945092574L;

	public ApplicationFrame(final JPanel configurationPanel, final Model model, final Controller controller, final InputPanel inputPanel, final HistoryPanel historyPanel) {

		setLayout(new GridBagLayout());
		final GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0);
		gbc.weightx = 1.0;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.weighty = 0.0;
		getContentPane().add(configurationPanel, gbc);
		gbc.gridy++;
		gbc.weighty = 1.0;
		gbc.fill = GridBagConstraints.BOTH;
		getContentPane().add(historyPanel, gbc);
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.gridy++;
		gbc.weighty = 0.0;
		getContentPane().add(inputPanel, gbc);

		getRootPane().setDefaultButton(inputPanel.getSubmitButton());
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Xerocomus albotessellatus Heinem.

### Remarks
null


text:
package org.netbeans.editor;

import javax.swing.text.BadLocationException;
import javax.swing.text.Caret;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.beans.PropertyChangeListener;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
* Find management
*
* @author Miloslav Metelka
* @version 1.00
*/

public class FindSupport {

    private static final String FOUND_LOCALE = "find-found"; // NOI18N
    private static final String NOT_FOUND_LOCALE = "find-not-found"; // NOI18N
    private static final String WRAP_START_LOCALE = "find-wrap-start"; // NOI18N
    private static final String WRAP_END_LOCALE = "find-wrap-end"; // NOI18N
    private static final String ITEMS_REPLACED_LOCALE = "find-items-replaced"; // NOI18N
    public static final String REVERT_MAP = "revert-map"; // NOI18N

    /** Shared instance of FindSupport class */
    static FindSupport findSupport;

    /** Find properties */
    private Map findProps;

    /** Support for firing change events */
    WeakPropertyChangeSupport changeSupport
    = new WeakPropertyChangeSupport();

    /** Current finder creator.
    * It can be changed by setFinderCreator.
    */
    FinderCreator finderCreator;

    /** Were the find properties already initialized
    * from settings?
    */
    private boolean findPropsInited;

    private FindSupport() {
        // prevent instance creation
    }

    /** Get shared instance of find support */
    public static FindSupport getFindSupport() {
        if (findSupport == null) {
            findSupport = new FindSupport();
        }
        return findSupport;
    }

    /** Get current finder creator */
    public FinderCreator getFinderCreator() {
        if (finderCreator == null) {
            finderCreator = new DefaultFinderCreator();
        }
        return finderCreator;
    }

    /** Set customized finder creator */
    public void setFinderCreator(FinderCreator finderCreator) {
        this.finderCreator = finderCreator;
        firePropertyChange(null, null, null);
    }

    public Map getDefaultFindProperties() {
        HashMap props = new HashMap();
        Class kitClass = BaseKit.class;
        props.put(SettingsNames.FIND_WHAT, Settings.getValue(
                      kitClass, SettingsNames.FIND_WHAT));
        props.put(SettingsNames.FIND_REPLACE_WITH, Settings.getValue(
                      kitClass, SettingsNames.FIND_REPLACE_WITH));
        props.put(SettingsNames.FIND_HIGHLIGHT_SEARCH, Settings.getValue(
                      kitClass, SettingsNames.FIND_HIGHLIGHT_SEARCH));
        props.put(SettingsNames.FIND_INC_SEARCH, Settings.getValue(
                      kitClass, SettingsNames.FIND_INC_SEARCH));
        props.put(SettingsNames.FIND_BACKWARD_SEARCH, Settings.getValue(
                      kitClass, SettingsNames.FIND_BACKWARD_SEARCH));
        props.put(SettingsNames.FIND_WRAP_SEARCH, Settings.getValue(
                      kitClass, SettingsNames.FIND_WRAP_SEARCH));
        props.put(SettingsNames.FIND_MATCH_CASE, Settings.getValue(
                      kitClass, SettingsNames.FIND_MATCH_CASE));
        props.put(SettingsNames.FIND_WHOLE_WORDS, Settings.getValue(
                      kitClass, SettingsNames.FIND_WHOLE_WORDS));
        props.put(SettingsNames.FIND_REG_EXP, Settings.getValue(
                      kitClass, SettingsNames.FIND_REG_EXP));
        props.put(SettingsNames.FIND_HISTORY, Settings.getValue(
                      kitClass, SettingsNames.FIND_HISTORY));

        return props;
    }

    public Map getFindProperties() {
        if (findProps == null) {
            findProps = getDefaultFindProperties();
        }
        return findProps;
    }

    /** Get find property with specified name */
    public Object getFindProperty(String name) {
        return getFindProperties().get(name);
    }

    private Map getValidFindProperties(Map props) {
        return (props != null) ? props : getFindProperties();
    }

    /** Get finder depending on find properties */
    public FinderFactory.StringFinder getStringFinder(BaseDocument doc, Map props) {
        FinderFactory.StringFinder stringFinder
        = (FinderFactory.StringFinder)doc.getProperty(BaseDocument.STRING_FINDER_PROP);

        if (stringFinder == null) {
            stringFinder = getFinderCreator().createFinder(doc,
                           getValidFindProperties(props));
            doc.putProperty(BaseDocument.STRING_FINDER_PROP, stringFinder);
        }

        return stringFinder;
    }

    /** Get opposite direction finder depending on find properties */
    public FinderFactory.StringFinder getStringBwdFinder(BaseDocument doc, Map props) {
        FinderFactory.StringFinder stringBwdFinder
        = (FinderFactory.StringFinder)doc.getProperty(BaseDocument.STRING_BWD_FINDER_PROP);

        if (stringBwdFinder == null) {
            stringBwdFinder = getFinderCreator().createBwdFinder(doc,
                              getValidFindProperties(props));
            doc.putProperty(BaseDocument.STRING_BWD_FINDER_PROP, stringBwdFinder);
        }

        return stringBwdFinder;
    }

    /** Get position pairs finder depending on find properties */
    public FinderFactory.BlocksFinder getBlocksFinder(BaseDocument doc, Map props) {
        FinderFactory.BlocksFinder blocksFinder
        = (FinderFactory.BlocksFinder)doc.getProperty(BaseDocument.BLOCKS_FINDER_PROP);

        if (blocksFinder == null) {
            blocksFinder = getFinderCreator().createBlocksFinder(doc,
                           getValidFindProperties(props));
        }
        return blocksFinder;
    }

    int[] getBlocks(int[] blocks, BaseDocument doc,
                    int startPos, int endPos) throws BadLocationException {
        FinderFactory.BlocksFinder ppf = getBlocksFinder(doc, null);
        if (ppf == null) { // not yet assigned
            return blocks;
        }
        synchronized (ppf) {
            ppf.setBlocks(blocks);
            doc.find(ppf, startPos, endPos);
            return ppf.getBlocks();
        }
    }

    /** Get find property without performing initialization
    * of find properties. This is useful for example for base document
    * when it wants to query whether it should do highlight search.
    */
    Object getPropertyNoInit(String name) {
        if (findProps == null) {
            return null;
        } else {
            return getFindProperty(name);
        }
    }

    /** Set find property with specified name and fire change.
    */
    public void putFindProperty(String name, Object newValue) {
        Object oldValue = getFindProperty(name);
        if ((oldValue == null && newValue == null)
                || (oldValue != null && oldValue.equals(newValue))
           ) {
            return;
        }
        if (newValue != null) {
            getFindProperties().put(name, newValue);
        } else {
            getFindProperties().remove(name);
        }
        firePropertyChange(name, oldValue, newValue);
    }

    /** Add/replace properties from some other map
    * to current find properties. If the added properties
    * are different than the original ones,
    * the property change is fired.
    */
    public void putFindProperties(Map propsToAdd) {
        if (!getFindProperties().equals(propsToAdd)) {
            getFindProperties().putAll(propsToAdd);
            firePropertyChange(null, null, null);
        }
    }

    public boolean incSearch(Map props) {
        props = getValidFindProperties(props);
        Boolean b = (Boolean)props.get(SettingsNames.FIND_INC_SEARCH);
        if (b != null && b.booleanValue()) { // inc search enabled
            JTextComponent c = Utilities.getLastActiveComponent();
            if (c != null) {
                Caret caret = c.getCaret();
                BaseDocument doc = (BaseDocument)c.getDocument();
                int dot = caret.getDot();
                Finder finder = getFinderCreator().createFinder(doc, props);
                int pos;
                try {
                    b = (Boolean)props.get(SettingsNames.FIND_BACKWARD_SEARCH);
                    boolean back = (b != null && b.booleanValue());
                    if (back) {
                        pos = doc.find(finder, dot, 0); // !!! handle wrap search
                    } else {
                        pos = doc.find(finder, dot, -1); // !!! handle wrap search
                    }
                } catch (BadLocationException e) {
                    if (Boolean.getBoolean("netbeans.debug.exceptions")) { // NOI18N
                        e.printStackTrace();
                    }
                    return false;
                }

                // possibly create incSearch layer
                BaseTextUI ui = (BaseTextUI)c.getUI();
                EditorUI editorUI = ui.getEditorUI();
                DrawLayerFactory.IncSearchLayer incLayer
                = (DrawLayerFactory.IncSearchLayer)editorUI.findLayer(
                      DrawLayerFactory.INC_SEARCH_LAYER_NAME);
                if (incLayer == null) {
                    incLayer = new DrawLayerFactory.IncSearchLayer();
                    if (!editorUI.addLayer(incLayer,
                        DrawLayerFactory.INC_SEARCH_LAYER_VISIBILITY)
                    ) {
                        return false; // couldn't add layer
                    }
                } else {
                    if (incLayer.isEnabled()) {
                        incLayer.setEnabled(false);
                        try {
                            editorUI.repaintOffset(incLayer.getOffset());
                        } catch (BadLocationException e) {
                            if (Boolean.getBoolean("netbeans.debug.exceptions")) { // NOI18N
                                e.printStackTrace();
                            }
                        }
                    }
                }

                if (pos >= 0) {
                    String s = (String)props.get(SettingsNames.FIND_WHAT);
                    int len = (s != null) ? s.length() : 0;
                    if (len > 0) {
                        incLayer.setEnabled(true);
                        incLayer.setArea(pos, len);
                        try {
                            Rectangle r0 = (Rectangle)ui.modelToView(c, pos, null);
                            Rectangle r = (Rectangle)ui.modelToView(c, pos + len, null);
                            r.add(r0);
                            editorUI.repaintOffset(pos);
                            editorUI.scrollRectToVisible(r, EditorUI.SCROLL_DEFAULT);
                        } catch (BadLocationException e) {
                            if (Boolean.getBoolean("netbeans.debug.exceptions")) { // NOI18N
                                e.printStackTrace();
                                return false;
                            }
                        }
                        return true;
                    }
                } else { // string not found
                    // !!!          ((BaseCaret)c.getCaret()).dispatchUpdate();
                }
            }
        } else { // inc search not enabled
            incSearchReset();
        }
        return false;
    }

    public void incSearchReset() {
        JTextComponent c = Utilities.getLastActiveComponent();
        if (c==null) return; //  #19558 bugfix. Editor window has been closed => c==null
        EditorUI editorUI = ((BaseTextUI)c.getUI()).getEditorUI();
        DrawLayerFactory.IncSearchLayer incLayer
        = (DrawLayerFactory.IncSearchLayer)editorUI.findLayer(
              DrawLayerFactory.INC_SEARCH_LAYER_NAME);
        if (incLayer != null) {
            if (incLayer.isEnabled()) {
                incLayer.setEnabled(false);
                try {
                    editorUI.repaintOffset(incLayer.getOffset());
                } catch (BadLocationException e) {
                    if (Boolean.getBoolean("netbeans.debug.exceptions")) { // NOI18N
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private boolean isBackSearch(Map props, boolean oppositeDir) {
        Boolean b = (Boolean)props.get(SettingsNames.FIND_BACKWARD_SEARCH);
        boolean back = (b != null && b.booleanValue());
        if (oppositeDir) {
            back = !back;
        }
        return back;
    }

    /** Find the text from the caret position.
    * @param props search properties
    * @param oppositeDir whether search in opposite direction
    */
    public boolean find(Map props, boolean oppositeDir) {
        incSearchReset();
        props = getValidFindProperties(props);
        boolean back = isBackSearch(props, oppositeDir);
        JTextComponent c = Utilities.getLastActiveComponent();
        Object findWhat = props.get(SettingsNames.FIND_WHAT);
        if (findWhat == null) { // nothing to search for
            return true;
        }

        String exp = "'" + findWhat + "' "; // NOI18N
        if (c != null) {
            Utilities.clearStatusText(c);
            Caret caret = c.getCaret();
            int dotPos = caret.getDot();
            try {
                int[] blk = findInBlock(c, dotPos, 0, -1, props, oppositeDir);
                if (blk != null) {
                    if (caret instanceof BaseCaret) { // support extended scroll mode
                        BaseCaret bCaret = (BaseCaret)caret;
                        if (back) { // back direction
                            bCaret.setDot(blk[1], bCaret, EditorUI.SCROLL_FIND);
                            bCaret.moveDot(blk[0], bCaret, EditorUI.SCROLL_FIND);

                        } else { // forward direction
                            bCaret.setDot(blk[0], bCaret, EditorUI.SCROLL_FIND);
                            bCaret.moveDot(blk[1], bCaret, EditorUI.SCROLL_FIND);
                        }

                    } else { // regular caret
                        if (back) {
                            caret.setDot(blk[1]);
                            caret.moveDot(blk[0]);
                        } else { // forward direction
                            caret.setDot(blk[0]);
                            caret.moveDot(blk[1]);
                        }
                    }

                    JumpList.checkAddEntry();
                    String msg = exp + LocaleSupport.getString(FOUND_LOCALE)
                                 + ' ' + Utilities.debugPosition((BaseDocument)c.getDocument(), blk[0]);
                    if (blk[2] == 1) { // wrap was done
                        msg += "; "; // NOI18N
                        msg += back ? LocaleSupport.getString(WRAP_END_LOCALE)
                               : LocaleSupport.getString(WRAP_START_LOCALE);

                        Utilities.setStatusBoldText(c, msg);
                    } else {
                        Utilities.setStatusText(c, msg);
                    }
                    return true;
                } else { // not found
                    Utilities.setStatusBoldText(c, exp + LocaleSupport.getString(
                                                    NOT_FOUND_LOCALE));
                    // issue 14189 - selection was not removed
                    c.getCaret().setDot(c.getCaret().getDot());
                }
            } catch (BadLocationException e) {
                if (Boolean.getBoolean("netbeans.debug.exceptions")) { // NOI18N
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /** Find the searched expression
    * @param startPos position from which to search. It must be inside the block.
    * @param blockStartPos starting position of the block. It must
    *   be valid position greater or equal than zero. It must be lower than
    *   or equal to blockEndPos (except blockEndPos=-1).
    * @param blockEndPos ending position of the block. It can be -1 for the end
    *   of document. It must be greater or equal than blockStartPos (except blockEndPos=-1).
    * @param props search properties
    * @param oppositeDir whether search in opposite direction
    * @param displayWrap whether display messages about the wrapping
    * @return either null when nothing was found or integer array with three members
    *    ret[0] - starting position of the found string
    *    ret[1] - ending position of the found string
    *    ret[2] - 1 or 0 when wrap was or wasn't performed in order to find the string
    */
    public int[] findInBlock(JTextComponent c, int startPos, int blockStartPos,
                             int blockEndPos, Map props, boolean oppositeDir) throws BadLocationException {
        if (c != null) {
            props = getValidFindProperties(props);
            BaseDocument doc = (BaseDocument)c.getDocument();
            FinderFactory.StringFinder sf
            = oppositeDir ? getStringBwdFinder(doc, props)
              : getStringFinder(doc, props);
            int pos = -1;
            boolean wrapDone = false;

            boolean back = isBackSearch(props, oppositeDir);
            Boolean b = (Boolean)props.get(SettingsNames.FIND_WRAP_SEARCH);
            boolean wrap = (b != null && b.booleanValue());
            int docLen = doc.getLength();
            if (blockEndPos == -1) {
                blockEndPos = docLen;
            }

            while (true) {
                pos = doc.find(sf, startPos, back ? blockStartPos : blockEndPos);
                if (pos != -1) {
                    break;
                }

                if (wrap) {
                    if (back) {
                        //Bug #20552 the wrap search check whole document
                        //instead of just the remaining not-searched part to be
                        //able to find expressions with the cursor in it

                        //blockStartPos = startPos;
                        startPos = blockEndPos;
                    } else {
                        //blockEndPos = startPos;
                        startPos = blockStartPos;
                    }
                    wrapDone = true;
                    wrap = false; // only one loop
                } else { // no wrap set
                    break;
                }

            }

            if (pos != -1) {
                int[] ret = new int[3];
                ret[0] = pos;
                ret[1] = pos + sf.getFoundLength();
                ret[2] = wrapDone ? 1 : 0;
                return ret;
            }
        }
        return null;
    }

    public boolean replace(Map props, boolean oppositeDir)
    throws BadLocationException {
        incSearchReset();
        props = getValidFindProperties(props);
        Boolean b = (Boolean)props.get(SettingsNames.FIND_BACKWARD_SEARCH);
        boolean back = (b != null && b.booleanValue());
        if (oppositeDir) {
            back = !back;
        }

        JTextComponent c = Utilities.getLastActiveComponent();
        if (c != null) {
            Caret caret = c.getCaret();
            if (!caret.isSelectionVisible()) {
                if (!find(props, oppositeDir)) { // nothing found
                    return false;
                }
            }
            // now there's selected text to be replaced
            BaseDocument doc = (BaseDocument)c.getDocument();
            int startPos = c.getSelectionStart();
            int len = c.getSelectionEnd() - startPos;
            doc.atomicLock();
            try {
                if (len > 0) {
                    doc.remove(startPos, len);
                }
                String s = (String)props.get(SettingsNames.FIND_REPLACE_WITH);
                if (s != null && s.length() > 0) {
                    doc.insertString(startPos, s, null);
                }
            } finally {
                doc.atomicUnlock();
            }
            if (back) {
                // Handle repetitive search ('a' replaced by 'aa') by moving the caret
                if (caret instanceof BaseCaret) {
                    ((BaseCaret)caret).setDot(startPos, (BaseCaret)caret, EditorUI.SCROLL_FIND);

                } else { // regular caret
                    caret.setDot(startPos);
                }
            }
        }
        return true;
    }

    public void replaceAll(Map props) {
        incSearchReset();
        JTextComponent c = Utilities.getLastActiveComponent();
        BaseDocument doc = (BaseDocument)c.getDocument();
        int maxCnt = doc.getLength();
        int replacedCnt = 0;
        int totalCnt = 0;

        props = getValidFindProperties(props);
        props = new HashMap(props);
        props.put(SettingsNames.FIND_WRAP_SEARCH, Boolean.FALSE);

        // bugfix of #20476
        // if replaceAll, then set backward search to false.
        // Also reset FinderFactory.StringFinder, that is stored as property  BaseDocument.STRING_FINDER_PROP
        // via firePropertyChange ...
        props.put(SettingsNames.FIND_BACKWARD_SEARCH, Boolean.FALSE);
        firePropertyChange(null, null, null);

        String replaceWith = (String)props.get(SettingsNames.FIND_REPLACE_WITH);

        if (c != null) {
            doc.atomicLock();
            try {
                int pos = 0; // actual position
                while (true) {
                    int[] blk = findInBlock(c, pos, 0, -1, props, false);
                    if (blk == null) {
                        break;
                    }
                    totalCnt++;
                    int len = blk[1] - blk[0];
                    boolean skip = false; // cannot remove (because of guarded block)?
                    try {
                        doc.remove(blk[0], len);
                    } catch (GuardedException e) {
                        // replace in guarded block
                        skip = true;
                    }
                    if (skip) {
                        pos = blk[0] + len;

                    } else { // can and will insert the new string
                        if (replaceWith != null && replaceWith.length() > 0) {
                            doc.insertString(blk[0], replaceWith, null);
                        }
                        pos = blk[0] + ((replaceWith != null) ? replaceWith.length() : 0);
                        replacedCnt++;
                    }
                }

                // Display message about replacement
                MessageFormat fmt = new MessageFormat(
                                        LocaleSupport.getString(ITEMS_REPLACED_LOCALE));
                String msg = fmt.format(new Object[] { new Integer(replacedCnt), new Integer(totalCnt) });
                Utilities.setStatusText(c, msg);

            } catch (BadLocationException e) {
                e.printStackTrace();
            } finally {
                doc.atomicUnlock();
            }

        }
    }

    /** Get position of wrap mark for some document */
    public int getWrapSearchMarkPos(BaseDocument doc) {
        Mark mark = (Mark)doc.getProperty(BaseDocument.WRAP_SEARCH_MARK_PROP);
        try {
            return (mark != null) ? mark.getOffset() : doc.getLength();
        } catch (InvalidMarkException e) {
            throw new RuntimeException(); // shouldn't happen
        }
    }

    /** Set new position of wrap mark for some document */
    public void setWrapSearchMarkPos(BaseDocument doc, int pos) {
        //!!!
    }

    /** Add weak listener to listen to change of any property. The caller must
    * hold the listener object in some instance variable to prevent it
    * from being garbage collected.
    */
    public void addPropertyChangeListener(PropertyChangeListener l) {
        changeSupport.addPropertyChangeListener(l);
    }

    public synchronized void addPropertyChangeListener(String findPropertyName,
            PropertyChangeListener l) {
        changeSupport.addPropertyChangeListener(findPropertyName, l);
    }

    /** Remove listener for changes in properties */
    public void removePropertyChangeListener(PropertyChangeListener l) {
        changeSupport.removePropertyChangeListener(l);
    }

    void firePropertyChange(String settingName, Object oldValue, Object newValue) {
        changeSupport.firePropertyChange(this, settingName, oldValue, newValue);
    }

    public interface FinderCreator {

        /** Create finder for regular finding */
        public FinderFactory.StringFinder createFinder(BaseDocument doc, Map searchProps);

        /** Create finder for finding in opposite direction than regular finder */
        public FinderFactory.StringFinder createBwdFinder(BaseDocument doc, Map searchProps);

        /** Create finder that returns position pairs useful for highlight search */
        public FinderFactory.BlocksFinder createBlocksFinder(BaseDocument doc, Map searchProps);

    }

    public static class DefaultFinderCreator implements FinderCreator {

        protected Finder createFinder(BaseDocument doc,
                                      Map searchProps, boolean oppositeDir, boolean blocksFinder) {

            String text = (String)searchProps.get(SettingsNames.FIND_WHAT);
            if (text == null || text.length() == 0) {
                if (blocksFinder) {
                    return new FinderFactory.FalseBlocksFinder();
                } else {
                    return new FinderFactory.FalseFinder();
                }
            }

            Boolean b = (Boolean)searchProps.get(SettingsNames.FIND_BACKWARD_SEARCH);
            boolean bwdSearch = (b != null && b.booleanValue());
            if (oppositeDir) { // negate for opposite direction search
                bwdSearch = !bwdSearch;
            }

            b = (Boolean)searchProps.get(SettingsNames.FIND_MATCH_CASE);
            boolean matchCase = (b != null && b.booleanValue());
            b = (Boolean)searchProps.get(SettingsNames.FIND_SMART_CASE);
            boolean smartCase = (b != null && b.booleanValue());
            b = (Boolean)searchProps.get(SettingsNames.FIND_WHOLE_WORDS);
            boolean wholeWords = (b != null && b.booleanValue());

            if (smartCase && !matchCase) {
                int cnt = text.length();
                for (int i = 0; i < cnt; i++) {
                    if (Character.isUpperCase(text.charAt(i))) {
                        matchCase = true;
                    }
                }
            }

            //      searchProps.get(SettingsNames.FIND_REG_EXP);
            if (blocksFinder) {
                if (wholeWords) {
                    return new FinderFactory.WholeWordsBlocksFinder(doc, text, matchCase);
                } else {
                    return new FinderFactory.StringBlocksFinder(text, matchCase);
                }
            } else {
                if (wholeWords) {
                    if (bwdSearch) {
                        return new FinderFactory.WholeWordsBwdFinder(doc, text, matchCase);
                    } else {
                        return new FinderFactory.WholeWordsFwdFinder(doc, text, matchCase);
                    }
                } else {
                    if (bwdSearch) {
                        return new FinderFactory.StringBwdFinder(text, matchCase);
                    } else {
                        return new FinderFactory.StringFwdFinder(text, matchCase);
                    }
                }
            }
        }

        public FinderFactory.StringFinder createFinder(BaseDocument doc, Map searchProps) {
            return (FinderFactory.StringFinder)createFinder(doc, searchProps, false, false);
        }

        public FinderFactory.StringFinder createBwdFinder(BaseDocument doc, Map searchProps) {
            return (FinderFactory.StringFinder)createFinder(doc, searchProps, true, false);
        }

        /** Creates finder that makes position pairs of begining
        * and end of the matched word.
        */
        public FinderFactory.BlocksFinder createBlocksFinder(BaseDocument doc, Map searchProps) {
            return (FinderFactory.BlocksFinder)createFinder(doc, searchProps, false, true);
        }

    }

}


text:
package it.breex.bus.impl;

import it.breex.bus.event.AbstractResponseEvent;
import it.breex.bus.event.EventData;
import it.breex.bus.event.EventHandler;
import it.breex.bus.event.RequestEvent;

import java.util.UUID;

public class SynchEventManager extends AbstractEventManager {

	private final String nodeId = UUID.randomUUID().toString();

	@Override
	public String getLocalNodeId() {
		return nodeId;
	}

	@Override
	protected <I> void prepareRequest(final EventData<I> eventData) {
		processRequest(eventData);
	}

	@Override
	protected <I, O> void prepareResponse(EventData<I> requestEventData, final EventData<O> responseEventData) {
		AbstractResponseEvent<I, O> responseEvent = new AbstractResponseEvent<I, O>(responseEventData) {
		};
		processResponse(responseEvent, getResponseHandlers().remove(requestEventData.getId()));
	}

	@Override
	protected <I, O> void registerCallback(String eventName, EventHandler<RequestEvent<I, O>> eventHandler) {
	}

}