text:
namespace base {
class Thread;
class WaitableEvent;
}

class CefProcessIOThread;
class CefProcessUIThread;
class CefMessageLoopForUI;

// NOT THREAD SAFE, call only from the main thread.
// These functions shouldn't return NULL unless otherwise noted.
class CefProcess : public base::NonThreadSafe {
 public:
  explicit CefProcess(bool multi_threaded_message_loop);
  virtual ~CefProcess();

  // Creates key child threads. We need to do this explicitly since
  // CefThread::PostTask silently deletes a posted task if the target message
  // loop isn't created.
  void CreateChildThreads() {
    ui_thread();
    // Create the FILE thread before the IO thread because IO thread
    // initialization depends on existance of the FILE thread (for cache
    // support, etc).
    file_thread();
    io_thread();
  }

  CefProcessUIThread* ui_thread() {
    DCHECK(CalledOnValidThread());
    if (!created_ui_thread_)
      CreateUIThread();
    return ui_thread_.get();
  }

  // Do a single iteration of the UI message loop on the current thread. If
  // RunMessageLoop() was called you do not need to call this method.
  void DoMessageLoopIteration();

  // Run the UI message loop on the current thread.
  void RunMessageLoop();

  // Quit the UI message loop on the current thread.
  void QuitMessageLoop();

  // Returns the thread that we perform I/O coordination on (network requests,
  // communication with renderers, etc.
  // NOTE: You should ONLY use this to pass to IPC or other objects which must
  // need a MessageLoop*.  If you just want to post a task, use
  // CefThread::PostTask (or other variants) as they take care of checking
  // that a thread is still alive, race conditions, lifetime differences etc.
  // If you still must use this, need to check the return value for NULL.
  CefProcessIOThread* io_thread() {
    DCHECK(CalledOnValidThread());
    if (!created_io_thread_)
      CreateIOThread();
    return io_thread_.get();
  }

  // Returns the thread that we perform random file operations on. For code
  // that wants to do I/O operations (not network requests or even file: URL
  // requests), this is the thread to use to avoid blocking the UI thread.
  // It might be nicer to have a thread pool for this kind of thing.
  base::Thread* file_thread() {
    DCHECK(CalledOnValidThread());
    if (!created_file_thread_)
      CreateFileThread();
    return file_thread_.get();
  }

#if defined(IPC_MESSAGE_LOG_ENABLED)
  // Enable or disable IPC logging for the browser, all processes
  // derived from ChildProcess (plugin etc), and all
  // renderers.
  void SetIPCLoggingEnabled(bool enable);
#endif

 private:
  void CreateUIThread();
  void CreateIOThread();
  void CreateFileThread();

  bool multi_threaded_message_loop_;

  bool created_ui_thread_;
  scoped_ptr<CefProcessUIThread> ui_thread_;
  scoped_ptr<CefMessageLoopForUI> ui_message_loop_;

  bool created_io_thread_;
  scoped_ptr<CefProcessIOThread> io_thread_;

  bool created_file_thread_;
  scoped_ptr<base::Thread> file_thread_;

  DISALLOW_COPY_AND_ASSIGN(CefProcess);
};

#endif  // CEF_LIBCEF_CEF_PROCESS_H_


text:
/* Decrease font-size on commit details to help the links fit */
.commit .sha-block {
	margin-left: 7px !important;
}
.commit .sha-block,
.commit .sha {
	font-size: 10px !important;
}
.signed-commit-badge-medium {
	padding: 2px 4px !important;
	margin-left: 5px !important;
	font-size: 10px !important;
}

redpajama_set_name: RedPajamaGithub


text:
print "Content-type: text/html\n\n";

if ($Misc ne "") {$B = $Misc;} else {$B = "";}

if ($data{'target'} ne "none" &&  $data{'target'} ne "")  {
	if ($data{'message'} =~ /\|/) {$Warning = qq!You have attempted to use illegal characters in your message.  Illegal characters include |.  Sorry to cause any inconvenience.
!;} else {
		@SendArray = split (/,/, $data{'target'});
		if (scalar(@SendArray) < 15) {
			foreach $Sender (@SendArray) {
				$Sender =~ s/\D//g;
				if (-e "$MainPath/users/$Sender") {
					open (OUT, ">>$MainPath/messages/$Sender");
					flock (OUT, 2);

					# Type (0 - News / 1 - Message)|Date [time()]|Sender|Content
					print OUT qq!1|@{[time()]}|@CountryData[34],$User|@{[&dirty($data{'message'})]}\n!;
					close (OUT);
				} else {
					$Warning .= qq!You have attempted to send a message to a country (#$Sender) which does not exist.  Please check your numbers and try again.
!;
				}
			}
		} else {
			$Warning .= qq!You have attempted to send a message to too many countries.  Reduce the number of countries you are sending the message to, and try again.!;
		}
	}
}

if (-e "$MainPath/messages/$User") {
	open (IN, "$MainPath/messages/$User");
	flock (IN, 1);
	@Message = <IN>;
	&chopper (@Message);
	close (IN);

	$Line = 0;
	foreach $Item (@Message) {
		if ($data{$Line} eq "kill") {$Warn = 1;} else {$Warn = 2;push (@NewMessages, "$Item\n");}
		@Mess = split(/\|/, $Item);
		if (@Mess[0] == 1 && $Warn == 2) {
			$Count ++;
			($Sec,$Min,$Hour,$Mday,$Mon,$Year,$Wday,$Yday,$Isdst) = localtime(@Mess[1]);
			$Mon++;
			$Year += 1900;
			if (length($Sec) == 1) {$Sec = "0$Sec"}
			if (length($Min) == 1) {$Min = "0$Min"}
			if (length($Hour) == 1) {$Hour = "0$Hour"}

			my ($Sender1, $Sender2) = split(/,/, @Mess[2]);
			$MesData .= qq!

$NewFont1 From	$NewFont2 $Sender1 (#$Sender2)	$NewFont1 Time Sent	$NewFont2 $Mon/$Mday/$Year - $Hour:$Min:$Sec

<hr height=1 width=100%
$NewFont2 @Mess[3]

$NewFont1 Click to Reply	$NewFont1 Delete	$NewFont1 <input type=checkbox name=$Line value=kill>

!;
		}
		$Line++;
	}
	unless ($Count < 1) {$MesData .= qq!
$Font<input type=submit name=submits value="Delete Messages">
!;}
	open (OUT, ">$MainPath/messages/$User");
	flock (OUT, 2);
	print OUT @NewMessages;
	close (OUT);
}

&StatLine;
print qqÑ
<Title>ASH - Message Menu</title>
$Font

$BannerCode

$LinkLine

<form method=POST action="Runner2.pl?$User&$Pword&9">

$Font$Warning

$NewFont1 Message To	<input type=text name=target value="$B" size=10 maxsize=4>	$NewFont2<input type=submit name=submit value="Send Message">

$NewFont1<textarea name=message rows=10 cols=72 wrap=virtual></textarea>

</form>
<form method=POST action="Runner2.pl?$User&$Pword&9">

$MesData

</form>
Ñ;

sub dirty {
	foreach $text (@_) {
		$text =~ s/\cM//g;
		$text =~ s/\n\n/
/g;
		$text =~ s/\n/
/g;
		$text =~ s/</</g;
		$text =~ s/>/>/g;
		$text =~ s/"/"/g;
	}
	return @_;
}


text:
package org.apache.geode.internal.cache.control;

import java.util.Set;

import org.apache.logging.log4j.Logger;

import org.apache.geode.CancelException;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.control.InternalResourceManager.ResourceType;
import org.apache.geode.internal.cache.control.MemoryThresholds.MemoryState;
import org.apache.geode.internal.cache.control.ResourceAdvisor.ResourceManagerProfile;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.logging.LoggingThread;
import org.apache.geode.internal.offheap.MemoryAllocator;
import org.apache.geode.internal.offheap.MemoryUsageListener;

/**
 * Allows for the setting of eviction and critical thresholds. These thresholds are compared against
 * current off-heap usage and, with the help of {#link InternalResourceManager}, dispatches events
 * when the thresholds are crossed.
 *
 * @since Geode 1.0
 */
public class OffHeapMemoryMonitor implements MemoryMonitor, MemoryUsageListener {
  private static final Logger logger = LogService.getLogger();
  private volatile MemoryThresholds thresholds = new MemoryThresholds(0);
  private volatile MemoryEvent mostRecentEvent = new MemoryEvent(ResourceType.OFFHEAP_MEMORY,
      MemoryState.DISABLED, MemoryState.DISABLED, null, 0L, true, this.thresholds);
  private volatile MemoryState currentState = MemoryState.DISABLED;

  // Set when startMonitoring() and stopMonitoring() are called
  // Package private for testing
  Boolean started = false;

  // Set to true when setEvictionThreshold(...) is called.
  private boolean hasEvictionThreshold = false;

  private Thread memoryListenerThread;

  private final OffHeapMemoryUsageListener offHeapMemoryUsageListener;
  private final InternalResourceManager resourceManager;
  private final ResourceAdvisor resourceAdvisor;
  private final InternalCache cache;
  private final ResourceManagerStats stats;
  /**
   * InternalResoruceManager insists on creating a OffHeapMemoryMonitor even when it does not have
   * off-heap memory. So we need to handle memoryAllocator being null.
   */
  private final MemoryAllocator memoryAllocator;

  OffHeapMemoryMonitor(final InternalResourceManager resourceManager, final InternalCache cache,
      final MemoryAllocator memoryAllocator, final ResourceManagerStats stats) {
    this.resourceManager = resourceManager;
    this.resourceAdvisor = (ResourceAdvisor) cache.getDistributionAdvisor();
    this.cache = cache;
    this.stats = stats;

    this.memoryAllocator = memoryAllocator;
    if (memoryAllocator != null) {
      this.thresholds = new MemoryThresholds(this.memoryAllocator.getTotalMemory());
    }

    this.offHeapMemoryUsageListener = new OffHeapMemoryUsageListener();
  }

  /**
   * Start monitoring off-heap memory usage by adding this as a listener to the off-heap memory
   * allocator.
   */
  private void startMonitoring() {
    synchronized (this) {
      if (this.started) {
        return;
      }

      Thread t =
          new LoggingThread("OffHeapMemoryListener", this.offHeapMemoryUsageListener);
      t.setPriority(Thread.MAX_PRIORITY);
      t.start();
      this.memoryListenerThread = t;

      this.memoryAllocator.addMemoryUsageListener(this);

      this.started = true;
    }
  }

  /**
   * Stop monitoring off-heap usage.
   */
  @Override
  public void stopMonitoring() {
    stopMonitoring(false);
  }

  public void stopMonitoring(boolean waitForThread) {
    Thread threadToWaitFor = null;
    synchronized (this) {
      if (!this.started) {
        return;
      }

      this.memoryAllocator.removeMemoryUsageListener(this);

      this.offHeapMemoryUsageListener.stop();
      if (waitForThread) {
        threadToWaitFor = this.memoryListenerThread;
      }
      this.memoryListenerThread = null;
      this.started = false;
    }
    if (threadToWaitFor != null) {
      try {
        threadToWaitFor.join();
      } catch (InterruptedException ignore) {
        Thread.currentThread().interrupt();
      }
    }
  }

  public volatile OffHeapMemoryMonitorObserver testHook;

  /**
   * Used by unit tests to be notified when OffHeapMemoryMonitor does something.
   */
  public interface OffHeapMemoryMonitorObserver {
    /**
     * Called at the beginning of updateMemoryUsed.
     *
     * @param bytesUsed the number of bytes of off-heap memory currently used
     * @param willSendEvent true if an event will be sent to the OffHeapMemoryUsageListener.
     */
    void beginUpdateMemoryUsed(long bytesUsed, boolean willSendEvent);

    void afterNotifyUpdateMemoryUsed(long bytesUsed);

    /**
     * Called at the beginning of updateStateAndSendEvent.
     *
     * @param bytesUsed the number of bytes of off-heap memory currently used
     * @param willSendEvent true if an event will be sent to the OffHeapMemoryUsageListener.
     */
    void beginUpdateStateAndSendEvent(long bytesUsed, boolean willSendEvent);

    void updateStateAndSendEventBeforeProcess(long bytesUsed, MemoryEvent event);

    void updateStateAndSendEventBeforeAbnormalProcess(long bytesUsed, MemoryEvent event);

    void updateStateAndSendEventIgnore(long bytesUsed, MemoryState oldState, MemoryState newState,
        long mostRecentBytesUsed, boolean deliverNextAbnormalEvent);
  }

  @Override
  public void updateMemoryUsed(final long bytesUsed) {
    final boolean willSendEvent = mightSendEvent(bytesUsed);
    final OffHeapMemoryMonitorObserver _testHook = this.testHook;
    if (_testHook != null) {
      _testHook.beginUpdateMemoryUsed(bytesUsed, willSendEvent);
    }
    if (!willSendEvent) {
      return;
    }
    this.offHeapMemoryUsageListener.deliverEvent();
    if (_testHook != null) {
      _testHook.afterNotifyUpdateMemoryUsed(bytesUsed);
    }
  }

  void setCriticalThreshold(final float criticalThreshold) {
    synchronized (this) {
      // If the threshold isn't changing then don't do anything.
      if (criticalThreshold == this.thresholds.getCriticalThreshold()) {
        return;
      }

      // Do some basic sanity checking on the new threshold
      if (criticalThreshold > 100.0f || criticalThreshold < 0.0f) {
        throw new IllegalArgumentException(
            "Critical percentage must be greater than 0.0 and less than or equal to 100.0.");
      }
      if (this.memoryAllocator == null) {
        throw new IllegalStateException(
            "No off-heap memory has been configured.");
      }
      if (criticalThreshold != 0 && this.thresholds.isEvictionThresholdEnabled()
          && criticalThreshold <= this.thresholds.getEvictionThreshold()) {
        throw new IllegalArgumentException(
            "Critical percentage must be greater than the eviction percentage.");
      }

      this.cache.setQueryMonitorRequiredForResourceManager(criticalThreshold != 0);

      this.thresholds = new MemoryThresholds(this.thresholds.getMaxMemoryBytes(), criticalThreshold,
          this.thresholds.getEvictionThreshold());

      updateStateAndSendEvent(getBytesUsed());

      // Start or stop monitoring based upon whether a threshold has been set
      if (this.thresholds.isEvictionThresholdEnabled()
          || this.thresholds.isCriticalThresholdEnabled()) {
        startMonitoring();
      } else if (!this.thresholds.isEvictionThresholdEnabled()
          && !this.thresholds.isCriticalThresholdEnabled()) {
        stopMonitoring();
      }

      this.stats.changeOffHeapCriticalThreshold(this.thresholds.getCriticalThresholdBytes());
    }
  }

  @Override
  public boolean hasEvictionThreshold() {
    return this.hasEvictionThreshold;
  }

  void setEvictionThreshold(final float evictionThreshold) {
    this.hasEvictionThreshold = true;

    synchronized (this) {
      // If the threshold isn't changing then don't do anything.
      if (evictionThreshold == this.thresholds.getEvictionThreshold()) {
        return;
      }

      // Do some basic sanity checking on the new threshold
      if (evictionThreshold > 100.0f || evictionThreshold < 0.0f) {
        throw new IllegalArgumentException(
            "Eviction percentage must be greater than 0.0 and less than or equal to 100.0.");
      }
      if (this.memoryAllocator == null) {
        throw new IllegalStateException(
            "No off-heap memory has been configured.");
      }
      if (evictionThreshold != 0 && this.thresholds.isCriticalThresholdEnabled()
          && evictionThreshold >= this.thresholds.getCriticalThreshold()) {
        throw new IllegalArgumentException(
            "Eviction percentage must be less than the critical percentage.");
      }

      this.thresholds = new MemoryThresholds(this.thresholds.getMaxMemoryBytes(),
          this.thresholds.getCriticalThreshold(), evictionThreshold);

      updateStateAndSendEvent(getBytesUsed());

      // Start or stop monitoring based upon whether a threshold has been set
      if (this.thresholds.isEvictionThresholdEnabled()
          || this.thresholds.isCriticalThresholdEnabled()) {
        startMonitoring();
      } else if (!this.thresholds.isEvictionThresholdEnabled()
          && !this.thresholds.isCriticalThresholdEnabled()) {
        stopMonitoring();
      }

      this.stats.changeOffHeapEvictionThreshold(this.thresholds.getEvictionThresholdBytes());
    }
  }

  /**
   * Compare the number of bytes used (fetched from the JVM) to the thresholds. If necessary, change
   * the state and send an event for the state change.
   *
   * @return true if an event was sent
   */
  public boolean updateStateAndSendEvent() {
    return updateStateAndSendEvent(getBytesUsed());
  }

  /**
   * Compare the number of bytes used to the thresholds. If necessary, change the state and send an
   * event for the state change.
   *
   * Public for testing.
   *
   * @param bytesUsed Number of bytes of off-heap memory currently used.
   * @return true if an event was sent
   */
  public boolean updateStateAndSendEvent(long bytesUsed) {
    boolean result = false;
    synchronized (this) {
      final MemoryEvent mre = this.mostRecentEvent;
      final MemoryState oldState = mre.getState();
      final MemoryThresholds thresholds = this.thresholds;
      final OffHeapMemoryMonitorObserver _testHook = this.testHook;
      MemoryState newState = thresholds.computeNextState(oldState, bytesUsed);
      if (oldState != newState) {
        this.currentState = newState;

        MemoryEvent event = new MemoryEvent(ResourceType.OFFHEAP_MEMORY, oldState, newState,
            this.cache.getMyId(), bytesUsed, true, thresholds);
        if (_testHook != null) {
          _testHook.updateStateAndSendEventBeforeProcess(bytesUsed, event);
        }
        this.mostRecentEvent = event;
        processLocalEvent(event);
        updateStatsFromEvent(event);
        result = true;

      } else if (!oldState.isNormal() && bytesUsed != mre.getBytesUsed()
          && this.deliverNextAbnormalEvent) {
        this.deliverNextAbnormalEvent = false;
        MemoryEvent event = new MemoryEvent(ResourceType.OFFHEAP_MEMORY, oldState, newState,
            this.cache.getMyId(), bytesUsed, true, thresholds);
        if (_testHook != null) {
          _testHook.updateStateAndSendEventBeforeAbnormalProcess(bytesUsed, event);
        }
        this.mostRecentEvent = event;
        processLocalEvent(event);
        result = true;
      } else {
        if (_testHook != null) {
          _testHook.updateStateAndSendEventIgnore(bytesUsed, oldState, newState, mre.getBytesUsed(),
              this.deliverNextAbnormalEvent);
        }

      }
    }
    return result;
  }

  /**
   * Return true if the given number of bytes compared to the current monitor state would generate a
   * new memory event.
   *
   * @param bytesUsed Number of bytes of off-heap memory currently used.
   * @return true if a new event might need to be sent
   */
  private boolean mightSendEvent(long bytesUsed) {
    final MemoryEvent mre = this.mostRecentEvent;
    final MemoryState oldState = mre.getState();
    final MemoryThresholds thresholds = mre.getThresholds();
    MemoryState newState = thresholds.computeNextState(oldState, bytesUsed);
    if (oldState != newState) {
      return true;
    } else if (!oldState.isNormal() && bytesUsed != mre.getBytesUsed()
        && this.deliverNextAbnormalEvent) {
      return true;
    }
    return false;
  }

  private volatile boolean deliverNextAbnormalEvent = false;

  /**
   * Used by the OffHeapMemoryUsageListener to tell us that the next abnormal event should be
   * delivered even if the state does not change as long as the memory usage changed. For some
   * reason, unknown to me, if we stay in an abnormal state for more than a second then we want to
   * send another event to update the memory usage.
   */
  void deliverNextAbnormalEvent() {
    this.deliverNextAbnormalEvent = true;
  }

  /**
   * Update resource manager stats based upon the given event.
   *
   * @param event Event from which to derive data for updating stats.
   */
  private void updateStatsFromEvent(MemoryEvent event) {
    if (event.isLocal()) {
      if (event.getState().isCritical() && !event.getPreviousState().isCritical()) {
        this.stats.incOffHeapCriticalEvents();
      } else if (!event.getState().isCritical() && event.getPreviousState().isCritical()) {
        this.stats.incOffHeapSafeEvents();
      }

      if (event.getState().isEviction() && !event.getPreviousState().isEviction()) {
        this.stats.incOffHeapEvictionStartEvents();
      } else if (!event.getState().isEviction() && event.getPreviousState().isEviction()) {
        this.stats.incOffHeapEvictionStopEvents();
      }
    }
  }

  /**
   * Populate off-heap memory data in the given profile.
   *
   * @param profile Profile to populate.
   */
  @Override
  public void fillInProfile(final ResourceManagerProfile profile) {
    final MemoryEvent eventToPopulate = this.mostRecentEvent;
    profile.setOffHeapData(eventToPopulate.getBytesUsed(), eventToPopulate.getState(),
        eventToPopulate.getThresholds());
  }

  @Override
  public MemoryState getState() {
    return this.currentState;
  }

  @Override
  public MemoryThresholds getThresholds() {
    MemoryThresholds saveThresholds = this.thresholds;

    return new MemoryThresholds(saveThresholds.getMaxMemoryBytes(),
        saveThresholds.getCriticalThreshold(), saveThresholds.getEvictionThreshold());
  }

  /**
   * Returns the number of bytes of memory reported by the memory allocator as currently in use.
   */
  @Override
  public long getBytesUsed() {
    if (this.memoryAllocator == null) {
      return 0;
    }
    return this.memoryAllocator.getUsedMemory();
  }

  /**
   * Deliver a memory event from one of the monitors to both local listeners and remote resource
   * managers. Also, if a critical event is received and a query monitor has been enabled, then the
   * query monitor will be notified.
   *
   * Package private for testing.
   *
   * @param event Event to process.
   */
  void processLocalEvent(MemoryEvent event) {
    assert event.isLocal();

    if (logger.isDebugEnabled()) {
      logger.debug("Handling new local event {}", event);
    }

    if (event.getState().isCritical() && !event.getPreviousState().isCritical()) {
      logger.error("Member: {} above {} critical threshold",
          new Object[] {event.getMember(), "off-heap"});
    } else if (!event.getState().isCritical() && event.getPreviousState().isCritical()) {
      logger.error("Member: {} below {} critical threshold",
          new Object[] {event.getMember(), "off-heap"});
    }

    if (event.getState().isEviction() && !event.getPreviousState().isEviction()) {
      logger
          .info("Member: {} above {} eviction threshold",
              new Object[] {event.getMember(), "off-heap"});
    } else if (!event.getState().isEviction() && event.getPreviousState().isEviction()) {
      logger
          .info("Member: {} below {} eviction threshold",
              new Object[] {event.getMember(), "off-heap"});
    }

    if (logger.isDebugEnabled()) {
      logger.debug("Informing remote members of event {}", event);
    }

    this.resourceAdvisor.updateRemoteProfile();
    this.resourceManager.deliverLocalEvent(event);
  }

  @Override
  public void notifyListeners(final Set<ResourceListener> listeners, final ResourceEvent event) {
    for (ResourceListener listener : listeners) {
      try {
        listener.onEvent(event);
      } catch (CancelException ignore) {
        // ignore
      } catch (Throwable t) {
        logger.error("Exception occurred when notifying listeners ", t);
      }
    }
  }

  @Override
  public String toString() {
    return "OffHeapMemoryMonitor [thresholds=" + this.thresholds + ", mostRecentEvent="
        + this.mostRecentEvent + "]";
  }

  class OffHeapMemoryUsageListener implements Runnable {
    private boolean deliverEvent = false;
    private boolean stopRequested = false;

    OffHeapMemoryUsageListener() {}

    public synchronized void deliverEvent() {
      this.deliverEvent = true;
      this.notifyAll();
    }

    public synchronized void stop() {
      this.stopRequested = true;
      this.notifyAll();
    }

    @Override
    public void run() {
      if (logger.isDebugEnabled()) {
        logger.debug("OffHeapMemoryUsageListener is starting {}", this);
      }
      int callsWithNoEvent = 0;
      final int MS_TIMEOUT = 10;
      final int MAX_CALLS_WITH_NO_EVENT = 1000 / MS_TIMEOUT;
      boolean exitRunLoop = false;
      while (!exitRunLoop) {
        if (!updateStateAndSendEvent()) {
          callsWithNoEvent++;
          if (callsWithNoEvent > MAX_CALLS_WITH_NO_EVENT) {
            deliverNextAbnormalEvent();
            callsWithNoEvent = 0;
          }
        } else {
          callsWithNoEvent = 0;
        }

        synchronized (this) {
          if (this.stopRequested) {
            exitRunLoop = true;
          } else if (this.deliverEvent) {
            // No need to wait.
            // Loop around and call updateStateAndSendEvent.
            this.deliverEvent = false;
          } else {
            // Wait to be notified that off-heap memory changed
            // or for the wait to timeout.
            // In some cases we need to generate an event even
            // when we have not been notified (see GEODE-438).
            // So we don't want this wait to be for very long.
            try {
              this.wait(MS_TIMEOUT);
              this.deliverEvent = false;
            } catch (InterruptedException ignore) {
              logger.warn("OffHeapMemoryUsageListener was interrupted {}", this);
              this.stopRequested = true;
              exitRunLoop = true;
            }
          }
        }
      }

      if (logger.isDebugEnabled()) {
        logger.debug("OffHeapMemoryUsageListener is stopping {}", this);
      }
    }

    @Override
    public String toString() {
      final StringBuilder sb = new StringBuilder(getClass().getSimpleName());
      sb.append(" Thread").append(" #").append(System.identityHashCode(this));
      return sb.toString();
    }
  }
}


text:
[clappr](../../../index.md) / [io.clappr.player.plugin.control](../../index.md) / [TimeIndicatorPlugin](../index.md) / [Companion](./index.md)

# Companion

`companion object Companion : `[`NamedType`](../../../io.clappr.player.base/-named-type/index.md)

### Companion Object Properties

| Name | Summary |
|---|---|
| [entry](entry.md) | `val entry: `[`Core`](../../../io.clappr.player.plugin/-plugin-entry/-core/index.md) |
| [name](name.md) | `val name: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html) |


text:
#ifndef _FALCON_TREE_FORWARD_BTREE_HPP
#define _FALCON_TREE_FORWARD_BTREE_HPP

#include <falcon/tree/btree_base.hpp>

namespace falcon {

template <typename _T, bool _ValueOnlyInLeaf = false>
struct forward_btree : public btree_base<_T, forward_btree<_T, false>, false>
{
	typedef forward_btree<_T, false> self_type;
	typedef _T value_type;

private:
	typedef btree_base<_T, forward_btree<_T, false>, false> base_type;

public:
	using base_type::left;
	using base_type::right;
	using base_type::children;
	using base_type::swap_left;
	using base_type::swap_right;
	using base_type::swap_tree;
	using base_type::swap;

public:
	CPP_CONSTEXPR forward_btree(const value_type& value = value_type())
	: base_type(value)
	{}

	CPP_CONSTEXPR forward_btree(self_type* __left, self_type* __right, const value_type& value = value_type())
	: base_type(__left, __right, value)
	{}

	self_type& operator=(const self_type& other)
	{
		base_type::operator=(other);
		return *this;
	}

	/*self_type& operator=(const value_type& value)
	{
		_value = value;
		return *this;
	}*/
};

template <typename _T>
struct forward_btree<_T, true> : btree_base<_T, forward_btree<_T, true>, true>
{
	typedef forward_btree<_T, true> self_type;
	typedef _T value_type;
	typedef _T* pointer_type;
	typedef const _T* const_pointer_type;

private:
	typedef btree_base<_T, forward_btree<_T, true>, true> base_type;

public:

public:
	using base_type::left;
	using base_type::right;
	using base_type::children;
	using base_type::extend_left;
	using base_type::extend_right;
	using base_type::extend_children;
	using base_type::swap_left;
	using base_type::swap_right;
	using base_type::swap_tree;
	using base_type::swap;

public:
	forward_btree(const value_type& value)
	: base_type(value)
	{}

	forward_btree(pointer_type pointer = 0)
	: base_type(pointer)
	{}

	forward_btree(self_type* __left, self_type* __right)
	: base_type(__left, __right)
	{}

	self_type& operator=(const self_type& other)
	{
		base_type::operator=(other);
		return *this;
	}
};

}

#endif


text:
package android.widget.scroll;

import android.util.ScrollViewScenario;

import android.widget.Button;
import android.widget.LinearLayout;

/**
 * A series of short buttons, some of which are embedded within another
 * layout.
 */
public class ShortButtons extends ScrollViewScenario {

    private final int mNumButtons = 10;
    protected final float mButtonHeightFactor = 0.2f;

    public int getNumButtons() {
        return mNumButtons;
    }

    public Button getButtonAt(int index) {
        if (index < 3) {
            return getContentChildAt(index);
        } else {
            LinearLayout ll = getContentChildAt(3);
            return (Button) ll.getChildAt(index - 3);
        }
    }

    @Override
    protected void init(Params params) {
        final int numButtonsInSubLayout = getNumButtons() - 3;
        params.addButtons(3, "top-level", mButtonHeightFactor)
                .addVerticalLLOfButtons("embedded",
                        numButtonsInSubLayout,
                        numButtonsInSubLayout * mButtonHeightFactor);
    }
}


text:
'use strict';

var observable = require("data/observable");
var myChallengesService = require("~/data/my-challenges-service");
var helperModule = require("~/common/helper");
var moment = require('moment');

var MyDoneChallengesModel = new observable.Observable();

MyDoneChallengesModel.set('isLoading', true);

var responseContent;

myChallengesService.getCompletedChallenges(getDoneChallengesSuccess, helperModule.handleHttpRequestError);

function getDoneChallengesSuccess(response) {
    responseContent =  response.content.toJSON();

    //if (responseContent.length === 0){
    //    responseContent = [{
    //        'ChallengeTitle': 'No done challenges yet'
    //        }];
    //}else {
        for (var i = 0; i < responseContent.length; i++) {
            responseContent[i]["Difficulty"] = helperModule.formatDifficultyToEnum(parseInt(responseContent[i]["Difficulty"])).toString();
        }
   // }

    MyDoneChallengesModel.set('doneChallenges', responseContent);
    MyDoneChallengesModel.set('isLoading', false);
}

function viewChallenge(args){
    var id = responseContent[args.index]['Id'];
    helperModule.navigateAnimated("./views/profile/challenge-done-details", {'id' : id });
};

exports.MyDoneChallengesModel = MyDoneChallengesModel;
exports.viewChallenge = viewChallenge;


text:
package com.elitemobiletechnology.gamecenterapp;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.elitemobiletechnology.gamecenterapp.com.elitemobiletechnology.gamecenterapp.utils.Constants;

/**
 * Created by SteveYang on 3/6/15.
 */

public class ShowGameActivity extends ActionBarActivity {
    private static final String TAG = "ShowGameActivity";
    ActionBar actionBar;
    FragmentManager fragmentManager;
    Fragment listFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_game);
        actionBar = getSupportActionBar();
        actionBar.setBackgroundDrawable(new ColorDrawable(R.color.white));
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeAsUpIndicator(R.drawable.back_button);
        fragmentManager = getFragmentManager();
        if(savedInstanceState==null) {
            addGameListFragment();
        }
    }

    private void addGameListFragment() {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        listFragment = new ListFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(Constants.IS_GAME_RATING, false);
        listFragment.setArguments(bundle);
        fragmentTransaction.add(android.R.id.content, listFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case android.R.id.home:
                    super.onBackPressed();
                break;
            case R.id.buttonAdd:
                Intent intent = new Intent(this,FormActivity.class);
                    startActivityForResult(intent,Constants.ADD_GAME_REQUEST);
                break;
        }
        return (super.onOptionsItemSelected(menuItem));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_show_game, menu);
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        listFragment.onActivityResult(requestCode,resultCode,data);
    }

}


text:
using Machine.Specifications;
using Penfold;
using System;
using System.IO;

namespace Tests.Features
{
    public class CommentSpecification : Specification
    {
        public CommentSpecification()
        {
            describe["Executing a specification"] = () =>
            {
                context["with a single line comment"] = () =>
                {
                    var specification = new MySpecification { Logger = new StringWriter() };

                    before = () =>
                    {
                        specification.comment = "I want to write specs";
                        specification.it["does something"] = () => { };
                        specification.Execute();
                    };

                    it["writes the comment into the log with the correct indentation"] = () =>
                    {
                        specification.Logger.ToString().ShouldContain(
                            "Specification"           + Environment.NewLine +
                            "  I want to write specs" + Environment.NewLine +
                            "  does something"
                        );
                    };
                };

                context["with a multi-line comment"] = () =>
                {
                    var specification = new MySpecification { Logger = new StringWriter() };

                    before = () =>
                    {
                        specification.comment = @"
                            as a programmer
                            I want to write specs
                            in order to improve my code quality
                        ";

                        specification.it["does something"] = () => { };
                        specification.Execute();
                    };

                    it["writes the comment into the log with the correct indentation"] = () =>
                    {
                        specification.Logger.ToString().ShouldContain(
                            "Specification" + Environment.NewLine +
                            "  as a programmer" + Environment.NewLine +
                            "  I want to write specs" + Environment.NewLine +
                            "  in order to improve my code quality" + Environment.NewLine +
                            "  does something"
                        );
                    };
                };

                context["with a comment after an assertion"] = () =>
                {
                    var specification = new MySpecification { Logger = new StringWriter() };

                    before = () =>
                    {
                        specification.comment = "comment before";
                        specification.it["does something"] = () => { };
                        specification.comment = "comment after";
                        specification.it["does something else"] = () => { };
                        specification.Execute();
                    };

                    it["writes the comment into the log with the correct indentation"] = () =>
                    {
                        specification.Logger.ToString().ShouldContain(
                            "Specification" + Environment.NewLine +
                            "  comment before" + Environment.NewLine +
                            "  does something" + Environment.NewLine +
                            "  comment after" + Environment.NewLine +
                            "  does something else"
                        );
                    };
                };
            };
        }
    }
}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace CoreLABSBundle\Entity;

use CoreLABSBundle\Entity\CoreUserVO;
use Doctrine\DBAL\Connection as DBLAConn;
use CoreLABSBundle\Entity\CoreUserSearchOptions as SearchOptions;

/**
 * Description of CoreUserDAO
 *
 * DAO object for fetching user (core_user) related information
 *
 * @author Daniel F
 */
class CoreUserDAO {

    private $conn;
    private $field_map;

    function __construct(DBLAConn $conn) {
        $this->conn = $conn;
        $this->field_map = array("un" => "username", "fn" => "firstname", "ln" => "lastname");
    }

    /*
     * TODO: Use specific options class instead of generic stdClass
     */

    public function getUsers(SearchOptions $options) {
        $users = array();

        $qb = $this->conn->createQueryBuilder();

        $qb->select('id', 'firstname', 'lastname', 'phone', 'email', 'username')
                ->from('core_users')
                ->setMaxResults($options->limit);

        $order = "ASC";

        $andCond = $qb->expr()->andX();

        if( isset($options->fType) && isset($options->fValue)){
            $andCond->add($qb->expr()->like($this->field_map[$options->fType],$qb->expr()->literal("%" . $options->fValue . "%")));
        }

//        if (is_numeric($options->nextItem)) {
//
//            $filter = "id >= :id";
//            $order = 'ASC';
//
//            if ($options->direction == -1) {
//                $filter = "id <= :id";
//                $order = 'DESC';
//            }
//
//            $qb->andWhere($filter)
//                    ->setParameter("id", $options->nextItem);
//        }

        $qb->andWhere($andCond);

        $qb->orderBy('id', $order);

        $stmt = $qb->execute();

        while ($user_data = $stmt->fetch()) {
            /* @var $user CoreUserVO */
            $user = new CoreUserVO($user_data["id"]);
            $user->setUsername($user_data["username"]);
            $user->setFirstname($user_data["firstname"]);
            $user->setLastname($user_data["lastname"]);
            $user->setEmail($user_data["email"]);
            $user->setPhone($user_data["phone"]);

            $users[] = $user;
        }

        $stmt->closeCursor();

        if( $options->direction == -1 ){
            $users = \array_reverse($users);
        }

        return $users;
    }

    /**
     *
     * @param type $key
     * @param type $type
     * @param type $active
     * @param type $item_cnt
     * @param type $item_id
     * @return CoreUserVO
     * @throws \Exception
     */
    public function findUsers($key, $type = "un", $active = 1, $item_id = "FIRST", $item_cnt = 10) {

        $users = array();

        $stmt = $this->prepareQuery($key, $type, $active, $item_cnt, $item_id);

        if (!$stmt->execute()) {
            throw new \Exception($stmt->error, $stmt->errno);
        }

        $user_data = new \stdClass();

        if (!$stmt->bind_result($user_data->id, $user_data->firstname, $user_data->lastname, $user_data->phone, $user_data->email, $user_data->username)) {
            throw new \Exception($stmt->error, $stmt->errno);
        }

        while ($stmt->fetch()) {
            /* @var $user CoreUserVO */
            $user = new CoreUserVO($user_data->id);
            $user->setUsername($user_data->username);
            $user->setFirstname($user_data->firstname);
            $user->setLastname($user_data->lastname);
            $user->setEmail($user_data->email);
            $user->setPhone($user_data->phone);

            $users[] = $user;
        }

        $stmt->close();

        return $users;
    }

    /**
     *
     * @param type $type
     * @param type $active
     * @param type $item_cnt
     * @param type $last_id
     * @return type
     * @throws \Exception
     */
    private function prepareQuery($key, $type, $active, $item_cnt, $item_id) {

        $query = "";

        $s_field = array_key_exists($type, $this->field_map) ? $this->field_map[$type] : $this->field_map["un"];

        //sort diration for the query
        $dir = !\strcmp("LAST", $item_id) ? "ASC" : "DESC";

        //where parameters for the query
        $where_params = array();
        $types = array();
        $val_params = array();

        if (!empty($key)) {
            $where_params[] = $s_field . " = ?";
            $types[] = \PDO::PARAM_STR;
            $val_params[] = $key;
        }

        if (!empty($active)) {
            $where_params[] = "active = ?";
            $types[] = \PDO::PARAM_INT;
            $val_params[] = $active;
        }

        $where = " WHERE " . \implode(" AND ", $where_params);

        $q_templ = "SELECT id, firstname, lastname, phone, email, username FROM core_users " . $where . " ORDER BY id " . $dir . " LIMIT ?";

        echo $q_templ;
        echo $types;
        exit();

        if (!($stmt = $this->mysqli->prepare($q_templ))) {
            throw new \Exception($$this->mysqli->error, $$this->mysqli->errno);
        }

//        $key_param = "%" . $key . "%";
//
        if (!$stmt->bind_param("i", $item_cnt)) {
            throw new \Exception($stmt->error, $stmt->errno);
        }

        return $stmt;
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gbif.crawler.metasync.protocols.biocase.model;

import java.net.URI;

import org.apache.commons.digester3.annotations.rules.BeanPropertySetter;
import org.apache.commons.digester3.annotations.rules.ObjectCreate;
import org.apache.commons.digester3.annotations.rules.SetProperty;
import org.joda.time.DateTime;

import lombok.ToString;

/**
 * Archive in either ABCD or DwC-A form. To distinguish between the two look at the namespace which
 * should be either ABCD or DwC.
 */
@ObjectCreate(pattern = "inventory/datasets/dataset/archives/archive")
@ToString
public class BiocaseArchive {

  @SetProperty(pattern = "inventory/datasets/dataset/archives/archive", attributeName = "modified")
  private DateTime modified;

  @SetProperty(pattern = "inventory/datasets/dataset/archives/archive", attributeName = "fileSize")
  private int fileSize;

  @SetProperty(pattern = "inventory/datasets/dataset/archives/archive", attributeName = "rcount")
  private int rcount;

  @SetProperty(pattern = "inventory/datasets/dataset/archives/archive", attributeName = "rowType")
  private URI rowType;

  @SetProperty(pattern = "inventory/datasets/dataset/archives/archive", attributeName = "namespace")
  private URI namespace;

  @BeanPropertySetter(pattern = "inventory/datasets/dataset/archives/archive")
  private URI archiveUrl;

  public DateTime getModified() {
    return modified;
  }

  public void setModified(DateTime modified) {
    this.modified = modified;
  }

  public int getFileSize() {
    return fileSize;
  }

  public void setFileSize(int fileSize) {
    this.fileSize = fileSize;
  }

  public int getRcount() {
    return rcount;
  }

  public void setRcount(int rcount) {
    this.rcount = rcount;
  }

  public URI getRowType() {
    return rowType;
  }

  public void setRowType(URI rowType) {
    this.rowType = rowType;
  }

  public URI getNamespace() {
    return namespace;
  }

  public void setNamespace(URI namespace) {
    this.namespace = namespace;
  }

  public URI getArchiveUrl() {
    return archiveUrl;
  }

  public void setArchiveUrl(URI archiveUrl) {
    this.archiveUrl = archiveUrl;
  }

}


text: package org.apache.tomcat;


text:
*superplay* is a HTML5 WebApp remote control for a media
server. Simply put, use any mobile-device and let the Raspberry Pi to
play videos on your TV. (like apple TV)

###

Currently, *superplay* has been tested with the
[Raspberry Pi](http://www.raspberrypi.org/) on the
*Raspbian* image.

You can install node in 2 ways:

1: Install node the easy way (takes 2 minutes)

2: Install node the hard way (takes 2 hours)

## 1: Install node the easy way

The first step is to log in to your Raspberry Pi and
download the *superplay* source code:

~~~
$ wget https://github.com/jalalhejazi/superplay/archive/master.zip
$ unzip master.zip
$ cd superplay-master
~~~

Or, using *git* (only if you need to code with me :-)

~~~
SSH  $ git clone git@github.com:Jalalhejazi/superplay.git
HTTP $ git clone https://github.com/jalalhejazi/superplay.git
	 $ cd superplay
~~~

Now that you have it, take a look at the command-line options:

~~~
$ ./bin/superplay --help
~~~

This will check your system for the Node.js runtime and, if
it's not available, automatically prompt you to download and
install node (The Raspberry Pi requires the ARM version)

## 2: Install node the hard way

If node isn't available for your system, or you
want to install it globally, take a look around
[nodejs.org/dist/](http://nodejs.org/dist/) and try to find
a suitable binary.
This build takes forever (unless you go to sleep after make install)

save all these commands as shell script file
here is a link install-node.sh

~~~
wget http://nodejs.org/dist/v0.10.26/node-v0.10.26.tar.gz
tar -zxf node-v0.10.26.tar.gz
cd node-v0.10.26
./configure
make
sudo make install
~~~

secure copy your install-node.sh to your pi home directory:

~~~
$ scp install-node.sh pi@192.168.1.x:
~~~

then start the compile+build+installation process

~~~
pi@raspberrypi ~ $     sudo sh install-node.sh

This build takes forever ( 2 hours or more)
I use "screen -r" to monitor the progress
~~~

### how to validate if your node installation is working

~~~
nodejs --version
node   --version
npm    --version
~~~

### after installation play some videos :-)

And with everything in place,
start the server and add a directory of media files:

~~~

$ ./bin/superplay --add ~/mp4
Adding files from directory /home/pi/mp4 ...... all loaded!
Firing up the superplay HTTP server on port 8000

$ ./bin/superplay --add ~/mp4 --port 1234
Adding files from directory /home/pi/mp4 ...... all loaded!
Firing up the superplay HTTP server on port 1234

~~~

Now simply point your web browser to `http://192.168.1.x:1234`
(or wherever the pi is on your local network), find a
movie title, and click to play :)

As an added convenience, save this page to your phone's home
screen and run it like a native application.
On the iPhone or any mobile device click the share button within the browser, then "Add to Home Screen".

If it's running as a background job, you may want to redirect the output:

~~~
$ ./bin/superplay &> /dev/null &
~~~

I hope you enjoy playing around as much I enjoyed hacking my pi

@JalalHejazi


text:
#ifndef TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_DATA_VECTORIZATION_UTILS_H_
#define TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_DATA_VECTORIZATION_UTILS_H_

#include "tensorflow/core/framework/function.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"

namespace tensorflow {
namespace grappler {
namespace vectorization_utils {

// Given a MapDefun node (`map_defun_node`) in a FunctionDef (`outer_scope`)
// that maps a function in lib across some input vector elements,
// `VectorizeMapDefun` attempts to create a vectorized version of `outer_scope`
// by "lifting" operations from the MapDefun function to the new function
// (`result`); that is, replacing operations in the MapDefun function with
// operations that produce the same vector output(s) as executing the original
// operations on elements of vector input(s) would. If all operations in the
// MapDefun function are successfully lifted, `result` has no MapDefun node
// altogether. However, if some operations cannot be lifted, and this
// vectorization only succeeds partially, a MapDefun node remains in `result` to
// be used for operations that were not lifted, and the modified MapDefun
// function is added to `lib`. The newly vectorized function `result` is also
// added to `lib`.
//
// Returns Status::OK() if the vectorization is completely or partially
// successful. Otherwise, returns an error, and sets `result` to nullptr.
//
// Example:
//   If the input to the `VectorizeMapDefun` function is a MapDefun
// whose `map_defun_fn` performs the Cast operation, the vectorization will
// eliminate the MapDefun. This is because the Cast operation supports
// any tensor shape and can thus be lifted to `result`.
//
// Before:
//
//
// outer_scope     +------+
// +---------------+ Arg0 +---------+
// |               +---+--+         |
// |                   |            |
// |  map_defun_fn +---v--+         |
// |   +-----------+ Arg0 +-----+   |
// |   |           +---+--+     |   |
// |   |               |        |   |
// |   |               |        |   |
// |   |           +---v--+     |   |
// |   |           | Cast |     |   |
// |   |           +---+--+     |   |
// |   |               |        |   |
// |   |           +---v--+     |   |
// |   +-----------+ Ret0 +-----+   |
// |               +---+--+         |
// |                   |            |
// |               +---v--+         |
// +---------------+ Ret0 +---------+
//                 +------+
//
//
// After:
//
// result          +------+
// +---------------+ Arg0 +---------+
// |               +---+--+         |
// |                   |            |
// |               +---v--+         |
// |               | Cast |         |
// |               +---+--+         |
// |                   |            |
// |               +---v--+         |
// +---------------+ Ret0 +---------+
//                 +------+
//
Status VectorizeMapDefun(const FunctionDef& outer_scope,
                         const NodeDef& map_defun_node, FunctionDefLibrary* lib,
                         FunctionDef** result);

}  // namespace vectorization_utils
}  // namespace grappler
}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_DATA_VECTORIZATION_UTILS_H_


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.hybridnetwork.fluent;

import com.azure.core.http.HttpPipeline;
import java.time.Duration;

/** The interface for HybridNetworkManagementClient class. */
public interface HybridNetworkManagementClient {
    /**
     * Gets The ID of the target subscription.
     *
     * @return the subscriptionId value.
     */
    String getSubscriptionId();

    /**
     * Gets server parameter.
     *
     * @return the endpoint value.
     */
    String getEndpoint();

    /**
     * Gets Api Version.
     *
     * @return the apiVersion value.
     */
    String getApiVersion();

    /**
     * Gets The HTTP pipeline to send requests through.
     *
     * @return the httpPipeline value.
     */
    HttpPipeline getHttpPipeline();

    /**
     * Gets The default poll interval for long-running operation.
     *
     * @return the defaultPollInterval value.
     */
    Duration getDefaultPollInterval();

    /**
     * Gets the NetworkFunctionsClient object to access its operations.
     *
     * @return the NetworkFunctionsClient object.
     */
    NetworkFunctionsClient getNetworkFunctions();

    /**
     * Gets the DevicesClient object to access its operations.
     *
     * @return the DevicesClient object.
     */
    DevicesClient getDevices();

    /**
     * Gets the OperationsClient object to access its operations.
     *
     * @return the OperationsClient object.
     */
    OperationsClient getOperations();

    /**
     * Gets the VendorsClient object to access its operations.
     *
     * @return the VendorsClient object.
     */
    VendorsClient getVendors();

    /**
     * Gets the VendorSkusClient object to access its operations.
     *
     * @return the VendorSkusClient object.
     */
    VendorSkusClient getVendorSkus();

    /**
     * Gets the VendorSkuPreviewsClient object to access its operations.
     *
     * @return the VendorSkuPreviewsClient object.
     */
    VendorSkuPreviewsClient getVendorSkuPreviews();

    /**
     * Gets the NetworkFunctionVendorsClient object to access its operations.
     *
     * @return the NetworkFunctionVendorsClient object.
     */
    NetworkFunctionVendorsClient getNetworkFunctionVendors();

    /**
     * Gets the NetworkFunctionVendorSkusClient object to access its operations.
     *
     * @return the NetworkFunctionVendorSkusClient object.
     */
    NetworkFunctionVendorSkusClient getNetworkFunctionVendorSkus();

    /**
     * Gets the VendorNetworkFunctionsClient object to access its operations.
     *
     * @return the VendorNetworkFunctionsClient object.
     */
    VendorNetworkFunctionsClient getVendorNetworkFunctions();

    /**
     * Gets the RoleInstancesClient object to access its operations.
     *
     * @return the RoleInstancesClient object.
     */
    RoleInstancesClient getRoleInstances();
}


text:
using System.Linq;
using System.Threading.Tasks;
using GeekBudget.Application.Tabs;
using GeekBudget.DataAccess.Tests;
using GeekBudget.Domain.Tabs;
using GeekBudget.Tests;
using Xunit;

namespace GeekBudget.Application.Tests
{
    public class TabServiceTests : IClassFixture<TestingConnection>
    {
        private readonly TestingConnection _connection;

        public TabServiceTests(TestingConnection connection)
        {
            _connection = connection;
        }

        [Fact]
        public async Task GetAll_ReturnAll()
        {
            // Arrange
            var context = _connection.CreateNewContext();
            context.Tabs.Add(new Tab() {Id = 1});
            context.Tabs.Add(new Tab() {Id = 2});
            context.SaveChanges();
            var service = new TabService(context);

            // Act
            var result = await service.GetAll();

            // Assert
            Assert.Equal(2, result.Data.Count());
        }

        [Fact]
        public async Task Get_ExistingTab_ReturnsTab()
        {
            // Arrange
            var context = _connection.CreateNewContext();
            context.Tabs.Add(new Tab() { Id = 1 });
            context.SaveChanges();
            var service = new TabService(context);

            // Act
            var result = await service.Get(1);

            // Assert
            Assert.NotNull(result.Data);
        }

        [Fact]
        public async Task Get_NonExistingTab_ReturnsNull()
        {
            // Arrange
            var context = _connection.CreateNewContext();
            context.Tabs.Add(new Tab() { Id = 1 });
            context.SaveChanges();
            var service = new TabService(context);

            // Act
            var result = await service.Get(9);

            // Assert
            Assert.Null(result.Data);
        }
    }
}


text:
class SignatureWithCommentMapper
  include XmlSchemaMapper
  schema File.expand_path('../../vendor/ezags-protocols/eZAGS/public/UploadService.xsd', File.dirname(__FILE__))
  type 'SignatureWithComment'

  # @return [SignatureTypeMapper]
  # minOccurs: 1, maxOccurs: 1
  attr_accessor :signature
  # @return [NOTEmptyString]
  # minOccurs: 0, maxOccurs: 1
  attr_accessor :comment

end


text:
package vpp1904_test

import (
	"testing"

	. "github.com/onsi/gomega"
	"go.ligato.io/vpp-agent/v3/plugins/vpp/binapi/vpp1904/interfaces"
)

func TestGetInterfaceVRF(t *testing.T) {
	ctx, ifHandler := ifTestSetup(t)
	defer ctx.TeardownTestCtx()

	ctx.MockVpp.MockReply(&interfaces.SwInterfaceGetTableReply{
		VrfID: 1,
	})

	vrfID, err := ifHandler.GetInterfaceVrf(1)
	Expect(err).To(BeNil())
	Expect(vrfID).To(BeEquivalentTo(1))
}

func TestGetInterfaceIPv6VRF(t *testing.T) {
	ctx, ifHandler := ifTestSetup(t)
	defer ctx.TeardownTestCtx()

	ctx.MockVpp.MockReply(&interfaces.SwInterfaceGetTableReply{
		VrfID: 1,
	})

	vrfID, err := ifHandler.GetInterfaceVrfIPv6(1)
	Expect(err).To(BeNil())
	Expect(vrfID).To(BeEquivalentTo(1))
}

func TestGetInterfaceVRFError(t *testing.T) {
	ctx, ifHandler := ifTestSetup(t)
	defer ctx.TeardownTestCtx()

	ctx.MockVpp.MockReply(&interfaces.SwInterfaceGetTable{})

	_, err := ifHandler.GetInterfaceVrf(1)
	Expect(err).ToNot(BeNil())
}

func TestGetInterfaceVRFRetval(t *testing.T) {
	ctx, ifHandler := ifTestSetup(t)
	defer ctx.TeardownTestCtx()

	ctx.MockVpp.MockReply(&interfaces.SwInterfaceGetTableReply{
		Retval: 1,
	})

	_, err := ifHandler.GetInterfaceVrf(1)
	Expect(err).ToNot(BeNil())
}

func TestSetInterfaceVRF(t *testing.T) {
	ctx, ifHandler := ifTestSetup(t)
	defer ctx.TeardownTestCtx()

	ctx.MockVpp.MockReply(&interfaces.SwInterfaceSetTableReply{})

	err := ifHandler.SetInterfaceVrf(1, 2)
	Expect(err).To(BeNil())
	vppMsg, ok := ctx.MockChannel.Msg.(*interfaces.SwInterfaceSetTable)
	Expect(ok).To(BeTrue())
	Expect(vppMsg.SwIfIndex).To(BeEquivalentTo(1))
	Expect(vppMsg.VrfID).To(BeEquivalentTo(2))
}

func TestSetInterfaceIPv6VRF(t *testing.T) {
	ctx, ifHandler := ifTestSetup(t)
	defer ctx.TeardownTestCtx()

	ctx.MockVpp.MockReply(&interfaces.SwInterfaceSetTableReply{})

	err := ifHandler.SetInterfaceVrfIPv6(1, 2)
	Expect(err).To(BeNil())
	vppMsg, ok := ctx.MockChannel.Msg.(*interfaces.SwInterfaceSetTable)
	Expect(ok).To(BeTrue())
	Expect(vppMsg.SwIfIndex).To(BeEquivalentTo(1))
	Expect(vppMsg.VrfID).To(BeEquivalentTo(2))
	Expect(vppMsg.IsIPv6).To(BeEquivalentTo(1))
}

func TestSetInterfaceVRFError(t *testing.T) {
	ctx, ifHandler := ifTestSetup(t)
	defer ctx.TeardownTestCtx()

	ctx.MockVpp.MockReply(&interfaces.SwInterfaceSetTable{})

	err := ifHandler.SetInterfaceVrf(1, 2)
	Expect(err).To(HaveOccurred())
}

func TestSetInterfaceVRFRetval(t *testing.T) {
	ctx, ifHandler := ifTestSetup(t)
	defer ctx.TeardownTestCtx()

	ctx.MockVpp.MockReply(&interfaces.SwInterfaceSetTableReply{
		Retval: 1,
	})

	err := ifHandler.SetInterfaceVrf(1, 2)
	Expect(err).ToNot(BeNil())
}


text:
/**
 * Created by tushar on 22/01/17.
 */

export const event = <T> (type: string, detail: T): Command => ({
  run (e: Hoe, ce: HTMLElement): void {
    ce.dispatchEvent(new CustomEvent(type, detail))
  }
})
export const noop = (): Command => ({
  run () {
  }
})


text:
package org.onosproject.routing.cpr;

/**
 * Name/Value constants for properties.
 */
public final class OsgiPropertyConstants {
    private OsgiPropertyConstants() {
    }

    static final String FORCE_UNPROVISION = "forceUnprovision";
    static final boolean FORCE_UNPROVISION_DEFAULT = false;
}


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Core\Bridge\Doctrine\Orm\Extension;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\EagerLoadingTrait;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\Exception\PropertyNotFoundException;
use ApiPlatform\Core\Exception\ResourceClassNotFoundException;
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;

/**
 * Eager loads relations.
 *
 * @author Charles Sarrazin <charles@sarraz.in>
 * @author Kévin Dunglas <dunglas@gmail.com>
 * @author Antoine Bluchet <soyuka@gmail.com>
 * @author Baptiste Meyer <baptiste.meyer@gmail.com>
 */
final class EagerLoadingExtension implements ContextAwareQueryCollectionExtensionInterface, QueryItemExtensionInterface
{
    use EagerLoadingTrait;

    private $propertyNameCollectionFactory;
    private $propertyMetadataFactory;
    private $classMetadataFactory;
    private $maxJoins;
    private $serializerContextBuilder;
    private $requestStack;

    /**
     * @TODO move $fetchPartial after $forceEager (@soyuka) in 3.0
     */
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, int $maxJoins = 30, bool $forceEager = true, RequestStack $requestStack = null, SerializerContextBuilderInterface $serializerContextBuilder = null, bool $fetchPartial = false, ClassMetadataFactoryInterface $classMetadataFactory = null)
    {
        if (null !== $this->requestStack) {
            @trigger_error(sprintf('Passing an instance of "%s" is deprecated since version 2.2 and will be removed in 3.0. Use the data provider\'s context instead.', RequestStack::class), E_USER_DEPRECATED);
        }
        if (null !== $this->serializerContextBuilder) {
            @trigger_error(sprintf('Passing an instance of "%s" is deprecated since version 2.2 and will be removed in 3.0. Use the data provider\'s context instead.', SerializerContextBuilderInterface::class), E_USER_DEPRECATED);
        }

        $this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
        $this->propertyMetadataFactory = $propertyMetadataFactory;
        $this->resourceMetadataFactory = $resourceMetadataFactory;
        $this->classMetadataFactory = $classMetadataFactory;
        $this->maxJoins = $maxJoins;
        $this->forceEager = $forceEager;
        $this->fetchPartial = $fetchPartial;
        $this->serializerContextBuilder = $serializerContextBuilder;
        $this->requestStack = $requestStack;
    }

    /**
     * {@inheritdoc}
     */
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass = null, string $operationName = null, array $context = [])
    {
        $this->apply(true, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);
    }

    /**
     * The context may contain serialization groups which helps defining joined entities that are readable.
     */
    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = [])
    {
        $this->apply(false, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);
    }

    private function apply(bool $collection, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass = null, string $operationName = null, array $context)
    {
        if (null === $resourceClass) {
            throw new InvalidArgumentException('The "$resourceClass" parameter must not be null');
        }

        $options = [];
        if (null !== $operationName) {
            $options[($collection ? 'collection' : 'item').'_operation_name'] = $operationName;
        }

        $forceEager = $this->shouldOperationForceEager($resourceClass, $options);
        $fetchPartial = $this->shouldOperationFetchPartial($resourceClass, $options);

        if (!isset($context['groups']) && !isset($context['attributes'])) {
            $contextType = isset($context['api_denormalize']) ? 'denormalization_context' : 'normalization_context';
            $context += $this->getNormalizationContext($context['resource_class'] ?? $resourceClass, $contextType, $options);
        }

        $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context);
    }

    /**
     * Joins relations to eager load.
     *
     * @param bool $wasLeftJoin  if the relation containing the new one had a left join, we have to force the new one to left join too
     * @param int  $joinCount    the number of joins
     * @param int  $currentDepth the current max depth
     *
     * @throws RuntimeException when the max number of joins has been reached
     */
    private function joinRelations(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, bool $forceEager, bool $fetchPartial, string $parentAlias, array $options = [], array $normalizationContext = [], bool $wasLeftJoin = false, int &$joinCount = 0, int $currentDepth = null)
    {
        if ($joinCount > $this->maxJoins) {
            throw new RuntimeException('The total number of joined relations has exceeded the specified maximum. Raise the limit if necessary, or use the "max_depth" option of the Symfony serializer.');
        }

        $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth;
        $entityManager = $queryBuilder->getEntityManager();
        $classMetadata = $entityManager->getClassMetadata($resourceClass);
        $attributesMetadata = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($resourceClass)->getAttributesMetadata() : null;

        if (!empty($normalizationContext[AbstractNormalizer::GROUPS])) {
            $options['serializer_groups'] = $normalizationContext[AbstractNormalizer::GROUPS];
        }

        foreach ($classMetadata->associationMappings as $association => $mapping) {
            //Don't join if max depth is enabled and the current depth limit is reached
            if (0 === $currentDepth && isset($normalizationContext[AbstractObjectNormalizer::ENABLE_MAX_DEPTH])) {
                continue;
            }

            try {
                $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $options);
            } catch (PropertyNotFoundException $propertyNotFoundException) {
                //skip properties not found
                continue;
            } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
                //skip associations that are not resource classes
                continue;
            }

            if (
                // Always skip extra lazy associations
                ClassMetadataInfo::FETCH_EXTRA_LAZY === $mapping['fetch'] ||
                // We don't want to interfere with doctrine on this association
                (false === $forceEager && ClassMetadataInfo::FETCH_EAGER !== $mapping['fetch'])
            ) {
                continue;
            }

            if (isset($normalizationContext[AbstractNormalizer::ATTRIBUTES])) {
                if ($inAttributes = isset($normalizationContext[AbstractNormalizer::ATTRIBUTES][$association])) {
                    // prepare the child context
                    $normalizationContext[AbstractNormalizer::ATTRIBUTES] = $normalizationContext[AbstractNormalizer::ATTRIBUTES][$association];
                } else {
                    unset($normalizationContext[AbstractNormalizer::ATTRIBUTES]);
                }
            } else {
                $inAttributes = null;
            }

            $isNotReadableLink = false === $propertyMetadata->isReadableLink();
            if (
                false === $propertyMetadata->getAttribute('fetchEager', false) &&
                (
                    false === $propertyMetadata->isReadable() ||
                    ((null === $inAttributes && $isNotReadableLink) || (false === $inAttributes))
                )
            ) {
                continue;
            }

            $isNullable = $mapping['joinColumns'][0]['nullable'] ?? true;
            if (false !== $wasLeftJoin || true === $isNullable) {
                $method = 'leftJoin';
            } else {
                $method = 'innerJoin';
            }

            $associationAlias = $queryNameGenerator->generateJoinAlias($association);
            $queryBuilder->{$method}(sprintf('%s.%s', $parentAlias, $association), $associationAlias);
            ++$joinCount;

            if (true === $fetchPartial) {
                try {
                    $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $options);
                } catch (ResourceClassNotFoundException $resourceClassNotFoundException) {
                    continue;
                }
            } else {
                $queryBuilder->addSelect($associationAlias);
            }

            // Avoid recursion
            if ($mapping['targetEntity'] === $resourceClass) {
                $queryBuilder->addSelect($associationAlias);
                continue;
            }

            if (isset($attributesMetadata[$association])) {
                $maxDepth = $attributesMetadata[$association]->getMaxDepth();

                // The current depth is the lowest max depth available in the ancestor tree.
                if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) {
                    $currentDepth = $maxDepth;
                }
            }

            $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $options, $normalizationContext, 'leftJoin' === $method, $joinCount, $currentDepth);
        }
    }

    private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions)
    {
        $select = [];
        $entityManager = $queryBuilder->getEntityManager();
        $targetClassMetadata = $entityManager->getClassMetadata($entity);
        if ($targetClassMetadata->subClasses) {
            $queryBuilder->addSelect($associationAlias);
        } else {
            foreach ($this->propertyNameCollectionFactory->create($entity) as $property) {
                $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);

                if (true === $propertyMetadata->isIdentifier()) {
                    $select[] = $property;
                    continue;
                }

                //the field test allows to add methods to a Resource which do not reflect real database fields
                if ($targetClassMetadata->hasField($property) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) {
                    $select[] = $property;
                }

                if (array_key_exists($property, $targetClassMetadata->embeddedClasses)) {
                    foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) {
                        $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions);
                        $propertyName = "$property.$embeddedProperty";
                        if ($targetClassMetadata->hasField($propertyName) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) {
                            $select[] = $propertyName;
                        }
                    }
                }
            }

            $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select)));
        }
    }

    /**
     * Gets serializer context.
     *
     * @param string $contextType normalization_context or denormalization_context
     * @param array  $options     represents the operation name so that groups are the one of the specific operation
     */
    private function getNormalizationContext(string $resourceClass, string $contextType, array $options): array
    {
        $request = null;
        if (null !== $this->requestStack && null !== $this->serializerContextBuilder && null !== $request = $this->requestStack->getCurrentRequest()) {
            return $this->serializerContextBuilder->createFromRequest($request, 'normalization_context' === $contextType);
        }

        $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);
        if (isset($options['collection_operation_name'])) {
            $context = $resourceMetadata->getCollectionOperationAttribute($options['collection_operation_name'], $contextType, null, true);
        } elseif (isset($options['item_operation_name'])) {
            $context = $resourceMetadata->getItemOperationAttribute($options['item_operation_name'], $contextType, null, true);
        } else {
            $context = $resourceMetadata->getAttribute($contextType);
        }

        return $context ?? [];
    }
}


text:
/**
 * @author  Tümay Çeber <tumayceber@gmail.com>
 * @link    https://github.com/brendtumi/bkmexpress
 * @license http://opensource.org/licenses/MIT
 * @date 26.04.2017
 */

/* tslint:disable:max-classes-per-file */
export class RawBexResponse<T> {
    public call?: string | null = null;
    public result?: string | null = null;
    public code?: string | null = null;
    public message?: string;
    public description?: string | null = null;
    // TODO: type Map<String, Object>
    public parameters?: any | null = null;
    public data?: T | null = null;
    public error?: string = "";
}

export class BexResponse<T> {
    protected call?: string | null = null;
    protected result?: string | null = null;
    protected code?: string | null = null;
    protected message?: string;
    protected description?: string | null = null;
    // TODO: type Map<String, Object>
    protected parameters?: any | null = null;
    protected data?: T;

    public constructor(obj?: RawBexResponse<T>) {
        if (obj && obj.message) {
            this.message = obj.message;
        }
        if (obj && obj.result) {
            this.result = obj.result;
        }
        if (obj && obj.code) {
            this.code = obj.code;
        }
        if (obj && obj.call) {
            this.call = obj.call;
        }
        if (obj && obj.description) {
            this.description = obj.description;
        }
        if (obj && obj.parameters) {
            this.parameters = obj.parameters;
        }
        if (obj && obj.data) {
            this.data = obj.data;
        }
    }

    get Message(): string {
        return this.message;
    }

    set Message(message: string) {
        this.message = message;
    }

    get Result(): string {
        return this.result;
    }

    set Result(result: string) {
        this.result = result;
    }

    get Code(): string {
        return this.code;
    }

    set Code(code: string) {
        this.code = code;
    }

    get Call(): string {
        return this.call;
    }

    set Call(call: string) {
        this.call = call;
    }

    get Description(): string {
        return this.description;
    }

    set Description(description: string) {
        this.description = description;
    }

    get Parameters(): any {
        return this.parameters;
    }

    set Parameters(parameters: any) {
        this.parameters = parameters;
    }

    get Data(): T {
        return this.data;
    }

    set Data(data: T) {
        this.data = data;
    }
}


text:
#include <industrial_robot_client/joint_trajectory_action.h>
#include <industrial_robot_client/utils.h>
#include <industrial_utils/param_utils.h>
#include <industrial_utils/utils.h>

namespace industrial_robot_client
{
namespace joint_trajectory_action
{
JointTrajectoryAction::JointTrajectoryAction() :
    action_server_(node_, "joint_trajectory_action", boost::bind(&JointTrajectoryAction::goalCB, this, _1),
                   boost::bind(&JointTrajectoryAction::cancelCB, this, _1), false), has_active_goal_(false)
{
  ros::NodeHandle pn("~");

  pn.param("constraints/goal_threshold", goal_threshold_, DEFAULT_GOAL_THRESHOLD_);

  if (!industrial_utils::param::getJointNames("controller_joint_names", "robot_description", joint_names_))
    ROS_ERROR("Failed to initialize joint_names.");

  // The controller joint names parameter includes empty joint names for those joints not supported
  // by the controller.  These are removed since the trajectory action should ignore these.
  std::remove(joint_names_.begin(), joint_names_.end(), std::string());
  ROS_INFO_STREAM("Filtered joint names to " << joint_names_.size() << " joints");

  pub_trajectory_command_ = node_.advertise<trajectory_msgs::JointTrajectory>("joint_path_command", 1);
  sub_trajectory_state_ = node_.subscribe("feedback_states", 1, &JointTrajectoryAction::controllerStateCB, this);
  sub_robot_status_ = node_.subscribe("robot_status", 1, &JointTrajectoryAction::robotStatusCB, this);

  watchdog_timer_ = node_.createTimer(ros::Duration(WATCHD0G_PERIOD_), &JointTrajectoryAction::watchdog, this);
  action_server_.start();
}

JointTrajectoryAction::~JointTrajectoryAction()
{
}

void JointTrajectoryAction::robotStatusCB(const industrial_msgs::RobotStatusConstPtr &msg)
{
  last_robot_status_ = msg; //caching robot status for later use.
}

void JointTrajectoryAction::watchdog(const ros::TimerEvent &e)
{
  // Some debug logging
  if (!last_trajectory_state_)
  {
    ROS_DEBUG("Waiting for subscription to joint trajectory state");
  }
  if (!trajectory_state_recvd_)
  {
    ROS_DEBUG("Trajectory state not received since last watchdog");
  }

  // Aborts the active goal if the controller does not appear to be active.
  if (has_active_goal_)
  {
    if (!trajectory_state_recvd_)
    {
      // last_trajectory_state_ is null if the subscriber never makes a connection
      if (!last_trajectory_state_)
      {
        ROS_WARN("Aborting goal because we have never heard a controller state message.");
      }
      else
      {
        ROS_WARN_STREAM(
            "Aborting goal because we haven't heard from the controller in " << WATCHD0G_PERIOD_ << " seconds");
      }

      abortGoal();

    }
  }

  // Reset the trajectory state received flag
  trajectory_state_recvd_ = false;
}

void JointTrajectoryAction::goalCB(JointTractoryActionServer::GoalHandle & gh)
{
  ROS_INFO("Received new goal");

  if (!gh.getGoal()->trajectory.points.empty())
  {
    if (industrial_utils::isSimilar(joint_names_, gh.getGoal()->trajectory.joint_names))
    {

      // Cancels the currently active goal.
      if (has_active_goal_)
      {
        ROS_WARN("Received new goal, canceling current goal");
        abortGoal();
      }

      // Sends the trajectory along to the controller
      if (withinGoalConstraints(last_trajectory_state_, gh.getGoal()->trajectory))
      {

        ROS_INFO_STREAM("Already within goal constraints, setting goal succeeded");
        gh.setAccepted();
        gh.setSucceeded();
        has_active_goal_ = false;

      }
      else
      {
        gh.setAccepted();
        active_goal_ = gh;
        has_active_goal_ = true;

        ROS_INFO("Publishing trajectory");

        current_traj_ = active_goal_.getGoal()->trajectory;
        pub_trajectory_command_.publish(current_traj_);
      }
    }
    else
    {
      ROS_ERROR("Joint trajectory action failing on invalid joints");
      control_msgs::FollowJointTrajectoryResult rslt;
      rslt.error_code = control_msgs::FollowJointTrajectoryResult::INVALID_JOINTS;
      gh.setRejected(rslt, "Joint names do not match");
    }
  }
  else
  {
    ROS_ERROR("Joint trajectory action failed on empty trajectory");
    control_msgs::FollowJointTrajectoryResult rslt;
    rslt.error_code = control_msgs::FollowJointTrajectoryResult::INVALID_GOAL;
    gh.setRejected(rslt, "Empty trajectory");
  }

  // Adding some informational log messages to indicate unsupported goal constraints
  if (gh.getGoal()->goal_time_tolerance.toSec() > 0.0)
  {
    ROS_WARN_STREAM("Ignoring goal time tolerance in action goal, may be supported in the future");
  }
  if (!gh.getGoal()->goal_tolerance.empty())
  {
    ROS_WARN_STREAM(
        "Ignoring goal tolerance in action, using paramater tolerance of " << goal_threshold_ << " instead");
  }
  if (!gh.getGoal()->path_tolerance.empty())
  {
    ROS_WARN_STREAM("Ignoring goal path tolerance, option not supported by ROS-Industrial drivers");
  }
}

void JointTrajectoryAction::cancelCB(JointTractoryActionServer::GoalHandle & gh)
{
  ROS_DEBUG("Received action cancel request");
  if (active_goal_ == gh)
  {
    // Stops the controller.
    trajectory_msgs::JointTrajectory empty;
    empty.joint_names = joint_names_;
    pub_trajectory_command_.publish(empty);

    // Marks the current goal as canceled.
    active_goal_.setCanceled();
    has_active_goal_ = false;
  }
  else
  {
    ROS_WARN("Active goal and goal cancel do not match, ignoring cancel request");
  }
}

void JointTrajectoryAction::controllerStateCB(const control_msgs::FollowJointTrajectoryFeedbackConstPtr &msg)
{
  //ROS_DEBUG("Checking controller state feedback");
  last_trajectory_state_ = msg;
  trajectory_state_recvd_ = true;

  if (!has_active_goal_)
  {
    //ROS_DEBUG("No active goal, ignoring feedback");
    return;
  }
  if (current_traj_.points.empty())
  {
    ROS_DEBUG("Current trajectory is empty, ignoring feedback");
    return;
  }

  if (!industrial_utils::isSimilar(joint_names_, msg->joint_names))
  {
    ROS_ERROR("Joint names from the controller don't match our joint names.");
    return;
  }

  // Checking for goal constraints
  // Checks that we have ended inside the goal constraints and has motion stopped

  ROS_DEBUG("Checking goal constraints");
  if (withinGoalConstraints(last_trajectory_state_, current_traj_))
  {
    if (last_robot_status_)
    {
      // Additional check for motion stoppage since the controller goal may still
      // be moving.  The current robot driver calls a motion stop if it receives
      // a new trajectory while it is still moving.  If the driver is not publishing
      // the motion state (i.e. old driver), this will still work, but it warns you.
      if (last_robot_status_->in_motion.val == industrial_msgs::TriState::FALSE)
      {
        ROS_INFO("Inside goal constraints, stopped moving, return success for action");
        active_goal_.setSucceeded();
        has_active_goal_ = false;
      }
      else if (last_robot_status_->in_motion.val == industrial_msgs::TriState::UNKNOWN)
      {
        ROS_INFO("Inside goal constraints, return success for action");
        ROS_WARN("Robot status in motion unknown, the robot driver node and controller code should be updated");
        active_goal_.setSucceeded();
        has_active_goal_ = false;
      }
      else
      {
        ROS_DEBUG("Within goal constraints but robot is still moving");
      }
    }
    else
    {
      ROS_INFO("Inside goal constraints, return success for action");
      ROS_WARN("Robot status is not being published the robot driver node and controller code should be updated");
      active_goal_.setSucceeded();
      has_active_goal_ = false;
    }
  }
}

void JointTrajectoryAction::abortGoal()
{
  // Stops the controller.
  trajectory_msgs::JointTrajectory empty;
  pub_trajectory_command_.publish(empty);

  // Marks the current goal as aborted.
  active_goal_.setAborted();
  has_active_goal_ = false;
}

bool JointTrajectoryAction::withinGoalConstraints(const control_msgs::FollowJointTrajectoryFeedbackConstPtr &msg,
                                                  const trajectory_msgs::JointTrajectory & traj)
{
  bool rtn = false;
  if (traj.points.empty())
  {
    ROS_WARN("Empty joint trajectory passed to check goal constraints, return false");
    rtn = false;
  }
  else
  {
    int last_point = traj.points.size() - 1;

    if (industrial_robot_client::utils::isWithinRange(last_trajectory_state_->joint_names,
                                                      last_trajectory_state_->actual.positions, traj.joint_names,
                                                      traj.points[last_point].positions, goal_threshold_))
    {
      rtn = true;
    }
    else
    {
      rtn = false;
    }
  }
  return rtn;
}

} //joint_trajectory_action
} //industrial_robot_client


text:
![Selectize.js](docs/selectize-wordmark.png)

→ Selectize is looking for [new members on the maintenance team](https://github.com/selectize/selectize.js/discussions/1678)!

[![NPM version](http://img.shields.io/npm/v/@selectize/selectize.svg?style=flat)](https://www.npmjs.com/package/@selectize/selectize)
[![CDNJS version](http://img.shields.io/cdnjs/v/selectize.js.svg?style=flat)](https://cdnjs.com/libraries/selectize.js)
\
![Node.js CI](https://github.com/selectize/selectize.js/workflows/Node.js%20CI/badge.svg)
\
[![Discussion & Help](https://img.shields.io/badge/Discuss-Keybase-cc004c?style=flat)](https://keybase.io/team/selectize)

Selectize is an extensible [jQuery](http://jquery.com/)-based custom `<select>`; UI control. It's useful for tagging, contact lists, country selectors, and so on. The goal is to provide a solid & usable experience with a clean and powerful API.

- [Demos](https://selectize.dev/demos.html)
- [Changelog](https://github.com/selectize/selectize.js/releases)
- [Documentation](https://selectize.dev/docs.html)

## Features

- **Smart Option Searching / Ranking**
  Options are efficiently scored and sorted on-the-fly (using [sifter](https://github.com/brianreavis/sifter.js)). Want to search for an item's title _and_ description? No problem.
- **Caret between items**
  Order matters sometimes. Use the ← and → arrow keys to move between selected items.
- **Select & delete multiple items at once**
  Hold down option on Mac or ctrl on Windows to select more than one item to delete.
- **Díåcritîçs supported**
  Great for international environments.
- **Item creation**
  Allow users to create items on the fly (async saving is supported; the control locks until the callback is fired).
- **Remote data loading**
  For when you have thousands of options and want them provided by the server as the user types.
- **Clean API & code**
  Interface with it and make modifications easily. Pull requests are always welcome!
- **Extensible**
  [Plugin API](docs/plugins.md) for developing custom features (uses [microplugin](https://github.com/brianreavis/microplugin.js)).
- **Touch Support**
  Plays nice with iOS 5+ devices.

### Dependencies

- [jquery](https://github.com/jquery/jquery) (1.7 and greater), as [peer dependency](https://nodejs.org/en/blog/npm/peer-dependencies/)
  - **Note:** it is installed automatically in development, or in projects using NPM 1 or 2. When using NPM from version 3 on, just a warning is thrown and the user needs to manually install an explicit version in their own project (e.g. `npm install --save jquery@3.5.1`).

**Optional:**

- [jquery-ui](https://github.com/jquery/jquery-ui) (required by `drag_drop` plugin)

### Installation

Selectize can be installed via NPM `npm install @selectize/selectize`

#### Installing Manually

All pre-built files needed to use Selectize can be found in the
["dist"](dist/) folder.

If you're looking to get started with minimal fuss, include
`selectize.min.js` (bundles Sifter and Microplugin
dependencies – also available un-minified for debugging, just remove the
`.min` part) and `css/selectize.default.css`.

Selectize is available at [cdnjs](https://cdnjs.com/libraries/selectize.js).

- [**js/**](dist/js)
  - [selectize.js](dist/js/selectize.js) — With dependencies, minus jquery
  - [selectize.min.js](dist/js/selectize.min.js) — With dependencies, minus jquery
- [**scss/**](dist/scss) — Sass source files for customization (Bootstrap 3+ compatible)
- [**less/**](dist/less) — Less source files for customization (Bootstrap 2/3 compatible)
- [**css/**](dist/css)
  - [selectize.css](dist/css/selectize.css) — Core styles
  - [selectize.default.css](dist/css/selectize.default.css) — Default theme (with core styles)
  - [selectize.default.css](dist/css/selectize.legacy.css) — Default Legacy theme (with core styles)
  - [selectize.bootstrap2.css](dist/css/selectize.bootstrap2.css) - Bootstrap 2 theme
  - [selectize.bootstrap3.css](dist/css/selectize.bootstrap3.css) - Bootstrap 3 theme
  - [selectize.bootstrap4.css](dist/css/selectize.bootstrap4.css) - Bootstrap 4 theme
  - [selectize.bootstrap5.css](dist/css/selectize.bootstrap5.css) - Bootstrap 5 theme

### Usage

```js
$("select").selectize(options);
```

The available options are [documented here](https://selectize.dev/docs.html).

### Contributing

When issuing a pull request:

- please **do not include/commit changes in the `dist/` or `lib/` folders** to avoid
  merge conflicts. A good way to include the right files is to use
  `git gui` or `git add` when committing to select the files you want to
  add to your commit.

- please **include tests** with your feature so that we're not tempted to
  break it in the future!

Add an entry to the top of the CHANGELOG, and update the documentation
in `docs/` as needed. (Refactors and documentation changes don't need a
changelog entry.)

Squash your commits together in one or a few complete, logical commits,
with a concise and descriptive message. One commit means one
feature/bugfix/thing that has changed, or a diff bringing the code one
step forward to a better, working state.

Once your commit is nice and clean, and you want to _discard the other
changes_, you can use `git checkout .` (that will erase changes to
tracked files) and `git clean [-i/--interactive]` (to erase untracked
files). **However, be careful with those commands, as their function
is to erase things/changes.**

However, be careful not to add the `dist/` files in your commit, as
Grunt automatically regenerates the files in `dist/` as the source is
changed.

#### Tests

Please ensure all the tests pass:

```sh
npm test # defaults to ChromHeadless
BROWSERS=Firefox npm test
BROWSERS=Firefox,Chrome npm test
BROWSERS=Firefox,Chrome,Safari npm test
```

#### Local environment

To run Selectize locally:

```sh
npm start
```

You can then run the examples at `http://localhost:4000/`.

## License

Copyright © 2013–2016 [Brian Reavis](http://twitter.com/brianreavis) & [Contributors](https://github.com/selectize/selectize.js/graphs/contributors)\
Copyright © 2020-2022 Selectize Team & [Contributors](https://github.com/selectize/selectize.js/graphs/contributors)

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: <http://www.apache.org/licenses/LICENSE-2.0>

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.