text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>pixi-viewport API Documentation</title>

    <meta name="description" content="Documentation for pixi-viewport library" />

        <meta name="keywords" content="docs, documentation, html5, javascript, jsdoc, camera, viewport, bounce, snap, 2d" />
        <meta name="keyword" content="docs, documentation, html5, javascript, jsdoc, camera, viewport, bounce, snap, 2d" />

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

    <link href="https://fonts.googleapis.com/css?family=Libre+Franklin:400,700" rel="stylesheet">
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/bootstrap.min.css">
    <link type="text/css" rel="stylesheet" href="styles/main.css">

pixi-viewport

    <button id="menuToggle" class="btn btn-link btn-lg menu-toggle">

    </button>

        <input id="search" type="text" class="form-control input-md" placeholder="Search...">

                Animate

            Members

deltaHeight

deltaWidth

height

startHeight

startWidth

time

width

            Methods

setupPosition

setupZoom

                Bounce

            Methods

calcUnderflowX

calcUnderflowY

                Clamp

                ClampZoom

            Methods

clamp

                Decelerate

            Methods

activate

moved

                Drag

            Methods

checkButtons

checkKeyPress

handleKeyPresses

mouseButtons

                Follow

                MouseEdges#MouseEdges

                Pinch

            Members

active

pinching

                Plugin

            Methods

destroy

down

move

pause

reset

resize

resume

up

update

wheel

                PluginManager

            Methods

add

get

pause

remove

removeAll

reset

resume

                Snap#Snap

                SnapZoom#SnapZoom

                Viewport

            Members

bottom

center

corner

dirty

forceHitArea

left

pause

right

scaled

screenHeightInWorldPixels

screenWidthInWorldPixels

screenWorldHeight

screenWorldWidth

top

worldHeight

worldScreenHeight

worldScreenWidth

worldWidth

            Methods

animate

bounce

clamp

clampZoom

decelerate

destroy

drag

ensureVisible

findCover

findFit

findFitHeight

findFitWidth

fit

fitHeight

fitWidth

fitWorld

follow

getVisibleBounds

mouseEdges

moveCenter

moveCorner

OOB

pinch

resize

setZoom

snap

snapZoom

toScreen

toWorld

update

wheel

zoom

zoomPercent

            Events

bounce-x-end

bounce-x-start

bounce-y-end

bounce-y-start

clicked

drag-end

drag-start

frame-end

mouse-edge-end

mouse-edge-start

moved

moved-end

pinch-end

pinch-start

snap-end

snap-start

snap-zoom-end

snap-zoom-start

wheel

wheel-scroll

zoomed

zoomed-end

                Wheel#Wheel

Source: js/plugins/Follow.js

js/plugins/Follow.js

import { Plugin } from './Plugin';
const DEFAULT_FOLLOW_OPTIONS = {
    speed: 0,
    acceleration: null,
    radius: null
};
/**
 * Plugin to follow a display-object.
 *
 * @see Viewport.follow
 * @public
 */
export class Follow extends Plugin {
    /**
     * This is called by {@link Viewport.follow}.
     *
     * @param parent
     * @param target - target to follow
     * @param options
     */
    constructor(parent, target, options = {}) {
        super(parent);
        this.target = target;
        this.options = Object.assign({}, DEFAULT_FOLLOW_OPTIONS, options);
        this.velocity = { x: 0, y: 0 };
    }
    update(elapsed) {
        if (this.paused) {
            return;
        }
        const center = this.parent.center;
        let toX = this.target.x;
        let toY = this.target.y;
        if (this.options.radius) {
            const distance = Math.sqrt(Math.pow(this.target.y - center.y, 2) + Math.pow(this.target.x - center.x, 2));
            if (distance > this.options.radius) {
                const angle = Math.atan2(this.target.y - center.y, this.target.x - center.x);
                toX = this.target.x - (Math.cos(angle) * this.options.radius);
                toY = this.target.y - (Math.sin(angle) * this.options.radius);
            }
            else {
                return;
            }
        }
        const deltaX = toX - center.x;
        const deltaY = toY - center.y;
        if (deltaX || deltaY) {
            if (this.options.speed) {
                if (this.options.acceleration) {
                    const angle = Math.atan2(toY - center.y, toX - center.x);
                    const distance = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
                    if (distance) {
                        const decelerationDistance = (Math.pow(this.velocity.x, 2) + Math.pow(this.velocity.y, 2)) / (2 * this.options.acceleration);
                        if (distance > decelerationDistance) {
                            this.velocity = {
                                x: Math.min(this.velocity.x + this.options.acceleration * elapsed, this.options.speed),
                                y: Math.min(this.velocity.y + this.options.acceleration * elapsed, this.options.speed)
                            };
                        }
                        else {
                            this.velocity = {
                                x: Math.max(this.velocity.x - this.options.acceleration * this.options.speed, 0),
                                y: Math.max(this.velocity.y - this.options.acceleration * this.options.speed, 0)
                            };
                        }
                        const changeX = Math.cos(angle) * this.velocity.x;
                        const changeY = Math.sin(angle) * this.velocity.y;
                        const x = Math.abs(changeX) > Math.abs(deltaX) ? toX : center.x + changeX;
                        const y = Math.abs(changeY) > Math.abs(deltaY) ? toY : center.y + changeY;
                        this.parent.moveCenter(x, y);
                        this.parent.emit('moved', { viewport: this.parent, type: 'follow' });
                    }
                }
                else {
                    const angle = Math.atan2(toY - center.y, toX - center.x);
                    const changeX = Math.cos(angle) * this.options.speed;
                    const changeY = Math.sin(angle) * this.options.speed;
                    const x = Math.abs(changeX) > Math.abs(deltaX) ? toX : center.x + changeX;
                    const y = Math.abs(changeY) > Math.abs(deltaY) ? toY : center.y + changeY;
                    this.parent.moveCenter(x, y);
                    this.parent.emit('moved', { viewport: this.parent, type: 'follow' });
                }
            }
            else {
                this.parent.moveCenter(toX, toY);
                this.parent.emit('moved', { viewport: this.parent, type: 'follow' });
            }
        }
    }
}

                Documentation generated by JSDoc 3.6.11 on Sun Oct 23 2022 07:02:33 GMT-0700 (Pacific Daylight Time)


text:
class RailsDataExplorer
  module Statistics

    # Responsibilities:
    #  * Provide random numeric data, following a power distribution.
    #
    class RngPowerLaw

      # @param min [Numeric]
      # @param max [Numeric]
      # @param pow [Numeric]
      # @param rng [Proc, optional] a random number generator
      def initialize(min = 1, max = 1000, pow = 2, rng = lambda { Kernel.rand })
        @min, @max, @pow, @rng = min, max, pow, rng
        @max += 1
      end

      # Returns random data following a power distribution.
      def rand
        y = (
          (
            (@max ** (@pow + 1) - @min ** (@pow + 1)) * @rng.call + @min ** (@pow + 1)
          ) ** (1.0 / (@pow + 1))
        ).to_i
        (@max - 1 - y) + @min
      end

    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package grpcproxy

import (
	"sync"

	"github.com/coreos/etcd/clientv3"
	pb "github.com/coreos/etcd/etcdserver/etcdserverpb"

	"golang.org/x/net/context"
)

type watchergroups struct {
	cw clientv3.Watcher

	mu        sync.Mutex
	groups    map[watchRange]*watcherGroup
	idToGroup map[receiverID]*watcherGroup

	proxyCtx context.Context
}

func (wgs *watchergroups) addWatcher(rid receiverID, w watcher) {
	wgs.mu.Lock()
	defer wgs.mu.Unlock()

	groups := wgs.groups

	if wg, ok := groups[w.wr]; ok {
		rev := wg.add(rid, w)
		wgs.idToGroup[rid] = wg

		if rev == 0 {
			// The group is newly created, the create event has not been delivered
			// to this group yet.
			// We can rely on etcd server to deliver the create event.
			// Or we might end up sending created event twice.
			return
		}

		resp := &pb.WatchResponse{
			Header: &pb.ResponseHeader{
				// todo: fill in ClusterId
				// todo: fill in MemberId:
				Revision: rev,
				// todo: fill in RaftTerm:
			},
			WatchId: rid.watcherID,
			Created: true,
		}
		w.ch <- resp

		return
	}

	ctx, cancel := context.WithCancel(wgs.proxyCtx)

	wch := wgs.cw.Watch(ctx, w.wr.key,
		clientv3.WithRange(w.wr.end),
		clientv3.WithProgressNotify(),
		clientv3.WithCreatedNotify(),
	)

	watchg := newWatchergroup(wch, cancel)
	watchg.add(rid, w)
	go watchg.run()
	groups[w.wr] = watchg
	wgs.idToGroup[rid] = watchg
}

func (wgs *watchergroups) removeWatcher(rid receiverID) (int64, bool) {
	wgs.mu.Lock()
	defer wgs.mu.Unlock()

	if g, ok := wgs.idToGroup[rid]; ok {
		g.delete(rid)
		delete(wgs.idToGroup, rid)
		if g.isEmpty() {
			g.stop()
		}
		return g.revision(), true
	}
	return -1, false
}

func (wgs *watchergroups) maybeJoinWatcherSingle(rid receiverID, ws watcherSingle) bool {
	wgs.mu.Lock()
	defer wgs.mu.Unlock()

	group, ok := wgs.groups[ws.w.wr]
	if ok {
		return group.add(receiverID{streamID: ws.sws.id, watcherID: ws.w.id}, ws.w) != -1
	}

	if ws.canPromote() {
		wg := newWatchergroup(ws.ch, ws.cancel)
		wgs.groups[ws.w.wr] = wg
		wg.add(receiverID{streamID: ws.sws.id, watcherID: ws.w.id}, ws.w)
		go wg.run()
		return true
	}

	return false
}

func (wgs *watchergroups) stop() {
	wgs.mu.Lock()
	defer wgs.mu.Unlock()
	for _, wg := range wgs.groups {
		wg.stop()
	}
	wgs.groups = nil
}


text:
package org.apache.tinkerpop.gremlin.groovy.engine;

import org.junit.Test;

import javax.script.SimpleBindings;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

import static org.junit.Assert.assertTrue;

/**
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class ScriptEnginesTest {
    @Test
    public void shouldFailUntilImportExecutes() throws Exception {
        final ScriptEngines engines = new ScriptEngines(se -> {});
        engines.reload("gremlin-groovy", Collections.<String>emptySet(),
                Collections.<String>emptySet(), Collections.emptyMap());

        final Set<String> imports = new HashSet<String>() {{
            add("import java.awt.Color");
        }};

        final AtomicInteger successes = new AtomicInteger(0);
        final AtomicInteger failures = new AtomicInteger(0);

        final Thread threadImport = new Thread(() -> {
            engines.addImports(imports);
        });

        // issue 1000 scripts in one thread using a class that isn't imported.  this will result in failure.
        // while that thread is running start a new thread that issues an addImports to include that class.
        // this should block further evals in the first thread until the import is complete at which point
        // evals in the first thread will resume and start to succeed
        final Thread threadEvalAndTriggerImport = new Thread(() ->
            IntStream.range(0, 1000).forEach(i -> {
                try {
                    engines.eval("Color.BLACK", new SimpleBindings(), "gremlin-groovy");
                    successes.incrementAndGet();
                } catch (Exception ex) {
                    if (failures.incrementAndGet() == 500) threadImport.start();
                }
            })
        );

        threadEvalAndTriggerImport.start();

        threadEvalAndTriggerImport.join();
        threadImport.join();

        assertTrue(successes.intValue() > 0);
        assertTrue(failures.intValue() >= 500);

        engines.close();
    }
}


text:
package com.gemstone.gemfire.internal.cache;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;

import org.apache.logging.log4j.Logger;

import com.gemstone.gemfire.DataSerializer;
import com.gemstone.gemfire.cache.TransactionDataNotColocatedException;
import com.gemstone.gemfire.distributed.DistributedSystemDisconnectedException;
import com.gemstone.gemfire.distributed.internal.DM;
import com.gemstone.gemfire.distributed.internal.DirectReplyProcessor;
import com.gemstone.gemfire.distributed.internal.DistributionManager;
import com.gemstone.gemfire.distributed.internal.DistributionMessage;
import com.gemstone.gemfire.distributed.internal.DistributionStats;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.ReplyException;
import com.gemstone.gemfire.distributed.internal.ReplyMessage;
import com.gemstone.gemfire.distributed.internal.ReplyProcessor21;
import com.gemstone.gemfire.distributed.internal.ReplySender;
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
import com.gemstone.gemfire.internal.Assert;
import com.gemstone.gemfire.internal.InternalDataSerializer;
import com.gemstone.gemfire.internal.Version;
import com.gemstone.gemfire.internal.cache.BucketRegion.RawValue;
import com.gemstone.gemfire.internal.cache.tier.sockets.ClientProxyMembershipID;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import com.gemstone.gemfire.internal.logging.LogService;
import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
import com.gemstone.gemfire.internal.offheap.OffHeapHelper;
import com.gemstone.gemfire.internal.util.BlobHelper;

/**
 * This message is used as the request for a
 * {@link com.gemstone.gemfire.cache.Region#get(Object)}operation. The reply is
 * sent in a {@link com.gemstone.gemfire.internal.cache.RemoteGetMessage.GetReplyMessage}.
 *
 * Replicate regions can use this message to send a Get request to another peer.
 *
 * @since 6.5
 */
public final class RemoteGetMessage extends RemoteOperationMessageWithDirectReply
  {
  private static final Logger logger = LogService.getLogger();

  private Object key;

  /** The callback arg of the operation */
  private Object cbArg;

  private ClientProxyMembershipID context;

  /**
   * Empty constructor to satisfy {@link DataSerializer} requirements
   */
  public RemoteGetMessage() {
  }

  private RemoteGetMessage(InternalDistributedMember recipient, String regionPath,
      DirectReplyProcessor processor,
      final Object key, final Object aCallbackArgument, ClientProxyMembershipID context) {
    super(recipient, regionPath, processor);
    this.key = key;
    this.cbArg = aCallbackArgument;
    this.context = context;
  }

  @Override
  final public int getProcessorType()
  {
      return DistributionManager.SERIAL_EXECUTOR;
    }

  @Override
  public boolean isSevereAlertCompatible() {
    // allow forced-disconnect processing for all cache op messages
    return true;
  }

  @Override
  protected final boolean operateOnRegion(
      final DistributionManager dm, LocalRegion r, long startTime)
      throws RemoteOperationException
  {
    if (logger.isTraceEnabled(LogMarker.DM)) {
      logger.trace(LogMarker.DM, "RemoteGetMessage operateOnRegion: {}", r.getFullPath());
    }

    if (this.getTXUniqId() != TXManagerImpl.NOTX) {
      assert r.getDataView() instanceof TXStateProxy;
    }

    if ( ! (r instanceof PartitionedRegion) ) { // prs already wait on initialization
      r.waitOnInitialization(); // bug #43371 - accessing a region before it's initialized
    }

    RawValue valueBytes;
    Object val = null;
      try {
        if (r.keyRequiresRegionContext()) {
          ((KeyWithRegionContext)this.key).setRegionContext(r);
        }
        KeyInfo keyInfo = r.getKeyInfo(key, cbArg);
        val = r.getDataView().getSerializedValue(r, keyInfo, false, this.context, null, false, false/*for replicate regions*/);
        valueBytes = val instanceof RawValue ? (RawValue)val : new RawValue(val);

        if (logger.isTraceEnabled(LogMarker.DM)) {
          logger.trace(LogMarker.DM, "GetMessage sending serialized value {} back via GetReplyMessage using processorId: {}",
                       valueBytes, getProcessorId());
        }

        //      r.getPrStats().endPartitionMessagesProcessing(startTime);
        GetReplyMessage.send(getSender(), getProcessorId(), valueBytes, getReplySender(dm));

        // Unless there was an exception thrown, this message handles sending the
        // response
        return false;
      }
      catch(DistributedSystemDisconnectedException sde) {
        sendReply(getSender(), this.processorId, dm, new ReplyException(new RemoteOperationException(LocalizedStrings.GetMessage_OPERATION_GOT_INTERRUPTED_DUE_TO_SHUTDOWN_IN_PROGRESS_ON_REMOTE_VM.toLocalizedString(), sde)), r, startTime);
        return false;
      }
      catch (PrimaryBucketException pbe) {
        sendReply(getSender(), getProcessorId(), dm, new ReplyException(pbe), r, startTime);
        return false;
      }
      catch (DataLocationException e) {
        sendReply(getSender(), getProcessorId(), dm, new ReplyException(e), r, startTime);
        return false;
      }finally {
        OffHeapHelper.release(val);
      }

  }

  @Override
  protected void appendFields(StringBuffer buff)
  {
    super.appendFields(buff);
    buff.append("; key=").append(this.key).append("; callback arg=").append(this.cbArg);
  }

  public int getDSFID() {
    return R_GET_MESSAGE;
  }

  @Override
  public void fromData(DataInput in) throws IOException, ClassNotFoundException
  {
    super.fromData(in);
    this.key = DataSerializer.readObject(in);
    this.cbArg = DataSerializer.readObject(in);
    this.context = DataSerializer.readObject(in);
  }

  @Override
  public void toData(DataOutput out) throws IOException
  {
    super.toData(out);
    DataSerializer.writeObject(this.key, out);
    DataSerializer.writeObject(this.cbArg, out);
    DataSerializer.writeObject(this.context, out);
  }

  public void setKey(Object key)
  {
    this.key = key;
  }

  /**
   * Sends a ReplicateRegion
   * {@link com.gemstone.gemfire.cache.Region#get(Object)} message
   *
   * @param recipient
   *          the member that the get message is sent to
   * @param r
   *          the ReplicateRegion for which get was performed upon
   * @param key
   *          the object to which the value should be feteched
   * @param requestingClient the client requesting the value
   * @return the processor used to fetch the returned value associated with the
   *         key
   */
  public static RemoteGetResponse send(InternalDistributedMember recipient,
      LocalRegion r, final Object key, final Object aCallbackArgument, ClientProxyMembershipID requestingClient)
      throws RemoteOperationException
  {
    Assert.assertTrue(recipient != null,
        "PRDistribuedGetReplyMessage NULL reply message");
    RemoteGetResponse p = new RemoteGetResponse(r.getSystem(), Collections.singleton(recipient), key);
    RemoteGetMessage m = new RemoteGetMessage(recipient, r.getFullPath(), p,
        key, aCallbackArgument, requestingClient);
    Set failures = r.getDistributionManager().putOutgoing(m);
    if (failures != null && failures.size() > 0) {
      throw new RemoteOperationException(LocalizedStrings.GetMessage_FAILED_SENDING_0.toLocalizedString(m));
    }

    return p;
  }

  /**
   * This message is used for the reply to a
   * {@link com.gemstone.gemfire.cache.Region#get(Object)}operation This is the
   * reply to a {@link RemoteGetMessage}.
   *
   * Since the {@link com.gemstone.gemfire.cache.Region#get(Object)}operation
   * is used <bold>very </bold> frequently the performance of this class is
   * critical.
   *
   * @since 6.5
   */
  public static final class GetReplyMessage extends ReplyMessage
   {
    /**
     * The raw value in the cache which may be serialized to the output stream, if
     * it is NOT already a byte array
     */
    private transient RawValue rawVal;

    /** Indicates that the value already a byte array (aka user blob) and does
     * not need de-serialization
     */
    public boolean valueIsByteArray;

    /*
     * Used on the fromData side to transfer the value bytes to the requesting
     * thread
     */
    public transient byte[] valueInBytes;

    public transient Version remoteVersion;

    /**
     * Empty constructor to conform to DataSerializable interface
     */
    public GetReplyMessage() {
    }

    private GetReplyMessage(int processorId, RawValue val) {
      setProcessorId(processorId);
      this.rawVal = val;
      this.valueIsByteArray = val.isValueByteArray();
    }

    /** GetReplyMessages are always processed in-line */
    @Override
    public boolean getInlineProcess() {
      return true;
    }

    /**
     * Return the value from the get operation, serialize it bytes as late as
     * possible to avoid making un-neccesary byte[] copies.  De-serialize those
     * same bytes as late as possible to avoid using precious threads (aka P2P readers).
     * @param recipient the origin VM that performed the get
     * @param processorId the processor on which the origin thread is waiting
     * @param val the raw value that will eventually be serialized
     * @param replySender distribution manager used to send the reply
     */
    public static void send(InternalDistributedMember recipient,
        int processorId, RawValue val, ReplySender replySender)
        throws RemoteOperationException
    {
      Assert.assertTrue(recipient != null,
          "PRDistribuedGetReplyMessage NULL reply message");
      GetReplyMessage m = new GetReplyMessage(processorId, val);
      m.setRecipient(recipient);
      replySender.putOutgoing(m);
    }

    /**
     * Processes this message. This method is invoked by the receiver of the
     * message.
     *
     * @param dm
     *          the distribution manager that is processing the message.
     */
    @Override
    public void process(final DM dm, ReplyProcessor21 processor)
    {
      final boolean isDebugEnabled = logger.isTraceEnabled(LogMarker.DM);

      final long startTime = getTimestamp();
      if (isDebugEnabled) {
        logger.trace(LogMarker.DM, "GetReplyMessage process invoking reply processor with processorId:{}", this.processorId);
      }

      if (processor == null) {
        if (isDebugEnabled) {
          logger.trace(LogMarker.DM, "GetReplyMessage processor not found");
        }
        return;
      }
      processor.process(this);

      if (isDebugEnabled) {
        logger.trace(LogMarker.DM, "{} Processed {}", processor, this);
      }
      dm.getStats().incReplyMessageTime(DistributionStats.getStatTime() - startTime);
    }

    @Override
    public int getDSFID() {
      return R_GET_REPLY_MESSAGE;
    }

    @Override
    public void toData(DataOutput out) throws IOException
    {
      super.toData(out);
      out.writeByte(this.valueIsByteArray ? 1 : 0);
      this.rawVal.writeAsByteArray(out);
    }

    @Override
    public void fromData(DataInput in) throws IOException,
        ClassNotFoundException
    {
      super.fromData(in);
      this.valueIsByteArray = (in.readByte() == 1);
      this.valueInBytes = DataSerializer.readByteArray(in);
      if (!this.valueIsByteArray) {
        this.remoteVersion = InternalDataSerializer
            .getVersionForDataStreamOrNull(in);
      }
    }

    @Override
    public String toString()
    {
      StringBuffer sb = new StringBuffer();
      sb.append("GetReplyMessage ").append("processorid=").append(
          this.processorId).append(" reply to sender ")
          .append(this.getSender())
          .append(" returning serialized value=")
          .append(this.rawVal);
      return sb.toString();
    }
  }

  /**
   * A processor to capture the value returned by {@link
   * com.gemstone.gemfire.internal.cache.RemoteGetMessage.GetReplyMessage}
   *
   * @author Mitch Thomas
   * @since 5.0
   */
  public static class RemoteGetResponse extends RemoteOperationResponse {

    private volatile GetReplyMessage getReply;
    private volatile boolean returnValueReceived;
    private volatile long start;
    final Object key;

    public RemoteGetResponse(InternalDistributedSystem ds, Set recipients, Object key) {
      super(ds, recipients, false);
      this.key = key;
    }

    @Override
    public void process(DistributionMessage msg)
    {
      if (DistributionStats.enableClockStats) {
        this.start = DistributionStats.getStatTime();
      }
      if (msg instanceof GetReplyMessage) {
        GetReplyMessage reply = (GetReplyMessage)msg;
        // De-serialization needs to occur in the requesting thread, not a P2P thread
        // (or some other limited resource)
        if (reply.valueInBytes != null) {
          this.getReply = reply;
        }
        this.returnValueReceived = true;
      }
      super.process(msg);
    }

    /**
     * De-seralize the value, if the value isn't already a byte array, this
     * method should be called in the context of the requesting thread for the
     * best scalability
     * @param preferCD
     * @see EntryEventImpl#deserialize(byte[])
     * @return the value object
     */
    public Object getValue(boolean preferCD) throws RemoteOperationException
    {
      final GetReplyMessage reply = this.getReply;
      try {
        if (reply != null) {
          if (reply.valueIsByteArray) {
            return reply.valueInBytes;
          }
          else if (preferCD) {
            return CachedDeserializableFactory.create(reply.valueInBytes);
          }
          else {
            return BlobHelper.deserializeBlob(reply.valueInBytes,
                reply.remoteVersion, null);
          }
        }
        return null;
      }
      catch (IOException e) {
        throw new RemoteOperationException(LocalizedStrings.GetMessage_UNABLE_TO_DESERIALIZE_VALUE_IOEXCEPTION.toLocalizedString(), e);
      }
      catch (ClassNotFoundException e) {
        throw new RemoteOperationException(LocalizedStrings.GetMessage_UNABLE_TO_DESERIALIZE_VALUE_CLASSNOTFOUNDEXCEPTION.toLocalizedString(), e);
      }
    }

    /**
     * @return Object associated with the key that was sent in the get message
     */
    public Object waitForResponse(boolean preferCD)
        throws RemoteOperationException {
      try {
//        waitForRepliesUninterruptibly();
          waitForCacheException();
          if (DistributionStats.enableClockStats) {
            getDistributionManager().getStats().incReplyHandOffTime(this.start);
          }
      }
      catch (RemoteOperationException e) {
        e.checkKey(key);
        final String msg = "RemoteGetResponse got RemoteOperationException; rethrowing";
        logger.debug(msg, e);
        throw e;
      } catch (TransactionDataNotColocatedException e) {
        // Throw this up to user!
        throw e;
      }
      if (!this.returnValueReceived) {
        throw new RemoteOperationException(LocalizedStrings.GetMessage_NO_RETURN_VALUE_RECEIVED.toLocalizedString());
      }
      return getValue(preferCD);
    }
  }

}


text:
require('should');
var request = require('supertest');

var Sails = require('sails').Sails;

describe('parametized policies hook - nested factories', function(){

    var sails;

    before(function(done){

        this.timeout(11000);

        Sails().lift({
            hooks: {
                'parametized-policies': require('../'),
                grunt: false,
            },
            log: {
                level: 'error'
            },
            paths: {
                controllers: __dirname + '/controllers',
                policies: __dirname + '/policies',
                policyFactories: __dirname + '/policyFactories',
            },
            routes: {
                'GET /policies-args': 'NestedController.policiesArgs',
                'GET /mixed-args': 'NestedController.mixedArgs',
                'GET /factories-args': 'NestedController.factoriesArgs',
            },
            policies: {
                'NestedController': {
                    'policiesArgs': ['and(isAdmin, accept)'],
                    'mixedArgs': 'and(isAdmin, is(\'User\'))',
                    'factoriesArgs': 'and(is(\'Admin\'), is(\'User\'))',
                }
            }
        }, function(err, _sails){

            if(err) return done(err);

            sails = _sails;

            return done();
        });
    });

    after(function(done){

        if(sails){
            sails.lower(done);
        }

    });

    it('should start the sails server', function(){
        return true;
    });

    it('should handle factory with policies as arguments', function(done){
        request(sails.hooks.http.app)
            .get('/policies-args')
            .expect('Admin', done);
    });

    it('should handle factory with mixed arguments', function(done){
        request(sails.hooks.http.app)
            .get('/mixed-args')
            .expect('AdminUser', done);
    });

    it('should handle factory with factories as arguments', function(done){
        request(sails.hooks.http.app)
            .get('/factories-args')
            .expect('AdminUser', done);
    });
})


text:
namespace updater {

namespace {

HResultOr<bool> IsUserRunningSplitToken() {
  HANDLE token = NULL;
  if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
    return base::unexpected(HRESULTFromLastError());
  base::win::ScopedHandle token_holder(token);
  TOKEN_ELEVATION_TYPE elevation_type = TokenElevationTypeDefault;
  DWORD size_returned = 0;
  if (!::GetTokenInformation(token_holder.Get(), TokenElevationType,
                             &elevation_type, sizeof(elevation_type),
                             &size_returned)) {
    return base::unexpected(HRESULTFromLastError());
  }
  bool is_split_token = elevation_type == TokenElevationTypeFull ||
                        elevation_type == TokenElevationTypeLimited;
  DCHECK(is_split_token || elevation_type == TokenElevationTypeDefault);
  return base::ok(is_split_token);
}

HRESULT GetSidIntegrityLevel(PSID sid, MANDATORY_LEVEL* level) {
  if (!::IsValidSid(sid))
    return E_FAIL;
  SID_IDENTIFIER_AUTHORITY* authority = ::GetSidIdentifierAuthority(sid);
  if (!authority)
    return E_FAIL;
  constexpr SID_IDENTIFIER_AUTHORITY kMandatoryLabelAuth =
      SECURITY_MANDATORY_LABEL_AUTHORITY;
  if (std::memcmp(authority, &kMandatoryLabelAuth,
                  sizeof(SID_IDENTIFIER_AUTHORITY))) {
    return E_FAIL;
  }
  PUCHAR count = ::GetSidSubAuthorityCount(sid);
  if (!count || *count != 1)
    return E_FAIL;
  DWORD* rid = ::GetSidSubAuthority(sid, 0);
  if (!rid)
    return E_FAIL;
  if ((*rid & 0xFFF) != 0 || *rid > SECURITY_MANDATORY_PROTECTED_PROCESS_RID)
    return E_FAIL;
  *level = static_cast<MANDATORY_LEVEL>(*rid >> 12);
  return S_OK;
}

// Gets the mandatory integrity level of a process.
// TODO(crbug.com/1233748): consider reusing
// base::GetCurrentProcessIntegrityLevel().
HRESULT GetProcessIntegrityLevel(DWORD process_id, MANDATORY_LEVEL* level) {
  HANDLE process = ::OpenProcess(PROCESS_QUERY_INFORMATION, false, process_id);
  if (!process)
    return HRESULTFromLastError();
  base::win::ScopedHandle process_holder(process);
  HANDLE token = NULL;
  if (!::OpenProcessToken(process_holder.Get(),
                          TOKEN_QUERY | TOKEN_QUERY_SOURCE, &token)) {
    return HRESULTFromLastError();
  }
  base::win::ScopedHandle token_holder(token);
  DWORD label_size = 0;
  if (::GetTokenInformation(token_holder.Get(), TokenIntegrityLevel, nullptr, 0,
                            &label_size) ||
      ::GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
    return E_FAIL;
  }
  std::unique_ptr<TOKEN_MANDATORY_LABEL, base::FreeDeleter> label(
      static_cast<TOKEN_MANDATORY_LABEL*>(std::malloc(label_size)));
  if (!::GetTokenInformation(token_holder.Get(), TokenIntegrityLevel,
                             label.get(), label_size, &label_size)) {
    return HRESULTFromLastError();
  }
  return GetSidIntegrityLevel(label->Label.Sid, level);
}

bool IsExplorerRunningAtMediumOrLower() {
  base::NamedProcessIterator iter(L"EXPLORER.EXE", nullptr);
  while (const base::ProcessEntry* process_entry = iter.NextProcessEntry()) {
    MANDATORY_LEVEL level = MandatoryLevelUntrusted;
    if (SUCCEEDED(GetProcessIntegrityLevel(process_entry->pid(), &level)) &&
        level <= MandatoryLevelMedium) {
      return true;
    }
  }
  return false;
}

// Creates a WS_POPUP | WS_VISIBLE with zero
// size, of the STATIC WNDCLASS. It uses the default running EXE module
// handle for creation.
//
// A visible centered foreground window is needed as the parent in Windows 7 and
// above, to allow the UAC prompt to come up in the foreground, centered.
// Otherwise, the elevation prompt will be minimized on the taskbar. A zero size
// window works. A plain vanilla WS_POPUP allows the window to be free of
// adornments. WS_EX_TOOLWINDOW prevents the task bar from showing the
// zero-sized window.
//
// Returns NULL on failure. Call ::GetLastError() to get extended error
// information on failure.
HWND CreateForegroundParentWindowForUAC() {
  CWindow foreground_parent;
  if (foreground_parent.Create(L"STATIC", NULL, NULL, NULL,
                               WS_POPUP | WS_VISIBLE, WS_EX_TOOLWINDOW)) {
    foreground_parent.CenterWindow(NULL);
    ::SetForegroundWindow(foreground_parent);
  }
  return foreground_parent.Detach();
}

// Compares the OS, service pack, and build numbers using `::VerifyVersionInfo`,
// in accordance with `type_mask` and `oper`.
bool CompareOSVersionsInternal(const OSVERSIONINFOEX& os,
                               DWORD type_mask,
                               BYTE oper) {
  DCHECK(type_mask);
  DCHECK(oper);

  ULONGLONG cond_mask = 0;
  cond_mask = ::VerSetConditionMask(cond_mask, VER_MAJORVERSION, oper);
  cond_mask = ::VerSetConditionMask(cond_mask, VER_MINORVERSION, oper);
  cond_mask = ::VerSetConditionMask(cond_mask, VER_SERVICEPACKMAJOR, oper);
  cond_mask = ::VerSetConditionMask(cond_mask, VER_SERVICEPACKMINOR, oper);
  cond_mask = ::VerSetConditionMask(cond_mask, VER_BUILDNUMBER, oper);

  // `::VerifyVersionInfo` could return `FALSE` due to an error other than
  // `ERROR_OLD_WIN_VERSION`. We do not handle that case here.
  // https://msdn.microsoft.com/ms725492.
  OSVERSIONINFOEX os_in = os;
  return ::VerifyVersionInfo(&os_in, type_mask, cond_mask);
}

}  // namespace

NamedObjectAttributes::NamedObjectAttributes(const std::wstring& name,
                                             const CSecurityDesc& sd)
    : name(name), sa(CSecurityAttributes(sd)) {}
NamedObjectAttributes::~NamedObjectAttributes() = default;

HRESULT HRESULTFromLastError() {
  const auto error_code = ::GetLastError();
  return (error_code != NO_ERROR) ? HRESULT_FROM_WIN32(error_code) : E_FAIL;
}

HMODULE GetModuleHandleFromAddress(void* address) {
  MEMORY_BASIC_INFORMATION mbi = {0};
  size_t result = ::VirtualQuery(address, &mbi, sizeof(mbi));
  DCHECK_EQ(result, sizeof(mbi));
  return static_cast<HMODULE>(mbi.AllocationBase);
}

HMODULE GetCurrentModuleHandle() {
  return GetModuleHandleFromAddress(
      reinterpret_cast<void*>(&GetCurrentModuleHandle));
}

// The event name saved to the environment variable does not contain the
// decoration added by GetNamedObjectAttributes.
HRESULT CreateUniqueEventInEnvironment(const std::wstring& var_name,
                                       UpdaterScope scope,
                                       HANDLE* unique_event) {
  DCHECK(unique_event);

  const std::wstring event_name = base::ASCIIToWide(base::GenerateGUID());
  NamedObjectAttributes attr =
      GetNamedObjectAttributes(event_name.c_str(), scope);

  HRESULT hr = CreateEvent(&attr, unique_event);
  if (FAILED(hr))
    return hr;

  if (!::SetEnvironmentVariable(var_name.c_str(), event_name.c_str()))
    return HRESULTFromLastError();

  return S_OK;
}

HRESULT OpenUniqueEventFromEnvironment(const std::wstring& var_name,
                                       UpdaterScope scope,
                                       HANDLE* unique_event) {
  DCHECK(unique_event);

  wchar_t event_name[MAX_PATH] = {0};
  if (!::GetEnvironmentVariable(var_name.c_str(), event_name,
                                std::size(event_name))) {
    return HRESULTFromLastError();
  }

  NamedObjectAttributes attr = GetNamedObjectAttributes(event_name, scope);
  *unique_event = ::OpenEvent(EVENT_ALL_ACCESS, false, attr.name.c_str());

  if (!*unique_event)
    return HRESULTFromLastError();

  return S_OK;
}

HRESULT CreateEvent(NamedObjectAttributes* event_attr, HANDLE* event_handle) {
  DCHECK(event_handle);
  DCHECK(event_attr);
  DCHECK(!event_attr->name.empty());
  *event_handle = ::CreateEvent(&event_attr->sa,
                                true,   // manual reset
                                false,  // not signaled
                                event_attr->name.c_str());

  if (!*event_handle)
    return HRESULTFromLastError();

  return S_OK;
}

NamedObjectAttributes GetNamedObjectAttributes(const wchar_t* base_name,
                                               UpdaterScope scope) {
  DCHECK(base_name);

  switch (scope) {
    case UpdaterScope::kUser: {
      std::wstring user_sid;
      GetProcessUser(nullptr, nullptr, &user_sid);
      return {
          base::StrCat({kGlobalPrefix, base_name, user_sid}),
          GetCurrentUserDefaultSecurityDescriptor().value_or(CSecurityDesc())};
    }
    case UpdaterScope::kSystem:
      // Grant access to administrators and system.
      return {base::StrCat({kGlobalPrefix, base_name}),
              GetAdminDaclSecurityDescriptor(GENERIC_ALL)};
  }
}

absl::optional<CSecurityDesc> GetCurrentUserDefaultSecurityDescriptor() {
  CAccessToken token;
  if (!token.GetProcessToken(TOKEN_QUERY))
    return absl::nullopt;

  CSecurityDesc security_desc;
  CSid sid_owner;
  if (!token.GetOwner(&sid_owner))
    return absl::nullopt;

  security_desc.SetOwner(sid_owner);
  CSid sid_group;
  if (!token.GetPrimaryGroup(&sid_group))
    return absl::nullopt;

  security_desc.SetGroup(sid_group);

  CDacl dacl;
  if (!token.GetDefaultDacl(&dacl))
    return absl::nullopt;

  CSid sid_user;
  if (!token.GetUser(&sid_user))
    return absl::nullopt;
  if (!dacl.AddAllowedAce(sid_user, GENERIC_ALL))
    return absl::nullopt;

  security_desc.SetDacl(dacl);

  return security_desc;
}

CSecurityDesc GetAdminDaclSecurityDescriptor(ACCESS_MASK accessmask) {
  CSecurityDesc sd;
  CDacl dacl;
  dacl.AddAllowedAce(Sids::System(), accessmask);
  dacl.AddAllowedAce(Sids::Admins(), accessmask);

  sd.SetOwner(Sids::Admins());
  sd.SetGroup(Sids::Admins());
  sd.SetDacl(dacl);
  sd.MakeAbsolute();
  return sd;
}

std::wstring GetAppClientsKey(const std::string& app_id) {
  return GetAppClientsKey(base::ASCIIToWide(app_id));
}

std::wstring GetAppClientsKey(const std::wstring& app_id) {
  return base::StrCat({CLIENTS_KEY, app_id});
}

std::wstring GetAppClientStateKey(const std::string& app_id) {
  return GetAppClientStateKey(base::ASCIIToWide(app_id));
}

std::wstring GetAppClientStateKey(const std::wstring& app_id) {
  return base::StrCat({CLIENT_STATE_KEY, app_id});
}

std::wstring GetAppCommandKey(const std::wstring& app_id,
                              const std::wstring& command_id) {
  return base::StrCat(
      {GetAppClientsKey(app_id), L"\\", kRegKeyCommands, L"\\", command_id});
}

std::wstring GetRegistryKeyClientsUpdater() {
  return GetAppClientsKey(kUpdaterAppId);
}

std::wstring GetRegistryKeyClientStateUpdater() {
  return GetAppClientStateKey(kUpdaterAppId);
}

int GetDownloadProgress(int64_t downloaded_bytes, int64_t total_bytes) {
  if (downloaded_bytes == -1 || total_bytes == -1 || total_bytes == 0)
    return -1;
  DCHECK_LE(downloaded_bytes, total_bytes);
  return 100 * base::clamp(static_cast<double>(downloaded_bytes) / total_bytes,
                           0.0, 1.0);
}

base::win::ScopedHandle GetUserTokenFromCurrentSessionId() {
  base::win::ScopedHandle token_handle;

  DWORD bytes_returned = 0;
  DWORD* session_id_ptr = nullptr;
  if (!::WTSQuerySessionInformation(
          WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSSessionId,
          reinterpret_cast<LPTSTR*>(&session_id_ptr), &bytes_returned)) {
    PLOG(ERROR) << "WTSQuerySessionInformation failed.";
    return token_handle;
  }

  DCHECK_EQ(bytes_returned, sizeof(*session_id_ptr));
  DWORD session_id = *session_id_ptr;
  ::WTSFreeMemory(session_id_ptr);
  VLOG(1) << "::WTSQuerySessionInformation session id: " << session_id;

  HANDLE token_handle_raw = nullptr;
  if (!::WTSQueryUserToken(session_id, &token_handle_raw)) {
    PLOG(ERROR) << "WTSQueryUserToken failed";
    return token_handle;
  }

  token_handle.Set(token_handle_raw);
  return token_handle;
}

bool PathOwnedByUser(const base::FilePath& path) {
  // TODO(crbug.com/1147094): Implement for Win.
  return true;
}

HResultOr<bool> IsTokenAdmin(HANDLE token) {
  SID_IDENTIFIER_AUTHORITY nt_authority = SECURITY_NT_AUTHORITY;
  PSID administrators_group = nullptr;
  if (!::AllocateAndInitializeSid(&nt_authority, 2, SECURITY_BUILTIN_DOMAIN_RID,
                                  DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
                                  &administrators_group)) {
    return base::unexpected(HRESULTFromLastError());
  }
  base::ScopedClosureRunner free_sid(
      base::BindOnce([](PSID sid) { ::FreeSid(sid); }, administrators_group));
  BOOL is_member = false;
  if (!::CheckTokenMembership(token, administrators_group, &is_member))
    return base::unexpected(HRESULTFromLastError());
  return base::ok(is_member);
}

// TODO(crbug.com/1212187): maybe handle filtered tokens.
HResultOr<bool> IsUserAdmin() {
  return IsTokenAdmin(NULL);
}

HResultOr<bool> IsUserNonElevatedAdmin() {
  HANDLE token = NULL;
  if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_READ, &token))
    return base::unexpected(HRESULTFromLastError());
  bool is_user_non_elevated_admin = false;
  base::win::ScopedHandle token_holder(token);
  TOKEN_ELEVATION_TYPE elevation_type = TokenElevationTypeDefault;
  DWORD size_returned = 0;
  if (::GetTokenInformation(token_holder.Get(), TokenElevationType,
                            &elevation_type, sizeof(elevation_type),
                            &size_returned)) {
    if (elevation_type == TokenElevationTypeLimited) {
      is_user_non_elevated_admin = true;
    }
  }
  return base::ok(is_user_non_elevated_admin);
}

HResultOr<bool> IsCOMCallerAdmin() {
  ScopedKernelHANDLE token;

  {
    HRESULT hr = ::CoImpersonateClient();
    if (hr == RPC_E_CALL_COMPLETE) {
      // RPC_E_CALL_COMPLETE indicates that the caller is in-proc.
      return base::ok(::IsUserAnAdmin());
    }

    if (FAILED(hr)) {
      return base::unexpected(hr);
    }

    base::ScopedClosureRunner co_revert_to_self(
        base::BindOnce([]() { ::CoRevertToSelf(); }));

    if (!::OpenThreadToken(::GetCurrentThread(), TOKEN_QUERY, TRUE,
                           ScopedKernelHANDLE::Receiver(token).get())) {
      hr = HRESULTFromLastError();
      LOG(ERROR) << __func__ << ": ::OpenThreadToken failed: " << std::hex
                 << hr;
      return base::unexpected(hr);
    }
  }

  HResultOr<bool> result = IsTokenAdmin(token.get());
  if (!result.has_value()) {
    HRESULT hr = result.error();
    DCHECK(FAILED(hr));
    LOG(ERROR) << __func__ << ": IsTokenAdmin failed: " << std::hex << hr;
  }
  return result;
}

bool IsUACOn() {
  // The presence of a split token definitively indicates that UAC is on. But
  // the absence of the token does not necessarily indicate that UAC is off.
  HResultOr<bool> is_split_token = IsUserRunningSplitToken();
  if (is_split_token.has_value() && is_split_token.value())
    return true;

  return IsExplorerRunningAtMediumOrLower();
}

bool IsElevatedWithUACOn() {
  HResultOr<bool> is_user_admin = IsUserAdmin();
  if (is_user_admin.has_value() && !is_user_admin.value())
    return false;

  return IsUACOn();
}

std::string GetUACState() {
  std::string s;

  HResultOr<bool> is_user_admin = IsUserAdmin();
  if (is_user_admin.has_value())
    base::StringAppendF(&s, "IsUserAdmin: %d, ", is_user_admin.value());

  HResultOr<bool> is_user_non_elevated_admin = IsUserNonElevatedAdmin();
  if (is_user_non_elevated_admin.has_value())
    base::StringAppendF(&s, "IsUserNonElevatedAdmin: %d, ",
                        is_user_non_elevated_admin.value());

  base::StringAppendF(&s, "IsUACOn: %d, ", IsUACOn());
  base::StringAppendF(&s, "IsElevatedWithUACOn: %d", IsElevatedWithUACOn());

  return s;
}

std::wstring GetServiceName(bool is_internal_service) {
  std::wstring service_name = GetServiceDisplayName(is_internal_service);
  service_name.erase(base::ranges::remove_if(service_name, isspace),
                     service_name.end());
  return service_name;
}

std::wstring GetServiceDisplayName(bool is_internal_service) {
  return base::StrCat(
      {base::ASCIIToWide(PRODUCT_FULLNAME_STRING), L" ",
       is_internal_service ? kWindowsInternalServiceName : kWindowsServiceName,
       L" ", kUpdaterVersionUtf16});
}

REGSAM Wow6432(REGSAM access) {
  CHECK(access);

  return KEY_WOW64_32KEY | access;
}

HResultOr<DWORD> ShellExecuteAndWait(const base::FilePath& file_path,
                                     const std::wstring& parameters,
                                     const std::wstring& verb) {
  VLOG(1) << __func__ << ": path: " << file_path
          << ", parameters:" << parameters << ", verb:" << verb;
  DCHECK(!file_path.empty());

  const HWND hwnd = CreateForegroundParentWindowForUAC();
  const base::ScopedClosureRunner destroy_window(base::BindOnce(
      [](HWND hwnd) {
        if (hwnd)
          ::DestroyWindow(hwnd);
      },
      hwnd));

  SHELLEXECUTEINFO shell_execute_info = {};
  shell_execute_info.cbSize = sizeof(SHELLEXECUTEINFO);
  shell_execute_info.fMask = SEE_MASK_FLAG_NO_UI | SEE_MASK_NOCLOSEPROCESS |
                             SEE_MASK_NOZONECHECKS | SEE_MASK_NOASYNC;
  shell_execute_info.hProcess = NULL;
  shell_execute_info.hwnd = hwnd;
  shell_execute_info.lpVerb = verb.c_str();
  shell_execute_info.lpFile = file_path.value().c_str();
  shell_execute_info.lpParameters = parameters.c_str();
  shell_execute_info.lpDirectory = NULL;
  shell_execute_info.nShow = SW_SHOW;
  shell_execute_info.hInstApp = NULL;

  if (!::ShellExecuteEx(&shell_execute_info)) {
    const HRESULT hr = HRESULTFromLastError();
    VLOG(1) << __func__ << ": ::ShellExecuteEx failed: " << std::hex << hr;
    return base::unexpected(hr);
  }

  if (!shell_execute_info.hProcess) {
    VLOG(1) << __func__ << ": Started process, PID unknown";
    return base::ok(0);
  }

  const base::Process process(shell_execute_info.hProcess);
  const DWORD pid = process.Pid();
  VLOG(1) << __func__ << ": Started process, PID: " << pid;

  // Allow the spawned process to show windows in the foreground.
  if (!::AllowSetForegroundWindow(pid)) {
    LOG(WARNING) << __func__
                 << ": ::AllowSetForegroundWindow failed: " << ::GetLastError();
  }

  int ret_val = 0;
  if (!process.WaitForExit(&ret_val))
    return base::unexpected(HRESULTFromLastError());

  return base::ok(static_cast<DWORD>(ret_val));
}

HResultOr<DWORD> RunElevated(const base::FilePath& file_path,
                             const std::wstring& parameters) {
  return ShellExecuteAndWait(file_path, parameters, L"runas");
}

HRESULT RunDeElevated(const std::wstring& path,
                      const std::wstring& parameters) {
  Microsoft::WRL::ComPtr<IShellWindows> shell;
  HRESULT hr = ::CoCreateInstance(CLSID_ShellWindows, nullptr,
                                  CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&shell));
  if (FAILED(hr))
    return hr;

  long hwnd = 0;
  Microsoft::WRL::ComPtr<IDispatch> dispatch;
  hr = shell->FindWindowSW(base::win::ScopedVariant(CSIDL_DESKTOP).AsInput(),
                           base::win::ScopedVariant().AsInput(), SWC_DESKTOP,
                           &hwnd, SWFO_NEEDDISPATCH, &dispatch);
  if (FAILED(hr))
    return hr;

  Microsoft::WRL::ComPtr<IServiceProvider> service;
  hr = dispatch.As(&service);
  if (FAILED(hr))
    return hr;

  Microsoft::WRL::ComPtr<IShellBrowser> browser;
  hr = service->QueryService(SID_STopLevelBrowser, IID_PPV_ARGS(&browser));
  if (FAILED(hr))
    return hr;

  Microsoft::WRL::ComPtr<IShellView> view;
  hr = browser->QueryActiveShellView(&view);
  if (FAILED(hr))
    return hr;

  hr = view->GetItemObject(SVGIO_BACKGROUND, IID_PPV_ARGS(&dispatch));
  if (FAILED(hr))
    return hr;

  Microsoft::WRL::ComPtr<IShellFolderViewDual> folder;
  hr = dispatch.As(&folder);
  if (FAILED(hr))
    return hr;

  hr = folder->get_Application(&dispatch);
  if (FAILED(hr))
    return hr;

  Microsoft::WRL::ComPtr<IShellDispatch2> shell_dispatch;
  hr = dispatch.As(&shell_dispatch);
  if (FAILED(hr))
    return hr;

  return shell_dispatch->ShellExecute(
      base::win::ScopedBstr(path).Get(),
      base::win::ScopedVariant(parameters.c_str()),
      base::win::ScopedVariant::kEmptyVariant,
      base::win::ScopedVariant::kEmptyVariant,
      base::win::ScopedVariant::kEmptyVariant);
}

absl::optional<base::FilePath> GetGoogleUpdateExePath(UpdaterScope scope) {
  base::FilePath goopdate_base_dir;
  if (!base::PathService::Get(scope == UpdaterScope::kSystem
                                  ? base::DIR_PROGRAM_FILESX86
                                  : base::DIR_LOCAL_APP_DATA,
                              &goopdate_base_dir)) {
    LOG(ERROR) << "Can't retrieve GoogleUpdate base directory.";
    return absl::nullopt;
  }

  base::FilePath goopdate_dir =
      goopdate_base_dir.AppendASCII(COMPANY_SHORTNAME_STRING)
          .AppendASCII("Update");
  if (!base::CreateDirectory(goopdate_dir)) {
    LOG(ERROR) << "Can't create GoogleUpdate directory: " << goopdate_dir;
    return absl::nullopt;
  }

  return goopdate_dir.AppendASCII(base::WideToASCII(kLegacyExeName));
}

HRESULT DisableCOMExceptionHandling() {
  Microsoft::WRL::ComPtr<IGlobalOptions> options;
  HRESULT hr = ::CoCreateInstance(CLSID_GlobalOptions, nullptr,
                                  CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&options));
  if (FAILED(hr))
    return hr;
  return hr = options->Set(COMGLB_EXCEPTION_HANDLING,
                           COMGLB_EXCEPTION_DONOT_HANDLE);
}

std::wstring BuildMsiCommandLine(
    const std::wstring& arguments,
    const absl::optional<base::FilePath>& installer_data_file,
    const base::FilePath& msi_installer) {
  if (!msi_installer.MatchesExtension(L".msi")) {
    return std::wstring();
  }

  return base::StrCat(
      {L"msiexec ", arguments,
       installer_data_file
           ? base::StrCat(
                 {L" ",
                  base::UTF8ToWide(base::ToUpperASCII(kInstallerDataSwitch)),
                  L"=\"", installer_data_file->value(), L"\""})
           : L"",
       L" REBOOT=ReallySuppress /qn /i \"", msi_installer.value(),
       L"\" /log \"", msi_installer.value(), L".log\""});
}

std::wstring BuildExeCommandLine(
    const std::wstring& arguments,
    const absl::optional<base::FilePath>& installer_data_file,
    const base::FilePath& exe_installer) {
  if (!exe_installer.MatchesExtension(L".exe")) {
    return std::wstring();
  }

  return base::StrCat({base::CommandLine(exe_installer).GetCommandLineString(),
                       L" ", arguments, [&installer_data_file]() {
                         if (!installer_data_file)
                           return std::wstring();

                         base::CommandLine installer_data_args(
                             base::CommandLine::NO_PROGRAM);
                         installer_data_args.AppendSwitchPath(
                             kInstallerDataSwitch, *installer_data_file);
                         return installer_data_args.GetCommandLineString();
                       }()});
}

bool IsServiceRunning(const std::wstring& service_name) {
  ScopedScHandle scm(::OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT));
  if (!scm.IsValid()) {
    LOG(ERROR) << "::OpenSCManager failed. service_name: " << service_name
               << ", error: " << std::hex << HRESULTFromLastError();
    return false;
  }

  ScopedScHandle service(
      ::OpenService(scm.Get(), service_name.c_str(), SERVICE_QUERY_STATUS));
  if (!service.IsValid()) {
    LOG(ERROR) << "::OpenService failed. service_name: " << service_name
               << ", error: " << std::hex << HRESULTFromLastError();
    return false;
  }

  SERVICE_STATUS status = {0};
  if (!::QueryServiceStatus(service.Get(), &status)) {
    LOG(ERROR) << "::QueryServiceStatus failed. service_name: " << service_name
               << ", error: " << std::hex << HRESULTFromLastError();
    return false;
  }

  VLOG(1) << "IsServiceRunning. service_name: " << service_name
          << ", status: " << std::hex << status.dwCurrentState;
  return status.dwCurrentState == SERVICE_RUNNING ||
         status.dwCurrentState == SERVICE_START_PENDING;
}

HKEY UpdaterScopeToHKeyRoot(UpdaterScope scope) {
  return scope == UpdaterScope::kSystem ? HKEY_LOCAL_MACHINE
                                        : HKEY_CURRENT_USER;
}

absl::optional<OSVERSIONINFOEX> GetOSVersion() {
  // `::RtlGetVersion` is being used here instead of `::GetVersionEx`, because
  // the latter function can return the incorrect version if it is shimmed using
  // an app compat shim.
  using RtlGetVersion = LONG(WINAPI*)(OSVERSIONINFOEX*);
  static const RtlGetVersion rtl_get_version = reinterpret_cast<RtlGetVersion>(
      ::GetProcAddress(::GetModuleHandle(L"ntdll.dll"), "RtlGetVersion"));
  if (!rtl_get_version)
    return absl::nullopt;

  OSVERSIONINFOEX os_out = {};
  os_out.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

  rtl_get_version(&os_out);
  if (!os_out.dwMajorVersion)
    return absl::nullopt;

  return os_out;
}

bool CompareOSVersions(const OSVERSIONINFOEX& os_version, BYTE oper) {
  DCHECK(oper);

  constexpr DWORD kOSTypeMask = VER_MAJORVERSION | VER_MINORVERSION |
                                VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR;
  constexpr DWORD kBuildTypeMask = VER_BUILDNUMBER;

  // If the OS and the service pack match, return the build number comparison.
  return CompareOSVersionsInternal(os_version, kOSTypeMask, VER_EQUAL)
             ? CompareOSVersionsInternal(os_version, kBuildTypeMask, oper)
             : CompareOSVersionsInternal(os_version, kOSTypeMask, oper);
}

bool EnableSecureDllLoading() {
  static const auto set_default_dll_directories =
      reinterpret_cast<decltype(&::SetDefaultDllDirectories)>(::GetProcAddress(
          ::GetModuleHandle(L"kernel32.dll"), "SetDefaultDllDirectories"));

  if (!set_default_dll_directories)
    return true;

#if defined(COMPONENT_BUILD)
  const DWORD directory_flags = LOAD_LIBRARY_SEARCH_DEFAULT_DIRS;
#else
  const DWORD directory_flags = LOAD_LIBRARY_SEARCH_SYSTEM32;
#endif

  return set_default_dll_directories(directory_flags);
}

bool EnableProcessHeapMetadataProtection() {
  if (!::HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, nullptr,
                            0)) {
    LOG(ERROR) << __func__
               << ": Failed to enable heap metadata protection: " << std::hex
               << HRESULTFromLastError();
    return false;
  }

  return true;
}

absl::optional<base::ScopedTempDir> CreateSecureTempDir() {
  base::FilePath temp_dir;
  if (!base::CreateNewTempDirectory(FILE_PATH_LITERAL(COMPANY_SHORTNAME_STRING),
                                    &temp_dir)) {
    return absl::nullopt;
  }

  base::ScopedTempDir temp_dir_owner;
  if (temp_dir_owner.Set(temp_dir)) {
    return temp_dir_owner;
  } else {
    return absl::nullopt;
  }
}

base::ScopedClosureRunner SignalShutdownEvent(UpdaterScope scope) {
  NamedObjectAttributes attr = GetNamedObjectAttributes(kShutdownEvent, scope);

  base::win::ScopedHandle shutdown_event_handle(
      ::CreateEvent(&attr.sa, true, false, attr.name.c_str()));
  if (!shutdown_event_handle.IsValid()) {
    VLOG(1) << __func__ << "Could not create the shutdown event: " << std::hex
            << HRESULTFromLastError();
    return {};
  }

  auto shutdown_event =
      std::make_unique<base::WaitableEvent>(std::move(shutdown_event_handle));
  shutdown_event->Signal();
  return base::ScopedClosureRunner(
      base::BindOnce(&base::WaitableEvent::Reset, std::move(shutdown_event)));
}

bool IsShutdownEventSignaled(UpdaterScope scope) {
  NamedObjectAttributes attr = GetNamedObjectAttributes(kShutdownEvent, scope);

  base::win::ScopedHandle event_handle(
      ::OpenEvent(EVENT_ALL_ACCESS, false, attr.name.c_str()));
  if (!event_handle.IsValid())
    return false;

  base::WaitableEvent event(std::move(event_handle));
  return event.IsSignaled();
}

bool StopGoogleUpdateProcesses(UpdaterScope scope) {
  // Filters processes running under `path_prefix`.
  class PathPrefixProcessFilter : public base::ProcessFilter {
   public:
    explicit PathPrefixProcessFilter(const base::FilePath& path_prefix)
        : path_prefix_(path_prefix) {}

    bool Includes(const base::ProcessEntry& entry) const override {
      base::Process process(::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,
                                          false, entry.th32ProcessID));
      if (!process.IsValid())
        return false;

      DWORD path_len = MAX_PATH;
      wchar_t path_string[MAX_PATH];
      if (!::QueryFullProcessImageName(process.Handle(), 0, path_string,
                                       &path_len)) {
        return false;
      }

      return path_prefix_.IsParent(base::FilePath(path_string));
    }

   private:
    const base::FilePath path_prefix_;
  };

  constexpr base::TimeDelta kShutdownWaitSeconds = base::Seconds(45);

  absl::optional<base::FilePath> target = GetGoogleUpdateExePath(scope);
  if (!target)
    return false;

  PathPrefixProcessFilter path_prefix_filter(target->DirName());
  return base::CleanupProcesses(kLegacyExeName, kShutdownWaitSeconds, -1,
                                &path_prefix_filter);
}

absl::optional<base::CommandLine> CommandLineForLegacyFormat(
    const std::wstring& cmd_string) {
  wchar_t** args = nullptr;
  int num_args = 0;
  args = ::CommandLineToArgvW(cmd_string.c_str(), &num_args);

  auto is_switch = [](const std::wstring& arg) { return arg[0] == L'-'; };

  auto is_legacy_switch = [](const std::wstring& arg) {
    return arg[0] == L'/';
  };

  // First argument is the program.
  base::CommandLine command_line(base::FilePath{args[0]});

  for (int i = 1; i < num_args; ++i) {
    const std::wstring next_arg = i < num_args - 1 ? args[i + 1] : L"";

    if (is_switch(args[i]) || is_switch(next_arg)) {
      // Won't parse Chromium-style command line.
      return absl::nullopt;
    }

    if (!is_legacy_switch(args[i])) {
      // This is a bare argument.
      command_line.AppendArg(base::WideToASCII(args[i]));
      continue;
    }

    const std::string switch_name = base::WideToASCII(&args[i][1]);
    if (switch_name.empty()) {
      VLOG(1) << "Empty switch in command line: [" << cmd_string << "]";
      return absl::nullopt;
    }

    if (is_legacy_switch(next_arg) || next_arg.empty()) {
      command_line.AppendSwitch(switch_name);
    } else {
      // Next argument is the value for this switch.
      command_line.AppendSwitchNative(switch_name, next_arg);
      ++i;
    }
  }

  return command_line;
}

absl::optional<base::FilePath> GetApplicationDataDirectory(UpdaterScope scope) {
  base::FilePath app_data_dir;
  if (!base::PathService::Get(scope == UpdaterScope::kSystem
                                  ? base::DIR_PROGRAM_FILES
                                  : base::DIR_LOCAL_APP_DATA,
                              &app_data_dir)) {
    LOG(ERROR) << "Can't retrieve app data directory.";
    return absl::nullopt;
  }
  return app_data_dir;
}

absl::optional<base::FilePath> GetBaseInstallDirectory(UpdaterScope scope) {
  absl::optional<base::FilePath> app_data_dir =
      GetApplicationDataDirectory(scope);
  return app_data_dir ? app_data_dir->AppendASCII(COMPANY_SHORTNAME_STRING)
                            .AppendASCII(PRODUCT_FULLNAME_STRING)
                      : app_data_dir;
}

base::FilePath GetExecutableRelativePath() {
  return base::FilePath::FromASCII(kExecutableName);
}

}  // namespace updater


text:
Facter.add(:domain) do
  setcode do
    # Get the domain from various sources; the order of these
    # steps is important

    # In some OS 'hostname -f' will change the hostname to '-f'
    # We know that Solaris and HP-UX exhibit this behavior
    # On good OS, 'hostname -f' will return the FQDN which is preferable
    # Due to dangerous behavior of 'hostname -f' on old OS, we will explicitly opt-in
    # 'hostname -f' --hkenney May 9, 2012
    basic_hostname = 'hostname 2> /dev/null'
    windows_hostname = 'hostname > NUL'
    full_hostname = 'hostname -f 2> /dev/null'
    can_do_hostname_f = Regexp.union /Linux/i, /FreeBSD/i, /Darwin/i

    hostname_command = if Facter.value(:kernel) =~ can_do_hostname_f
                         full_hostname
                       elsif Facter.value(:kernel) == "windows"
                         windows_hostname
                       else
                         basic_hostname
                       end

    if name = Facter::Core::Execution.exec(hostname_command) \
      and name =~ /.*?\.(.+$)/

      return_value = $1
    elsif Facter.value(:kernel) != "windows" and domain = Facter::Core::Execution.exec('dnsdomainname 2> /dev/null') \
      and domain =~ /.+/

      return_value = domain
    elsif FileTest.exists?("/etc/resolv.conf")
      domain = nil
      search = nil
      File.open("/etc/resolv.conf") { |file|
        file.each { |line|
          if line =~ /^\s*domain\s+(\S+)/
            domain = $1
          elsif line =~ /^\s*search\s+(\S+)/
            search = $1
          end
        }
      }
      return_value ||= domain
      return_value ||= search
    end

    if return_value
      return_value.gsub(/\.$/, '')
    end
  end
end

Facter.add(:domain) do
  confine :kernel => :windows
  setcode do
    require 'facter/util/registry'

    domain = nil
    regvalue = Facter::Util::Registry.hklm_read('SYSTEM\CurrentControlSet\Services\Tcpip\Parameters', 'Domain')

    if regvalue and not regvalue.empty?
      domain = regvalue
    else
      require 'facter/util/wmi'
      Facter::Util::WMI.execquery("select DNSDomain from Win32_NetworkAdapterConfiguration where IPEnabled = True").each { |nic|
        if nic.DNSDomain && nic.DNSDomain.length > 0
          domain = nic.DNSDomain
          break
        end
      }
    end

    if domain
      domain.gsub(/\.$/, '')
    end
  end
end


text:
using System;
using System.Linq;
using System.Windows.Forms;

namespace HTTPServer
{
    public partial class MainForm : Form
    {
        private HTTPServer server;

        public MainForm()
        {
            InitializeComponent();

            try
            {
                server = new HTTPServer("http://localhost:8080/", "HTTPServerCatalog");

                server.Request += server_NewRequest;
                server.Response += server_NewResponse;

                server.Start();
            }
            catch
            {
                MessageBox.Show("Во время выполнения программы произошла ошибка");
            }
        }

        private void addTextToOutput(string text)
        {
            richTextBoxOutput.Invoke(new Action(() => { richTextBoxOutput.Text = text + richTextBoxOutput.Text; }));
        }

        private void server_NewRequest(object sender, RequestEventArgs e)
        {
            addTextToOutput("Сервер получил запрос\n" + e.ToString());
        }

        void server_NewResponse(object sender, ResponseEventArgs e)
        {
            addTextToOutput("Сервер отправил ответ\n" + e.ToString());
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            server.Stop();
        }
    }
}


text:
package ru.elazarev.extra;

import org.junit.Test;
import java.util.Comparator;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Test for ExtraTask class.
 * @author Eugene Lazarev mailto(helycopternicht@rambler.ru)
 * @since 03.07.17
 */
public class ExtraTaskTest {

    /**
     * Test merge method.
     */
    @Test
    public void whenTwoSortedArraysThenOneSortedArray() {
        ExtraTask ex = new ExtraTask();
        Integer[] first = {1, 2, 6, 10, 16};
        Integer[] second = {7, 11, 3, 4, 20};
        Integer[] expect = {1, 2, 3, 4, 6, 7, 10, 11, 16, 20};

        assertThat(ex.merge(first, second, new IntComparator()), is(expect));
    }

    /**
     * Test merge method.
     */
    @Test
    public void whenTwoSortedArraysWithDifferentLengthThenOneSortedArray() {
        ExtraTask ex = new ExtraTask();
        Integer[] first = {1, 2, 6, 10, 16};
        Integer[] second = {3, 7, 4};
        Integer[] expect = {1, 2, 3, 4, 6, 7, 10, 16};

        assertThat(ex.merge(first, second, new IntComparator()), is(expect));
    }

    /**
     * Test merge method.
     */
    @Test
    public void whenOneArrayIsEmptyThenOneSortedArray() {
        ExtraTask ex = new ExtraTask();
        Integer[] first = {1, 2, 6, 10, 16};
        Integer[] second = {};
        Integer[] expect = {1, 2, 6, 10, 16};

        assertThat(ex.merge(first, second, new IntComparator()), is(expect));
    }

    /**
     * Integer comparator.
     */
    class IntComparator implements Comparator<Integer> {
        /**
         * Compares its two arguments for order.  Returns a negative integer,
         * zero, or a positive integer as the first argument is less than, equal
         * to, or greater than the second.
         * @param o1 the first object to be compared.
         * @param o2 the second object to be compared.
         * @return a negative integer, zero, or a positive integer as the
         *         first argument is less than, equal to, or greater than the
         *         second.
         */
        @Override
        public int compare(Integer o1, Integer o2) {
            return o1.compareTo(o2);
        }
    }

}


text:
<?php

namespace NasExt\Forms;

use Nette;

/**
 * @property array $items
 * @property string|int $value
 * @property string $prompt
 *
 * @author Dusan Hudak
 * @author Ales Wita
 * @license MIT
 */
class DependentData
{
	use Nette\SmartObject;

	/** @var array */
	private $items = [];

	/** @var string|int */
	private $value;

	/** @var string */
	private $prompt;

	/**
	 * @param array $items
	 * @param string|int $value
	 * @param string $prompt
	 */
	public function __construct(array $items = [], $value = null, $prompt = null)
	{
		$this->items = $items;
		$this->value = $value;
		$this->prompt = $prompt;
	}

	/**
	 * @return array
	 */
	public function getItems()
	{
		return $this->items;
	}

	/**
	 * @param array $items
	 * @return self
	 */
	public function setItems(array $items)
	{
		$this->items = $items;
		return $this;
	}

	/**
	 * @return string|int
	 */
	public function getValue()
	{
		return $this->value;
	}

	/**
	 * @param string|int $value
	 * @return self
	 */
	public function setValue($value)
	{
		$this->value = $value;
		return $this;
	}

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

	/**
	 * @param string $value
	 * @return self
	 */
	public function setPrompt($value)
	{
		$this->prompt = $value;
		return $this;
	}

	/**
	 * @param array $disabledItems
	 * @return array
	 */
	public function getPreparedItems($disabledItems = null)
	{
		$items = [];
		foreach ($this->items as $key => $item) {
			$elements = [];
			if (is_array($item)) {
				$groupItems = [];
				foreach ($item as $innerKey => $innerItem) {
					$el = $this->getPreparedElement($innerKey, $innerItem, $disabledItems);
					$this->addElementToItemsList($groupItems, $el);
				}

				$items[$key] = [
					'key' => $key,
					'value' => $groupItems,
				];

			} else {
				$el = $this->getPreparedElement($key, $item, $disabledItems);
				$this->addElementToItemsList($items, $el);
			}
		}
		// make a List so the order of items is preserved when sent as JSON to client
		return array_values($items);
	}

	/**
	 * @param string $key
	 * @param mixed $item
	 * @param array|null $disabledItems
	 * @return Nette\Utils\Html
	 */
	private function getPreparedElement($key, $item, $disabledItems = null)
	{
		if (!($item instanceof Nette\Utils\Html)) {
			$el = Nette\Utils\Html::el('option')->value($key)->setText($item);

		} else {
			$el = $item;
		}

		// disable element
		if (is_array($disabledItems) && array_key_exists($key, $disabledItems) && $disabledItems[$key] === true) {
			$el->disabled(true);
		}

		return $el;
	}

	/**
	 * @param array &$items
	 * @param Nette\Utils\Html $el
	 */
	private function addElementToItemsList(&$items, $el)
	{
		$items[$el->getAttribute('value')] = [
			'key' => $el->getValue(),
			'value' => $el->getText(),
		];
		end($items);
		$lKey = key($items);
		foreach ($el->attrs as $attr => $val) {
			$items[$lKey]['attributes'][$attr] = $val;
		}
	}
}


text:
Octree in javascript. Extremely fast module to query points in 3D space. Can
be used to find points under mouse cursor in 3D scene. Compare: [hit-test
speed with native three.js vs octree](https://www.youtube.com/watch?v=9Z-Yzb-WSKg)

# usage

This module is best suited for static scenes, where points are not changed
over time. To get started initialize the tree:

``` js
// First we need to create the tree:
var createTree = require('yaot');

var tree = createTree();
var points = [
  0, 0, 0, // First point at 0, 0, 0
  10, 0, 0 // second point at 10, 0, 0
]
tree.init(points);

// Now we are ready to query it:
// Which points lie inside sphere with center at 0, 0, 0 and radius 2?
var matches = tree.intersectSphere(0, 0, 0, 2);
// matches[0] === 0 -> the point at first index of `points` array is there!

// Let's extend our sphere:
var matches = tree.intersectSphere(0, 0, 0, 20);
// matches[0] === 0 -> Point at index 0 is here too
// matches[1] === 3 -> Point at index 3 from `points` array also inisde
```

You can also query points which lies inside octants intersected by a ray. This
is very useful when you want to know which points lie under mouse cursor.

``` js
var rayOrigin = {
  x: 1, y: 0, z: 0
};
var rayDirection = {
  x: -1, y: 0, z: 0
};
var matches = tree.intersectRay(rayOrigin, rayDirection)

// If you want to limit where ray starts checking against intersection
// you can pass option `near` argumnet:
var near = 10; // by default it is 0, but could be made bigger!
var matches10PixelsAway = tree.intersectRay(rayOrigin, rayDirection, near);

// You can also limit upper bound by setting `far` argument:
var far = 100; // By default it is positive infinity, which matches all.
var matchesPointsBetween10And100Pixels =
    tree.intersectRay(rayOrigin, rayDirection, near, far);
```

To see how to use it with three.js please read about demo below.

# demo

A three.js demo is available [here](http://anvaka.github.io/yaot/demo/octree.html) ([src](https://github.com/anvaka/yaot/blob/master/demo/octree.js#L104)).
You can compare its performance to native three.js [`raycaster.intersectObjects()`
method](http://anvaka.github.io/yaot/demo/raycaster.html) ([src](https://github.com/anvaka/yaot/blob/master/demo/raycaster.js#L103)).
Open dev console on both pages to see the timers. Octree solution is 42 times faster than
native `raycaster.intersectObjects()`.

Keep in mind that raycaster is generalized solution which works with any three.js
objects, while octree is very much specialized.

This module is also used in the [code galaxies](http://anvaka.github.io/pm/).
Source code is [here](https://github.com/anvaka/unrender/blob/master/lib/hit-test.js).

# install

With [npm](https://npmjs.org) do:

```
npm install yaot
```

# license

MIT


text:
package org.mongodb.morphia.query.validation;

import org.junit.Test;
import org.mongodb.morphia.Key;
import org.mongodb.morphia.entities.SimpleEntity;

import java.util.ArrayList;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class EntityAnnotatedValueValidatorTest {
    @Test
    public void shouldAllowValueWithEntityAnnotationAndTypeOfKey() {
        // given
        ArrayList<ValidationFailure> validationFailures = new ArrayList<>();
        // when
        boolean validationApplied = EntityAnnotatedValueValidator.getInstance().apply(Key.class, new SimpleEntity(), validationFailures);
        // then
        assertThat(validationApplied, is(true));
        assertThat(validationFailures.size(), is(0));
    }

    @Test
    public void shouldNotValidateValueWithEntityAnnotationAndNonKeyType() {
        // given
        ArrayList<ValidationFailure> validationFailures = new ArrayList<>();
        // when
        boolean validationApplied = EntityAnnotatedValueValidator.getInstance().apply(String.class, new SimpleEntity(), validationFailures);
        // then
        assertThat(validationApplied, is(false));
        assertThat(validationFailures.size(), is(0));
    }

    @Test
    public void shouldRejectValueWithoutEntityAnnotationAndTypeOfKey() {
        // given
        ArrayList<ValidationFailure> validationFailures = new ArrayList<>();
        // when
        boolean validationApplied = EntityAnnotatedValueValidator.getInstance().apply(Key.class, "value", validationFailures);
        // then
        assertThat(validationApplied, is(true));
        assertThat(validationFailures.size(), is(1));
    }
}


text:
package org.apache.camel.component.braintree;

import com.braintreegateway.CreditCardVerification;
import com.braintreegateway.ResourceCollection;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.braintree.internal.BraintreeApiCollection;
import org.apache.camel.component.braintree.internal.CreditCardVerificationGatewayApiMethod;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.jupiter.api.Assertions.assertNotNull;

@EnabledIfSystemProperty(named = "braintreeAuthenticationType", matches = ".*")
public class CreditCardVerificationGatewayIT extends AbstractBraintreeTestSupport {

    private static final Logger LOG = LoggerFactory.getLogger(CreditCardVerificationGatewayIT.class);
    private static final String PATH_PREFIX
            = BraintreeApiCollection.getCollection().getApiName(CreditCardVerificationGatewayApiMethod.class).getName();

    // TODO provide parameter values for find
    @Disabled
    @Test
    public void testFind() {
        // using String message body for single parameter "id"
        final CreditCardVerification result = requestBody("direct://FIND", null, CreditCardVerification.class);

        assertNotNull(result, "find result");
        LOG.debug("find: " + result);
    }

    // TODO provide parameter values for search
    @Disabled
    @Test
    public void testSearch() {
        // using com.braintreegateway.CreditCardVerificationSearchRequest message body for single parameter "query"
        final ResourceCollection<CreditCardVerification> result
                = requestBody("direct://SEARCH", null, ResourceCollection.class);

        assertNotNull(result, "search result");
        LOG.debug("search: " + result);
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                // test route for find
                from("direct://FIND")
                        .to("braintree://" + PATH_PREFIX + "/find?inBody=id");
                // test route for search
                from("direct://SEARCH")
                        .to("braintree://" + PATH_PREFIX + "/search?inBody=query");
            }
        };
    }
}