text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

001
002
007
008package org.jsimpledb.kv.mvcc;
009
010import java.util.ArrayList;
011import java.util.HashMap;
012import java.util.HashSet;
013import java.util.List;
014import java.util.NavigableSet;
015import java.util.TreeSet;
016
017import org.dellroad.stuff.java.Predicate;
018import org.dellroad.stuff.java.TimedWait;
019import org.jsimpledb.util.ByteUtil;
020
021/**
022 * Manager of read/write locks on {@code byte[]} key ranges that ensures isolation and serialization while allowing concurrent
023 * access by multiple threads to a single underlying {@code byte[]} key/value store.
024 *
025 * <p>
026 * This implementation is straightforward: read locks can overlap, but write locks may not, and all locks owned
027 * by the same owner remain in force until all are {@linkplain #release released} at the same time.
028 * </p>
029 *
030 * <p>
031 * Instances are configured with a monitor object which is used for all internal locking and inter-thread wait/notify
032 * handshaking (by default, this instance). A user-supplied monitor object may be provided via the constructor.
033 * </p>
034 *
035 * <p>
036 * Two timeout values are supported:
037 * <ul>
038 *  <li>The wait timeout (specified as a parameter to {@link #lock lock()}) limits how long a thread will wait
039 *      on a lock held by another thread before giving up</li>
040 *  <li>The {@linkplain #getHoldTimeout hold timeout} limits how long a thread may hold
041 *      on to a contested lock before being forced to release all its locks; after that, the
042 *      next call to {@link #lock lock} or {@link #release release} will fail</li>
043 * </ul>
044 *
045 * <p>
046 * Note that if the hold timeout is set to zero (unlimited), then an application bug that leaks locks will result
047 * in those locks never being released.
048 * </p>
049 */
050public class LockManager {
051
052    private static final long TEN_YEARS_MILLIS = 10L * 365L * 24L * 60L * 60L * 1000L;
053
054    private final Object lockObject;
055
056    // Contains each owner's lock time, or null if hold timeout has expired.
057    // Invariant: if owner has any locks, then owner is a key in this map and value is not null.
058    // In the case owner's hold timeout expired and another owner forced it to release all of its locks, the expired
059    // owner will own no locks but still exist in this map (with a null value), until its next lock() or release().
060    private final HashMap<LockOwner, Long> lockTimes = new HashMap<>();
061
062    private final TreeSet<Lock> locksByMin = new TreeSet<>(Lock.MIN_COMPARATOR);            // locks ordered by minimum
063    private final TreeSet<Lock> locksByMax = new TreeSet<>(Lock.MAX_COMPARATOR);            // locks ordered by maximum
064    private final long nanoBasis = System.nanoTime();
065
066    private long holdTimeout;
067
068    /**
069     * Convenience constructor. Equivalent to <code>LockManager(null)</code>.
070     */
071    public LockManager() {
072        this(null);
073    }
074
075    /**
076     * Primary constructor.
077     *
078     * @param lockObject Java object used to synchronize field access and inter-thread wait/notify handshake,
079     *  or null to use this instance
080     */
081    public LockManager(Object lockObject) {
082        this.lockObject = lockObject != null ? lockObject : this;
083    }
084
085    /**
086     * Get the hold timeout configured for this instance.
087     *
088     * <p>
089     * The hold timeout limits how long a thread may hold on to a contested lock before being forced to release
090     * all of its locks; after that, the next call to {@link #lock lock} or {@link #release release} will fail.
091     * </p>
092     *
093     * @return hold timeout in milliseconds
094     */
095    public long getHoldTimeout() {
096        synchronized (this.lockObject) {
097            return this.holdTimeout;
098        }
099    }
100
101    /**
102     * Set the hold timeout for this instance. Default is zero (unlimited).
103     *
104     * @param holdTimeout how long a thread may hold a contestested lock before {@link LockResult#HOLD_TIMEOUT_EXPIRED}
105     *  will be returned by {@link #lock lock()} or {@link #release release()} in milliseconds, or zero for unlimited
106     * @throws IllegalArgumentException if {@code holdTimeout} is negative
107     */
108    public void setHoldTimeout(long holdTimeout) {
109        synchronized (this.lockObject) {
110            if (holdTimeout < 0)
111                throw new IllegalArgumentException("holdTimeout < 0");
112            this.holdTimeout = Math.min(holdTimeout, TEN_YEARS_MILLIS);             // limit to 10 years to avoid overflow
113        }
114    }
115
116    /**
117     * Acquire a lock on behalf of the specified owner.
118     *
119     * <p>
120     * This method will block for up to {@code waitTimeout} milliseconds if the lock is held by
121     * another thread, after which point {@link LockResult#WAIT_TIMEOUT_EXPIRED} is returned.
122     * The configured locking object will be used for inter-thread wait/notify handshaking.
123     * </p>
124     *
125     * <p>
126     * If {@code owner} already holds one or more locks, but the {@linkplain #getHoldTimeout hold timeout} has expired,
127     * then {@link LockResult#HOLD_TIMEOUT_EXPIRED} is returned and all of the other locks are will have already been
128     * automatically released.
129     * </p>
130     *
131     * <p>
132     * Once a lock is successfully acquired, it stays acquired until all locks are released together via {@link #release release()}.
133     * </p>
134     *
135     * @param owner lock owner
136     * @param minKey minimum key (inclusive); must not be null
137     * @param maxKey maximum key (exclusive), or null for no maximum
138     * @param write true for a write lock, false for a read lock
139     * @param waitTimeout how long to wait before returning {@link LockResult#WAIT_TIMEOUT_EXPIRED}
140     *  in milliseconds, or zero for unlimited
141     * @return a {@link LockResult}
142     * @throws InterruptedException if the current thread is interrupted while waiting for the lock
143     * @throws IllegalArgumentException if {@code owner}, {@code minKey}, or {@code range} is null
144     * @throws IllegalArgumentException if {@code minKey > maxKey}
145     * @throws IllegalArgumentException if {@code waitTimeout} is negative
146     */
147    public LockResult lock(LockOwner owner, byte[] minKey, byte[] maxKey, boolean write, long waitTimeout)
148      throws InterruptedException {
149        synchronized (this.lockObject) {
150
151            // Sanity check
152            if (owner == null)
153                throw new IllegalArgumentException("null owner");
154            if (waitTimeout < 0)
155                throw new IllegalArgumentException("waitTimeout < 0");
156            waitTimeout = Math.min(waitTimeout, TEN_YEARS_MILLIS);                  // limit to 10 years to avoid overflow
157
158            // Check hold timeout
159            final long lockerRemaining = this.checkHoldTimeout(owner);
160            if (lockerRemaining == -1)
161                return LockResult.HOLD_TIMEOUT_EXPIRED;
162
163            // Create lock
164            Lock lock = new Lock(owner, minKey, maxKey, write);
165
166            // Wait for lockability, until the first one of:
167            //  - Wait timeout
168            //  - Locker's hold timeout
169            //  - Lock owner's hold timeout
170            final LockChecker lockChecker = new LockChecker(lock);
171            if (!lockChecker.test()) {
172                long timeToWait = Math.min(waitTimeout, lockChecker.getTimeRemaining());
173                if (lockerRemaining != 0)
174                    timeToWait = Math.min(timeToWait, lockerRemaining);
175                if (!TimedWait.wait(this.lockObject, timeToWait, lockChecker))
176                    return LockResult.WAIT_TIMEOUT_EXPIRED;
177            }
178
179            // Check hold timeout again
180            if (this.checkHoldTimeout(owner) == -1)
181                return LockResult.HOLD_TIMEOUT_EXPIRED;
182
183            // Merge the lock with other locks it can merge with, removing those locks in the process
184            for (Lock that : lockChecker.getMergers()) {
185                final Lock mergedLock = lock.mergeWith(that);
186                if (mergedLock != null) {
187                    this.locksByMin.remove(that);
188                    this.locksByMax.remove(that);
189                    owner.locks.remove(that);
190                    lock = mergedLock;
191                }
192            }
193
194            // Add lock
195            this.locksByMin.add(lock);
196            this.locksByMax.add(lock);
197            owner.locks.add(lock);
198
199            // Set hold timeout (if not already set)
200            if (!this.lockTimes.containsKey(owner)) {
201                final long currentTime = System.nanoTime() - this.nanoBasis;
202                this.lockTimes.put(owner, currentTime);
203            } else
204                assert this.lockTimes.get(owner) != null;
205
206            // Done
207            return LockResult.SUCCESS;
208        }
209    }
210
211    /**
212     * Release all locks held by the specified owner.
213     *
214     * <p>
215     * If the owner's {@linkplain #getHoldTimeout hold timeout} has already expired, then all locks will have
216     * already been released and false is returned.
217     * </p>
218     *
219     * <p>
220     * Does nothing (and returns true) if {@code owner} does not own any locks.
221     * </p>
222     *
223     * @param owner lock owner
224     * @return true if successful, false if {@code owner}'s hold timeout expired
225     * @throws IllegalArgumentException if {@code owner} is null
226     */
227    public boolean release(LockOwner owner) {
228        synchronized (this.lockObject) {
229
230            // Sanity check
231            if (owner == null)
232                throw new IllegalArgumentException("null owner");
233
234            // Check if hold timeout has alread expired; in any case, remove lock time
235            if (this.lockTimes.containsKey(owner)) {
236                final Long lockTime = this.lockTimes.remove(owner);
237                if (lockTime == null)
238                    return false;
239            }
240
241            // Release all locks
242            this.doRelease(owner);
243
244            // Done
245            return true;
246        }
247    }
248
249    /**
250     * Check whether the {@linkplain #getHoldTimeout hold timeout} has expired for the given lock owner
251     * and if not return the amount of time remaining.
252     *
253     * <p>
254     * If the owner's hold timeout has expired, then {@code -1} is returned and any locks previously held by {@code owner}
255     * will have been automatically released.
256     * </p>
257     *
258     * @param owner lock owner
259     * @return milliseconds until {@code owner}'s hold timeout expires, zero if {@code owner} has no hold timeout
260     *  (e.g., nothing is locked or hold timeout disabled), or -1 if {@code owner}'s hold timeout has expired
261     * @throws IllegalArgumentException if {@code owner} is null
262     */
263    public long checkHoldTimeout(LockOwner owner) {
264        synchronized (this.lockObject) {
265            if (this.holdTimeout == 0)
266                return 0;
267            if (!this.lockTimes.containsKey(owner))
268                return 0;
269            final Long lockTime = this.lockTimes.get(owner);
270            if (lockTime == null)
271                return -1;
272            final long currentTime = System.nanoTime() - this.nanoBasis;
273            final long holdDeadline = lockTime + this.holdTimeout * 1000000L;
274            final long remaining = holdDeadline - currentTime;
275            if (remaining <= 0) {
276                this.lockTimes.put(owner, null);
277                this.doRelease(owner);
278                return -1;
279            }
280            return (remaining + 999999L) / 1000000L;
281        }
282    }
283
284    // Release all locks held by owner. Assumes synchronized already on this.lockObject.
285    private void doRelease(LockOwner owner) {
286        for (Lock lock : owner.locks) {
287            this.locksByMin.remove(lock);
288            this.locksByMax.remove(lock);
289        }
290        owner.locks.clear();
291        this.lockObject.notifyAll();
292    }
293
294    // Check whether we can lock, and fill the list of mergers and return zero if so. If not, return time remaining.
295    // Assumes synchronized already on this.lockObject.
296    private long checkLock(Lock lock, List<Lock> mergers) {
297
298        // Get lock's min & max
299        final byte[] lockMin = lock.getMin();
300        final byte[] lockMax = lock.getMax();
301
302    startOver:
303        while (true) {
304
305            // Get locks whose min is < lockMax
306            final NavigableSet<Lock> lhs = lockMax == null ? this.locksByMin :
307              this.locksByMin.headSet(Lock.getMinKey(lockMax, false), false);
308
309            // Get locks whose max is > lockMin
310            final NavigableSet<Lock> rhs = lockMin == null ? this.locksByMax : this.locksByMax.tailSet(
311              Lock.getMaxKey(ByteUtil.getNextKey(lockMin), false), true);
312
313            // Find overlapping locks and check for conflicts
314            final HashSet<Lock> overlaps = new HashSet<>();
315            for (Lock other : lhs) {
316
317                // Does this lock overlap?
318                if (!rhs.contains(other))
319                    continue;
320
321                // Do this lock & other lock conflict?
322                if (lock.conflictsWith(other)) {
323
324                    // See if other lock's owner's hold timeout has expired
325                    assert this.lockTimes.containsKey(other.owner);
326                    final long remaining = this.checkHoldTimeout(other.owner);
327                    if (remaining == -1)
328                        continue startOver;
329
330                    // Return time remaining until conflicting owner's hold timeout
331                    return Math.max(remaining, 1);
332                }
333
334                // Add overlap
335                overlaps.add(other);
336            }
337
338            //System.out.println(Thread.currentThread().getName() + ": LockChecker: BEFORE: lock = " + lock + "\n"
339            //+ "  lockByMin = " + this.locksByMin + "\n"
340            //+ "  lockByMax = " + this.locksByMax + "\n"
341            //+ "   overlaps = " + overlaps + "\n");
342
343            // Find overlaps we can merge with
344            for (Lock other : overlaps) {
345                if (lock.mergeWith(other) != null)
346                    mergers.add(other);
347            }
348
349            //System.out.println(Thread.currentThread().getName() + ": LockChecker: AFTER: lock = " + lock + "\n"
350            //+ "  lockByMin = " + this.locksByMin + "\n"
351            //+ "  lockByMax = " + this.locksByMax + "\n"
352            //+ "    mergers = " + mergers + "\n");
353
354            // Done
355            return 0;
356        }
357    }
358
359// LockResult
360
361    /**
362     * Possible return values from {@link LockManager#lock LockManager.lock()}.
363     */
364    public enum LockResult {
365
366        /**
367         * The lock was successfully acquired.
368         */
369        SUCCESS,
370
371        /**
372         * The timeout expired while waiting to acquire the lock.
373         */
374        WAIT_TIMEOUT_EXPIRED,
375
376        /**
377         * The owner's hold timeout expired.
378         */
379        HOLD_TIMEOUT_EXPIRED;
380    }
381
382// LockChecker predicate
383
384    private class LockChecker implements Predicate {
385
386        private final Lock lock;
387        private final ArrayList<Lock> mergers = new ArrayList<>();
388
389        private long timeRemaining;
390
391        LockChecker(Lock lock) {
392            this.lock = lock;
393        }
394
395        public List<Lock> getMergers() {
396            return this.mergers;
397        }
398
399        public long getTimeRemaining() {
400            return this.timeRemaining;
401        }
402
403        @Override
404        public boolean test() {
405
406            // Reset state
407            this.mergers.clear();
408
409            // See if we can lock
410            this.timeRemaining = LockManager.this.checkLock(this.lock, this.mergers);
411            return this.timeRemaining == 0;
412        }
413    }
414}
415


text:
package org.apache.hadoop.yarn.api.protocolrecords;

import org.apache.hadoop.classification.InterfaceAudience.Public;
import org.apache.hadoop.classification.InterfaceStability.Stable;
import org.apache.hadoop.yarn.api.ClientRMProtocol;

/**
 *
The request sent by clients to get queue information
 * from the ResourceManager.

 *
 * @see ClientRMProtocol#getQueueInfo(GetQueueInfoRequest)
 */
@Public
@Stable
public interface GetQueueInfoRequest {
  /**
   * Get the queue name for which to get queue information.
   * @return queue name for which to get queue information
   */
  String getQueueName();

  /**
   * Set the queue name for which to get queue information
   * @param queueName queue name for which to get queue information
   */
  void setQueueName(String queueName);

  /**
   * Is information about active applications<e/m> required?
   * @return true if applications' information is to be included,
   *         else false
   */
  boolean getIncludeApplications();

  /**
   * Should we get fetch information about active applications?
   * @param includeApplications fetch information about active
   *                            applications?
   */
  void setIncludeApplications(boolean includeApplications);

  /**
   * Is information about child queues required?
   * @return true if information about child queues is required,
   *         else false
   */
  boolean getIncludeChildQueues();

  /**
   * Should we fetch information about child queues?
   * @param includeChildQueues fetch information about child queues?
   */
  void setIncludeChildQueues(boolean includeChildQueues);

  /**
   * Is information on the entire child queue hierarchy required?
   * @return true if information about entire hierarchy is
   *         required, false otherwise
   */
  boolean getRecursive();

  /**
   * Should we fetch information on the entire child queue hierarchy?
   * @param recursive fetch information on the entire child queue
   *                  hierarchy?
   */
  void setRecursive(boolean recursive);
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Magister\Services\Contracts\Auth;

/**
 * Interface Guard.
 */
interface Guard
{
    /**
     * Determine if the current user is authenticated.
     *
     * @return bool
     */
    public function check();

    /**
     * Determine if the current user is a guest.
     *
     * @return bool
     */
    public function guest();

    /**
     * Get the currently authenticated user.
     *
     * @return \Magister\Services\Contracts\Auth\Authenticable|null
     */
    public function user();

    /**
     * Attempt to authenticate a user using the given credentials.
     *
     * @param array $credentials
     * @param bool  $login
     *
     * @return bool
     */
    public function attempt(array $credentials = [], $login = true);

    /**
     * Log a user into the application.
     *
     * @param \Magister\Services\Contracts\Auth\Authenticable $user
     *
     * @return void
     */
    public function login(Authenticable $user);

    /**
     * Log the user out of the application.
     *
     * @return void
     */
    public function logout();
}


text:
import { combineReducers } from 'redux';
import userReducer from './user';

export default combineReducers({
  user: userReducer,
});


text:
"""Implementation of Queue. First in, first out data structure."""
from dll import Dll

class Queue(object):
    """Create Queue Class object."""

    def __init__(self):
        """Queue initiliazation.

        Composed of Doubly-Linked List attributes and methods.
        """
        self._dll = Dll()
        self._length = self._dll._length
        self.head = self._dll.head
        self.tail = self._dll.tail

    @property
    def size(self):
        """Use dll length method to return size of list."""
        return self._dll._length

    def enqueue(self, data):
        """Add node to queue at head."""
        self._dll.push(data)

    def dequeue(self):
        """Remove node from queue at tail."""
        if self.size == 0:
            raise IndexError('The queue is empty.')
        else:
            return self._dll.shift()

    def peek(self):
        """Display next value that will be removed if dequeued is called."""
        if self.size == 0:
            return None
        return self._dll.tail.data

    def __len__(self):
        """Function overwrites built-in len function to show length."""
        return self.size


text:
package org.apache.hadoop.mapreduce.v2.app.job.impl;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Map;
import java.nio.ByteBuffer;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RawLocalFileSystem;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapTaskAttemptImpl;
import org.apache.hadoop.mapred.WrappedJvmID;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.TypeConverter;
import org.apache.hadoop.mapreduce.security.token.JobTokenIdentifier;
import org.apache.hadoop.mapreduce.split.JobSplit.TaskSplitMetaInfo;
import org.apache.hadoop.mapreduce.v2.api.records.JobId;
import org.apache.hadoop.mapreduce.v2.api.records.TaskId;
import org.apache.hadoop.mapreduce.v2.api.records.TaskType;
import org.apache.hadoop.mapreduce.v2.app.TaskAttemptListener;
import org.apache.hadoop.mapreduce.v2.util.MRBuilderUtils;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.util.SystemClock;
import org.apache.hadoop.yarn.server.api.AuxiliaryService;
import org.apache.hadoop.yarn.server.api.ApplicationInitializationContext;
import org.apache.hadoop.yarn.server.api.ApplicationTerminationContext;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.junit.Test;
import org.junit.Assert;

public class TestShuffleProvider {

  @Test
  public void testShuffleProviders() throws Exception {
    ApplicationId appId = ApplicationId.newInstance(1, 1);
    JobId jobId = MRBuilderUtils.newJobId(appId, 1);
    TaskId taskId = MRBuilderUtils.newTaskId(jobId, 1, TaskType.MAP);
    Path jobFile = mock(Path.class);

    EventHandler eventHandler = mock(EventHandler.class);
    TaskAttemptListener taListener = mock(TaskAttemptListener.class);
    when(taListener.getAddress()).thenReturn(new InetSocketAddress("localhost", 0));

    JobConf jobConf = new JobConf();
    jobConf.setClass("fs.file.impl", StubbedFS.class, FileSystem.class);
    jobConf.setBoolean("fs.file.impl.disable.cache", true);
    jobConf.set(JobConf.MAPRED_MAP_TASK_ENV, "");

    jobConf.set(YarnConfiguration.NM_AUX_SERVICES,
      TestShuffleHandler1.MAPREDUCE_TEST_SHUFFLE_SERVICEID + "," +
      TestShuffleHandler2.MAPREDUCE_TEST_SHUFFLE_SERVICEID);

    String serviceName = TestShuffleHandler1.MAPREDUCE_TEST_SHUFFLE_SERVICEID;
    String serviceStr = String.format(YarnConfiguration.NM_AUX_SERVICE_FMT, serviceName);
    jobConf.set(serviceStr, TestShuffleHandler1.class.getName());

    serviceName = TestShuffleHandler2.MAPREDUCE_TEST_SHUFFLE_SERVICEID;
    serviceStr = String.format(YarnConfiguration.NM_AUX_SERVICE_FMT, serviceName);
    jobConf.set(serviceStr, TestShuffleHandler2.class.getName());

    jobConf.set(MRJobConfig.MAPREDUCE_JOB_SHUFFLE_PROVIDER_SERVICES,
                  TestShuffleHandler1.MAPREDUCE_TEST_SHUFFLE_SERVICEID
                     + "," + TestShuffleHandler2.MAPREDUCE_TEST_SHUFFLE_SERVICEID);

    Credentials credentials = new Credentials();
    Token<JobTokenIdentifier> jobToken = new Token<JobTokenIdentifier>(
        ("tokenid").getBytes(), ("tokenpw").getBytes(),
        new Text("tokenkind"), new Text("tokenservice"));
    TaskAttemptImpl taImpl =
        new MapTaskAttemptImpl(taskId, 1, eventHandler, jobFile, 1,
            mock(TaskSplitMetaInfo.class), jobConf, taListener,
            jobToken, credentials,
            new SystemClock(), null);

    jobConf.set(MRJobConfig.APPLICATION_ATTEMPT_ID, taImpl.getID().toString());

    ContainerLaunchContext launchCtx =
        TaskAttemptImpl.createContainerLaunchContext(null,
            jobConf, jobToken, taImpl.createRemoteTask(),
            TypeConverter.fromYarn(jobId),
            mock(WrappedJvmID.class), taListener,
            credentials);

    Map<String, ByteBuffer> serviceDataMap = launchCtx.getServiceData();
    Assert.assertNotNull("TestShuffleHandler1 is missing", serviceDataMap.get(TestShuffleHandler1.MAPREDUCE_TEST_SHUFFLE_SERVICEID));
    Assert.assertNotNull("TestShuffleHandler2 is missing", serviceDataMap.get(TestShuffleHandler2.MAPREDUCE_TEST_SHUFFLE_SERVICEID));
    Assert.assertTrue("mismatch number of services in map", serviceDataMap.size() == 3); // 2 that we entered + 1 for the built-in shuffle-provider
  }

  static public class StubbedFS extends RawLocalFileSystem {
    @Override
    public FileStatus getFileStatus(Path f) throws IOException {
      return new FileStatus(1, false, 1, 1, 1, f);
    }
  }

  static public class TestShuffleHandler1 extends AuxiliaryService {
    public static final String MAPREDUCE_TEST_SHUFFLE_SERVICEID = "test_shuffle1";
    public TestShuffleHandler1() {
      super("testshuffle1");
    }
    @Override
    public void initializeApplication(ApplicationInitializationContext context) {
    }
    @Override
    public void stopApplication(ApplicationTerminationContext context) {
    }
    @Override
    public synchronized ByteBuffer getMetaData() {
      return ByteBuffer.allocate(0); // Don't 'return null' because of YARN-1256
    }
  }

  static public class TestShuffleHandler2 extends AuxiliaryService {
    public static final String MAPREDUCE_TEST_SHUFFLE_SERVICEID = "test_shuffle2";
    public TestShuffleHandler2() {
      super("testshuffle2");
    }
    @Override
    public void initializeApplication(ApplicationInitializationContext context) {
    }
    @Override
    public void stopApplication(ApplicationTerminationContext context) {
    }
    @Override
    public synchronized ByteBuffer getMetaData() {
      return ByteBuffer.allocate(0); // Don't 'return null' because of YARN-1256
    }
  }
}


text:
package limiters

import (
	"errors"
	"time"
)

var (
	defaultTimer = &defaultTimerImpl{}

	// ErrLimitExceeded signals that the counter limit has hit
	ErrLimitExceeded = errors.New("Limit exceeded")
)

// Counter abstracts counter interface
type Counter interface {
	IncrBy(int64) error
	Total() (int64, error)
}

// timer just abstracts time provider, this helps during testing
type timer interface {
	UnixNano() int64
}

type defaultTimerImpl struct{}

func (t *defaultTimerImpl) UnixNano() int64 { return time.Now().UnixNano() }

// CheckAndIncrement is a simple strategy to check a counter value for the limit and
// increment it if the counter value is still under the limit.
// NOTE: This strategy is not precise due to race condition but this is sufficient in most cases.
func CheckAndIncrement(counter Counter, incrVal, maxVal int64) error {
	val, err := counter.Total()
	if err != nil {
		return err
	}
	if val+incrVal > maxVal {
		return ErrLimitExceeded
	}
	return counter.IncrBy(incrVal)
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using IdleLandsRedux.DataAccess.Mappings;
using IdleLandsRedux.GameLogic.DataEntities.Interfaces.Reductions;
using IdleLandsRedux.Common;

namespace IdleLandsRedux.GameLogic.DataEntities
{
    public partial class SpecificCharacter : Character, ICalcPhysicalAttackTargets, ICalcDamageReduction, IEquatable<SpecificCharacter>
    {
        public int Special { get; set; } //For stuff like rage (barbarian), focus (archer) etc
        public StatsModifierCollection CalculatedStats { get; set; }
        public StatsObject TotalStats { get; set; }
        public TransientStatsObject TransientStats { get; set; } //Accumulated damage, poison etc

        public bool Dead { get; set; }
        public bool Fled { get; set; }
        public bool StillParticipatingInCombat { get { return !Dead && !Fled; } }

        public SpecificCharacter() : base()
        {
        }

        public SpecificCharacter(Character c) : base()
        {
            if(c == null)
            {
                throw new ArgumentNullException(nameof(c));
            }

            this.Id = c.Id;
            this.Name = c.Name;
            this.Gender = c.Gender;
            this.Stats = c.Stats;
            this.Equipment = c.Equipment;
        }

        public virtual int DamageReduction()
        {
            return 0;
        }

        public virtual ICollection<Tuple<Character, int>> PhysicalAttackTargets(ICollection<Tuple<Character, int>> allEnemies)
        {
            var validTargets = allEnemies.Where(x => x.Item1.Id != this.Id).ToList();
            var tuple = validTargets.OrderBy(x => x.Item1.Stats.Dexterity).First();
            validTargets.Remove(tuple);
            validTargets.Add(new Tuple<Character, int>(tuple.Item1, 200));
            return validTargets;
        }

        #region IEquatable members

        public override bool Equals(object obj)
        {
            var sc = obj as SpecificCharacter;

            return Equals(sc);
        }

        public bool Equals(SpecificCharacter sc)
        {
            if (sc == null)
                return false;

            if (ReferenceEquals(sc, this))
                return true;

            return sc.Id == 0 && this.Id == 0 ? false : sc.Id == this.Id;
        }

        public override int GetHashCode()
        {
            unchecked
            { // Overflow is fine, just wrap
                int hash = 13;
                hash = (hash * 7) + Id.GetHashCode();
                if (!string.IsNullOrEmpty(Name))
                    hash = (hash * 7) + Name.GetHashCode();
                return hash;
            }
        }

        #endregion
    }
}


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 robote13\catalog\components;

/**
 *
 * @author Tartharia
 */
trait RelationsTrait
{
    //put your code here
}


text:
:- module(validate, [
  validate_plan/8
]).

:- use_module(library(semweb/rdf11)).
:- use_module(library(semweb/rdfs)).
:- use_module(library(dcg/basics)).
:- use_module(library(oslc)).
:- use_module(library(pddl_generator)).

:- rdf_meta validate_plan(r, -, -, r, -, -, r, -).
:- rdf_meta callable_bnode(-, r, -, -).

:- thread_local context/1.

validate_plan(Domain, DomainGraph, DomainFile, Problem, ProblemGraph, ProblemFile, Plan, PlanGraph) :-
  generate_pddl(Plan, PlanGraph, PlanString),
  setup_call_cleanup(tmp_file_stream(text, PlanFile, PlanStream), (
    write(PlanStream, PlanString),
    close(PlanStream),
    setup_call_cleanup(true, (
      process_create('validate', ['-v', DomainFile, ProblemFile, PlanFile], [stdout(pipe(ValidPlanStream))]),
      findall(StepResource,
        rdf(Plan, pddl:step, StepResource, PlanGraph),
      StepResources),
      predsort(order_compare, StepResources, SortedSteps),
      Context = _{
             domain : Domain,
       domain_graph : DomainGraph,
            problem : Problem,
      problem_graph : ProblemGraph,
         plan_graph : PlanGraph },
      assertz(context(Context)),
      read_lines(ValidPlanStream, [_|SortedSteps])
    ), (retractall(context(_)), close(ValidPlanStream)))
  ), delete_file(PlanFile)).

read_lines(Out, SortedSteps) :-
  read_line_to_codes(Out, Line),
  read_lines(Line, Out, SortedSteps).

read_lines(end_of_file, _, _) :- !.
read_lines(Codes, Out, SortedSteps) :-
  (phrase(parse(SortedSteps, NewSortedSteps), Codes, [])
  -> true
  ; NewSortedSteps = SortedSteps
  ),
  read_line_to_codes(Out, Line),
  read_lines(Line, Out, NewSortedSteps).

order_compare(Ineq, Thing1, Thing2) :-
  rdf(Thing1, sh:order, Order1^^xsd:integer),
  rdf(Thing2, sh:order, Order2^^xsd:integer),
  ( Order1 =< Order2
  -> Ineq = <
  ; Ineq = >
  ).

parse([_|T], T) -->
  checking, !.

parse([Step|T], [Step|T]) -->
  adding(Step), !.

parse([Step|T], [Step|T]) -->
  deleting(Step), !.

parse([Step|T], [Step|T]) -->
  updating(Step).

checking -->
  "Checking next happening (time ", string(_), eos.

adding(Step) -->
  ("Adding (", callable_bnode(PBN, pddl:'Predicate'), ")"),
  {
    context(Context),
    rdf_assert(Step, pddl:adding, PBN, Context.plan_graph)
  }.

deleting(Step) -->
  ("Deleting (", callable_bnode(PBN, pddl:'Predicate'), ")"),
  {
    context(Context),
    rdf_assert(Step, pddl:deleting, PBN, Context.plan_graph)
  }.

updating(Step) -->
  "Updating (", callable_bnode(FBN, pddl:'Function'), ") (",
  integer(Current), ") by ", integer(Argument), " ", label(AssignmentOperator),
  {
    context(Context),
    rdf_create_bnode(UBN),
    find_assignment_operator(AssignmentOperator, AssignmentOperatorType),
    create_resource(UBN, [AssignmentOperatorType], [pddl:'AssignmentOperatorShape'], [
      pddl:current = '^^'(Current, xsd:integer),
      pddl:parameter = FBN,
      pddl:argument = '^^'(Argument, xsd:integer)
    ], rdf(Context.plan_graph)),
    rdf_assert(Step, pddl:updating, UBN, Context.plan_graph)
  }.

callable_bnode(CBN, Class) -->
  label(Callable),
  arguments(Arguments),
  {
    length(Arguments, Arity),
    find_callable(Callable, Arity, CallableResource, Class),
    rdf_create_bnode(CBN),
    context(Context),
    create_resource(CBN, [CallableResource], [], [], rdf(Context.plan_graph)),
    findall(ParameterResource,
      rdf(CallableResource, pddl:parameter, ParameterResource, Context.domain_graph),
    ParameterResources),
    predsort(order_compare, ParameterResources, SortedParameters),
    callable_arguments(SortedParameters, Arguments, CBN, Context)
  }.

label(Label) -->
  string_without(" )\n", Codes),
  { atom_codes(Label, Codes) }.

arguments([H|T]) -->
  " ",
  string_without(" )", Codes),
  { atom_codes(H, Codes) },
  arguments(T).

arguments([]) --> [], !.

find_callable(CallablePattern, Arity, CallableResource, Class) :-
  context(Context),
  { icase(CallableLabel, CallablePattern) },
  rdf(CallableResource, rdfs:label, CallableLabel^^xsd:string, Context.domain_graph),
  rdfs_subclass_of(CallableResource, Class),
  aggregate_all(count, rdf(CallableResource, pddl:parameter, _), Arity).

callable_arguments([], [], _, _) :- !.
callable_arguments([SortedParameter|T], [Argument|T2], PBN, Context) :-
  find_object(Argument, ArgumentResource),
  oslc_resource(PBN, [SortedParameter=ArgumentResource], rdf(Context.plan_graph)),
  callable_arguments(T, T2, PBN, Context).

find_object(ObjectPattern, ObjectResource) :-
  context(Context),
  { icase(ObjectLabel, ObjectPattern) },
  ( rdf(ObjectResource, rdfs:label, ObjectLabel^^xsd:string, Context.domain_graph)
  ; rdf(ObjectResource, rdfs:label, ObjectLabel^^xsd:string, Context.problem_graph)
  ),
  rdfs_individual_of(ObjectResource, pddl:'PrimitiveType').

find_assignment_operator(AssignmentOperatorPattern, AssignmentOperatorType) :-
  { icase(ObjectLabel, AssignmentOperatorPattern) },
  rdf(AssignmentOperatorType, rdfs:label, ObjectLabel^^xsd:string),
  rdfs_subclass_of(AssignmentOperatorType, pddl:'AssignmentOperator').


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE197_Numeric_Truncation_Error__short_fgets_81.h
Label Definition File: CWE197_Numeric_Truncation_Error__short.label.xml
Template File: sources-sink-81.tmpl.h
*/
/*
 * @description
 * CWE: 197 Numeric Truncation Error
 * BadSource: fgets Read data from the console using fgets()
 * GoodSource: Less than CHAR_MAX
 * Sinks:
 *    BadSink : Convert data to a char
 * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
 *
 * */

#include "std_testcase.h"

namespace CWE197_Numeric_Truncation_Error__short_fgets_81
{

class CWE197_Numeric_Truncation_Error__short_fgets_81_base
{
public:
    /* pure virtual function */
    virtual void action(short data) const = 0;
};

#ifndef OMITBAD

class CWE197_Numeric_Truncation_Error__short_fgets_81_bad : public CWE197_Numeric_Truncation_Error__short_fgets_81_base
{
public:
    void action(short data) const;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE197_Numeric_Truncation_Error__short_fgets_81_goodG2B : public CWE197_Numeric_Truncation_Error__short_fgets_81_base
{
public:
    void action(short data) const;
};

#endif /* OMITGOOD */

}


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Roles extends Application
{

   // private $session;

    public function actor($role = ROLE_GUEST)
        {
            //$this->load->library('session');
            $this->session->set_userdata('userrole',$role);
            redirect($_SERVER['HTTP_REFERER']); // back where we came from
        }

}


text:
package edu.usfca.xj.appkit.gview.base;

import java.awt.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Path2D {

    private List points = new ArrayList();

    public Path2D() {

    }

    public void clear() {
        points.clear();
    }

    public void add(Vector2D v) {
        points.add(v);
    }

    public void add(double x, double y) {
        add(new Vector2D(x, y));
    }

    public void draw(Graphics g) {
        Vector2D lastV = null;

        Iterator iterator = points.iterator();
        while(iterator.hasNext()) {
            Vector2D v = (Vector2D)iterator.next();
            if(lastV != null)
                g.drawLine((int)lastV.getX(), (int)lastV.getY(), (int)v.getX(), (int)v.getY());

            lastV = v;
        }
    }

    public boolean contains(double x, double y) {
        Vector2D oldv = null;
        Iterator iterator = points.iterator();
        while(iterator.hasNext()) {
            Vector2D v = (Vector2D)iterator.next();
            if(oldv != null) {
                Rect r = new Rect(oldv, v);
                r.inset(-4);
                if(r.contains(x, y))
                    return true;
            }
            oldv = v;
        }
        return false;
    }

    public Vector2D getEndDirection() {
        if(points.size()<2)
            return null;

        Vector2D v1 = (Vector2D)points.get(points.size()-2);
        Vector2D v2 = (Vector2D)points.get(points.size()-1);
        return v1.sub(v2);
    }
}


text:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE RankNTypes #-}
-----------------------------------------------------------------------------
--
-- Module      :  AI.Network.RMM.LSTM
-- Copyright   :  (c) JP Moresmau
-- License     :  BSD3
--
-- Maintainer  :  JP Moresmau <jp@moresmau.fr>
-- Stability   :  experimental
-- Portability :
--
-- | Long Short Term Memory networks
--
-----------------------------------------------------------------------------

module AI.Network.RNN.LSTM where

import Control.DeepSeq

import Data.List

import Numeric.LinearAlgebra.HMatrix

import AI.Network.RNN.Types
import AI.Network.RNN.Util
import AI.Network.RNN.Expr
import Debug.Trace
import qualified Data.IntMap as I

import Numeric.AD

-- | The LSTM data type, with the different weights and states
data LSTMNetwork = LSTMNetwork
    { lstmSize :: !Int
    , lstmWeightsW :: !(Matrix Double)
    , lstmWeightsU :: !(Matrix Double)
    , lstmBias :: !(Vector Double)
    , lstmState :: !(Vector Double)
    , lstmOutput :: !(Vector Double)
    } deriving (Show,Read,Eq)

--instance Show LSTMNetwork where
--     show s = let
--        a= show $ (rnnsize s,toVector s)
--        in trace (show $ length a) a
--
--instance Read LSTMNetwork where
--    readsPrec d s =
--        let [(ok,r)] = readsPrec d s
--            dat = uncurry fromVector ok
--        in [(dat,r)]

-- | Force evaluation instance
instance NFData LSTMNetwork where
    rnf LSTMNetwork{..} = rnf (lstmSize,lstmWeightsW,lstmWeightsU,lstmBias,lstmState,lstmOutput)

-- | Implement the network evaluation and conversions functions
instance RNNEval LSTMNetwork where
    type Size LSTMNetwork = Int
    evalStep n@LSTMNetwork{..} is =
        let z = (lstmWeightsW #> is) + (lstmWeightsU #> lstmOutput) + lstmBias
            [i,f,c1,o] = takesV (replicate 4 lstmSize) z
            c2 = cmap tanh c1
            ns = (c2 * cmap sigmoid i) + (cmap sigmoid f * lstmState)
            no = cmap sigmoid o * cmap tanh ns
        in force (n{lstmState=ns,lstmOutput=no},no)
    fromVector sz vs =
        let
            msize = sz * sz
            [v1,v2,v3,v4,v5] = takesV [msize * 4,msize * 4, sz * 4,sz,sz] vs
            m1 = reshape sz v1
            m2 = reshape sz v2
        in LSTMNetwork sz m1 m2 v3 v4 v5
    toVector LSTMNetwork{..} = force $ vjoin
        [ flatten lstmWeightsW, flatten lstmWeightsU, lstmBias, lstmState, lstmOutput]
    rnnsize = lstmSize
    fullSize = lstmFullSize .lstmSize

-- | Full size of a network
lstmFullSize :: FullSize LSTMNetwork
lstmFullSize sz = (sz * sz) * 8 + sz* 4 + sz + sz

data LSTMIO = LSTMIO
    { lioInput :: Matrix Double
    , lioLstms :: [LSTMNetwork]
    , lioOutput :: Matrix Double
    , lioSer   :: Maybe (Vector Double)
    } deriving (Eq)

instance NFData LSTMIO where
  rnf LSTMIO{..} = rnf (lioInput,lioLstms,lioOutput)

instance RNNEval LSTMIO  where
    type Size LSTMIO = (Int,Int,Int,Int)
    evalStep io@LSTMIO{..} is =
        let inps = cmap sigmoid $ lioInput #> (vjoin [is,scalar 1])
            (lstm2,outs) = evalStep lioLstms inps
        in (io{lioLstms=lstm2,lioSer=Nothing},lioOutput #> outs)
    fromVector (is,lnnSize,lnnNumber,os) vs =
        let [v1,v2,v3] = takesV [(is+1)* lnnSize ,lnnNumber * (lstmFullSize lnnSize),os * lnnSize ] vs
            m1 = reshape (is+1) v1
            m2 = reshape lnnSize v3
        in LSTMIO m1 (fromVector (replicate lnnNumber lnnSize) v2) m2 $ Just vs
    toVector LSTMIO{..} = case lioSer of
        Just vs -> vs
        Nothing -> vjoin [flatten lioInput,toVector lioLstms,flatten lioOutput]
    rnnsize LSTMIO{..} = (cols lioInput - 1, rnnsize $ head lioLstms, length lioLstms,rows lioOutput)
    fullSize =lstmioFullSize . rnnsize
--        let (r1,c1)=size lioInput
--            (r2,c2)=size lioOutput
--        in (r1*c1) + (fullSize lioLstms) + (r2*c2)

instance Show LSTMIO where
    show l = show (rnnsize l,toVector l)

instance Read LSTMIO where
    readsPrec d s =
        let [(ok,r)] = readsPrec d s
            dat = uncurry fromVector ok
        in [(dat,r)]

lstmioFullSize :: FullSize LSTMIO
lstmioFullSize (is,lnnSize,lnnNumber,os) = (is+1) * lnnSize + lnnNumber * (lstmFullSize lnnSize) + os * lnnSize

data LSTMList = LSTMList
    { llSize :: (Int,Int,Int,Int)
    , llData :: [Double]
    } deriving (Show, Read, Eq)

instance NFData LSTMList where
  rnf LSTMList{..} = rnf (llSize,llData)

instance RNNEval LSTMList where
    type Size LSTMList = (Int,Int,Int,Int)
    rnnsize = llSize
    fullSize =lstmioFullSize . rnnsize
    toDList = llData
    fromDList sz = LSTMList sz
    toVector = fromList . toDList
    fromVector sz = fromDList sz . toList
    evalStep l@LSTMList{..} is =
        let lstmio :: LSTMIO = fromDList llSize llData
            (io2,out) = evalStep lstmio is
        in (l{llData=toDList io2},out)

-- | Implementation of the LSTM evaluation step without explicit matrices and vectors
-- just using lists, so we can use AD on it
lstmList :: (Num b,Floating b) => Int -> [b] -> [b] -> ([b],[b])
lstmList sz lstm is = let
    msize = sz * sz
    [mW,mU,vB,vS,vO] = takes [msize * 4,msize * 4, sz * 4,sz,sz] lstm
    z = zipWith3 (\a b c->a+b+c) (listMProd mW is) (listMProd mU vO) vB
    [i,f,c1,o] = takes (replicate 4 sz) z
    c2 = map tanh c1
    ns = zipWith (+) (zipWith (*) c2 (map sigmoid i)) (zipWith (*) (map sigmoid f) vS)
    no = zipWith (*) (map sigmoid o) (map tanh ns)
    in (mW++mU++vB++ns++no,no)

-- | Cost calculation using list representation for AD
cost' :: (Num b,Floating b,Fractional b) => Int -> [[b]] -> [[b]] -> [b] -> b
cost' sz is os lstm = let
    (_,res) = mapAccumL (lstmList sz) lstm is
--    in - (calcMeanList $ three (last res) (last os))
--    in - (calcMeanList $ concat $ zipWith (three) res os)
    in sum $ zipWith err os res
    where
      err :: (Num b,Floating b) => [b] -> [b] -> b
      err a b  = sum (zipWith (\c d -> (c- d)**2 ) a b)
--      one i o = zipWith (*) o (map log i)
--      two i o = zipWith (*) (map (\x->1 - x) o) (map (\x->1 - log x) i)
--      three i o= zipWith (+) (one i o) (two i o)

-- | Gradient descent learning
-- The third parameter is a call back function to monitor progress and stop the learning process if needed
learnGradientDescent :: (Monad m) => LSTMNetwork -> TrainData a -> (LSTMNetwork -> TrainData a -> Int -> m Bool) -> m LSTMNetwork
learnGradientDescent lstm td progressF =  go (toList $ toVector lstm) 0
    -- go2 gds 0
    where
      go2 (ls:lss) gen =  do
        let rnn::LSTMNetwork = fromVector (tdRecSize td) (fromList ls)
        cont <- progressF rnn td gen
        if cont
            then go2 lss (gen+1)
            else return rnn
      go ls gen = do
        let rnn::LSTMNetwork = fromVector (tdRecSize td) (fromList ls)
        cont <- progressF rnn td gen
        if cont
            then do
                let
                    gs= gf ls -- gradients using AD
                    ls2 = zipWith (\o g->o-g*0.1) ls gs
                go ls2 (gen+1)
            else return rnn
      lis = map toList (tdInputs td)
      los = map toList (tdOutputs td)
      gf = grad (cost' (tdRecSize td) (map (map auto) lis) (map (map auto) los))
      gds = gradientDescent (cost' (tdRecSize td) (map (map auto) lis) (map (map auto) los)) (toList $ toVector lstm)

-- | Gradient descent learning using symbolic differentiation
--   The goal was to calculate the derivative once and then just close and eval the result using the current data
--   However it is much slower than normal automatic differentiation
learnGradientDescentSym :: (Monad m) => LSTMNetwork -> TrainData a -> (LSTMNetwork -> TrainData a -> Int -> m Bool) -> m LSTMNetwork
learnGradientDescentSym lstm td progressF =  go (toList $ toVector lstm) 0
    where
      go ls gen = do
        let rnn::LSTMNetwork = fromVector (tdRecSize td) (fromList ls)
        cont <- progressF rnn td gen
        if cont
            then do
                let
                    i = I.fromList $ zip [0..] ls
                    cexpr = map (\g-> close g i) gf
                    gs = map eval cexpr
                    ls2 = zipWith (\o g->o-g*0.1) ls gs
                go ls2 (gen+1)
            else return rnn
      lis = map toList (tdInputs td)
      los = map toList (tdOutputs td)
      ls0 = toList $ toVector lstm
      gf = map fullSimplify $ grad (cost'
            (tdRecSize td)
            (map (map (\x -> autoEval (Lit $ Lit x) I.empty)) lis)
            (map (map (\x -> autoEval (Lit $ Lit x) I.empty)) los))
            (zipWith (\_ i->Var i) ls0 [0..])

-- | RMSProp learning, as far as I can make out
-- The third parameter is a call back function to monitor progress and stop the learning process if needed
learnRMSProp :: (Monad m) => LSTMNetwork -> TrainData a -> (LSTMNetwork -> TrainData a -> Int -> m Bool) -> m LSTMNetwork
learnRMSProp lstm td progressF = go ls0 (replicate myl 0) (replicate myl 0) (replicate myl 0) 0
    where
      go ls rgs rgs2 ugs gen = do
        let rnn::LSTMNetwork = fromVector (tdRecSize td) (fromList ls)
        cont <- progressF rnn td gen
        if cont
            then do
                let
                    gs= gf ls -- gradients using AD
                    rgup = zipWith (\rg g-> 0.95 * rg + 0.05 * g) rgs ls
                    rg2up = zipWith (\rg2 g-> 0.95 * rg2 + 0.05 * (g ** 2)) rgs2 ls
                    ugup = zipWith4 (\ud zg rg rg2 -> 0.9 * ud - 1e-4 * zg / sqrt(rg2 - rg ** 2 + 1e-4)) ugs gs rgup rg2up
                    ls2 = zipWith (+) ls ugup
                go (force ls2) (force rgup) (force rg2up) (force ugup) (gen+1)
            else return rnn
      lis = map toList (tdInputs td)
      los = map toList (tdOutputs td)
      gf = grad (cost' (tdRecSize td) (map (map auto) lis) (map (map auto) los))
      ls0 = toList $ toVector lstm
      myl= length ls0


text:
import tvm
from tvm import te
import numpy as np
from tvm import rpc
from tvm.contrib import util, xcode, coreml_runtime

import pytest
import os

proxy_host = os.environ.get("TVM_IOS_RPC_PROXY_HOST", "localhost")
proxy_port = os.environ.get("TVM_IOS_RPC_PROXY_PORT", 9090)
destination = os.environ.get("TVM_IOS_RPC_DESTINATION", "")
key = "iphone"

@pytest.mark.skip("skip because coremltools is not available in CI")
def test_coreml_runtime():

    import coremltools
    from coremltools.models.neural_network import NeuralNetworkBuilder

    def create_coreml_model():
        shape = (2,)
        alpha = 2

        inputs = [
            ("input0", coremltools.models.datatypes.Array(*shape)),
            ("input1", coremltools.models.datatypes.Array(*shape)),
        ]
        outputs = [
            ("output0", coremltools.models.datatypes.Array(*shape)),
            ("output1", coremltools.models.datatypes.Array(*shape)),
        ]
        builder = NeuralNetworkBuilder(inputs, outputs)
        builder.add_elementwise(
            name="Add", input_names=["input0", "input1"], output_name="output0", mode="ADD"
        )
        builder.add_elementwise(
            name="Mul", alpha=alpha, input_names=["input0"], output_name="output1", mode="MULTIPLY"
        )
        return coremltools.models.MLModel(builder.spec)

    def verify(coreml_model, model_path, ctx):
        coreml_model = create_coreml_model()

        out_spec = coreml_model.output_description._fd_spec
        out_names = [spec.name for spec in out_spec]

        # inference via coremltools
        inputs = {}
        for in_spec in coreml_model.input_description._fd_spec:
            name = in_spec.name
            shape = in_spec.type.multiArrayType.shape
            inputs[name] = np.random.random_sample(shape)

        coreml_outputs = [coreml_model.predict(inputs)[name] for name in out_names]

        # inference via tvm coreml runtime
        runtime = coreml_runtime.create("main", model_path, ctx)
        for name in inputs:
            runtime.set_input(name, tvm.nd.array(inputs[name], ctx))
        runtime.invoke()
        tvm_outputs = [runtime.get_output(i).asnumpy() for i in range(runtime.get_num_outputs())]

        for c_out, t_out in zip(coreml_outputs, tvm_outputs):
            np.testing.assert_almost_equal(c_out, t_out, 3)

    def check_remote(coreml_model):
        temp = util.tempdir()
        compiled_model = xcode.compile_coreml(coreml_model, out_dir=temp.temp_dir)
        xcode.popen_test_rpc(
            proxy_host, proxy_port, key, destination=destination, libs=[compiled_model]
        )
        compiled_model = os.path.basename(compiled_model)
        remote = rpc.connect(proxy_host, proxy_port, key=key)
        ctx = remote.cpu(0)
        verify(coreml_model, compiled_model, ctx)

    def check_local(coreml_model):
        temp = util.tempdir()
        compiled_model = xcode.compile_coreml(coreml_model, out_dir=temp.temp_dir)
        ctx = tvm.cpu(0)
        verify(coreml_model, compiled_model, ctx)

    coreml_model = create_coreml_model()
    check_remote(coreml_model)
    check_local(coreml_model)

if __name__ == "__main__":
    test_coreml_runtime()


text:
<?php declare(strict_types=1);

namespace Smsapi\Tests\Client\Authentication;

use Smsapi\Client\AuthenticationInterface;
use Smsapi\Client\Authentication\BasicAuthentication;
use Smsapi\Tests\Client\AbstractAuthenticationTest;

final class BasicAuthenticationTest extends AbstractAuthenticationTest
{
    /**
     * @return AuthenticationInterface
     */
    public function getAuthentication(): AuthenticationInterface
    {
        return new BasicAuthentication('username', '5f4dcc3b5aa765d61d8327deb882cf99');
    }
}


text:
@interface PodsDummy_CVLogger : NSObject
@end
@implementation PodsDummy_CVLogger
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
   Copyright 2009 TiTA Project, Vienna University of Technology

   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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <parent>
	<groupId>at.ac.tuwien.ifs</groupId>
	<artifactId>tita-parent</artifactId>
	<version>1.0.0-SNAPSHOT</version>
  </parent>

  <artifactId>tita-jasperreports</artifactId>
  <packaging>jar</packaging>
  <name>tita-jasperreports</name>

  <description>
    JasperReports
  </description>

  <dependencies>
    <!-- Springframework dependencies -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
    </dependency>

    <!-- logging support -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
    </dependency>

    <!-- test dependencies -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>

	<!-- Jasper dependencies -->
	<dependency>
		<groupId>jasperreports</groupId>
		<artifactId>jasperreports</artifactId>
	</dependency>
	<dependency>
      <groupId>com.lowagie</groupId>
	  <artifactId>itext</artifactId>
	  <version>${itext.version}</version>
    </dependency>

	<!-- wicket dependencies -->
	<dependency>
		<groupId>org.apache.wicket</groupId>
		<artifactId>wicket</artifactId>
	</dependency>

  </dependencies>

</project>


text:
package com.ftchinese.jobs.common

import java.io.FileInputStream
import java.security.KeyStore

/**
 * Keystore manager
 * Created by wanbo on 16/3/25.
 */
object KeystoreManager extends Logging {

    private val path = "../conf/"

    def loadKeystore(keyName: String): KeyStore ={

        val keyStore = KeyStore.getInstance("PKCS12")

        try {

            var fileName = ""

            keyName match {
                case "pad1" =>
                    fileName = ""
                case "phone2" =>
                    fileName = "mobile.p12"
                case _ =>
                    throw new Exception("Didn't find the keystore type !")
            }

            keyStore.load(new FileInputStream(path + fileName), getKeystorePassword)

        } catch {
            case e: Exception =>
                log.error("Load Keystore error:" + e)
        }

        keyStore
    }

    def getKeystorePassword: Array[Char] ={
        Array[Char]()
    }
}


text:
package co.cask.cdap.hive.datasets;

import co.cask.cdap.api.data.batch.RecordWritable;
import co.cask.tephra.TransactionAware;
import com.google.gson.Gson;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.OutputFormat;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Progressable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * Map reduce output format to write to datasets that implement {@link RecordWritable}.
 */
public class DatasetOutputFormat implements OutputFormat<Void, Text> {
  private static final Logger LOG = LoggerFactory.getLogger(DatasetOutputFormat.class);

  @Override
  public RecordWriter<Void, Text> getRecordWriter(FileSystem ignored, final JobConf jobConf, String name,
                                                  Progressable progress) throws IOException {
    DatasetAccessor datasetAccessor = new DatasetAccessor(jobConf);
    try {
      datasetAccessor.initialize();
    } catch (Exception e) {
      throw new IOException("Could not get dataset.", e);
    }

    return new DatasetRecordWriter(datasetAccessor);
  }

  @Override
  public void checkOutputSpecs(FileSystem ignored, JobConf jobConf) throws IOException {
    // This is called prior to returning a RecordWriter. We make sure here that the
    // dataset we want to write to is RecordWritable.
    DatasetAccessor datasetAccessor = new DatasetAccessor(jobConf);
    try {
      datasetAccessor.initialize();
    } catch (Exception e) {
      throw new IOException("Could not get dataset.", e);
    }
  }

  private class DatasetRecordWriter implements RecordWriter<Void, Text> {
    private final DatasetAccessor datasetAccessor;
    private final RecordWritable recordWritable;
    private final Type recordType;

    public DatasetRecordWriter(DatasetAccessor datasetAccessor) {
      this.datasetAccessor = datasetAccessor;
      this.recordWritable = datasetAccessor.getDataset();
      this.recordType = recordWritable.getRecordType();
    }

    @Override
    public void write(Void key, Text value) throws IOException {
      if (value == null) {
        throw new IOException("Writable value is null.");
      }
      recordWritable.write(new Gson().fromJson(value.toString(), recordType));
    }

    @Override
    public void close(Reporter reporter) throws IOException {
      try {
        if (recordWritable instanceof TransactionAware) {
          try {
            // Commit changes made to the dataset being written
            // NOTE: because the transaction wrapping a Hive query is a long running one,
            // we don't track changes and don't check conflicts - we can just commit the changes.
            ((TransactionAware) recordWritable).commitTx();
          } catch (Exception e) {
            LOG.error("Could not commit changes for table {}", recordWritable);
            throw new IOException(e);
          }
        }
      } finally {
        recordWritable.close();
        datasetAccessor.close();
      }
    }
  }
}


text:
Template.cardStub.onCreated(function() {
  var self =  this;
    if (self.isBeingEdited == undefined) {
      self.isBeingEdited = new ReactiveVar;
      self.isBeingEdited.set( false );
    };
});

Template.cardStub.helpers({
  isBeingEdited: function(){
    return Template.instance().isBeingEdited.get();
  }
});

Template.cardStub.events({
  "click .edit-this-card": function(event, template){
    event.preventDefault();
    if (template.isBeingEdited == undefined) {
        template.isBeingEdited = new ReactiveVar(true);
      }
      if ( template.isBeingEdited.get() == false) {
        template.isBeingEdited.set(true);
      }
  },
  "click .cancel-editing-of-card": function(event, template){
    event.preventDefault();
    if ( template.isBeingEdited.get() == true) {
      template.isBeingEdited.set(false);
    }
  }
});

//Autoform Hooks
var updateCardHooks = {
  after:{
    "method": function(error,result) {
      var self = this;
      if(error){
        toastr.error(error.message,error.reson);
      }
      if(result){
        self.template.get("isBeingEdited").set(false);
        toastr.success(result.toastrMessage, result.toastrTitle);
      }
    },
  }
};

AutoForm.hooks({
  updateCardForm: updateCardHooks,
});


text:
package com.p3.glass.nevermind;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Nevermind extends Activity {
	private TextView mTextView;
	private ProgressBar mProgressBar;
	private TextToSpeech mSpeech;
	private boolean mSpoken = false;

	private long WaitTime = 500;
	private Handler mHandler = new Handler();
	private Runnable mRunnable = new Runnable() {
		@Override
		public void run() {

			if (!mSpoken) {
				// This is to avoid repetition
				mSpeech.speak("Canceling", TextToSpeech.QUEUE_FLUSH, null);
				mSpoken = true;
			}

			mProgressBar.setVisibility(ProgressBar.GONE);

			Runnable runnable = new Runnable() {
				@Override
				public void run() {
					finish();
				}
			};
			Handler handler = new Handler();
			handler.postDelayed(runnable, 1000);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
        mSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                // Do nothing.
            }
        });

		mTextView = (TextView)findViewById(R.id.textView);
		mProgressBar = (ProgressBar)findViewById(R.id.progressBar);
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mProgressBar.setVisibility(ProgressBar.VISIBLE);
		glasscancel();
	}

	@Override
    public void onDestroy() {
		mSpeech.shutdown();
        mSpeech = null;
        super.onDestroy();
	}

	private void glasscancel() {
		mTextView.setText("Returning to OK Glass");
		mHandler.postDelayed(mRunnable, WaitTime);
	}
}


text:
/**
 * Support and FAQ: visit Atmel Support
 */
#ifndef CONF_TWI_H
#define CONF_TWI_H

#include <twi_megarf.h>

 //!< TWI slave bus address
#define SLAVE_BUS_ADDR                                0xA0
//!< TWI slave memeory address length
#define SLAVE_MEM_ADDR_LENGTH         TWI_SLAVE_ONE_BYTE_SIZE
//!< TWI data transfer rate
#define TWI_SPEED_HZ         125000

#endif // CONF_TWI_H


text:
.. DynIP documentation master file, created by
   sphinx-quickstart on Mon Aug 22 22:57:01 2011.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

DynIP documentation
===================

.. include:: ../README.rst

Modules
=======

dynip
-----

.. automodule:: dynip
    :members:
    :show-inheritance:

dynip.server
^^^^^^^^^^^^

.. automodule:: dynip.server
    :members:
    :show-inheritance:

dynip.client
^^^^^^^^^^^^

.. automodule:: dynip.client
    :members:
    :show-inheritance:

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
package models

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"
	"encoding/json"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"
	"github.com/go-openapi/validate"
)

// FpolicyEvent The information that a FPolicy process needs to determine what file access operations to monitor and for which of the monitored events notifications should be sent to the external FPolicy server.
//
// swagger:model fpolicy_event
type FpolicyEvent struct {

	// file operations
	FileOperations *FpolicyEventFileOperations `json:"file_operations,omitempty"`

	// filters
	Filters *FpolicyEventFilters `json:"filters,omitempty"`

	// Specifies the name of the FPolicy event.
	// Example: event_nfs_close
	Name string `json:"name,omitempty"`

	// Protocol for which event is created. If you specify protocol, then you
	// must also specify a valid value for the file operation parameters.
	//   The value of this parameter must be one of the following:
	//     * cifs  - for the CIFS protocol.
	//     * nfsv3 - for the NFSv3 protocol.
	//     * nfsv4 - for the NFSv4 protocol.
	//
	// Enum: [cifs nfsv3 nfsv4]
	Protocol string `json:"protocol,omitempty"`

	// svm
	Svm *FpolicyEventSvm `json:"svm,omitempty"`

	// Specifies whether volume operation monitoring is required.
	VolumeMonitoring *bool `json:"volume_monitoring,omitempty"`
}

// Validate validates this fpolicy event
func (m *FpolicyEvent) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateFileOperations(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateFilters(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateProtocol(formats); err != nil {
		res = append(res, err)
	}

	if err := m.validateSvm(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *FpolicyEvent) validateFileOperations(formats strfmt.Registry) error {
	if swag.IsZero(m.FileOperations) { // not required
		return nil
	}

	if m.FileOperations != nil {
		if err := m.FileOperations.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("file_operations")
			}
			return err
		}
	}

	return nil
}

func (m *FpolicyEvent) validateFilters(formats strfmt.Registry) error {
	if swag.IsZero(m.Filters) { // not required
		return nil
	}

	if m.Filters != nil {
		if err := m.Filters.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("filters")
			}
			return err
		}
	}

	return nil
}

var fpolicyEventTypeProtocolPropEnum []interface{}

func init() {
	var res []string
	if err := json.Unmarshal([]byte(`["cifs","nfsv3","nfsv4"]`), &res); err != nil {
		panic(err)
	}
	for _, v := range res {
		fpolicyEventTypeProtocolPropEnum = append(fpolicyEventTypeProtocolPropEnum, v)
	}
}

const (

	// BEGIN DEBUGGING
	// fpolicy_event
	// FpolicyEvent
	// protocol
	// Protocol
	// cifs
	// END DEBUGGING
	// FpolicyEventProtocolCifs captures enum value "cifs"
	FpolicyEventProtocolCifs string = "cifs"

	// BEGIN DEBUGGING
	// fpolicy_event
	// FpolicyEvent
	// protocol
	// Protocol
	// nfsv3
	// END DEBUGGING
	// FpolicyEventProtocolNfsv3 captures enum value "nfsv3"
	FpolicyEventProtocolNfsv3 string = "nfsv3"

	// BEGIN DEBUGGING
	// fpolicy_event
	// FpolicyEvent
	// protocol
	// Protocol
	// nfsv4
	// END DEBUGGING
	// FpolicyEventProtocolNfsv4 captures enum value "nfsv4"
	FpolicyEventProtocolNfsv4 string = "nfsv4"
)

// prop value enum
func (m *FpolicyEvent) validateProtocolEnum(path, location string, value string) error {
	if err := validate.EnumCase(path, location, value, fpolicyEventTypeProtocolPropEnum, true); err != nil {
		return err
	}
	return nil
}

func (m *FpolicyEvent) validateProtocol(formats strfmt.Registry) error {
	if swag.IsZero(m.Protocol) { // not required
		return nil
	}

	// value enum
	if err := m.validateProtocolEnum("protocol", "body", m.Protocol); err != nil {
		return err
	}

	return nil
}

func (m *FpolicyEvent) validateSvm(formats strfmt.Registry) error {
	if swag.IsZero(m.Svm) { // not required
		return nil
	}

	if m.Svm != nil {
		if err := m.Svm.Validate(formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("svm")
			}
			return err
		}
	}

	return nil
}

// ContextValidate validate this fpolicy event based on the context it is used
func (m *FpolicyEvent) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateFileOperations(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateFilters(ctx, formats); err != nil {
		res = append(res, err)
	}

	if err := m.contextValidateSvm(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *FpolicyEvent) contextValidateFileOperations(ctx context.Context, formats strfmt.Registry) error {

	if m.FileOperations != nil {
		if err := m.FileOperations.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("file_operations")
			}
			return err
		}
	}

	return nil
}

func (m *FpolicyEvent) contextValidateFilters(ctx context.Context, formats strfmt.Registry) error {

	if m.Filters != nil {
		if err := m.Filters.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("filters")
			}
			return err
		}
	}

	return nil
}

func (m *FpolicyEvent) contextValidateSvm(ctx context.Context, formats strfmt.Registry) error {

	if m.Svm != nil {
		if err := m.Svm.ContextValidate(ctx, formats); err != nil {
			if ve, ok := err.(*errors.Validation); ok {
				return ve.ValidateName("svm")
			}
			return err
		}
	}

	return nil
}

// MarshalBinary interface implementation
func (m *FpolicyEvent) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *FpolicyEvent) UnmarshalBinary(b []byte) error {
	var res FpolicyEvent
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// FpolicyEventFileOperations Specifies the file operations for the FPolicy event. You must specify a valid protocol in the protocol parameter.
// The event will check the operations specified from all client requests using the protocol.
//
// swagger:model FpolicyEventFileOperations
type FpolicyEventFileOperations struct {

	// File close operations
	Close bool `json:"close,omitempty"`

	// File create operations
	Create bool `json:"create,omitempty"`

	// Directory create operations
	CreateDir bool `json:"create_dir,omitempty"`

	// File delete operations
	Delete bool `json:"delete,omitempty"`

	// Directory delete operations
	DeleteDir bool `json:"delete_dir,omitempty"`

	// Get attribute operations
	Getattr bool `json:"getattr,omitempty"`

	// Link operations
	Link bool `json:"link,omitempty"`

	// Lookup operations
	Lookup bool `json:"lookup,omitempty"`

	// File open operations
	Open bool `json:"open,omitempty"`

	// File read operations
	Read bool `json:"read,omitempty"`

	// File rename operations
	Rename bool `json:"rename,omitempty"`

	// Directory rename operations
	RenameDir bool `json:"rename_dir,omitempty"`

	// Set attribute operations
	Setattr bool `json:"setattr,omitempty"`

	// Symbolic link operations
	Symlink bool `json:"symlink,omitempty"`

	// File write operations
	Write bool `json:"write,omitempty"`
}

// Validate validates this fpolicy event file operations
func (m *FpolicyEventFileOperations) Validate(formats strfmt.Registry) error {
	return nil
}

// ContextValidate validates this fpolicy event file operations based on context it is used
func (m *FpolicyEventFileOperations) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	return nil
}

// MarshalBinary interface implementation
func (m *FpolicyEventFileOperations) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *FpolicyEventFileOperations) UnmarshalBinary(b []byte) error {
	var res FpolicyEventFileOperations
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// FpolicyEventFilters Specifies the list of filters for a given file operation for the specified protocol.
// When you specify the filters, you must specify the valid protocols and a valid file operations.
//
// swagger:model FpolicyEventFilters
type FpolicyEventFilters struct {

	// Filter the client request for close with modification.
	CloseWithModification bool `json:"close_with_modification,omitempty"`

	// Filter the client request for close with read.
	CloseWithRead bool `json:"close_with_read,omitempty"`

	// Filter the client request for close without modification.
	CloseWithoutModification bool `json:"close_without_modification,omitempty"`

	// Filter the client requests for directory operations. When this filter is specified directory operations are not monitored.
	ExcludeDirectory bool `json:"exclude_directory,omitempty"`

	// Filter the client requests for the first-read.
	FirstRead bool `json:"first_read,omitempty"`

	// Filter the client requests for the first-write.
	FirstWrite bool `json:"first_write,omitempty"`

	// Filter the client request for alternate data stream.
	MonitorAds bool `json:"monitor_ads,omitempty"`

	// Filter the client request for offline bit set. FPolicy server receives notification only when offline files are accessed.
	OfflineBit bool `json:"offline_bit,omitempty"`

	// Filter the client request for open with delete intent.
	OpenWithDeleteIntent bool `json:"open_with_delete_intent,omitempty"`

	// Filter the client request for open with write intent.
	OpenWithWriteIntent bool `json:"open_with_write_intent,omitempty"`

	// Filter the client setattr requests for changing the access time of a file or directory.
	SetattrWithAccessTimeChange bool `json:"setattr_with_access_time_change,omitempty"`

	// Filter the client setattr requests for changing the allocation size of a file.
	SetattrWithAllocationSizeChange bool `json:"setattr_with_allocation_size_change,omitempty"`

	// Filter the client setattr requests for changing the creation time of a file or directory.
	SetattrWithCreationTimeChange bool `json:"setattr_with_creation_time_change,omitempty"`

	// Filter the client setattr requests for changing dacl on a file or directory.
	SetattrWithDaclChange bool `json:"setattr_with_dacl_change,omitempty"`

	// Filter the client setattr requests for changing group of a file or directory.
	SetattrWithGroupChange bool `json:"setattr_with_group_change,omitempty"`

	// Filter the client setattr requests for changing the mode bits on a file or directory.
	SetattrWithModeChange bool `json:"setattr_with_mode_change,omitempty"`

	// Filter the client setattr requests for changing the modification time of a file or directory.
	SetattrWithModifyTimeChange bool `json:"setattr_with_modify_time_change,omitempty"`

	// Filter the client setattr requests for changing owner of a file or directory.
	SetattrWithOwnerChange bool `json:"setattr_with_owner_change,omitempty"`

	// Filter the client setattr requests for changing sacl on a file or directory.
	SetattrWithSaclChange bool `json:"setattr_with_sacl_change,omitempty"`

	// Filter the client setattr requests for changing the size of a file.
	SetattrWithSizeChange bool `json:"setattr_with_size_change,omitempty"`

	// Filter the client request for write with size change.
	WriteWithSizeChange bool `json:"write_with_size_change,omitempty"`
}

// Validate validates this fpolicy event filters
func (m *FpolicyEventFilters) Validate(formats strfmt.Registry) error {
	return nil
}

// ContextValidate validates this fpolicy event filters based on context it is used
func (m *FpolicyEventFilters) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	return nil
}

// MarshalBinary interface implementation
func (m *FpolicyEventFilters) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *FpolicyEventFilters) UnmarshalBinary(b []byte) error {
	var res FpolicyEventFilters
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}

// FpolicyEventSvm fpolicy event svm
//
// swagger:model FpolicyEventSvm
type FpolicyEventSvm struct {

	// SVM UUID
	// Read Only: true
	UUID string `json:"uuid,omitempty"`
}

// Validate validates this fpolicy event svm
func (m *FpolicyEventSvm) Validate(formats strfmt.Registry) error {
	return nil
}

// ContextValidate validate this fpolicy event svm based on the context it is used
func (m *FpolicyEventSvm) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
	var res []error

	if err := m.contextValidateUUID(ctx, formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}

func (m *FpolicyEventSvm) contextValidateUUID(ctx context.Context, formats strfmt.Registry) error {

	if err := validate.ReadOnly(ctx, "svm"+"."+"uuid", "body", string(m.UUID)); err != nil {
		return err
	}

	return nil
}

// MarshalBinary interface implementation
func (m *FpolicyEventSvm) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

// UnmarshalBinary interface implementation
func (m *FpolicyEventSvm) UnmarshalBinary(b []byte) error {
	var res FpolicyEventSvm
	if err := swag.ReadJSON(b, &res); err != nil {
		return err
	}
	*m = res
	return nil
}


text:
require File.dirname(__FILE__) + '/../spec_helper'

[ { :asset_class => Stylesheet,
    :name => 'stylesheet',
    :default_mime_type => 'text/css',
    :default_directory => '/css',
    :inline_element => 'style' },

  { :asset_class => Javascript,
    :name => 'javascript',
    :default_mime_type => 'text/javascript',
    :default_directory => '/js',
    :inline_element => 'script' }

].each do |current_tag|

  describe "<r:#{current_tag[:name]}> tags in a Page context" do
    scenario :pages, :javascripts, :stylesheets

    before :each do
      create_page "text_asset_tags"
      @page = pages(:text_asset_tags)
    end

    it "should render an error if no 'name' attribute is provided" do
      @page.should render(%{<r:#{current_tag[:name]} />}).with_error(
          "`#{current_tag[:name]}' tag must contain a `name' attribute.")
    end

    it "should render an error when the 'name' attribute calls out an invalid filename" do
      @page.should render(%{<r:#{current_tag[:name]} name="bogus asset name" />}).with_error(
          "#{current_tag[:name]} not found")
    end

    it "should render the content of the #{current_tag[:name]} when the 'as' attribute is not provided" do
      @page.should render(%{<r:#{current_tag[:name]} name="main" />}).as(
          "Main #{current_tag[:name]} content")
    end

    it "should render the content of the #{current_tag[:name]} when the 'as' attribute is set to 'content'" do
      @page.should render(%{<r:#{current_tag[:name]} name="main" as="content" />}).as(
          "Main #{current_tag[:name]} content")
    end

    it "should render the url of the #{current_tag[:name]} when the 'as' attribute is set to 'url'" do
      Sns::Config["#{current_tag[:name]}_directory"] = 'foo/bar/baz'
      @page.should render(%{<r:#{current_tag[:name]} name="main" as="url" />}).as(
          "/foo/bar/baz/main")

      Sns::Config.restore_defaults
      @page.should render(%{<r:#{current_tag[:name]} name="main" as="url" />}).as(
          "#{current_tag[:default_directory]}/main")
    end

    describe "when the 'as' attribute is set to 'inline'" do

      it "should render a <#{current_tag[:inline_element]}> element containing the content of the #{current_tag[:name]} with the type attribute matching the #{current_tag[:name]}_mime_type setting" do
        # try with a custom mime_type value
        Sns::Config["#{current_tag[:name]}_mime_type"] = 'bologna'
        @page.should render(%{<r:#{current_tag[:name]} name="main" as="inline" />}).as(
            %{<#{current_tag[:inline_element]} type="bologna">\n} <<
            %{//<![CDATA[\n} <<
            %{Main #{current_tag[:name]} content\n} <<
            %{//]]>\n} <<
            %{</#{current_tag[:inline_element]}>}
        )

        # try with the default mime_type value
        Sns::Config.restore_defaults
        @page.should render(%{<r:#{current_tag[:name]} name="main" as="inline" />}).as(
            %{<#{current_tag[:inline_element]} type="#{current_tag[:default_mime_type]}">\n} <<
            %{//<![CDATA[\n} <<
            %{Main #{current_tag[:name]} content\n} <<
            %{//]]>\n} <<
            %{</#{current_tag[:inline_element]}>}
        )
      end

      it %{if a 'type' element is defined in the <r:#{current_tag[:name]}> tag, this should override the default value as the <#{current_tag[:inline_element]}> element's 'type' attribute} do
        @page.should render(%{<r:#{current_tag[:name]} name="main" as="inline" type="oscar" />}).as(
            %{<#{current_tag[:inline_element]} type="oscar">\n} <<
            %{//<![CDATA[\n} <<
            %{Main #{current_tag[:name]} content\n} <<
            %{//]]>\n} <<
            %{</#{current_tag[:inline_element]}>}
        )
      end

      it %{should pass additional attributes into the <#{current_tag[:inline_element]}> element (and downcase each attribute name)} do
        Sns::Config.restore_defaults
        @page.should render(%{<r:#{current_tag[:name]} name="main" as="inline" another="mayer" ATTRIB="WEINER" />}).as(
            %{<#{current_tag[:inline_element]} type="#{current_tag[:default_mime_type]}" another="mayer" attrib="WEINER">\n} <<
            %{//<![CDATA[\n} <<
            %{Main #{current_tag[:name]} content\n} <<
            %{//]]>\n} <<
            %{</#{current_tag[:inline_element]}>}
        )
      end

    end

    describe "when the 'as' attribute is set to 'link'" do

      it "should render a <#{current_tag[:inline_element]}> element with a 'src' attribute referencing the #{current_tag[:name]} and with the type attribute matching the #{current_tag[:name]}_mime_type setting" do
        # try with a custom mime_type value
        Sns::Config["#{current_tag[:name]}_mime_type"] = 'bologna'
        Sns::Config["#{current_tag[:name]}_directory"] = 'foo/bar/baz'
        if current_tag[:name] == 'stylesheet'
          @page.should render(%{<r:stylesheet name="main" as="link" />}).as(
              %{<link rel="stylesheet" href="/foo/bar/baz/main" type="bologna" />}
          )
        elsif current_tag[:name] == 'javascript'
           @page.should render(%{<r:javascript name="main" as="link" />}).as(
              %{<script src="/foo/bar/baz/main" type="bologna"></script>}
          )
        end

        # try with the default mime_type and directory values
        Sns::Config.restore_defaults
        if current_tag[:name] == 'stylesheet'
          @page.should render(%{<r:stylesheet name="main" as="link" />}).as(
              %{<link rel="stylesheet" href="#{current_tag[:default_directory]}/main" type="#{current_tag[:default_mime_type]}" />}
          )
        elsif current_tag[:name] == 'javascript'
           @page.should render(%{<r:javascript name="main" as="link" />}).as(
              %{<script src="#{current_tag[:default_directory]}/main" type="#{current_tag[:default_mime_type]}"></script>}
          )
        end
      end

      it %{if a 'type' element is defined in the <r:#{current_tag[:name]}> tag, this should override the default value as the <#{current_tag[:inline_element]}> element's 'type' attribute} do
        if current_tag[:name] == 'stylesheet'
          @page.should render(%{<r:stylesheet name="main" as="link" type="oscar" />}).as(
              %{<link rel="stylesheet" href="#{current_tag[:default_directory]}/main" type="oscar" />}
          )
        elsif current_tag[:name] == 'javascript'
           @page.should render(%{<r:javascript name="main" as="link" type="oscar" />}).as(
              %{<script src="#{current_tag[:default_directory]}/main" type="oscar"></script>}
          )
        end
      end

      it %{should pass additional attributes into the <#{current_tag[:inline_element]}> element (and downcase each attribute name)} do
        Sns::Config.restore_defaults
        if current_tag[:name] == 'stylesheet'
          @page.should render(%{<r:stylesheet name="main" as="link" another="mayer" ATTRIB="WEINER" />}).as(
              %{<link rel="stylesheet" href="#{current_tag[:default_directory]}/main" type="#{current_tag[:default_mime_type]}" another="mayer" attrib="WEINER" />}
          )
        elsif current_tag[:name] == 'javascript'
           @page.should render(%{<r:javascript name="main" as="link" another="mayer" ATTRIB="WEINER" />}).as(
              %{<script src="#{current_tag[:default_directory]}/main" type="#{current_tag[:default_mime_type]}" another="mayer" attrib="WEINER"></script>}
          )
        end
      end

    end

  end

  describe "<r:#{current_tag[:name]}> tags in a #{current_tag[:asset_class].to_s} context" do
    scenario :pages, :javascripts, :stylesheets

    before :each do
      @text_asset = current_tag[:asset_class].new
    end

    it "should render an error if no 'name' attribute is provided" do
      @text_asset.content = %{<r:#{current_tag[:name]} />}
      lambda{@text_asset.render}.should raise_error(
          current_tag[:asset_class]::TagError,
          "`#{current_tag[:name]}' tag must contain a `name' attribute."
      )
    end

    it "should render an error when the 'name' attribute calls out an invalid filename" do
      @text_asset.content = %{<r:#{current_tag[:name]} name="bogus asset name" />}
      lambda{@text_asset.render}.should raise_error(
          current_tag[:asset_class]::TagError,
          "#{current_tag[:name]} not found"
      )
    end

    it "should render the referenced file's content for each tag with a valid 'name' attribute" do
      send("create_#{current_tag[:name]}", "another_file")

      @text_asset.content = %{<r:#{current_tag[:name]} name="main" />}
      @text_asset.content << %{<r:#{current_tag[:name]} name="another_file" />}
      @text_asset.content << %{<r:#{current_tag[:name]} name="main" />}
      @text_asset.render.should == "Main #{current_tag[:name]} content" <<
                                   "#{current_tag[:name]} content for another_file" <<
                                   "Main #{current_tag[:name]} content"
    end

  end

  alternate_tag = case current_tag[:name]
    when "stylesheet"
      "javascript"
    when "javascript"
      "stylesheet"
  end

  describe "<r:#{alternate_tag}> tags in a #{current_tag[:asset_class].to_s} context" do
    it "should not be available (should throw a tag-not-found error)" do
      @text_asset = current_tag[:asset_class].new(:content => "<r:#{alternate_tag} />")
      lambda{@text_asset.render}.should raise_error(
          StandardTags::TagError,
          "undefined tag `#{alternate_tag}'"
      )
    end
  end

end


text:
using Rawr.Base.Algorithms;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;

namespace Rawr.UnitTests
{
    ///
    ///This is a test class for MarkovProcessTest and is intended
    ///to contain all MarkovProcessTest Unit Tests
    ///
    [TestClass()]
    public class MarkovProcessTest
    {
        private TestContext testContextInstance;
        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext {
            get { return testContextInstance; }
            set { testContextInstance = value; }
        }

        #region Additional test attributes
        //
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion

        // tests from http://elitistjerks.com/f75/t40398-mathematics_dynamic_cycles/

        public class Ability
        {
            public double Damage { get; set; }
            public double Duration { get; set; }
        }

        public class AbilitySequence : Ability
        {
            public AbilitySequence(params Ability[] abilities)
            {
                foreach (Ability ability in abilities)
                {
                    Damage += ability.Damage;
                    Duration += ability.Duration;
                }
            }
        }

        [TestMethod]
        public void MarkovProcessTest1()
        {
            //S0:
            //A => S0 0.5
            //  => S1 0.5
            //S1:
            //B => S0 1

            Ability A = new Ability() { Damage = 100, Duration = 2 };
            Ability B = new Ability() { Damage = 200, Duration = 1 };

            State<Ability> S0 = new State<Ability>() { Name = "S0" };
            State<Ability> S1 = new State<Ability>() { Name = "S1" };

            S0.Transitions = new List<StateTransition<Ability>>()
            {
                new StateTransition<Ability>() { Ability = A, TargetState = S0, TransitionDuration = A.Duration, TransitionProbability = 0.5 },
                new StateTransition<Ability>() { Ability = A, TargetState = S1, TransitionDuration = A.Duration, TransitionProbability = 0.5 },
            };
            S1.Transitions = new List<StateTransition<Ability>>()
            {
                new StateTransition<Ability>() { Ability = B, TargetState = S0, TransitionDuration = B.Duration, TransitionProbability = 1.0 },
            };
            List<State<Ability>> stateSpace = new List<State<Ability>>() { S0, S1 };

            MarkovProcess<Ability> mp = new MarkovProcess<Ability>(stateSpace);

            Assert.AreEqual(mp.StateWeight[0], 2.0 / 3.0, 0.000000000001, "S0");
            Assert.AreEqual(mp.StateWeight[1], 1.0 / 3.0, 0.000000000001, "S1");
            Assert.AreEqual(mp.AverageTransitionDuration, 5.0 / 3.0, 0.000000000001, "time");

            double averageDamage = 0.0;
            foreach (KeyValuePair<Ability, double> kvp in mp.AbilityWeight)
            {
                averageDamage += kvp.Key.Damage * kvp.Value;
            }
            Assert.AreEqual(averageDamage, 100.0 * 4.0 / 3.0, 0.000000000001, "damage");

            Assert.AreEqual(averageDamage / mp.AverageTransitionDuration, 80.0, 0.000000000001, "dps");
        }

        [TestMethod]
        public void MarkovProcessTest2()
        {
            //S0:
            //A  => S0 0.5
            //AB  => S0 0.5

            Ability A = new Ability() { Damage = 100, Duration = 2 };
            Ability B = new Ability() { Damage = 200, Duration = 1 };
            Ability AB = new AbilitySequence(A, B);

            State<Ability> S0 = new State<Ability>() { Name = "S0" };

            S0.Transitions = new List<StateTransition<Ability>>()
            {
                new StateTransition<Ability>() { Ability = A, TargetState = S0, TransitionDuration = A.Duration, TransitionProbability = 0.5 },
                new StateTransition<Ability>() { Ability = AB, TargetState = S0, TransitionDuration = AB.Duration, TransitionProbability = 0.5 },
            };
            List<State<Ability>> stateSpace = new List<State<Ability>>() { S0 };

            MarkovProcess<Ability> mp = new MarkovProcess<Ability>(stateSpace);

            Assert.AreEqual(mp.StateWeight[0], 1.0, 0.000000000001, "S0");
            Assert.AreEqual(mp.AverageTransitionDuration, 2.5, 0.000000000001, "time");

            double averageDamage = 0.0;
            foreach (KeyValuePair<Ability, double> kvp in mp.AbilityWeight)
            {
                averageDamage += kvp.Key.Damage * kvp.Value;
            }
            Assert.AreEqual(averageDamage, 200.0, "damage");

            Assert.AreEqual(averageDamage / mp.AverageTransitionDuration, 80.0, 0.000000000001, "dps");
        }

        [TestMethod]
        public void MarkovProcessTest3()
        {
            //S0:
            //AB-ABar1 => S0 0.8 * 0.8
            //         => S1 1 - 0.8 * 0.8
            //S1:
            //MBAM-ABar => S0 0.8
            //          => S1 0.2

            Ability AB = new Ability();
            Ability ABar1 = new Ability();
            Ability MBAM = new Ability();
            Ability ABar = new Ability();

            Ability ABABar1 = new AbilitySequence(AB, ABar1);
            Ability MBAMABar = new AbilitySequence(MBAM, ABar);

            State<Ability> S0 = new State<Ability>() { Name = "S0" };
            State<Ability> S1 = new State<Ability>() { Name = "S1" };

            S0.Transitions = new List<StateTransition<Ability>>()
            {
                new StateTransition<Ability>() { Ability = ABABar1, TargetState = S0, TransitionDuration = ABABar1.Duration, TransitionProbability = 0.8 * 0.8 },
                new StateTransition<Ability>() { Ability = ABABar1, TargetState = S1, TransitionDuration = ABABar1.Duration, TransitionProbability = 1.0 - 0.8 * 0.8 },
            };
            S1.Transitions = new List<StateTransition<Ability>>()
            {
                new StateTransition<Ability>() { Ability = MBAMABar, TargetState = S0, TransitionDuration = MBAMABar.Duration, TransitionProbability = 0.8 },
                new StateTransition<Ability>() { Ability = MBAMABar, TargetState = S1, TransitionDuration = MBAMABar.Duration, TransitionProbability = 0.2 },
            };
            List<State<Ability>> stateSpace = new List<State<Ability>>() { S0, S1 };

            MarkovProcess<Ability> mp = new MarkovProcess<Ability>(stateSpace);

            Assert.AreEqual(mp.StateWeight[0], 0.69, 0.01, "S0");
            Assert.AreEqual(mp.StateWeight[1], 0.31, 0.01, "S1");
        }
    }
}


text:
using namespace v8;

NAN_METHOD(Delay) {
  Nan::Maybe<int> maybeDelay = Nan::To<int>(info[0]);
  Nan::MaybeLocal<Function> maybeCallback = Nan::To<Function>(info[1]);

  if(maybeDelay.IsNothing() == true) {
    Nan::ThrowError("Error converting first argument to integer");
  }

  int delay = maybeDelay.FromJust();

  Nan::Local<Function> callback;

  if(maybeCallback.ToLocal(&callback) == false) {
    Nan::ThrowError("Error converting second argument to function");
  }

  printf("FAUX %d\n", delay);
  fflush(stdout);

  #ifdef _WIN32
   Sleep(delay);
  #else
   usleep(delay * 1000);
  #endif

  Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, 0, NULL);
}

NAN_MODULE_INIT(Init) {
  Nan::Set(target, Nan::New("delay").ToLocalChecked(),
      Nan::GetFunction(Nan::New<FunctionTemplate>(Delay)).ToLocalChecked());
}

NODE_MODULE(myaddon, Init)


text:
ifndef CHPL_MAKE_HOME
export CHPL_MAKE_HOME=$(shell pwd)/../..
endif

CHPL_MAKE_HOST_TARGET = --target
include $(CHPL_MAKE_HOME)/make/Makefile.base

#
# set up the directories
#
GMP_ABS_DIR = $(shell pwd)
GMP_INSTALL_DIR = $(GMP_ABS_DIR)/$(GMP_INSTALL_SUBDIR)
GMP_BUILD_DIR = $(GMP_ABS_DIR)/$(GMP_BUILD_SUBDIR)
GMP_DIR = $(GMP_ABS_DIR)
GMP_UNPACKED_DIR = gmp-$(GMP_VERSION)
GMP_TARBALL = $(GMP_UNPACKED_DIR)a.tar.bz2

ifeq ($(CHPL_MAKE_TARGET_ARCH),knc)
CHPL_GMP_CFG_OPTIONS=--host=x86_64 --disable-assembly
ifeq ($(CHPL_MAKE_TARGET_COMPILER),intel)
CHPL_GMP_CFLAGS=-mmic
CHPL_GMP_CXXFLAGS=-mmic
endif
endif

default: all

all: gmp

clean: FORCE
	rm -rf $(GMP_BUILD_SUBDIR)

cleanall: FORCE
	rm -rf build

clobber: FORCE
	rm -rf build install $(GMP_SUBDIR)

$(GMP_UNPACKED_DIR):
	cd $(GMP_DIR) && tar --bzip2 -xf $(GMP_TARBALL)

gmp-config: $(GMP_UNPACKED_DIR) FORCE
	mkdir -p $(GMP_BUILD_DIR)
	cd $(GMP_BUILD_DIR) && $(GMP_SUBDIR)/configure CC='$(CC)' CFLAGS='$(CFLAGS) $(CHPL_GMP_CFLAGS)' CXX='$(CXX)' CXXFLAGS='$(CXXFLAGS) $(CHPL_GMP_CXXFLAGS)' --prefix=$(GMP_INSTALL_DIR) $(CHPL_GMP_CFG_OPTIONS)

# Determine the number of available cpus on the system. Used as the -j argument
# when calling make below. This can be overridden at the command line with
# NPROCS=<int>.
NPROCS := $(shell python -c 'import multiprocessing ; print multiprocessing.cpu_count()')

gmp-build: FORCE
	cd $(GMP_BUILD_DIR) && $(MAKE) -j$(NPROCS)
ifneq ($(CHPL_MAKE_TARGET_ARCH),knc)
	cd $(GMP_BUILD_DIR) && $(MAKE) -j$(NPROCS) check
endif
	cd $(GMP_BUILD_DIR) && $(MAKE) install

gmp: gmp-config gmp-build

FORCE:


text:
package com.datamountaineer.streamreactor.connect.converters.source

import com.datamountaineer.streamreactor.common.converters.MsgKey

import java.util.Collections
import org.apache.kafka.connect.data.Schema
import org.apache.kafka.connect.source.SourceRecord

class BytesConverter extends Converter {
  override def convert(kafkaTopic: String,
                       sourceTopic: String,
                       messageId: String,
                       bytes: Array[Byte],
                       keys: Seq[String] = Seq.empty,
                       keyDelimiter: String = ".",
                       properties: Map[String, String] = Map.empty): SourceRecord = {
    new SourceRecord(Collections.singletonMap(Converter.TopicKey, sourceTopic),
      null,
      kafkaTopic,
      MsgKey.schema,
      MsgKey.getStruct(sourceTopic, messageId),
      Schema.BYTES_SCHEMA,
      bytes)
  }
}


text:
var Flashy = Flashy || {};

Flashy.message = function(type, message) {
  var container = $('#flash');

  container.append($("<div/>").
    addClass("alert").
    addClass("alert-" + type).
    append($("<button/>").
      attr('type', 'button').
      addClass('close').
      attr('data-dismiss', 'alert').
      html('×')).
    append(message));
};


text:
<?php

namespace Symfony\Component\Uid\Tests\Fixtures;

use Symfony\Component\Uid\Ulid;

final class CustomUlid extends Ulid
{
}


text:
#import <WebCore/DOMTestInterface.h>

namespace WebCore {
class TestInterface;
}

WEBCORE_EXPORT WebCore::TestInterface* core(DOMTestInterface *);
WEBCORE_EXPORT DOMTestInterface *kit(WebCore::TestInterface*);


text:
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          Toggle navigation

          </button>
          Start Bootstrap

              About

              Services

              Portfolio

              Contact