text:
package org.apache.tez.dag.app.rm;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerExitStatus;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.NodeReport;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.event.Event;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.tez.dag.api.TezConfiguration;
import org.apache.tez.dag.api.TezUncheckedException;
import org.apache.tez.dag.api.TaskLocationHint;
import org.apache.tez.dag.api.TaskLocationHint.TaskBasedLocationAffinity;
import org.apache.tez.dag.api.client.DAGClientServer;
import org.apache.tez.dag.api.oldrecords.TaskAttemptState;
import org.apache.tez.dag.app.AppContext;
import org.apache.tez.dag.app.DAGAppMaster;
import org.apache.tez.dag.app.DAGAppMasterState;
import org.apache.tez.dag.app.dag.TaskAttempt;
import org.apache.tez.dag.app.dag.Vertex;
import org.apache.tez.dag.app.dag.event.DAGAppMasterEvent;
import org.apache.tez.dag.app.dag.event.DAGAppMasterEventSchedulingServiceError;
import org.apache.tez.dag.app.dag.event.DAGAppMasterEventType;
import org.apache.tez.dag.app.dag.event.DAGEventSchedulerUpdateTAAssigned;
import org.apache.tez.dag.app.rm.TaskSchedulerService.TaskSchedulerAppCallback;
import org.apache.tez.dag.app.rm.container.AMContainer;
import org.apache.tez.dag.app.rm.container.AMContainerEventAssignTA;
import org.apache.tez.dag.app.rm.container.AMContainerEventCompleted;
import org.apache.tez.dag.app.rm.container.AMContainerEventLaunchRequest;
import org.apache.tez.dag.app.rm.container.AMContainerEventStopRequest;
import org.apache.tez.dag.app.rm.container.AMContainerEventTASucceeded;
import org.apache.tez.dag.app.rm.container.AMContainerState;
import org.apache.tez.dag.app.rm.container.ContainerSignatureMatcher;
import org.apache.tez.dag.app.rm.node.AMNodeEventContainerAllocated;
import org.apache.tez.dag.app.rm.node.AMNodeEventNodeCountUpdated;
import org.apache.tez.dag.app.rm.node.AMNodeEventStateChanged;
import org.apache.tez.dag.app.rm.node.AMNodeEventTaskAttemptEnded;
import org.apache.tez.dag.app.rm.node.AMNodeEventTaskAttemptSucceeded;
import org.apache.tez.dag.records.TaskAttemptTerminationCause;

import com.google.common.base.Preconditions;

public class TaskSchedulerEventHandler extends AbstractService
                                         implements TaskSchedulerAppCallback,
                                               EventHandler<AMSchedulerEvent> {
  static final Log LOG = LogFactory.getLog(TaskSchedulerEventHandler.class);

  protected final AppContext appContext;
  @SuppressWarnings("rawtypes")
  private final EventHandler eventHandler;
  protected TaskSchedulerService taskScheduler;
  private DAGAppMaster dagAppMaster;
  private Map<ApplicationAccessType, String> appAcls = null;
  private Thread eventHandlingThread;
  private volatile boolean stopEventHandling;
  // Has a signal (SIGTERM etc) been issued?
  protected volatile boolean isSignalled = false;
  final DAGClientServer clientService;
  private final ContainerSignatureMatcher containerSignatureMatcher;
  private int cachedNodeCount = -1;
  private AtomicBoolean shouldUnregisterFlag =
      new AtomicBoolean(false);

  BlockingQueue<AMSchedulerEvent> eventQueue
                              = new LinkedBlockingQueue<AMSchedulerEvent>();

  @SuppressWarnings("rawtypes")
  public TaskSchedulerEventHandler(AppContext appContext,
      DAGClientServer clientService, EventHandler eventHandler, ContainerSignatureMatcher containerSignatureMatcher) {
    super(TaskSchedulerEventHandler.class.getName());
    this.appContext = appContext;
    this.eventHandler = eventHandler;
    this.clientService = clientService;
    this.containerSignatureMatcher = containerSignatureMatcher;
  }

  public Map<ApplicationAccessType, String> getApplicationAcls() {
    return appAcls;
  }

  public void setSignalled(boolean isSignalled) {
    this.isSignalled = isSignalled;
    LOG.info("TaskScheduler notified that iSignalled was : " + isSignalled);
  }

  public int getNumClusterNodes() {
    return cachedNodeCount;
  }

  public Resource getAvailableResources() {
    return taskScheduler.getAvailableResources();
  }

  public Resource getTotalResources() {
    return taskScheduler.getTotalResources();
  }

  public synchronized void handleEvent(AMSchedulerEvent sEvent) {
    LOG.info("Processing the event " + sEvent.toString());
    switch (sEvent.getType()) {
    case S_TA_LAUNCH_REQUEST:
      handleTaLaunchRequest((AMSchedulerEventTALaunchRequest) sEvent);
      break;
    case S_TA_ENDED: // TaskAttempt considered complete.
      AMSchedulerEventTAEnded event = (AMSchedulerEventTAEnded)sEvent;
      switch(event.getState()) {
      case FAILED:
      case KILLED:
        handleTAUnsuccessfulEnd((AMSchedulerEventTAEnded) sEvent);
        break;
      case SUCCEEDED:
        handleTASucceeded(event);
        break;
      default:
        throw new TezUncheckedException("Unexecpted TA_ENDED state: " + event.getState());
      }
      break;
    case S_CONTAINER_DEALLOCATE:
      handleContainerDeallocate((AMSchedulerEventDeallocateContainer)sEvent);
      break;
    case S_NODE_UNBLACKLISTED:
      // fall through
    case S_NODE_BLACKLISTED:
      handleNodeBlacklistUpdate((AMSchedulerEventNodeBlacklistUpdate)sEvent);
      break;
    case S_NODE_UNHEALTHY:
      break;
    case S_NODE_HEALTHY:
      // Consider changing this to work like BLACKLISTING.
      break;
    default:
      break;
    }
  }

  @Override
  public void handle(AMSchedulerEvent event) {
    int qSize = eventQueue.size();
    if (qSize != 0 && qSize % 1000 == 0) {
      LOG.info("Size of event-queue in RMContainerAllocator is " + qSize);
    }
    int remCapacity = eventQueue.remainingCapacity();
    if (remCapacity < 1000) {
      LOG.warn("Very low remaining capacity in the event-queue "
          + "of RMContainerAllocator: " + remCapacity);
    }
    try {
      eventQueue.put(event);
    } catch (InterruptedException e) {
      throw new TezUncheckedException(e);
    }
  }

  @SuppressWarnings("unchecked")
  private void sendEvent(Event<?> event) {
    eventHandler.handle(event);
  }

  private void handleNodeBlacklistUpdate(AMSchedulerEventNodeBlacklistUpdate event) {
    if (event.getType() == AMSchedulerEventType.S_NODE_BLACKLISTED) {
      taskScheduler.blacklistNode(event.getNodeId());
    } else if (event.getType() == AMSchedulerEventType.S_NODE_UNBLACKLISTED) {
      taskScheduler.unblacklistNode(event.getNodeId());
    } else {
      throw new TezUncheckedException("Invalid event type: " + event.getType());
    }
  }

  private void handleContainerDeallocate(
                                  AMSchedulerEventDeallocateContainer event) {
    ContainerId containerId = event.getContainerId();
    // TODO what happens to the task that was connected to this container?
    // current assumption is that it will eventually call handleTaStopRequest
    //TaskAttempt taskAttempt = (TaskAttempt)
    taskScheduler.deallocateContainer(containerId);
    // TODO does this container need to be stopped via C_STOP_REQUEST
    sendEvent(new AMContainerEventStopRequest(containerId));
  }

  private void handleTAUnsuccessfulEnd(AMSchedulerEventTAEnded event) {
    TaskAttempt attempt = event.getAttempt();
    boolean wasContainerAllocated = taskScheduler.deallocateTask(attempt, false);
    // use stored value of container id in case the scheduler has removed this
    // assignment because the task has been deallocated earlier.
    // retroactive case
    ContainerId attemptContainerId = attempt.getAssignedContainerID();

    if(!wasContainerAllocated) {
      LOG.info("Task: " + attempt.getID() +
          " has no container assignment in the scheduler");
      if (attemptContainerId != null) {
        LOG.error("No container allocated to task: " + attempt.getID()
            + " according to scheduler. Task reported container id: "
            + attemptContainerId);
      }
    }

    if (attemptContainerId != null) {
      // TODO either ways send the necessary events
      // Ask the container to stop.
      sendEvent(new AMContainerEventStopRequest(attemptContainerId));
      // Inform the Node - the task has asked to be STOPPED / has already
      // stopped.
      sendEvent(new AMNodeEventTaskAttemptEnded(appContext.getAllContainers().
          get(attemptContainerId).getContainer().getNodeId(), attemptContainerId,
          attempt.getID(), event.getState() == TaskAttemptState.FAILED));
    }
  }

  private void handleTASucceeded(AMSchedulerEventTAEnded event) {
    TaskAttempt attempt = event.getAttempt();
    ContainerId usedContainerId = event.getUsedContainerId();

    // This could be null if a task fails / is killed before a container is
    // assigned to it.
    if (event.getUsedContainerId() != null) {
      sendEvent(new AMContainerEventTASucceeded(usedContainerId,
          event.getAttemptID()));
      sendEvent(new AMNodeEventTaskAttemptSucceeded(appContext.getAllContainers().
          get(usedContainerId).getContainer().getNodeId(), usedContainerId,
          event.getAttemptID()));
    }

    boolean wasContainerAllocated = taskScheduler.deallocateTask(attempt, true);
    if (!wasContainerAllocated) {
      LOG.error("De-allocated successful task: " + attempt.getID()
          + ", but TaskScheduler reported no container assigned to task");
    }
  }

  private void handleTaLaunchRequest(AMSchedulerEventTALaunchRequest event) {
    TaskAttempt taskAttempt = event.getTaskAttempt();
    TaskLocationHint locationHint = event.getLocationHint();
    String hosts[] = null;
    String racks[] = null;
    if (locationHint != null) {
      TaskBasedLocationAffinity taskAffinity = locationHint.getAffinitizedTask();
      if (taskAffinity != null) {
        Vertex vertex = appContext.getCurrentDAG().getVertex(taskAffinity.getVertexName());
        Preconditions.checkNotNull(vertex, "Invalid vertex in task based affinity " + taskAffinity
            + " for attempt: " + taskAttempt.getID());
        int taskIndex = taskAffinity.getTaskIndex();
        Preconditions.checkState(taskIndex >=0 && taskIndex < vertex.getTotalTasks(),
            "Invalid taskIndex in task based affinity " + taskAffinity
            + " for attempt: " + taskAttempt.getID());
        TaskAttempt affinityAttempt = vertex.getTask(taskIndex).getSuccessfulAttempt();
        if (affinityAttempt != null) {
          Preconditions.checkNotNull(affinityAttempt.getAssignedContainerID(), affinityAttempt.getID());
          taskScheduler.allocateTask(taskAttempt,
              event.getCapability(),
              affinityAttempt.getAssignedContainerID(),
              Priority.newInstance(event.getPriority()),
              event.getContainerContext(),
              event);
          return;
        }
        LOG.info("Attempt: " + taskAttempt.getID() + " has task based affinity to " + taskAffinity
            + " but no locality information exists for it. Ignoring hint.");
        // fall through with null hosts/racks
      } else {
        hosts = (locationHint.getHosts() != null) ? locationHint
            .getHosts().toArray(
                new String[locationHint.getHosts().size()]) : null;
        racks = (locationHint.getRacks() != null) ? locationHint.getRacks()
            .toArray(new String[locationHint.getRacks().size()]) : null;
      }
    }

    taskScheduler.allocateTask(taskAttempt,
                               event.getCapability(),
                               hosts,
                               racks,
                               Priority.newInstance(event.getPriority()),
                               event.getContainerContext(),
                               event);
  }

  protected TaskSchedulerService createTaskScheduler(String host, int port,
      String trackingUrl, AppContext appContext) {
    boolean isLocal = getConfig().getBoolean(TezConfiguration.TEZ_LOCAL_MODE,
        TezConfiguration.TEZ_LOCAL_MODE_DEFAULT);
    if (isLocal) {
      return new LocalTaskSchedulerService(this, this.containerSignatureMatcher,
          host, port, trackingUrl, appContext);
    }
    else {
      return new YarnTaskSchedulerService(this, this.containerSignatureMatcher,
          host, port, trackingUrl, appContext);
    }
  }

  @Override
  public synchronized void serviceStart() {
    InetSocketAddress serviceAddr = clientService.getBindAddress();
    dagAppMaster = appContext.getAppMaster();
    taskScheduler = createTaskScheduler(serviceAddr.getHostName(),
        serviceAddr.getPort(), "", appContext);
    taskScheduler.init(getConfig());
    taskScheduler.start();
    if (shouldUnregisterFlag.get()) {
      // Flag may have been set earlier when task scheduler was not initialized
      taskScheduler.setShouldUnregister();
    }

    this.eventHandlingThread = new Thread("TaskSchedulerEventHandlerThread") {
      @Override
      public void run() {

        AMSchedulerEvent event;

        while (!stopEventHandling && !Thread.currentThread().isInterrupted()) {
          try {
            if (TaskSchedulerEventHandler.this.eventQueue.peek() == null) {
              notifyForTest();
            }
            event = TaskSchedulerEventHandler.this.eventQueue.take();
          } catch (InterruptedException e) {
            if(!stopEventHandling) {
              LOG.warn("Continuing after interrupt : ", e);
            }
            continue;
          }

          try {
            handleEvent(event);
          } catch (Throwable t) {
            LOG.error("Error in handling event type " + event.getType()
                + " to the TaskScheduler", t);
            // Kill the AM.
            sendEvent(new DAGAppMasterEvent(DAGAppMasterEventType.INTERNAL_ERROR));
            return;
          } finally {
            notifyForTest();
          }
        }
      }
    };
    this.eventHandlingThread.start();
  }

  protected void notifyForTest() {
  }

  @Override
  public void serviceStop() {
    synchronized(this) {
      this.stopEventHandling = true;
      if (eventHandlingThread != null)
        eventHandlingThread.interrupt();
    }
    if (taskScheduler != null) {
      ((AbstractService)taskScheduler).stop();
    }
  }

  // TaskSchedulerAppCallback methods
  @Override
  public synchronized void taskAllocated(Object task,
                                           Object appCookie,
                                           Container container) {
    ContainerId containerId = container.getId();
    if (appContext.getAllContainers().addContainerIfNew(container)) {
      appContext.getNodeTracker().nodeSeen(container.getNodeId());
      sendEvent(new AMNodeEventContainerAllocated(container
          .getNodeId(), container.getId()));
    }

    AMSchedulerEventTALaunchRequest event =
                         (AMSchedulerEventTALaunchRequest) appCookie;
    TaskAttempt taskAttempt = event.getTaskAttempt();
    // TODO - perhaps check if the task still needs this container
    // because the deallocateTask downcall may have raced with the
    // taskAllocated() upcall
    assert task.equals(taskAttempt);

    if (appContext.getAllContainers().get(containerId).getState() == AMContainerState.ALLOCATED) {
      sendEvent(new AMContainerEventLaunchRequest(containerId, taskAttempt.getVertexID(),
          event.getContainerContext()));
    }
    sendEvent(new DAGEventSchedulerUpdateTAAssigned(taskAttempt, container));
    sendEvent(new AMContainerEventAssignTA(containerId, taskAttempt.getID(),
        event.getRemoteTaskSpec(), event.getContainerContext().getLocalResources(), event
            .getContainerContext().getCredentials()));
  }

  @Override
  public synchronized void containerCompleted(Object task, ContainerStatus containerStatus) {
    // Inform the Containers about completion.
    AMContainer amContainer = appContext.getAllContainers().get(containerStatus.getContainerId());
    if (amContainer != null) {
      String message = "Container completed. ";
      TaskAttemptTerminationCause errCause = TaskAttemptTerminationCause.CONTAINER_EXITED;
      int exitStatus = containerStatus.getExitStatus();
      if (exitStatus == ContainerExitStatus.PREEMPTED) {
        message = "Container preempted externally. ";
        errCause = TaskAttemptTerminationCause.EXTERNAL_PREEMPTION;
      } else if (exitStatus == ContainerExitStatus.DISKS_FAILED) {
        message = "Container disk failed. ";
        errCause = TaskAttemptTerminationCause.NODE_DISK_ERROR;
      } else if (exitStatus != ContainerExitStatus.SUCCESS){
        message = "Container failed. ";
      }
      if (containerStatus.getDiagnostics() != null) {
        message += containerStatus.getDiagnostics();
      }
      sendEvent(new AMContainerEventCompleted(amContainer.getContainerId(), exitStatus, message, errCause));
    }
  }

  @Override
  public synchronized void containerBeingReleased(ContainerId containerId) {
    AMContainer amContainer = appContext.getAllContainers().get(containerId);
    if (amContainer != null) {
      sendEvent(new AMContainerEventStopRequest(containerId));
    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public synchronized void nodesUpdated(List<NodeReport> updatedNodes) {
    for (NodeReport nr : updatedNodes) {
      // Scheduler will find out from the node, if at all.
      // Relying on the RM to not allocate containers on an unhealthy node.
      eventHandler.handle(new AMNodeEventStateChanged(nr));
    }
  }

  @Override
  public synchronized void appShutdownRequested() {
    // This can happen if the RM has been restarted. If it is in that state,
    // this application must clean itself up.
    LOG.info("App shutdown requested by scheduler");
    sendEvent(new DAGAppMasterEvent(DAGAppMasterEventType.AM_REBOOT));
  }

  @Override
  public synchronized void setApplicationRegistrationData(
      Resource maxContainerCapability,
      Map<ApplicationAccessType, String> appAcls,
      ByteBuffer clientAMSecretKey) {
    this.appContext.getClusterInfo().setMaxContainerCapability(
        maxContainerCapability);
    this.appAcls = appAcls;
    this.clientService.setClientAMSecretKey(clientAMSecretKey);
  }

  // Not synchronized to avoid deadlocks from TaskScheduler callbacks.
  // TaskScheduler uses a separate thread for it's callbacks. Since this method
  // returns a value which is required, the TaskScheduler wait for the call to
  // complete and can hence lead to a deadlock if called from within a TSEH lock.
  @Override
  public AppFinalStatus getFinalAppStatus() {
    FinalApplicationStatus finishState = FinalApplicationStatus.UNDEFINED;
    StringBuffer sb = new StringBuffer();
    if (dagAppMaster == null) {
      finishState = FinalApplicationStatus.UNDEFINED;
      sb.append("App not yet initialized");
    } else {
      DAGAppMasterState appMasterState = dagAppMaster.getState();
      if (appMasterState == DAGAppMasterState.SUCCEEDED) {
        finishState = FinalApplicationStatus.SUCCEEDED;
      } else if (appMasterState == DAGAppMasterState.KILLED
          || (appMasterState == DAGAppMasterState.RUNNING && isSignalled)) {
        finishState = FinalApplicationStatus.KILLED;
      } else if (appMasterState == DAGAppMasterState.FAILED
          || appMasterState == DAGAppMasterState.ERROR) {
        finishState = FinalApplicationStatus.FAILED;
      } else {
        finishState = FinalApplicationStatus.UNDEFINED;
      }
      List<String> diagnostics = dagAppMaster.getDiagnostics();
      if(diagnostics != null) {
        for (String s : diagnostics) {
          sb.append(s).append("\n");
        }
      }
    }
    if(LOG.isDebugEnabled()) {
      LOG.debug("Setting job diagnostics to " + sb.toString());
    }

    String historyUrl = "";
    /*String historyUrl = JobHistoryUtils.getHistoryUrl(getConfig(),
        appContext.getApplicationID());
    LOG.info("History url is " + historyUrl);*/

    return new AppFinalStatus(finishState, sb.toString(), historyUrl);
  }

  // Not synchronized to avoid deadlocks from TaskScheduler callbacks.
  // TaskScheduler uses a separate thread for it's callbacks. Since this method
  // returns a value which is required, the TaskScheduler wait for the call to
  // complete and can hence lead to a deadlock if called from within a TSEH lock.
  @Override
  public float getProgress() {
    // at this point allocate has been called and so node count must be available
    // may change after YARN-1722
    int nodeCount = taskScheduler.getClusterNodeCount();
    if (nodeCount != cachedNodeCount) {
      cachedNodeCount = nodeCount;
      sendEvent(new AMNodeEventNodeCountUpdated(cachedNodeCount));
    }
    return dagAppMaster.getProgress();
  }

  @Override
  public void onError(Throwable t) {
    LOG.info("Error reported by scheduler", t);
    sendEvent(new DAGAppMasterEventSchedulingServiceError(t));
  }

  public void dagCompleted() {
    taskScheduler.resetMatchLocalityForAllHeldContainers();
  }

  @Override
  public void preemptContainer(ContainerId containerId) {
    taskScheduler.deallocateContainer(containerId);
    // Inform the Containers about completion.
    sendEvent(new AMContainerEventCompleted(containerId, ContainerExitStatus.INVALID,
        "Container preempted internally", TaskAttemptTerminationCause.INTERNAL_PREEMPTION));
  }

  public void setShouldUnregisterFlag() {
    LOG.info("TaskScheduler notified that it should unregister from RM");
    this.shouldUnregisterFlag.set(true);
    if (this.taskScheduler != null) {
      this.taskScheduler.setShouldUnregister();
    }
  }

  public boolean hasUnregistered() {
    return this.taskScheduler.hasUnregistered();
  }
}


text:
package com.hp.ov.sdk.rest.client.settings;

import static com.hp.ov.sdk.rest.client.settings.FirmwareDriverClient.FIRMWARE_DRIVER_URI;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;

import java.lang.reflect.Type;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import com.google.common.reflect.Reflection;
import com.google.common.reflect.TypeToken;
import com.hp.ov.sdk.dto.ResourceCollection;
import com.hp.ov.sdk.dto.firmware.FwBaseline;
import com.hp.ov.sdk.rest.client.BaseClient;
import com.hp.ov.sdk.rest.http.core.HttpMethod;
import com.hp.ov.sdk.rest.http.core.UrlParameter;
import com.hp.ov.sdk.rest.http.core.client.Request;
import com.hp.ov.sdk.rest.http.core.client.TaskTimeout;
import com.hp.ov.sdk.rest.reflect.ClientRequestHandler;

@RunWith(MockitoJUnitRunner.class)
public class FirmwareDriverClientTest {

    private static final String ANY_RESOURCE_ID = "random-UUID";
    private static final String ANY_RESOURCE_NAME = "random-Name";

    private BaseClient baseClient = mock(BaseClient.class);
    private FirmwareDriverClient client = Reflection.newProxy(FirmwareDriverClient.class,
            new ClientRequestHandler<>(baseClient, FirmwareDriverClient.class));

    @Test
    public void shouldGetFirmwareDriverById() {
        client.getById(ANY_RESOURCE_ID);

        String expectedUri = FIRMWARE_DRIVER_URI + "/" + ANY_RESOURCE_ID;
        Request expectedRequest = new Request(HttpMethod.GET, expectedUri);

        then(baseClient).should().executeRequest(expectedRequest, TypeToken.of(FwBaseline.class).getType());
    }

    @Test
    public void shouldGetAllFirmwareDrivers() {
        given(this.baseClient.executeRequest(any(Request.class), any(Type.class))).willReturn(new ResourceCollection<>());

        client.getAll();

        Request expectedRequest = new Request(HttpMethod.GET, FIRMWARE_DRIVER_URI);

        then(baseClient).should().executeRequest(expectedRequest,
                new TypeToken<ResourceCollection<FwBaseline>>() {}.getType());
    }

    @Test
    public void shouldGetFirmwareDriverByName() {
        client.getByName(ANY_RESOURCE_NAME);

        Request expectedRequest = new Request(HttpMethod.GET, FIRMWARE_DRIVER_URI);
        expectedRequest.addQuery(UrlParameter.getFilterByNameParameter(ANY_RESOURCE_NAME));

        then(baseClient).should().executeRequest(expectedRequest,
                new TypeToken<ResourceCollection<FwBaseline>>() {}.getType());
    }

    @Test
    public void shouldDeleteFirmwareDriver() {
        client.delete(ANY_RESOURCE_ID, TaskTimeout.of(321));

        String expectedUri = FIRMWARE_DRIVER_URI + "/" + ANY_RESOURCE_ID;
        Request expectedRequest = new Request(HttpMethod.DELETE, expectedUri);
        expectedRequest.setTimeout(321);

        then(baseClient).should().executeMonitorableRequest(expectedRequest);
    }

}

redpajama_set_name: RedPajamaGithub


text:
namespace Xunit
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading.Tasks;

    static class XunitExtensions
    {
        public async static Task PropertyChangedTo<T>(this T obj, Func<T, bool> predicate, int timeout = 10000)
        {
            if (predicate(obj)) return;

            var n = obj as INotifyPropertyChanged;
            if (n == null) throw new TimeoutException();

            var tcs = new TaskCompletionSource<int>();
            var handler = (PropertyChangedEventHandler)null;
            handler = new PropertyChangedEventHandler((sender, e) =>
            {
                if (predicate(obj))
                {
                    n.PropertyChanged -= handler;
                    tcs.TrySetResult(0);
                }
            });
            n.PropertyChanged += handler;

            var delay = Task.Delay(timeout);
            if (delay == await Task.WhenAny(delay, tcs.Task))
            {
                n.PropertyChanged -= handler;
                throw new TimeoutException($"{ obj }");
            }
        }

        public static Task CollectionChangedTo<T>(this IEnumerable<T> collection, params Func<T, bool>[] elementPredicate)
        {
            var predicate = new Func<T[], bool>(array =>
            {
                if (array.Length != elementPredicate.Length) return false;
                for (int i = 0; i < array.Length; i++) if (!elementPredicate[i](array[i])) return false;
                return true;
            });
            return CollectionChangedTo(collection, predicate);
        }

        public async static Task CollectionChangedTo<T>(this IEnumerable<T> collection, Func<T[], bool> predicate, int timeout = 10000)
        {
            if (predicate(collection.ToArray())) return;

            var collectionChanged = collection as INotifyCollectionChanged;
            if (collectionChanged == null) throw new TimeoutException();

            var tcs = new TaskCompletionSource<int>();
            var handler = (NotifyCollectionChangedEventHandler)null;
            handler = new NotifyCollectionChangedEventHandler((sender, e) =>
            {
                if (predicate(collection.ToArray()))
                {
                    collectionChanged.CollectionChanged -= handler;
                    tcs.TrySetResult(0);
                }
            });
            collectionChanged.CollectionChanged += handler;

            var delay = Task.Delay(timeout);
            if (delay == await Task.WhenAny(delay, tcs.Task))
            {
                collectionChanged.CollectionChanged -= handler;
                throw new TimeoutException($"[{ collection.Count() }] : { collection }");
            }
        }

        public static TheoryData<T> ToTheoryData<T>(this IEnumerable<T> enumerable)
        {
            var data = new TheoryData<T>();
            foreach (var item in enumerable)
            {
                data.Add(item);
            }
            return data;
        }

        public static IEnumerable<T> ToEnumerable<T>(this TheoryData<T> theoryData)
        {
            return theoryData.Select(d => (T)d[0]);
        }
    }
}


text:
package org.apache.flink.util;

import org.apache.flink.annotation.Internal;

import java.io.IOException;

/** An extension of {@link SerializedValue} that compresses the value after the serialization. */
@Internal
public class CompressedSerializedValue<T> extends SerializedValue<T> {

    private static final long serialVersionUID = -4358765382738374654L;

    private CompressedSerializedValue(byte[] compressedSerializedData) {
        super(compressedSerializedData);
    }

    private CompressedSerializedValue(T value) throws IOException {
        super(InstantiationUtil.serializeObjectAndCompress(value));
    }

    /**
     * Decompress and deserialize the data to get the original object.
     *
     * @param loader the classloader to deserialize
     * @return the deserialized object
     * @throws IOException exception during decompression and deserialization
     * @throws ClassNotFoundException if class is not found in the classloader
     */
    @Override
    public T deserializeValue(ClassLoader loader) throws IOException, ClassNotFoundException {
        Preconditions.checkNotNull(loader, "No classloader has been passed");
        return InstantiationUtil.decompressAndDeserializeObject(getByteArray(), loader);
    }

    /** Returns the size of the compressed serialized data. */
    public int getSize() {
        return getByteArray().length;
    }

    /**
     * Constructs a compressed serialized value for the given object.
     *
     * @param object the object to serialize and compress
     * @throws NullPointerException if object is null
     * @throws IOException exception during serialization and compression
     */
    public static <T> CompressedSerializedValue<T> fromObject(T object) throws IOException {
        Preconditions.checkNotNull(object, "Value must not be null");
        return new CompressedSerializedValue<>(object);
    }

    /**
     * Construct a compressed serialized value with a serialized byte array.
     *
     * <p>The byte array must be the result of serialization and compression with {@link
     * InstantiationUtil#serializeObjectAndCompress}.
     *
     * @param compressedSerializedData the compressed serialized byte array
     * @param <T> type of the object
     * @return {@link CompressedSerializedValue} that can be deserialized as the object
     */
    public static <T> CompressedSerializedValue<T> fromBytes(byte[] compressedSerializedData) {
        return new CompressedSerializedValue<>(compressedSerializedData);
    }

    // --------------------------------------------------------------------------------------------

    @Override
    public String toString() {
        return String.format("Compressed Serialized Value [byte array length: %d]", getSize());
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package utils;

// Permute.java -- A class generating all permutations
// Ryan Stansifer http://cs.fit.edu/~ryan/java/programs/combinations/Permute-java.html

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.lang.reflect.Array;

public class Permute implements Iterator {

   private final int size;
   private final Object [] elements;  // copy of original 0 .. size-1
   private final Object ar;           // array for output,  0 .. size-1
   private final int [] permutation;  // perm of nums 1..size, perm[0]=0

   private boolean next = true;

   // int[], double[] array won't work :-(
   public Permute (Object [] e) {
      size = e.length;
      elements = new Object [size];    // not suitable for primitives
      System.arraycopy (e, 0, elements, 0, size);
      ar = Array.newInstance (e.getClass().getComponentType(), size);
      System.arraycopy (e, 0, ar, 0, size);
      permutation = new int [size+1];
      for (int i=0; i<size+1; i++) {
	 permutation [i]=i;
      }
   }

   private void formNextPermutation () {
      for (int i=0; i<size; i++) {
	 // i+1 because perm[0] always = 0
         // perm[]-1 because the numbers 1..size are being permuted
	 Array.set (ar, i, elements[permutation[i+1]-1]);
      }
   }

   @Override
   public boolean hasNext() {
      return next;
   }

   @Override
   public void remove() throws UnsupportedOperationException {
      throw new UnsupportedOperationException();
   }

   private void swap (final int i, final int j) {
      final int x = permutation[i];
      permutation[i] = permutation [j];
      permutation[j] = x;
   }

   // does not throw NoSuchElement; it wraps around!
   @Override
   public Object next() throws NoSuchElementException {

      formNextPermutation ();  // copy original elements

      int i = size-1;
      while (permutation[i]>permutation[i+1]) i--;

      if (i==0) {
	 next = false;
	 for (int j=0; j<size+1; j++) {
	    permutation [j]=j;
	 }
	 return ar;
      }

      int j = size;

      while (permutation[i]>permutation[j]) j--;
      swap (i,j);
      int r = size;
      int s = i+1;
      while (r>s) { swap(r,s); r--; s++; }

      return ar;
   }

   @Override
   public String toString () {
      final int n = Array.getLength(ar);
      final StringBuffer sb = new StringBuffer ("[");
      for (int j=0; j<n; j++) {
	 sb.append (Array.get(ar,j).toString());
	 if (j<n-1) sb.append (",");
      }
      sb.append("]");
      return new String (sb);
   }

   public static void main (String [] args) {
      for (Iterator i = new Permute(args); i.hasNext(); ) {
	 final String [] a = (String []) i.next();
	 System.out.println (i);
      }
   }
}


text:
import {
  get,
  Mixin,
  mixin
} from '../..';

QUnit.module('Ember.Mixin.apply');

function K() {}

QUnit.test('using apply() should apply properties', function() {
  let MixinA = Mixin.create({ foo: 'FOO', baz: K });
  let obj = {};
  mixin(obj, MixinA);

  equal(get(obj, 'foo'), 'FOO', 'should apply foo');
  equal(get(obj, 'baz'), K, 'should apply foo');
});

QUnit.test('applying anonymous properties', function() {
  let obj = {};
  mixin(obj, {
    foo: 'FOO',
    baz: K
  });

  equal(get(obj, 'foo'), 'FOO', 'should apply foo');
  equal(get(obj, 'baz'), K, 'should apply foo');
});

QUnit.test('applying null values', function() {
  expectAssertion(() => mixin({}, null));
});

QUnit.test('applying a property with an undefined value', function() {
  let obj = { tagName: '' };
  mixin(obj, { tagName: undefined });

  strictEqual(get(obj, 'tagName'), '');
});


text:
package io.zrz.graphql.core.lang;

import io.zrz.graphql.core.decl.GQLTypeDeclaration;
import io.zrz.graphql.core.types.GQLDeclarationRef;
import io.zrz.graphql.core.types.GQLListType;
import io.zrz.graphql.core.types.GQLNonNullType;

public class TypeResolver implements GQLTypeVisitor<GQLTypeDeclaration>
{

  private GQLTypeRegistry typeRegistry;

  public TypeResolver(GQLTypeRegistry typeRegistry)
  {
    this.typeRegistry = typeRegistry;
  }

  @Override
  public GQLTypeDeclaration visitNonNull(GQLNonNullType type)
  {
    throw new RuntimeException();
  }

  @Override
  public GQLTypeDeclaration visitList(GQLListType type)
  {
    throw new RuntimeException();
  }

  @Override
  public GQLTypeDeclaration visitDeclarationRef(GQLDeclarationRef type)
  {
    return typeRegistry.resolve(type);
  }

}


text:
set(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
  "/home/josh/git/LipReader/facerec_video.cpp" "/home/josh/git/LipReader/CMakeFiles/facerec_video.dir/facerec_video.cpp.o"
  )
set(CMAKE_CXX_COMPILER_ID "GNU")

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  )

# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
  "/usr/include/opencv"
  )
set(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
set(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})


text:
from gui.widgets import AbstractWidget

import Tkinter

class AbstractFrame(AbstractWidget.Widget):
    def __init__(self, name, row, column, **kwargs):
        AbstractWidget.Widget.__init__(self, name, row, column, **kwargs)
        self.widgets_list = []
        self.widgets_dict = {}

    def addChildWidgets(self, child_widgets):
        for widget in child_widgets:
            self.addWidget(widget)

    def addWidget(self, widget):
        self.widgets_list.append(widget)
        self.widgets_dict[widget.name] = widget

    def removeWidget(self, widget):
        self.widgets_list.remove(widget)
        del self.widgets_dict[widget.name]
        widget.widget.destroy()

    def enable(self, enabler):
        AbstractWidget.Widget.enable(self, enabler)
        for child in self.widgets_list:
            child.enable(enabler)

    def disable(self, disabler):
        AbstractWidget.Widget.disable(self, disabler)
        for child in self.widgets_list:
            child.disable(disabler)

    def loadDefaultValue(self):
        AbstractWidget.Widget.loadDefaultValue(self)
        for child in self.widgets_list:
            child.loadDefaultValue()

    def conditionalDisabling(self, disabler, values, widgets):
        for widget in widgets:
            if disabler.variable.get() in values:
                widget.enable(disabler.name)
            else:
                widget.disable(disabler.name)

    def save(self, file):
        AbstractWidget.Widget.save(self, file)
        for widget in self.widgets_list:
            widget.save(file)

    def load(self, file):
        AbstractWidget.Widget.load(self, file)
        for widget in self.widgets_list:
            widget.load(file)

    def validate(self):
        return all(map(lambda x: x.validate(), self.widgets_list))

    def getNotValidated(self):
        if len(self.widgets_dict) != 0:
            return {key: self.widgets_dict[key].getNotValidated() for key in self.widgets_dict if not self.widgets_dict[key].validate()}
        else:
            return {index: self.widgets_list[index].getNotValidated() for index in range(len(self.widgets_list)) if not self.widgets_list[index].validate()}

    def getValue(self):
        if len(self.widgets_dict) != 0:
            return {key: widget.getValue() for key, widget in self.widgets_dict.items() if not widget.no_value}

    def targetAdded(self):
        for widget in self.widgets_list:
            widget.targetAdded()

    def targetRemoved(self, deleted_tab):
        for widget in self.widgets_list:
            widget.targetRemoved(deleted_tab)

    def targetDisabled(self, tabs, current_tab):
        for widget in self.widgets_list:
            widget.targetDisabled(tabs, current_tab)

    def targetEnabled(self, tabs, current_tab):
        for widget in self.widgets_list:
            widget.targetEnabled(tabs, current_tab)

    def disableWidget(self, path_to_widget, disabler="PostOffice"):
        if len(path_to_widget) > 1:
            self.widgets_dict[path_to_widget[0]].disableWidget(path_to_widget[1:], disabler)
        else:
            self.widgets_dict[path_to_widget[0]].disable(disabler)

    def enableWidget(self, path_to_widget, enabler="PostOffice"):
        if len(path_to_widget) > 1:
            self.widgets_dict[path_to_widget[0]].enableWidget(path_to_widget[1:], enabler)
        else:
            self.widgets_dict[path_to_widget[0]].enable(enabler)

class Frame(AbstractFrame):
    def __init__(self, parent, name, row, column, **kwargs):
        AbstractFrame.__init__(self, name, row, column, **kwargs)
        self.create(Tkinter.Frame(parent))


text:
'use strict';

// Describe

var _tracky = require('../../../index');

var scrollEventKey = 'scroll';

var scrollEventOptions = {
  events: {
    scroll: {
      enable: true,
      breakpoints: [
        0, 50, 200, 500, 2000, {
          css: 'this-is-my-special-class-at-350',
          value: 350
        }, {
          value: '99%'
        }, {
          css: 'this-is-between-400-and-500',
          min: 400,
          max: 500,
          onMatch: function () {
            return 'match';
          },
          onUnmatch: function () {
            return 'unmatch';
          },
          onGreater: function () {
            return 'greater';
          },
          onLower: function () {
            return 'lower';
          }
        }, {
          css: 'mega-element-active',
          min: '40%',
          max: '60%'
        }, {
          min: 60,
          max: '40%'
        },
        NaN,
        null,
        false,
        {some: 'thing'},
        '100%'
        , {
          css: {
            lt: 'extra-class-for-lower-than',
            gt: 'extra-class-for-greater-than',
            eq: 'extra-class-for-equal-to',
            bt: 'extra-class-for-between'
          },
          applyLt: false,
          applyGt: false,
          applyEq: false,
          applyBt: false,
          axis: 'x',
          onMatch: function () {
            return 'match';
          },
          onUnmatch: function () {
            return 'unmatch';
          },
          value: [77, {percent: false}],
          min: [44, {percent: true}],
          max: [66, {percent: true}]
        }
      ]
    }
  }
};

var scrollEventOptionsDisabled = {
  events: {
    scroll: {
      enable: false
    }
  }
};

var trackyDefault = new _tracky('body', scrollEventOptions);

var mockedDomNode = {
  nodeName: 'BODY',
  scrollTop: 25,
  scrollLeft: 88,
  scrollHeight: 100,
  scrollWidth: 888,
  offsetWidth: 0,
  offsetHeight: 0,
  addEventListener : function() {},
  removeEventListener : function() {},
};

var mockedDomNodeNotBody = {
  nodeName: 'SOMETHINGELSE',
  scrollTop: 25,
  scrollLeft: 88,
  scrollHeight: 100,
  scrollWidth: 888,
  offsetWidth: 0,
  offsetHeight: 0,
  addEventListener : function() {},
  removeEventListener : function() {},
};

var mockedEvent = {
  target : mockedDomNodeNotBody,
};

trackyDefault._nodes = [[mockedDomNode,mockedDomNode],[mockedDomNodeNotBody,mockedDomNode]];

var trackyDefaultNoScroll = new _tracky('body', scrollEventOptionsDisabled);
var trackyScroll = trackyDefault._listeners.filter(
  function (l) {
    return l.key === scrollEventKey;
  }
)[0].instance;

describe(
  'tracky.scroll.js constructor', function () {

    it(
      'scroll instance should be available', function () {
        expect(
          function () {
            return trackyDefault._listeners.filter(
              function (l) {
                return l.key === scrollEventKey;
              }
            )[0].instance;
          }
        ).not.toThrowError();
      }
    );

    it(
      'scroll instance should not be available when enable set to false', function () {

        var instanceType = typeof (trackyDefaultNoScroll._listeners.filter(
          function (l) {
            return l.key === scrollEventKey;
          }
        )[0]).instance;

        expect(instanceType).toEqual('undefined');
      }
    );

    it(
      'should bind the event key as a string', function () {
        expect(trackyScroll._key).toBeDefined();
        expect(trackyScroll._key).toEqual(scrollEventKey);
      }
    );

    it(
      'should bind the parent tracky instance', function () {
        expect(trackyScroll._tracky).toBeDefined();
        // Todo: find a way how to make this check work
        // expect(trackyScroll._tracky).toBe(jasmine.any(_tracky));
      }
    );

    it(
      'should bind the scroll event options', function () {
        expect(trackyScroll._options).toBeDefined();
        expect(trackyScroll._options).toEqual(jasmine.any(Object));
      }
    );

    it(
      'should bind the global event options', function () {
        expect(trackyScroll._globalOptions).toBeDefined();
        expect(trackyScroll._globalOptions).toEqual(jasmine.any(Object));
      }
    );

    it(
      'should bind the enabled flag', function () {
        expect(trackyScroll._enabled).toBeDefined();
        expect(trackyScroll._enabled).toEqual(true);
      }
    );

    it(
      'should transform breakpoints as an array', function () {
        expect(trackyScroll._options.breakpoints).toBeDefined();
        expect(!!(trackyScroll._options.breakpoints instanceof Array)).toEqual(true);
      }
    );

    it(
      'should have classNames extracted and bound', function () {
        expect(trackyScroll._classNames).toBeDefined();
        expect(!!(trackyScroll._classNames instanceof Array)).toEqual(true);

        expect(trackyScroll._classNames).toContain('tracky-scroll-lt-0');
        expect(trackyScroll._classNames).toContain('tracky-scroll-gt-0');
        expect(trackyScroll._classNames).toContain('tracky-scroll-eq-0');
        expect(trackyScroll._classNames).toContain('tracky-scroll-lt-50');
        expect(trackyScroll._classNames).toContain('tracky-scroll-gt-50');
        expect(trackyScroll._classNames).toContain('tracky-scroll-eq-50');
        expect(trackyScroll._classNames).toContain('tracky-scroll-lt-200');
        expect(trackyScroll._classNames).toContain('tracky-scroll-gt-200');
        expect(trackyScroll._classNames).toContain('tracky-scroll-eq-200');
        expect(trackyScroll._classNames).toContain('tracky-scroll-lt-500');
        expect(trackyScroll._classNames).toContain('tracky-scroll-gt-500');
        expect(trackyScroll._classNames).toContain('tracky-scroll-eq-500');
        expect(trackyScroll._classNames).toContain('tracky-scroll-lt-2000');
        expect(trackyScroll._classNames).toContain('tracky-scroll-gt-2000');
        expect(trackyScroll._classNames).toContain('tracky-scroll-eq-2000');
        expect(trackyScroll._classNames).toContain('tracky-scroll-lt-350');
        expect(trackyScroll._classNames).toContain('tracky-scroll-gt-350');
        expect(trackyScroll._classNames).toContain('this-is-my-special-class-at-350');
        expect(trackyScroll._classNames).toContain('tracky-scroll-lt-99pc');
        expect(trackyScroll._classNames).toContain('tracky-scroll-gt-99pc');
        expect(trackyScroll._classNames).toContain('tracky-scroll-eq-99pc');
        expect(trackyScroll._classNames).toContain('this-is-between-400-and-500');
        expect(trackyScroll._classNames).toContain('mega-element-active');
        expect(trackyScroll._classNames).toContain('tracky-scroll-bt-60-40pc');
        expect(trackyScroll._classNames).toContain('tracky-scroll-lt-100pc');
        expect(trackyScroll._classNames).toContain('tracky-scroll-gt-100pc');
        expect(trackyScroll._classNames).toContain('tracky-scroll-eq-100pc');
        expect(trackyScroll._classNames).toContain('extra-class-for-lower-than');
        expect(trackyScroll._classNames).toContain('extra-class-for-greater-than');
        expect(trackyScroll._classNames).toContain('extra-class-for-equal-to');

      }
    );

    it(
      'should define a public start method', function () {
        expect(trackyScroll.start).toBeDefined();
        expect(trackyScroll.start).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public stop method', function () {
        expect(trackyScroll.stop).toBeDefined();
        expect(trackyScroll.stop).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public onStart method', function () {
        expect(trackyScroll.onStart).toBeDefined();
        expect(
          function () {
            trackyScroll.onStart()
          }
        ).not.toThrowError();
        expect(trackyScroll.onStart).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public onStop method', function () {
        expect(trackyScroll.onStop).toBeDefined();

        expect(
          function () {
            trackyScroll.onStop()
          }
        ).not.toThrowError();

        expect(trackyScroll.onStop).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public add method', function () {
        expect(trackyScroll.add).toBeDefined();
        expect(trackyScroll.add).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public onAdd method', function () {
        expect(trackyScroll.onAdd).toBeDefined();
        expect(trackyScroll.onAdd).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public remove method', function () {
        expect(trackyScroll.remove).toBeDefined();
        //expect(function() { trackyScroll.remove() }).not.toThrowError();
        expect(trackyScroll.remove).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public onRemove method', function () {
        expect(trackyScroll.onRemove).toBeDefined();
        //expect(function() { trackyScroll.onRemove() }).not.toThrowError();
        expect(trackyScroll.onRemove).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public enable method', function () {
        expect(trackyScroll.enable).toBeDefined();
        expect(
          function () {
            trackyScroll.enable()
          }
        ).not.toThrowError();
        expect(trackyScroll.enable).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public disable method', function () {
        expect(trackyScroll.disable).toBeDefined();
        //expect(function() { trackyScroll.disable() }).not.toThrowError();
        expect(trackyScroll.disable).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public attachClasses method', function () {
        expect(trackyScroll.attachClasses).toBeDefined();
        //expect(function() { trackyScroll.attachClasses() }).not.toThrowError();
        expect(trackyScroll.attachClasses).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public cleanupClasses method', function () {
        expect(trackyScroll.cleanupClasses).toBeDefined();
        //expect(function() { trackyScroll.cleanupClasses() }).not.toThrowError();
        expect(trackyScroll.cleanupClasses).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a private _listener method', function () {
        expect(trackyScroll._listener).toBeDefined();
        //expect(function() { trackyScroll._listener() }).not.toThrowError();
        expect(trackyScroll._listener).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public bindEvent method', function () {
        expect(trackyScroll.bindEvent).toBeDefined();
        //expect(trackyScroll.bindEvent()).not.toThrowError();
        expect(trackyScroll.bindEvent).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a private _percentRound method', function () {
        expect(trackyScroll._percentRound).toBeDefined();
        //expect(trackyScroll._percentRound()).not.toThrowError();
        expect(trackyScroll._percentRound).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a private _getScrollPosition method', function () {
        expect(trackyScroll._getScrollPosition).toBeDefined();
        //expect(trackyScroll._getScrollPosition()).not.toThrowError();
        expect(trackyScroll._getScrollPosition).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public bindBodyEvent method', function () {
        expect(trackyScroll.bindBodyEvent).toBeDefined();
        //expect(trackyScroll.bindBodyEvent()).not.toThrowError();
        expect(trackyScroll.bindBodyEvent).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public unbindBodyEvent method', function () {
        expect(trackyScroll.unbindBodyEvent).toBeDefined();
        //expect(trackyScroll.unbindBodyEvent()).not.toThrowError();
        expect(trackyScroll.unbindBodyEvent).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a private _isBody method', function () {
        expect(trackyScroll._isBody).toBeDefined();
        //expect(trackyScroll._isBody()).not.toThrowError();
        expect(trackyScroll._isBody).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public bindEvents method', function () {
        expect(trackyScroll.bindEvents).toBeDefined();
        //expect(trackyScroll.bindEvents()).not.toThrowError();
        expect(trackyScroll.bindEvents).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public unbindEvents method', function () {
        expect(trackyScroll.unbindEvents).toBeDefined();
        //expect(trackyScroll.unbindEvents()).not.toThrowError();
        expect(trackyScroll.unbindEvents).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a private _buildClassName method', function () {
        expect(trackyScroll._buildClassName).toBeDefined();
        //expect(trackyScroll._buildClassName()).not.toThrowError();
        expect(trackyScroll._buildClassName).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a private _extractClasses method', function () {
        expect(trackyScroll._extractClasses).toBeDefined();
        //expect(trackyScroll._extractClasses()).not.toThrowError();
        expect(trackyScroll._extractClasses).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public classify method', function () {
        expect(trackyScroll.classify).toBeDefined();
        //expect(trackyScroll.classify()).not.toThrowError();
        expect(trackyScroll.classify).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a private _applyCallbacks method', function () {
        expect(trackyScroll._applyCallbacks).toBeDefined();
        //expect(trackyScroll._applyCallbacks()).not.toThrowError();
        expect(trackyScroll._applyCallbacks).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should define a public callbackHandler method', function () {
        expect(trackyScroll.callbackHandler).toBeDefined();
        //expect(trackyScroll.callbackHandler()).not.toThrowError();
        expect(trackyScroll.callbackHandler).toEqual(jasmine.any(Function));
      }
    );

  }
);

describe(
  'tracky.scroll.js - _listener', function () {

    it(
      'method should be defined', function () {
        expect(trackyScroll._listener).toBeDefined();
        expect(trackyScroll._listener).toEqual(jasmine.any(Function));
      }
    );

    it(
      'method should be callable as function', function () {
        var mockedDomNode = {};
        expect(trackyScroll._listener()).toEqual(undefined);
        expect(trackyScroll._listener(mockedDomNode)).toEqual(undefined);
      }
    );

  }
);

describe(
  'tracky.scroll.js - bindEvent', function () {

    it(
      'method should be defined', function () {
        expect(trackyScroll.bindEvent).toBeDefined();
        expect(trackyScroll.bindEvent).toEqual(jasmine.any(Function));
      }
    );

    it(
      'method should be callable as function', function () {
        var mockedDomNode = {};
        var mockedDomNodeEventListener = {
          addEventListener: function () {
          }
        };
        expect(trackyScroll.bindEvent()).toEqual(undefined);
        expect(trackyScroll.bindEvent(mockedDomNode)).toEqual(undefined);
        expect(trackyScroll.bindEvent(mockedDomNodeEventListener)).toEqual(undefined);
      }
    );

  }
);

describe(
  'tracky.scroll.js - _getScrollPosition', function () {

    var mockedDomNode = {
      nodeName: 'NOTBODY',
      scrollTop: 25,
      scrollLeft: 88,
      scrollHeight: 100,
      scrollWidth: 888,
      offsetWidth: 0,
      offsetHeight: 0,
    };

    var mockedDomNodeBody = {
      nodeName: 'BODY',
      scrollTop: 25,
      scrollLeft: 88,
      scrollHeight: 100,
      scrollWidth: 888,
      offsetWidth: 0,
      offsetHeight: 0,
    };

    it(
      'method should be defined', function () {
        expect(trackyScroll._getScrollPosition).toBeDefined();
        expect(trackyScroll._getScrollPosition).toEqual(jasmine.any(Function));
      }
    );

    it(
      'method should return an object', function () {
        expect(trackyScroll._getScrollPosition()).toEqual(jasmine.any(Object));
      }
    );

    it(
      'method should return an object.absolute', function () {
        expect(trackyScroll._getScrollPosition().absolute).toBeDefined();
        expect(trackyScroll._getScrollPosition().absolute).toEqual(jasmine.any(Object));
      }
    );

    it(
      'method should return an object.absolute.top', function () {
        expect(trackyScroll._getScrollPosition().absolute.top).toBeDefined();
        expect(trackyScroll._getScrollPosition().absolute.top).toEqual(jasmine.any(Number));
      }
    );

    it(
      'method should return an object.absolute.left', function () {
        expect(trackyScroll._getScrollPosition().absolute.left).toBeDefined();
        expect(trackyScroll._getScrollPosition().absolute.left).toEqual(jasmine.any(Number));
      }
    );

    it(
      'method should return an object.percent', function () {
        expect(trackyScroll._getScrollPosition().percent).toBeDefined();
        expect(trackyScroll._getScrollPosition().percent).toEqual(jasmine.any(Object));
      }
    );

    it(
      'method should return an object.percent.top', function () {
        expect(trackyScroll._getScrollPosition().percent.top).toBeDefined();
        expect(trackyScroll._getScrollPosition().percent.top).toEqual(jasmine.any(Number));
      }
    );

    it(
      'method should return an object.percent.left', function () {
        expect(trackyScroll._getScrollPosition().percent.left).toBeDefined();
        expect(trackyScroll._getScrollPosition().percent.left).toEqual(jasmine.any(Number));
      }
    );

    it(
      'method should return current scroll position', function () {

        var sp = trackyScroll._getScrollPosition(mockedDomNode);

        expect(sp.absolute.top).toEqual(25);
        expect(sp.absolute.left).toEqual(88);
        expect(sp.percent.top).toEqual(25);
        expect(sp.percent.left).toEqual(10);
      }
    );

    it(
      'method should return current scroll position on body', function () {

        var sp = trackyScroll._getScrollPosition(mockedDomNodeBody);

        expect(sp.absolute.top).toEqual(0);
        expect(sp.absolute.left).toEqual(0);
        expect(sp.percent.top).toEqual(0);
        expect(sp.percent.left).toEqual(0);
      }
    );

  }
);

describe(
  'tracky.scroll.js - bindBodyEvent', function () {

    it(
      'method should be defined', function () {
        expect(trackyScroll.bindBodyEvent).toBeDefined();
        expect(trackyScroll.bindBodyEvent).toEqual(jasmine.any(Function));
      }
    );

    it(
      'method should be callable as function', function () {
        expect(trackyScroll.bindBodyEvent()).toEqual(undefined);
        expect(trackyScroll.bindBodyEvent()).toEqual(undefined);
      }
    );

  }
);

describe(
  'tracky.scroll.js - unbindBodyEvent', function () {

    it(
      'method should be defined', function () {
        expect(trackyScroll.unbindBodyEvent).toBeDefined();
        expect(trackyScroll.unbindBodyEvent).toEqual(jasmine.any(Function));
      }
    );

    it(
      'method should be callable as function', function () {
        expect(trackyScroll.unbindBodyEvent()).toEqual(undefined);
        expect(trackyScroll.unbindBodyEvent()).toEqual(undefined);
      }
    );

  }
);

describe(
  'tracky.scroll.js - unbindEvent', function () {

    var mockedDomNode = {
      removeEventListener  : function() {},
    };

    it(
      'method should be defined', function () {
        expect(trackyScroll.unbindEvent).toBeDefined();
        expect(trackyScroll.unbindEvent).toEqual(jasmine.any(Function));
      }
    );

    it(
      'method should be callable as function', function () {
        expect(trackyScroll.unbindEvent()).toEqual(undefined);
        expect(trackyScroll.unbindEvent()).toEqual(undefined);
        expect(trackyScroll.unbindEvent({})).toEqual(undefined);
        expect(trackyScroll.unbindEvent(mockedDomNode)).toEqual(undefined);
      }
    );

  }
);

describe(
  'tracky.scroll.js - bindEvents', function () {

    it(
      'method should be defined', function () {
        expect(trackyScroll.bindEvents).toBeDefined();
        expect(trackyScroll.bindEvents).toEqual(jasmine.any(Function));
      }
    );

    it(
      'method should be callable as function', function () {
        expect(trackyScroll.bindEvents()).toEqual(undefined);
        expect(trackyScroll.bindEvents()).toEqual(undefined);
      }
    );

  }
);

describe(
  'tracky.scroll.js - onStart', function () {

    it(
      'method should be defined', function () {
        expect(trackyScroll.onStart).toBeDefined();
        expect(trackyScroll.onStart).toEqual(jasmine.any(Function));
      }
    );

    it(
      'method should be callable as function', function () {
        expect(trackyScroll.onStart()).toEqual(undefined);
        expect(trackyScroll.onStart()).toEqual(undefined);
      }
    );

    it(
      'should assign a _bindListener', function () {

        trackyScroll.onStart();

        expect(trackyScroll._bindListener).toBeDefined();
        expect(function() { trackyScroll._bindListener(mockedEvent); }).not.toThrowError();
      }
    );

  }
);

describe(
  'tracky.scroll.js - onAdd', function () {

    it(
      'should be defined', function () {
        expect(trackyScroll.onAdd).toBeDefined();
        expect(trackyScroll.onAdd).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should be callable as function', function () {
        expect(trackyScroll.onAdd()).toEqual(undefined);
        expect(trackyScroll.onAdd()).toEqual(undefined);
        expect(trackyScroll.onAdd([mockedDomNodeNotBody,mockedDomNode])).toEqual(undefined);
      }
    );

  }
);

describe(
  'tracky.scroll.js - onRemove', function () {

    it(
      'should be defined', function () {
        expect(trackyScroll.onRemove).toBeDefined();
        expect(trackyScroll.onRemove).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should be callable as function', function () {
        expect(trackyScroll.onRemove()).toEqual(undefined);
        expect(trackyScroll.onRemove()).toEqual(undefined);
        expect(trackyScroll.onRemove([mockedDomNodeNotBody,mockedDomNode])).toEqual(undefined);
      }
    );

  }
);

describe(
  'tracky.scroll.js - callbackHandler', function () {

    it(
      'should be defined', function () {
        expect(trackyScroll.callbackHandler).toBeDefined();
        expect(trackyScroll.callbackHandler).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should be callable as function', function () {
        expect(trackyScroll.callbackHandler()).toEqual(undefined);
        expect(trackyScroll.callbackHandler()).toEqual(undefined);
        expect(trackyScroll.callbackHandler(mockedDomNodeNotBody,['added-class','another-one'],['removed-class'])).toEqual(undefined);
      }
    );

  }
);

describe(
  'tracky.scroll.js - getNodes', function () {

    it(
      'method should be defined', function () {
        expect(trackyScroll.getNodes).toBeDefined();
        expect(trackyScroll.getNodes).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should return an array', function () {
        expect(trackyScroll.getNodes()).toEqual(jasmine.any(Array));
      }
    );

    it(
      'should return nodes from the parent tracky instance', function () {
        expect(trackyScroll.getNodes()).toEqual(trackyDefault._nodes);
      }
    );

  }
);

describe(
  'tracky.scroll.js - _percentRound', function () {

    it(
      'method should be defined', function () {
        expect(trackyScroll._percentRound).toBeDefined();
        expect(trackyScroll._percentRound).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should return an integer', function () {
        expect(trackyScroll._percentRound(55.66)).toEqual(jasmine.any(Number));
        expect(trackyScroll._percentRound('test')).toEqual(jasmine.any(Number));
        expect(trackyScroll._percentRound('28%')).toEqual(jasmine.any(Number));
      }
    );

    it(
      'should return a rounded percent value', function () {
        expect(trackyScroll._percentRound(55.6666687998797564)).toEqual(56);
        expect(trackyScroll._percentRound(44)).toEqual(44);
        expect(trackyScroll._percentRound(0)).toEqual(0);
        expect(trackyScroll._percentRound(-66.44589)).toEqual(-66);
        expect(trackyScroll._percentRound(-555)).toEqual(-555);
      }
    );

    it(
      'should return 0 on malformed arguments', function () {
        expect(trackyScroll._percentRound(false)).toEqual(0);
        expect(trackyScroll._percentRound(null)).toEqual(0);
        expect(trackyScroll._percentRound({})).toEqual(0);
        expect(trackyScroll._percentRound(true)).toEqual(0);
        expect(trackyScroll._percentRound(NaN)).toEqual(0);
      }
    );

  }
);

describe(
  'tracky.scroll.js - _isBody', function () {

    var goodInput = {nodeName: 'BODY'};
    var malformed1 = null;
    var malformed2 = false;
    var malformed3 = {nonodename: 'haha'};
    var malformed4 = NaN;
    var malformed5 = 'burumm';
    var malformed6 = true;

    it(
      'method should be defined', function () {
        expect(trackyScroll._isBody).toBeDefined();
        expect(trackyScroll._isBody).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should return a boolean', function () {
        expect(trackyScroll._isBody(goodInput)).toEqual(jasmine.any(Boolean));
        expect(trackyScroll._isBody(malformed1)).toEqual(jasmine.any(Boolean));
        expect(trackyScroll._isBody(malformed2)).toEqual(jasmine.any(Boolean));
        expect(trackyScroll._isBody(malformed3)).toEqual(jasmine.any(Boolean));
        expect(trackyScroll._isBody(malformed4)).toEqual(jasmine.any(Boolean));
        expect(trackyScroll._isBody(malformed5)).toEqual(jasmine.any(Boolean));
        expect(trackyScroll._isBody(malformed6)).toEqual(jasmine.any(Boolean));
      }
    );

    it(
      'should return true if nodeName equals BODY', function () {
        expect(trackyScroll._isBody(goodInput)).toEqual(true);
      }
    );

    it(
      'should be able to deal with malformed inputs', function () {
        expect(trackyScroll._isBody(malformed1)).toEqual(false);
        expect(trackyScroll._isBody(malformed2)).toEqual(false);
        expect(trackyScroll._isBody(malformed3)).toEqual(false);
        expect(trackyScroll._isBody(malformed4)).toEqual(false);
        expect(trackyScroll._isBody(malformed5)).toEqual(false);
        expect(trackyScroll._isBody(malformed6)).toEqual(false);
      }
    );

  }
);

describe(
  'tracky.scroll.js - _transformValue', function () {

    var goodInput = 44;
    var goodInput2 = '44%';
    var goodInput3 = [44, {percent: true}];
    var goodInput4 = 55.666;
    var goodInput5 = -55;
    var goodInput6 = -55.666;
    var goodInput7 = '-55.666%';
    var malformed1 = null;
    var malformed2 = false;
    var malformed3 = {nonodename: 'haha'};
    var malformed4 = NaN;
    var malformed5 = 'burumm';
    var malformed6 = true;
    var malformed7 = ['44%', {percent: true}];
    var malformed8 = [['44%', {percent: true}], [22, {percent: false}]];

    it(
      'method should be defined', function () {
        expect(trackyScroll._transformValue).toBeDefined();
        expect(trackyScroll._transformValue).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should return an array with length of two on valid inputs', function () {
        expect(trackyScroll._transformValue(goodInput).length).toEqual(2);
        expect(trackyScroll._transformValue(goodInput2).length).toEqual(2);
        expect(trackyScroll._transformValue(goodInput3).length).toEqual(2);
        expect(trackyScroll._transformValue(goodInput4).length).toEqual(2);
        expect(trackyScroll._transformValue(goodInput5).length).toEqual(2);
        expect(trackyScroll._transformValue(goodInput6).length).toEqual(2);
        expect(trackyScroll._transformValue(goodInput7).length).toEqual(2);
      }
    );

    it(
      'should return an integer at index 0 on valid inputs ', function () {

        expect(trackyScroll._transformValue(goodInput)[0]).toEqual(jasmine.any(Number));
        expect(trackyScroll._transformValue(goodInput2)[0]).toEqual(jasmine.any(Number));
        expect(trackyScroll._transformValue(goodInput3)[0]).toEqual(jasmine.any(Number));
        expect(trackyScroll._transformValue(goodInput4)[0]).toEqual(jasmine.any(Number));
        expect(trackyScroll._transformValue(goodInput5)[0]).toEqual(jasmine.any(Number));
        expect(trackyScroll._transformValue(goodInput6)[0]).toEqual(jasmine.any(Number));
        expect(trackyScroll._transformValue(goodInput7)[0]).toEqual(jasmine.any(Number));

        expect(trackyScroll._transformValue(goodInput)[0]).toEqual(44);
        expect(trackyScroll._transformValue(goodInput2)[0]).toEqual(44);
        expect(trackyScroll._transformValue(goodInput3)[0]).toEqual(44);
        expect(trackyScroll._transformValue(goodInput4)[0]).toEqual(55.666);
        expect(trackyScroll._transformValue(goodInput5)[0]).toEqual(-55);
        expect(trackyScroll._transformValue(goodInput6)[0]).toEqual(-55.666);
        expect(trackyScroll._transformValue(goodInput7)[0]).toEqual(-55);

      }
    );

    it(
      'should return null on invalid inputs ', function () {

        expect(trackyScroll._transformValue(malformed1)).toEqual(null);
        expect(trackyScroll._transformValue(malformed2)).toEqual(null);
        expect(trackyScroll._transformValue(malformed3)).toEqual(null);
        expect(trackyScroll._transformValue(malformed4)).toEqual(null);
        expect(trackyScroll._transformValue(malformed5)).toEqual(null);
        expect(trackyScroll._transformValue(malformed6)).toEqual(null);
        expect(trackyScroll._transformValue(malformed7)).toEqual(null);
        expect(trackyScroll._transformValue(malformed8)).toEqual(null);

      }
    );

  }
);

describe(
  'tracky.scroll.js - _transformBreakpoints', function () {

    it(
      'method should be defined', function () {
        expect(trackyScroll._transformBreakpoints).toBeDefined();
        expect(trackyScroll._transformBreakpoints).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should return an array', function () {
        expect(trackyScroll._transformBreakpoints([])).toEqual(jasmine.any(Array));
        expect(trackyScroll._transformBreakpoints(null)).toEqual(jasmine.any(Array));
        expect(trackyScroll._transformBreakpoints(false)).toEqual(jasmine.any(Array));
        expect(trackyScroll._transformBreakpoints({})).toEqual(jasmine.any(Array));
        expect(trackyScroll._transformBreakpoints(NaN)).toEqual(jasmine.any(Array));
        expect(trackyScroll._transformBreakpoints(scrollEventOptions.events.scroll.breakpoints)).toEqual(
          jasmine.any(Array)
        );
      }
    );

    it(
      'should return an array with objects', function () {
        trackyScroll
          ._transformBreakpoints(scrollEventOptions.events.scroll.breakpoints)
          .forEach(
            function (bp) {
              expect(bp).toEqual(jasmine.any(Object));
            }
          );
      }
    );

    it(
      'should return an array with objects having property css', function () {
        trackyScroll
          ._transformBreakpoints(scrollEventOptions.events.scroll.breakpoints)
          .forEach(
            function (bp) {
              expect(bp.css).toBeDefined();
              expect(bp.css).toEqual(jasmine.any(Object));
              expect(bp.css.lt).toBeDefined();
              expect(bp.css.gt).toBeDefined();
              expect(bp.css.eq).toBeDefined();
              expect(bp.css.bt).toBeDefined();
            }
          );
      }
    );

    it(
      'should return an array with objects having property apply(Lt/Gt/Eq/Bt) as boolean', function () {
        trackyScroll
          ._transformBreakpoints(scrollEventOptions.events.scroll.breakpoints)
          .forEach(
            function (bp) {
              expect(bp.applyLt).toBeDefined();
              expect(bp.applyLt).toEqual(jasmine.any(Boolean));
              expect(bp.applyGt).toBeDefined();
              expect(bp.applyGt).toEqual(jasmine.any(Boolean));
              expect(bp.applyEq).toBeDefined();
              expect(bp.applyEq).toEqual(jasmine.any(Boolean));
              expect(bp.applyBt).toBeDefined();
              expect(bp.applyBt).toEqual(jasmine.any(Boolean));
            }
          );
      }
    );

    it(
      'should return an array with objects having property value/min/max', function () {
        trackyScroll
          ._transformBreakpoints(scrollEventOptions.events.scroll.breakpoints)
          .forEach(
            function (bp) {
              expect(bp.value).toBeDefined();
              expect(bp.min).toBeDefined();
              expect(bp.max).toBeDefined();
            }
          );
      }
    );

    it(
      'should set axis as x or y', function () {
        trackyScroll
          ._transformBreakpoints(scrollEventOptions.events.scroll.breakpoints)
          .forEach(
            function (bp) {
              expect(bp.axis).toBeDefined();
              expect(bp.axis).toEqual(jasmine.any(String));
              expect(bp.axis.length).toEqual(1);
              expect(['x', 'y'].indexOf(bp.axis)).toBeGreaterThan(-1);
            }
          );
      }
    );

    it(
      'should return a callback property with having properties match/unmatch/lower/greater', function () {
        trackyScroll
          ._transformBreakpoints(scrollEventOptions.events.scroll.breakpoints)
          .forEach(
            function (bp) {
              expect(bp.callbacks).toBeDefined();
              expect(bp.callbacks.match).toBeDefined();
              expect(bp.callbacks.unmatch).toBeDefined();
              expect(bp.callbacks.lower).toBeDefined();
              expect(bp.callbacks.greater).toBeDefined();
            }
          );
      }
    );

    it(
      'should bind onMatch callback property to breakpoint', function () {
        trackyScroll
          ._transformBreakpoints(
            {
              css: 'this-is-between-400-and-500',
              min: 400,
              max: 500,
              onMatch: function () {
                return 'match';
              }
            }
          )
          .forEach(
            function (bp) {
              expect(typeof bp.callbacks.match).toEqual('function');
              expect(bp.callbacks.match()).toEqual('match');
            }
          );
      }
    );

    it(
      'should bind onUnmatch callback property to breakpoint', function () {
        trackyScroll
          ._transformBreakpoints(
            {
              css: 'this-is-between-400-and-500',
              min: 400,
              max: 500,
              onUnmatch: function () {
                return 'unmatch';
              }
            }
          )
          .forEach(
            function (bp) {
              expect(typeof bp.callbacks.unmatch).toEqual('function');
              expect(bp.callbacks.unmatch()).toEqual('unmatch');
            }
          );
      }
    );

    it(
      'should bind onLower callback property to breakpoint', function () {
        trackyScroll
          ._transformBreakpoints(
            {
              css: 'this-is-between-400-and-500',
              min: 400,
              max: 500,
              onLower: function () {
                return 'lower';
              }
            }
          )
          .forEach(
            function (bp) {
              expect(typeof bp.callbacks.lower).toEqual('function');
              expect(bp.callbacks.lower()).toEqual('lower');
            }
          );
      }
    );

    it(
      'should bind onGreater callback property to breakpoint', function () {
        trackyScroll
          ._transformBreakpoints(
            {
              css: 'this-is-between-400-and-500',
              min: 400,
              max: 500,
              onGreater: function () {
                return 'greater';
              }
            }
          )
          .forEach(
            function (bp) {
              expect(typeof bp.callbacks.greater).toEqual('function');
              expect(bp.callbacks.greater()).toEqual('greater');
            }
          );
      }
    );

  }
);

describe(
  'tracky.scroll.js - _getBpsByClassNames', function () {

    var exampleArray = ['this-is-between-400-and-500', 'tracky-scroll-eq-99pc', 'not-found'];

    it(
      'method should be defined', function () {
        expect(trackyScroll._getBpsByClassNames).toBeDefined();
        expect(trackyScroll._getBpsByClassNames).toEqual(jasmine.any(Function));
      }
    );

    it(
      'should return an array or null', function () {
        expect(trackyScroll._getBpsByClassNames([])).toEqual(null);
        expect(trackyScroll._getBpsByClassNames(null)).toEqual(null);
        expect(trackyScroll._getBpsByClassNames(false)).toEqual(null);
        expect(trackyScroll._getBpsByClassNames({})).toEqual(null);
        expect(trackyScroll._getBpsByClassNames(NaN)).toEqual(null);
        expect(trackyScroll._getBpsByClassNames(exampleArray, ['eq', 'bt'])).toEqual(jasmine.any(Array));
        expect(trackyScroll._getBpsByClassNames(exampleArray, ['eq', 'bt']).length).toEqual(2);
      }
    );

    it(
      'should return an array with objects', function () {
        trackyScroll
          ._getBpsByClassNames(exampleArray, ['eq', 'bt'])
          .forEach(
            function (bp) {
              expect(bp).toEqual(jasmine.any(Object));
            }
          );
      }
    );

    it(
      'should return an array or null - findIn parameter', function () {
        expect(trackyScroll._getBpsByClassNames(exampleArray, null)).toEqual(null);
        expect(trackyScroll._getBpsByClassNames(exampleArray, ['something'])).toEqual(jasmine.any(Array));
        expect(trackyScroll._getBpsByClassNames(exampleArray, 'eq')).toEqual(null);
        expect(trackyScroll._getBpsByClassNames(exampleArray, {})).toEqual(null);
        expect(trackyScroll._getBpsByClassNames(exampleArray, NaN)).toEqual(null);
        expect(trackyScroll._getBpsByClassNames(exampleArray, ['eq', 'lt', 'gt', 'bt'])).toEqual(jasmine.any(Array));
        expect(trackyScroll._getBpsByClassNames(exampleArray, ['eq', 'lt', 'gt', 'bt']).length).toEqual(2);
      }
    );

  }
);


text:
package org.elasticsearch.common.inject;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Apply this to implementation classes when you want only one instance
 * (per {@link Injector}) to be reused for all injections for that binding.
 *
 * @author crazybob@google.com (Bob Lee)
 */
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RUNTIME)
@ScopeAnnotation
public @interface Singleton {
}


text:
    {{ item.data.code }}

{{ item.data.owner }}

{{ item.data.time_started | date: 'MM/dd/yyyy h:mma' | lowercase }}

State: {{ item.getResultState() }}

    <measure-bar class="animate-hide" ng-show="!item.expanded" measure-data="item.data.measures.metrics"></measure-bar>

    <measure-bar class="animate-hide" ng-show="!item.expanded" measure-data="item.data.measures.build"></measure-bar>

    <measure-bar class="animate-hide" ng-show="!item.expanded" measure-data="item.data.measures.unit_test"></measure-bar>

    <measure-bar class="animate-hide" ng-show="!item.expanded" measure-data="item.data.measures.functional_test"></measure-bar>

            <metrics-measurement stop-event item-metrics="item.data.measures.metrics" uib-popover-template="'components/directives/crossover-item/popovers/_metrics-measurement.html'" popover-trigger="outsideClick"></metrics-measurement>

            <build-measurement stop-event item-build="item.data.measures.build" uib-popover-template="'components/directives/crossover-item/popovers/_build-measurement.html'" popover-trigger="outsideClick"></build-measurement>

            <test-measurement stop-event title="Unit Test" item="item" measurement-index="unit_test" uib-popover-template="'components/directives/crossover-item/popovers/_unit-test-measurement.html'" popover-trigger="outsideClick"></test-measurement>

            <test-measurement stop-event title="Functional Test" item="item" measurement-index="functional_test" uib-popover-template="'components/directives/crossover-item/popovers/_functional-test-measurement.html'" popover-trigger="outsideClick"></test-measurement>

Result

                    <execution-result item="item"></execution-result>


text:
from fframework import asfunction
from moviemaker3.stacks.stack import Stack

class WeightedStack(Stack):
    """Elements in the WeightedStack should return (*weight*, *layer*);
    *layer* and *weight* are extracted by indexing (tuple assignment).  You
    might use ``fframework.compound()`` to generate tuple Functions."""

    def __init__(self, zero_layer=None, zero_weight=None):
        """*zero_layer* is the 0 to use in summing up the layers (the start
        value), it defaults to 0.

        *zero_weight* is the 0 to use in summing up the weights, it default to
        0, too."""

        if zero_layer is None:
            zero_layer = 0
        if zero_weight is None:
            zero_weight = 0

        Stack.__init__(self)
        self.zero_layer = asfunction(zero_layer)
        self.zero_weight = asfunction(zero_weight)

    def __call__(self, ps):
        """Blends the layers together.  Note that if all weights are zero,
        the result is undefined.  The start value for summing up the layers
        is *self.zero_layer*.  The start value for summing up the weights is
        *self.zero_weight*.  Both are evaluated with *ps*."""

        sumlayer = self.zero_layer(ps)
        weightsum = self.zero_weight(ps)
        for layer in self.elements:
            (weight, layer) = layer(ps)
            # We don't use augmented arithmetics because we might want to
            # employ broadcasting.
            sumlayer = sumlayer + weight * layer
            weightsum = weight + weightsum
        return sumlayer / weightsum


text:
namespace crashpad {

namespace {

template <typename T>
int ReadIntSysctlByName_NoLog(const char* name, T* value) {
  size_t value_len = sizeof(*value);
  return sysctlbyname(name, value, &value_len, nullptr, 0);
}

template <typename T>
T ReadIntSysctlByName(const char* name, T default_value) {
  T value;
  if (ReadIntSysctlByName_NoLog(name, &value) != 0) {
    PLOG(WARNING) << "sysctlbyname " << name;
    return default_value;
  }

  return value;
}

template <typename T>
T CastIntSysctlByName(const char* name, T default_value) {
  int int_value = ReadIntSysctlByName<int>(name, default_value);
  return InRangeCast<T>(int_value, default_value);
}

#if defined(ARCH_CPU_X86_FAMILY)
void CallCPUID(uint32_t leaf,
               uint32_t* eax,
               uint32_t* ebx,
               uint32_t* ecx,
               uint32_t* edx) {
  asm("cpuid"
      : "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx)
      : "a"(leaf), "b"(0), "c"(0), "d"(0));
}
#endif

}  // namespace

namespace internal {

SystemSnapshotMac::SystemSnapshotMac()
    : SystemSnapshot(),
      os_version_full_(),
      os_version_build_(),
      process_reader_(nullptr),
      snapshot_time_(nullptr),
      os_version_major_(0),
      os_version_minor_(0),
      os_version_bugfix_(0),
      os_server_(false),
      initialized_() {
}

SystemSnapshotMac::~SystemSnapshotMac() {
}

void SystemSnapshotMac::Initialize(ProcessReaderMac* process_reader,
                                   const timeval* snapshot_time) {
  INITIALIZATION_STATE_SET_INITIALIZING(initialized_);

  process_reader_ = process_reader;
  snapshot_time_ = snapshot_time;

  // MacOSVersionComponents() logs its own warnings if it can't figure anything
  // out. It's not fatal if this happens. The default values are reasonable.
  std::string os_version_string;
  MacOSVersionComponents(&os_version_major_,
                         &os_version_minor_,
                         &os_version_bugfix_,
                         &os_version_build_,
                         &os_server_,
                         &os_version_string);

  std::string uname_string;
  utsname uts;
  if (uname(&uts) != 0) {
    PLOG(WARNING) << "uname";
  } else {
    uname_string = base::StringPrintf(
        "%s %s %s %s", uts.sysname, uts.release, uts.version, uts.machine);
  }

  if (!os_version_string.empty()) {
    if (!uname_string.empty()) {
      os_version_full_ = base::StringPrintf(
          "%s; %s", os_version_string.c_str(), uname_string.c_str());
    } else {
      os_version_full_ = os_version_string;
    }
  } else {
    os_version_full_ = uname_string;
  }

  INITIALIZATION_STATE_SET_VALID(initialized_);
}

CPUArchitecture SystemSnapshotMac::GetCPUArchitecture() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

#if defined(ARCH_CPU_X86_FAMILY)
  return process_reader_->Is64Bit() ? kCPUArchitectureX86_64
                                    : kCPUArchitectureX86;
#elif defined(ARCH_CPU_ARM64)
  return kCPUArchitectureARM64;
#else
#error port to your architecture
#endif
}

uint32_t SystemSnapshotMac::CPURevision() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

#if defined(ARCH_CPU_X86_FAMILY)
  // machdep.cpu.family and machdep.cpu.model already take the extended family
  // and model IDs into account. See 10.9.2 xnu-2422.90.20/osfmk/i386/cpuid.c
  // cpuid_set_generic_info().
  uint16_t family = CastIntSysctlByName<uint16_t>("machdep.cpu.family", 0);
  uint8_t model = CastIntSysctlByName<uint8_t>("machdep.cpu.model", 0);
  uint8_t stepping = CastIntSysctlByName<uint8_t>("machdep.cpu.stepping", 0);

  return (family << 16) | (model << 8) | stepping;
#elif defined(ARCH_CPU_ARM64)
  // TODO(macos_arm64): Verify and test.
  return CastIntSysctlByName<uint32_t>("hw.cpufamily", 0);
#else
#error port to your architecture
#endif
}

uint8_t SystemSnapshotMac::CPUCount() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  return CastIntSysctlByName<uint8_t>("hw.ncpu", 1);
}

std::string SystemSnapshotMac::CPUVendor() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

#if defined(ARCH_CPU_X86_FAMILY)
  return ReadStringSysctlByName("machdep.cpu.vendor", true);
#elif defined(ARCH_CPU_ARM64)
  return ReadStringSysctlByName("machdep.cpu.brand_string", true);
#else
#error port to your architecture
#endif
}

void SystemSnapshotMac::CPUFrequency(
    uint64_t* current_hz, uint64_t* max_hz) const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
#if defined(ARCH_CPU_X86_FAMILY)
  *current_hz = ReadIntSysctlByName<uint64_t>("hw.cpufrequency", 0);
  *max_hz = ReadIntSysctlByName<uint64_t>("hw.cpufrequency_max", 0);
#elif defined(ARCH_CPU_ARM64)
  // TODO(https://crashpad.chromium.org/bug/352): When production arm64
  // hardware is available, determine whether CPU frequency is visible anywhere
  // (likely via a sysctl or via IOKit) and use it if feasible.
  *current_hz = 0;
  *max_hz = 0;
#else
#error port to your architecture
#endif
}

uint32_t SystemSnapshotMac::CPUX86Signature() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

#if defined(ARCH_CPU_X86_FAMILY)
  return ReadIntSysctlByName<uint32_t>("machdep.cpu.signature", 0);
#else
  NOTREACHED();
  return 0;
#endif
}

uint64_t SystemSnapshotMac::CPUX86Features() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

#if defined(ARCH_CPU_X86_FAMILY)
  return ReadIntSysctlByName<uint64_t>("machdep.cpu.feature_bits", 0);
#else
  NOTREACHED();
  return 0;
#endif
}

uint64_t SystemSnapshotMac::CPUX86ExtendedFeatures() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

#if defined(ARCH_CPU_X86_FAMILY)
  return ReadIntSysctlByName<uint64_t>("machdep.cpu.extfeature_bits", 0);
#else
  NOTREACHED();
  return 0;
#endif
}

uint32_t SystemSnapshotMac::CPUX86Leaf7Features() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

#if defined(ARCH_CPU_X86_FAMILY)
  // The machdep.cpu.leaf7_feature_bits sysctl isn't supported prior to OS X
  // 10.7, so read this by calling cpuid directly.
  //
  // machdep.cpu.max_basic could be used to check whether to read the leaf, but
  // that sysctl isn't supported prior to Mac OS X 10.6, so read the maximum
  // basic leaf by calling cpuid directly as well. All CPUs that Apple is known
  // to have shipped should support a maximum basic leaf value of at least 0xa.
  uint32_t eax, ebx, ecx, edx;
  CallCPUID(0, &eax, &ebx, &ecx, &edx);
  if (eax < 7) {
    return 0;
  }

  CallCPUID(7, &eax, &ebx, &ecx, &edx);
  return ebx;
#else
  NOTREACHED();
  return 0;
#endif
}

bool SystemSnapshotMac::CPUX86SupportsDAZ() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

#if defined(ARCH_CPU_X86_FAMILY)
  // The correct way to check for denormals-as-zeros (DAZ) support is to examine
  // mxcsr mask, which can be done with fxsave. See Intel Software Developer's
  // Manual, Volume 1: Basic Architecture (253665-051), 11.6.3 "Checking for the
  // DAZ Flag in the MXCSR Register". Note that since this function tests for
  // DAZ support in the CPU, it checks the mxcsr mask. Testing mxcsr would
  // indicate whether DAZ is actually enabled, which is a per-thread context
  // concern.
  //
  // All CPUs that Apple is known to have shipped should support DAZ.

  // Test for fxsave support.
  uint64_t features = CPUX86Features();
  if (!(features & (UINT64_C(1) << 24))) {
    return false;
  }

  // Call fxsave.
#if defined(ARCH_CPU_X86)
  CPUContextX86::Fxsave fxsave __attribute__((aligned(16))) = {};
#elif defined(ARCH_CPU_X86_64)
  CPUContextX86_64::Fxsave fxsave __attribute__((aligned(16))) = {};
#endif
  static_assert(sizeof(fxsave) == 512, "fxsave size");
  static_assert(offsetof(decltype(fxsave), mxcsr_mask) == 28,
                "mxcsr_mask offset");
  asm("fxsave %0" : "=m"(fxsave));

  // Test the DAZ bit.
  return fxsave.mxcsr_mask & (1 << 6);
#else
  NOTREACHED();
  return false;
#endif
}

SystemSnapshot::OperatingSystem SystemSnapshotMac::GetOperatingSystem() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  return kOperatingSystemMacOSX;
}

bool SystemSnapshotMac::OSServer() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  return os_server_;
}

void SystemSnapshotMac::OSVersion(int* major,
                                  int* minor,
                                  int* bugfix,
                                  std::string* build) const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  *major = os_version_major_;
  *minor = os_version_minor_;
  *bugfix = os_version_bugfix_;
  build->assign(os_version_build_);
}

std::string SystemSnapshotMac::OSVersionFull() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);
  return os_version_full_;
}

std::string SystemSnapshotMac::MachineDescription() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

  std::string model;
  std::string board_id;
  MacModelAndBoard(&model, &board_id);

  if (!model.empty()) {
    if (!board_id.empty()) {
      return base::StringPrintf("%s (%s)", model.c_str(), board_id.c_str());
    }
    return model;
  }
  if (!board_id.empty()) {
    return base::StringPrintf("(%s)", board_id.c_str());
  }
  return std::string();
}

bool SystemSnapshotMac::NXEnabled() const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

  int value;
  if (ReadIntSysctlByName_NoLog("kern.nx", &value) != 0) {
    {
      // Support for the kern.nx sysctlbyname is compiled out of production
      // kernels on macOS 10.14.5 and later, although it's available in
      // development and debug kernels. Compare 10.14.3
      // xnu-4903.241.1/bsd/kern/kern_sysctl.c to 10.15.0
      // xnu-6153.11.26/bsd/kern/kern_sysctl.c (10.14.4 and 10.14.5 xnu source
      // are not yet available). In newer production kernels, NX is always
      // enabled. See 10.15.0 xnu-6153.11.26/osfmk/x86_64/pmap.c nx_enabled.
#if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_14
      const bool nx_always_enabled = true;
#else  // DT >= 10.14
      base::ScopedClearLastError reset_errno;
      const bool nx_always_enabled = MacOSVersionNumber() >= 10'14'00;
#endif  // DT >= 10.14
      if (nx_always_enabled) {
        return true;
      }
    }

    // Even if sysctlbyname should have worked, NX is enabled by default in all
    // supported configurations, so return true even while warning.
    PLOG(WARNING) << "sysctlbyname kern.nx";
    return true;
  }

  return value;
}

void SystemSnapshotMac::TimeZone(DaylightSavingTimeStatus* dst_status,
                                 int* standard_offset_seconds,
                                 int* daylight_offset_seconds,
                                 std::string* standard_name,
                                 std::string* daylight_name) const {
  INITIALIZATION_STATE_DCHECK_VALID(initialized_);

  internal::TimeZone(*snapshot_time_,
                     dst_status,
                     standard_offset_seconds,
                     daylight_offset_seconds,
                     standard_name,
                     daylight_name);
}

}  // namespace internal
}  // namespace crashpad


text:
package scuff.web

import javax.servlet.http.HttpServletRequest

class Attribute[T](name: String) {
  def remove(req: HttpServletRequest): Unit = req removeAttribute name
  def set(req: HttpServletRequest, value: T) = req.setAttribute(name, value)
  def get(req: HttpServletRequest): Option[T] =
    req.getAttribute(name) match {
      case null => None
      case value => new Some(value.asInstanceOf[T])
    }
}


text:
SOCIAL MEDIA & RELATIONSHIPS

Introduction

Communication technology is invading our lives more than ever before. Email, social networks, and the Internet are more present than ever before. More than of all Internet users also communicate via social networks and over 85% of all teenagers have accounts on social networks.

Warm-up
What are the pros and cons of the growing presence of communication technology?
Do you have fewer face-to-face conversations than you had in the past?
At what age should children be able to start using communication technology? Explain the reasons underlying your opinion in this regard.