text:
package nu.validator.messages;

import nu.validator.json.JsonHandler;

import org.xml.sax.SAXException;

public class JsonMessageTextHandler implements MessageTextHandler {

    private static final char[] LEFT = {'\u201C'};

    private static final char[] RIGHT = {'\u201D'};

    private final JsonHandler handler;

    /**
     * @param handler
     */
    public JsonMessageTextHandler(final JsonHandler handler) {
        this.handler = handler;
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        handler.characters(ch, start, length);
    }

    @Override
    public void endCode() throws SAXException {
        handler.characters(RIGHT, 0, 1);
    }

    @Override
    public void endLink() throws SAXException {
    }

    @Override
    public void startCode() throws SAXException {
        handler.characters(LEFT, 0, 1);
    }

    @Override
    public void startLink(String href, String title) throws SAXException {
    }

}

redpajama_set_name: RedPajamaGithub


text:
package de.slackspace.openkeepass.crypto;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Sha256 {

    private Sha256() {
    }

    public static byte[] hash(String text) {
        if (text == null) {
            throw new IllegalArgumentException("Text must not be null");
        }

        try {
            return hash(text.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException("The encoding 'UTF-8' is not supported", e);
        }
    }

    public static byte[] hash(byte[] bytes) {
        if (bytes == null) {
            throw new IllegalArgumentException("Bytes must not be null");
        }

        return hash(bytes, 0, bytes.length);
    }

    public static byte[] hash(byte[] bytes, int offset, int length) {
        if (bytes == null) {
            throw new IllegalArgumentException("Bytes must not be null");
        }

        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(bytes, offset, length);
            return md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new UnsupportedOperationException("The algorithm 'SHA-256' is not supported", e);
        }
    }
}


text:
<?php

namespace yii\base;

/**
 * ViewEvent represents events triggered by the [[View]] component.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class ViewEvent extends Event
{
    /**
     * @var string the view file being rendered.
     */
    public $viewFile;
    /**
     * @var array the parameter array passed to the [[View::render()]] method.
     */
    public $params;
    /**
     * @var string the rendering result of [[View::renderFile()]].
     * Event handlers may modify this property and the modified output will be
     * returned by [[View::renderFile()]]. This property is only used
     * by [[View::EVENT_AFTER_RENDER]] event.
     */
    public $output;
    /**
     * @var bool whether to continue rendering the view file. Event handlers of
     * [[View::EVENT_BEFORE_RENDER]] may set this property to decide whether
     * to continue rendering the current view file.
     */
    public $isValid = true;
}


text:
"""Long tests for Multinomial."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import test_util
from tensorflow.python.ops import random_ops
from tensorflow.python.platform import test

class MultinomialTest(test.TestCase):
  # check that events with tiny probabilities are not over-sampled

  def testLargeDynamicRange(self):
    random_seed.set_random_seed(10)
    counts_by_indices = {}
    with self.test_session():
      samples = random_ops.multinomial(
          constant_op.constant([[-30, 0]], dtype=dtypes.float32),
          num_samples=1000000,
          seed=15)
      for _ in range(100):
        x = self.evaluate(samples)
        indices, counts = np.unique(x, return_counts=True)
        for index, count in zip(indices, counts):
          if index in counts_by_indices.keys():
            counts_by_indices[index] += count
          else:
            counts_by_indices[index] = count
    self.assertEqual(counts_by_indices[1], 100000000)

  def testLargeDynamicRange2(self):
    random_seed.set_random_seed(10)
    counts_by_indices = {}
    with self.test_session():
      samples = random_ops.multinomial(
          constant_op.constant([[0, -30]], dtype=dtypes.float32),
          num_samples=1000000,
          seed=15)
      for _ in range(100):
        x = self.evaluate(samples)
        indices, counts = np.unique(x, return_counts=True)
        for index, count in zip(indices, counts):
          if index in counts_by_indices.keys():
            counts_by_indices[index] += count
          else:
            counts_by_indices[index] = count
    self.assertEqual(counts_by_indices[0], 100000000)

  @test_util.run_deprecated_v1
  def testLargeDynamicRange3(self):
    random_seed.set_random_seed(10)
    counts_by_indices = {}
    # here the cpu undersamples and won't pass this test either
    with self.test_session():
      samples = random_ops.multinomial(
          constant_op.constant([[0, -17]], dtype=dtypes.float32),
          num_samples=1000000,
          seed=22)

      # we'll run out of memory if we try to draw 1e9 samples directly
      # really should fit in 12GB of memory...
      for _ in range(100):
        x = self.evaluate(samples)
        indices, counts = np.unique(x, return_counts=True)
        for index, count in zip(indices, counts):
          if index in counts_by_indices.keys():
            counts_by_indices[index] += count
          else:
            counts_by_indices[index] = count
    self.assertGreater(counts_by_indices[1], 0)

if __name__ == "__main__":
  test.main()


text:
BSLS_IDENT("$: $")

//@PURPOSE: Provide a spin lock.
//
//@CLASSES:
//  bsls::SpinLock: A mutex using "busy waiting" atomic operations
//  bsls::SpinLockGuard: Automatic locking-unlocking of SpinLock
//
//@DESCRIPTION: This component provides a "busy wait" mutual exclusion lock
// primitive ("mutex").  A 'SpinLock' is small and statically-initializable,
// but because it "spins" in a tight loop rather than using system operations
// to block the thread of execution, it is unsuited for use cases involving
// high contention or long critical regions.  Additionally, this component does
// not provide any guarantee of fairness when multiple threads are contending
// for the same lock.  Use 'SpinLockGuard' for automatic locking-unlocking in a
// scope.
//
// *WARNING*: A 'bsls::SpinLock' *must* be aggregate initialized to
// 'BSLS_SPINLOCK_UNLOCKED'.  For example:
//..
//  bsls::SpinLock lock = BSLS_SPINLOCK_UNLOCKED;
//..
// Note that 'SpinLock' is a struct requiring aggregate initialization to allow
// lock variables to be statically initialized when using a C++03 compiler
// (i.e., without using 'constexpr').
//
///Usage
///-----
// In this section we show intended use of this component.
//
///Example 1: Maintaining Static Count/Max Values
/// - - - - - - - - - - - - - - - - - - - - - - -
// Suppose that we want to determine the maximum number of threads executing a
// block of code concurrently.  Note that such a use case naturally calls for a
// statically initialized lock and the critical region involves a few integer
// operations; SpinLock may be suitable.
//
// First, we define a type to manage the count within a scope:
//..
// class MaxConcurrencyCounter {
//     // This type manages a count and high-water-mark within a scope.
//     // It decrements the count in its destructor upon leaving the scope.
//
//     // DATA
//     int            *d_count_p;
//     bsls::SpinLock *d_lock_p;
//
//   public:
//     // CREATORS
//     MaxConcurrencyCounter(int *count, int *max, bsls::SpinLock *lock);
//         // Acquire the specified 'lock' and increment the specified 'count'.
//         // If the resulting value is larger than the specified 'max',
//         // load it into 'max'. Release 'lock' and create a scoped guard to
//         // decrement 'count' on destruction.
//
//     ~MaxConcurrencyCounter();
//         // Acquire the lock specified at construction, decrement the count
//         // variable, and release the lock.
//   };
//
//   MaxConcurrencyCounter::MaxConcurrencyCounter(int            *count,
//                                                int            *max,
//                                                bsls::SpinLock *lock)
//   : d_count_p(count)
//   , d_lock_p(lock) {
//      bsls::SpinLockGuard guard(lock);
//      int result = ++(*count);
//      if (result > *max) {
//         *max = result;
//      }
//   }
//
//   MaxConcurrencyCounter::~MaxConcurrencyCounter() {
//      bsls::SpinLockGuard guard(d_lock_p);
//      --(*d_count_p);
//   }
//..
// Next, we declare static variables to track the call count and a SpinLock to
// guard them.  'SpinLock' may be statically initialized using the
// 'BSLS_SPINLOCK_UNLOCKED' constant:
//..
//   {
//      static int            threadCount = 0;
//      static int            maxThreads = 0;
//      static bsls::SpinLock threadLock = BSLS_SPINLOCK_UNLOCKED;
//..
// Next, by creating a 'MaxConcurrencyCounter' object, each thread entering the
// block of code uses the 'SpinLock' to synchronize manipulation of the static
// count variables:
//..
//      MaxConcurrencyCounter counter(&threadCount, &maxThreads, &threadLock);
//..
// Finally, closing the block synchronizes on the 'SpinLock' again to decrement
// the thread count.  Any intervening code can run in parallel.
//..
//   }
//..
//
///Example 2: Fine-Grained Locking
///- - - - - - - - - - - - - - - -
// Suppose that we have a large array of objects to be manipulated concurrently
// by multiple threads, but the size of the array itself does not change.
// (This might be because it represents an inherently fixed number of objects
// or because changes to the array size are infrequent and controlled by some
// other synchronization mechanism like a "reader-writer" lock).  Thus one
// thread can manipulate a particular object in the array concurrently with a
// different thread manipulating another.  If the manipulations are short and
// contention is likely to be low, SpinLock might be suitable due to its small
// size.
//
// In particular, imagine we want a threadsafe "multi-queue".  In this case, we
// would have an array of queues, each with a SpinLock member for fine-grained
// locking.  First, we define the type to be held in the array.
//..
//  template<typename TYPE>
//  class LightweightThreadsafeQueue {
//     // This type implements a threadsafe queue with a small memory
//     // footprint and low initialization costs. It is designed for
//     // low-contention use only.
//
//     // TYPES
//     struct Node {
//          TYPE  d_item;
//          Node *d_next_p;
//
//          Node(const TYPE& item) : d_item(item), d_next_p(0) {}
//      };
//
//     // DATA
//     Node           *d_front_p; // Front of queue, or 0 if empty
//     Node           *d_back_p; // Back of queue, or 0 if empty
//     bsls::SpinLock  d_lock;
//
//   public:
//     // CREATORS
//     LightweightThreadsafeQueue();
//       // Create an empty queue.
//
//     ~LightweightThreadsafeQueue();
//       // Destroy this object.
//
//     // MANIPULATORS
//     int dequeue(TYPE* value);
//        // Remove the element at the front of the queue and load it into the
//        // specified 'value'. Return '0' on success, or a nonzero value if
//        // the queue is empty.
//
//     void enqueue(const TYPE& value);
//        // Add the specified 'value' to the back of the queue.
//   };
//..
// Next, we implement the creators.  Note that a different idiom is used to
// initialize member variables of 'SpinLock' type than is used for static
// variables:
//..
//  template<typename TYPE>
//  LightweightThreadsafeQueue<TYPE>::LightweightThreadsafeQueue()
//  : d_front_p(0)
//  , d_back_p(0)
//  , d_lock(bsls::SpinLock::s_unlocked)
//  {}
//
//  template<typename TYPE>
//  LightweightThreadsafeQueue<TYPE>::~LightweightThreadsafeQueue() {
//     for (Node *node = d_front_p; 0 != node; ) {
//         Node *next = node->d_next_p;
//         delete node;
//         node = next;
//     }
//  }
//..
// Then we implement the manipulator functions using 'SpinLockGuard' to ensure
// thread safety.  Note that we do memory allocation and deallocation outside
// the scope of the lock, as these may involve system calls that should be
// avoided in the scope of a SpinLock.
//..
//  template<typename TYPE>
//  int LightweightThreadsafeQueue<TYPE>::dequeue(TYPE* value) {
//     Node *front;
//     {
//        bsls::SpinLockGuard guard(&d_lock);
//        front = d_front_p;
//        if (0 == front) {
//          return 1;
//        }
//
//        *value = front->d_item;
//
//        if (d_back_p == front) {
//           d_front_p = d_back_p = 0;
//        } else {
//           d_front_p = front->d_next_p;
//        }
//     }
//     delete front;
//     return 0;
//  }
//
//  template<typename TYPE>
//  void LightweightThreadsafeQueue<TYPE>::enqueue(const TYPE& value) {
//     Node *node = new Node(value);
//     bsls::SpinLockGuard guard(&d_lock);
//     if (0 == d_front_p && 0 == d_back_p) {
//        d_front_p = d_back_p = node;
//     } else {
//        d_back_p->d_next_p = node;
//        d_back_p = node;
//     }
//  }
//..
//  To illustrate fine-grained locking with this queue, we create a thread
//  function that will manipulate queues out of a large array at random.
//  Since each element in the array is locked independently, these threads
//  will rarely contend for the same queue and can run largely in parallel.
//..
// const int NUM_QUEUES = 10000;
// const int NUM_ITERATIONS = 20000;
//
// struct QueueElement {
//    int d_threadId;
//    int d_value;
// };
//
// struct ThreadParam {
//    LightweightThreadsafeQueue<QueueElement> *d_queues_p;
//    int                                       d_threadId;
// };
//
// void *addToRandomQueues(void *paramAddr) {
//    ThreadParam *param = (ThreadParam*)paramAddr;
//    LightweightThreadsafeQueue<QueueElement> *queues = param->d_queues_p;
//    int threadId = param->d_threadId;
//    unsigned seed = threadId;
//    for (int i = 0; i < NUM_ITERATIONS; ++i) {
//       int queueIndex = rand_r(&seed) % NUM_QUEUES;
//       LightweightThreadsafeQueue<QueueElement> *queue = queues + queueIndex;
//       QueueElement value = { threadId, i };
//       queue->enqueue(value);
//    }
//    return 0;
// }
//..
// Finally, we create the "multi-queue" and several of these threads to
// manipulate it.  We assume the existence of a createThread() function that
// starts a new thread of execution with a parameter, and we omit details of
// "joining" these threads.
//..
// enum { NUM_THREADS = 3};
// LightweightThreadsafeQueue<QueueElement> multiQueue[NUM_QUEUES];
// ThreadParam threadParams[NUM_THREADS];
// for (int i = 0; i < NUM_THREADS; ++i) {
//   threadParams[i].d_queues_p = multiQueue;
//   threadParams[i].d_threadId = i + 1;
//   createThread(addToRandomQueues, threadParams + i);
// }
//..
//

#include <bsls_assert.h>
#include <bsls_atomicoperations.h>
#include <bsls_keyword.h>
#include <bsls_platform.h>
#include <bsls_performancehint.h>

#define BSLS_SPINLOCK_UNLOCKED  { {0} }
    // Use this macro as the value for initializing an object of type
    // 'SpinLock'.  For example:
    //..
    //  SpinLock lock = BSLS_SPINLOCK_UNLOCKED;
    //..

#ifdef BSLS_PLATFORM_OS_WINDOWS
typedef unsigned long DWORD;
typedef int BOOL;

extern "C" {
    __declspec(dllimport) void __stdcall Sleep(
            DWORD dwMilliseconds);

    __declspec(dllimport) DWORD __stdcall SleepEx(
            DWORD dwMilliseconds,
            BOOL  bAlertable);
};
#else
#include <pthread.h>
#include <sched.h>
#include <time.h>
#endif

#if defined(BSLS_PLATFORM_CPU_X86) || defined(BSLS_PLATFORM_CPU_X86_64)
#include <immintrin.h>
#include <emmintrin.h>
#endif

namespace BloombergLP {
namespace bsls {

                             // ==============
                             // class SpinLock
                             // ==============
struct SpinLock {
    // A statically-initializable synchronization primitive that "spins" (i.e.,
    // executes user instructions in a tight loop) rather than blocking waiting
    // threads using system calls.  The following idiom is used to initialize
    // 'SpinLock' variables:
    //..
    //  SpinLock lock = BSLS_SPINLOCK_UNLOCKED;
    //..
    // A class member 'd_lock' of type 'SpinLock' may be initialized using the
    // following idiom:
    //..
    //  , d_lock(SpinLock::s_unlocked)
    //..

  private:
    // NOT IMPLEMENTED
    SpinLock& operator=(const SpinLock&) BSLS_KEYWORD_DELETED;

    // We would like to prohibit copy construction, but then this class would
    // not be a POD and could not be initialized statically:
    //
    // SpinLock(const SpinLock&);

    // PRIVATE TYPES
    enum {
        e_UNLOCKED = 0, // unlocked state value
        e_LOCKED = 1    // locked state value
    };

    // PRIVATE CLASS METHODS
    static void doBackoff(int *count);
        // This function provides a backoff mechanism for 'lock' and 'tryLock',
        // using the specified 'count' as the backoff counter.  'count' is
        // incremented within this method.

    static void pause();
        // If available, invoke a pause operation (e.g., Intel's 'pause'
        // instruction); otherwise do nothing.  (i.e., this method is a no-op).

    static void sleepMillis(int milliseconds);
        // Sleep the specified 'milliseconds'.  Note that this partially
        // reimplements 'bslmt::ThreadUtil::microSleep' locally, as 'bslmt' is
        // above 'bsls'.

    static void yield();
        // Move the current thread to the end of the scheduler's queue and
        // schedule another thread to run.  Note that this allows cooperating
        // threads of the same priority to share CPU resources equally.  Also
        // note that this reimplements 'bslmt::ThreadUtil::yield()' locally, as
        // 'bslmt' is above 'bsls'.

  public:
    // PUBLIC CLASS DATA
    static const SpinLock s_unlocked;
        // This constant SpinLock is always unlocked.  It is suitable for use
        // initializing class members of SpinLock type.

    // PUBLIC DATA
    AtomicOperations::AtomicTypes::Int d_state;
        // Public to allow this type to be a statically-initializable POD.  Do
        // not use directly.

    // MANIPULATORS
    void lock();
        // Spin (repeat a loop continuously without using the system to pause
        // or reschedule the thread) until this object is unlocked, then
        // atomically acquire the lock.

    void lockWithBackoff();
        // Repeat a loop continuously, potentially using the system to pause or
        // reschedule the thread, until this object is unlocked, then
        // atomically acquire the lock.  The spinning has backoff logic.  Note
        // that this method is recommended when system calls are permissible,
        // significant contention is expected, and no better mutual exclusion
        // primitive is available.

    void lockWithoutBackoff();
        // Spin (repeat a loop continuously without using the system to pause
        // or reschedule the thread) until this object is unlocked, then
        // atomically acquire the lock.  The spinning does not perform a
        // backoff.

    int tryLock(int numRetries = 0);
        // Attempt to acquire the lock; optionally specify the 'numRetries'
        // times to attempt again if this object is already locked.  Return 0
        // on success, and a non-zero value if the lock was not successfully
        // acquired.  The behavior is undefined unless '0 <= numRetries'.

    void unlock();
        // Release the lock.  The behavior is undefined unless the current
        // thread holds the lock.
};

                         // ===================
                         // class SpinLockGuard
                         // ===================
class SpinLockGuard {
    // This type implements a scoped guard for 'SpinLock'.

    // DATA
    SpinLock *d_lock_p; // lock proctored by this object

  private:
    // NOT IMPLEMENTED
    SpinLockGuard(const SpinLockGuard&);
    SpinLockGuard& operator=(const SpinLockGuard&);

  public:

    // CREATORS
    explicit SpinLockGuard(SpinLock *lock);
        // Create a proctor object that manages the specified 'lock'.  Invoke
        // 'lock->lock()'.

    ~SpinLockGuard();
        // Destroy this proctor object and invoke 'unlock()' on the lock
        // managed by this object.

    // MANIPULATORS
    SpinLock *release();
        // Return the lock pointer that was provided at construction and stop
        // managing it.  (Subsequent calls to 'release()' will return null and
        // the destruction of this object will not affect the lock.)  The lock
        // status is not changed by this call.
};

// ============================================================================
//                             INLINE DEFINITIONS
// ============================================================================

                             // --------------
                             // class SpinLock
                             // --------------
// PRIVATE CLASS METHODS
inline
void SpinLock::doBackoff(int *count) {
    if (BSLS_PERFORMANCEHINT_PREDICT_LIKELY(*count < 10)) {
        pause();
    } else if (BSLS_PERFORMANCEHINT_PREDICT_LIKELY(*count < 25)) {
        yield();
    } else {
        sleepMillis(10);
    }
    ++(*count);
}

inline
void SpinLock::pause() {
#if defined(BSLS_PLATFORM_CPU_X86) || defined(BSLS_PLATFORM_CPU_X86_64)
    _mm_pause();
#endif
}

inline
void SpinLock::sleepMillis(int milliseconds)
{
#ifdef BSLS_PLATFORM_OS_WINDOWS
    ::Sleep(milliseconds);
#else
    timespec naptime;
    naptime.tv_sec = 0;
    naptime.tv_nsec = 1000 * 1000 * milliseconds;
    nanosleep(&naptime, 0);
#endif
}

inline
void SpinLock::yield() {
#ifdef BSLS_PLATFORM_OS_WINDOWS
    ::SleepEx(0, 0);
#else
    sched_yield();
#endif
}

// MANIPULATORS
inline
void SpinLock::lock() {
    lockWithoutBackoff();
}

inline
void SpinLock::lockWithBackoff() {
    int count = 0;
    do {
        // Implementation note: the outer 'if' block is not logically necessary
        // but may reduce memory barrier costs when spinning.
        if (e_UNLOCKED == AtomicOperations::getIntAcquire(&d_state)) {
            if (e_UNLOCKED == AtomicOperations::swapIntAcqRel(&d_state,
                                                              e_LOCKED))
            {
                break;
            }
        }
        doBackoff(&count);
    } while (1);
}

inline
void SpinLock::lockWithoutBackoff() {
    do {
        // Implementation note: the outer 'if' block is not logically necessary
        // but may reduce memory barrier costs when spinning.
        if (e_UNLOCKED == AtomicOperations::getIntAcquire(&d_state)) {
            if (e_UNLOCKED == AtomicOperations::swapIntAcqRel(&d_state,
                                                              e_LOCKED))
            {
                break;
            }
        }
    } while (1);
}

inline
int SpinLock::tryLock(int numRetries) {
    int count = 0;
    do {
        // See lock() for implementation note.
        if (e_UNLOCKED == AtomicOperations::getIntAcquire(&d_state)) {
            if (e_UNLOCKED == AtomicOperations::swapIntAcqRel(&d_state,
                                                              e_LOCKED))
            {
                return 0;                                             // RETURN
            }
        }
        doBackoff(&count);
    } while (numRetries--);
    return -1;
}

inline
void SpinLock::unlock() {
    BSLS_ASSERT_SAFE(e_LOCKED == AtomicOperations::getInt(&d_state));

    AtomicOperations::setIntRelease(&d_state, e_UNLOCKED);
}

                          // -------------------
                          // class SpinLockGuard
                          // -------------------
inline
SpinLockGuard::SpinLockGuard(SpinLock *lock)
: d_lock_p(lock) {
    BSLS_ASSERT_SAFE(0 != lock);
    lock->lock();
}

inline
SpinLockGuard::~SpinLockGuard()
{
    if (0 != d_lock_p) {
        d_lock_p->unlock();
    }
}

// MANIPULATORS
inline
SpinLock *SpinLockGuard::release() {
    SpinLock *lock = d_lock_p;
    d_lock_p = 0;
    return lock;
}

}  // close package namespace
}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2020 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------


text:
// Code generated by go-swagger; DO NOT EDIT.

package subscription

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

import (
	"fmt"
	"io"

	"github.com/go-openapi/runtime"
	"github.com/killbill/kbcli/v2/kbcommon"

	strfmt "github.com/go-openapi/strfmt"
)

// CreateSubscriptionCustomFieldsReader is a Reader for the CreateSubscriptionCustomFields structure.
type CreateSubscriptionCustomFieldsReader struct {
	formats strfmt.Registry
}

// ReadResponse reads a server response into the received o.
func (o *CreateSubscriptionCustomFieldsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 201, 200:
		result := NewCreateSubscriptionCustomFieldsCreated()
		result.HttpResponse = response
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	default:
		errorResult := kbcommon.NewKillbillError(response.Code())
		if err := consumer.Consume(response.Body(), &errorResult); err != nil && err != io.EOF {
			return nil, err
		}
		return nil, errorResult
	}
}

// NewCreateSubscriptionCustomFieldsCreated creates a CreateSubscriptionCustomFieldsCreated with default headers values
func NewCreateSubscriptionCustomFieldsCreated() *CreateSubscriptionCustomFieldsCreated {
	return &CreateSubscriptionCustomFieldsCreated{}
}

/*CreateSubscriptionCustomFieldsCreated handles this case with default header values.

Custom field created successfully
*/
type CreateSubscriptionCustomFieldsCreated struct {
	HttpResponse runtime.ClientResponse
}

func (o *CreateSubscriptionCustomFieldsCreated) Error() string {
	return fmt.Sprintf("[POST /1.0/kb/subscriptions/{subscriptionId}/customFields][%d] createSubscriptionCustomFieldsCreated ", 201)
}

func (o *CreateSubscriptionCustomFieldsCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	return nil
}

// NewCreateSubscriptionCustomFieldsBadRequest creates a CreateSubscriptionCustomFieldsBadRequest with default headers values
func NewCreateSubscriptionCustomFieldsBadRequest() *CreateSubscriptionCustomFieldsBadRequest {
	return &CreateSubscriptionCustomFieldsBadRequest{}
}

/*CreateSubscriptionCustomFieldsBadRequest handles this case with default header values.

Invalid subscription id supplied
*/
type CreateSubscriptionCustomFieldsBadRequest struct {
	HttpResponse runtime.ClientResponse
}

func (o *CreateSubscriptionCustomFieldsBadRequest) Error() string {
	return fmt.Sprintf("[POST /1.0/kb/subscriptions/{subscriptionId}/customFields][%d] createSubscriptionCustomFieldsBadRequest ", 400)
}

func (o *CreateSubscriptionCustomFieldsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {

	return nil
}


text:
/*global MM*/
MM.setImageAlertWidget = function (imageInsertController, alertController) {
	'use strict';
	var alertControllerId;
	imageInsertController.addEventListener('imageInserted', function () {
		alertController.hide(alertControllerId);
	});
	imageInsertController.addEventListener('imageInsertError', function () {
		alertController.hide(alertControllerId);
		alertControllerId = alertController.show('Cannot insert image from this website:', 'Please save the image locally and drag the saved file to add it to the map', 'error');
	});
	imageInsertController.addEventListener('imageLoadStarted', function () {
		alertController.hide(alertControllerId);
		alertControllerId = alertController.show('<i class="icon-spinner icon-spin"/> Loading image');
	});
};


text:
<?php

$story = new stdClass();


text:
/* jslint node: true */
/* eslint-disable no-console */
'use strict';

const printUsageAndSetExitCode	= require('./oputil_common.js').printUsageAndSetExitCode;
const ExitCodes					= require('./oputil_common.js').ExitCodes;
const argv						= require('./oputil_common.js').argv;
const initConfigAndDatabases	= require('./oputil_common.js').initConfigAndDatabases;
const getHelpFor				= require('./oputil_help.js').getHelpFor;

const async						= require('async');
const _							= require('lodash');

exports.handleUserCommand		= handleUserCommand;

function handleUserCommand() {
	if(true === argv.help || !_.isString(argv.user) || 0 === argv.user.length) {
		return printUsageAndSetExitCode(getHelpFor('User'), ExitCodes.ERROR);
	}

	if(_.isString(argv.password)) {
		if(0 === argv.password.length) {
			process.exitCode = ExitCodes.BAD_ARGS;
			return console.error('Invalid password');
		}

		async.waterfall(
			[
				function init(callback) {
					initAndGetUser(argv.user, callback);
				},
				function setNewPass(user, callback) {
					user.setNewAuthCredentials(argv.password, function credsSet(err) {
						if(err) {
							process.exitCode = ExitCodes.ERROR;
							callback(new Error('Failed setting password'));
						} else {
							callback(null);
						}
					});
				}
			],
			function complete(err) {
				if(err) {
					console.error(err.message);
				} else {
					console.info('Password set');
				}
			}
		);
	} else if(argv.activate) {
		setAccountStatus(argv.user, true);
	} else if(argv.deactivate) {
		setAccountStatus(argv.user, false);
	}
}

function getUser(userName, cb) {
	const User = require('../../core/user.js');
	User.getUserIdAndName(argv.user, function userNameAndId(err, userId) {
		if(err) {
			process.exitCode = ExitCodes.BAD_ARGS;
			return cb(new Error('Failed to retrieve user'));
		} else {
			let u = new User();
			u.userId = userId;
			return cb(null, u);
		}
	});
}

function initAndGetUser(userName, cb) {
	async.waterfall(
		[
			function init(callback) {
				initConfigAndDatabases(callback);
			},
			function getUserObject(callback) {
				getUser(argv.user, (err, user) => {
					if(err) {
						process.exitCode = ExitCodes.BAD_ARGS;
						return callback(err);
					}
					return callback(null, user);
				});
			}
		],
		(err, user) => {
			return cb(err, user);
		}
	);
}

function setAccountStatus(userName, active) {
	async.waterfall(
		[
			function init(callback) {
				initAndGetUser(argv.user, callback);
			},
			function activateUser(user, callback) {
				const AccountStatus = require('../../core/user.js').AccountStatus;
				user.persistProperty('account_status', active ? AccountStatus.active : AccountStatus.inactive, callback);
			}
		],
		err => {
			if(err) {
				console.error(err.message);
			} else {
				console.info('User ' + ((true === active) ? 'activated' : 'deactivated'));
			}
		}
	);
}


text:
function attachAllEvents() {
    // Bind the navigation menu links
    $('#linkHome').click(showHomeView);
    $('#linkLogin').click(showLoginView);
    $('#linkRegister').click(showRegisterView);
    $('#linkListAds').click(listAds);
    $('#linkCreateAd').click(showCreateAdView);
    $('#linkLogout').click(logoutUser);

    // Bing the form with submit buttons
    $('#buttonLoginUser').on('click', loginUser);
    $('#buttonRegisterUser').on('click', registerUser);
    $('#buttonCreateAd').on('click', createAd);
    $('#buttonEditAd').on('click', editAd);

    // Bind the info / error boxes
    $('#infoBox, #errorBox').click(function () {
       $(this).fadeOut();
    });

    // Attach AJAX "loading" event listeners
    $(document).on({
        ajaxStart: function() { $('#loadingBox').show() },
        ajaxStop: function() { $('#loadingBox').hide() }
    });
}


text:
<?php
namespace ModuleDefault\Models;

use SuitUp\Database\Business\AbstractBusiness;

/**
 * HistoriaAmigosBusiness - Um arquivo que tem classe.
 */
class HistoriaAmigosBusiness extends AbstractBusiness
{
  /**
   *
   * @var Gateway\HistoriaAmigos
   */
  protected $gateway;

  /**
   * Retorna lista de amigos marcados na historia
   *
   * @param int $pkHistoria PK da historia
   * @return array
   */
  public function getListByHist($pkHistoria) {
    return $this->gateway->getListByHist($pkHistoria);
  }
}


text:
package io.apiman.manager.api.schema.format;

import io.apiman.manager.api.beans.apis.ApiDefinitionType;
import io.apiman.manager.api.core.exceptions.StorageException;
import io.apiman.manager.api.gateway.GatewayAuthenticationException;

import java.io.IOException;
import java.io.InputStream;

/**
 *
 *
 * @author Marc Savy {@literal <marc@blackparrotlabs.io>}
 */
public interface ApiDefinitionProvider {
    /**
     * Parse the input stream from the provider's format into a Jackson JsonNode structure (returning the root node).
     */
    String rewrite(ProviderContext providerCtx, InputStream is, ApiDefinitionType apiDefinitionType)
            throws IOException, StorageException, GatewayAuthenticationException, Exception;
}


text:
API to handle interactions between the digitalmarketplace applications and search.

- Python app, based on the [Flask framework](http://flask.pocoo.org/)

## Setup

Install [elasticsearch](http://www.elasticsearch.org/)

```
brew update
brew install elasticsearch
```

Install [Virtualenv](https://virtualenv.pypa.io/en/latest/)

```
sudo easy_install virtualenv
```

Create a virtual environment in the checked-out repository folder

 ```
cd digitalmarketplace-search-api
virtualenv ./venv
 ```

### Activate the virtual environment

```
source ./venv/bin/activate
```

### Upgrade dependencies

Install Python dependencies with pip

```pip install -r requirements_for_test.txt```

### Insert G6 services into elasticsearch index

Start elasticsearch (in a new console window/tab)

```
elasticsearch
```

The process for indexing of services is changing and this documentation will be updated shortly. In the meantime the explorer (see below) can be used to insert documents.

Set the required environment variable (in production this will point to the
load balancer in front of the Elasticsearch cluster).

```
export DM_ELASTICSEARCH_URL=http://localhost:9200
```

### Run the tests

```
./scripts/run_tests.sh
```

### Run the development server

To run the Search API for local development you can use the convenient run
script, which sets the required environment variables for local development:
```
./scripts/run_app.sh
```

More generally, the command to start the server is:
```
python application.py runserver
```

### Using the Search API locally

The Search API runs on port 5001. Calls to the API require a valid bearer
token. Tokens to be accepted can be set using the DM_SEARCH_API_AUTH_TOKENS
environment variable, e.g.:

```export DM_SEARCH_API_AUTH_TOKENS=myToken```

and then you can include this token in your request headers, e.g.:

```
curl -i -H "Authorization: Bearer myToken" 127.0.0.1:5001/search?q=email
```

Alternatively there is an API explorer running on

    [http://localhost:5001/_explorer](http://localhost:5001/_explorer)

Which provides a UI over the API calls.

### Using FeatureFlags

To use feature flags, check out the documentation in (the README of)
[digitalmarketplace-utils](https://github.com/alphagov/digitalmarketplace-utils#using-featureflags).


text:
@class HXPhotoModel;
@interface UIImageView (HXExtension)
- (void)hx_setImageWithModel:(HXPhotoModel *)model progress:(void (^)(CGFloat progress, HXPhotoModel *model))progressBlock completed:(void (^)(UIImage * image, NSError * error, HXPhotoModel * model))completedBlock;

- (void)hx_setImageWithModel:(HXPhotoModel *)model original:(BOOL)original progress:(void (^)(CGFloat progress, HXPhotoModel *model))progressBlock completed:(void (^)(UIImage * image, NSError * error, HXPhotoModel * model))completedBlock;
- (void)hx_setImageWithURL:(NSURL *)url
                  progress:(void (^)(CGFloat progress))progressBlock
                 completed:(void (^)(UIImage * image, NSError * error))completedBlock;
@end


text:
package com.greenstarnetwork.services.facilitymanager;

import javax.xml.ws.WebFault;

/**
 * This class was generated by Apache CXF 2.4.0
 * 2011-12-20T15:00:53.577-05:00
 * Generated source version: 2.4.0
 *
 */

@WebFault(name = "FacilityManagerException", targetNamespace = "http://facilitymanager.services.greenstarnetwork.com/")
public class FacilityManagerException_Exception extends Exception {
    public static final long serialVersionUID = 20111220150053L;

    private com.greenstarnetwork.services.facilitymanager.FacilityManagerException facilityManagerException;

    public FacilityManagerException_Exception() {
        super();
    }

    public FacilityManagerException_Exception(String message) {
        super(message);
    }

    public FacilityManagerException_Exception(String message, Throwable cause) {
        super(message, cause);
    }

    public FacilityManagerException_Exception(String message, com.greenstarnetwork.services.facilitymanager.FacilityManagerException facilityManagerException) {
        super(message);
        this.facilityManagerException = facilityManagerException;
    }

    public FacilityManagerException_Exception(String message, com.greenstarnetwork.services.facilitymanager.FacilityManagerException facilityManagerException, Throwable cause) {
        super(message, cause);
        this.facilityManagerException = facilityManagerException;
    }

    public com.greenstarnetwork.services.facilitymanager.FacilityManagerException getFaultInfo() {
        return this.facilityManagerException;
    }
}


text:
<!DOCTYPE html>

	<link href="js/bootstrap.min.css" rel="stylesheet"type="text/css">
	<link href="css/moncss.css" rel="stylesheet"type="text/css">

	<title>Comparison of notetaking software - Basic features</title>
	<meta charset="utf-8">

Comparison of notetaking software - Basic features

			<fieldset>

					<form action="" method="post">
						<legend style="color:red;font-weight: bold;font-style:italic;text-align: center;" >Formulaire</legend>

								Printing :

 <input type="radio" name="FeaturePrinting" value="oui">Yes <input type="radio" name="FeaturePrinting" value = "non">No <input type="radio" name="FeaturePrinting" value = "non">Partial

											<input  style="display:none;" id ="id2Printing"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Printing','id2Printing');">Changer type</button>

								Sync :

 <input type="radio" name="FeatureSync" value="oui">Yes <input type="radio" name="FeatureSync" value = "non">No <input type="radio" name="FeatureSync" value = "non">Partial

											<input  style="display:none;" id ="id2Sync"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Sync','id2Sync');">Changer type</button>

								File save/export/import formats :

											<input type="checkbox" name="Feature" >Proprietary

											<input type="checkbox" name="Feature" >encrypted; import: plain text

											<input type="checkbox" name="Feature" >RTF

											<input type="checkbox" name="Feature" >CSV

											<input type="checkbox" name="Feature" >MS Word

											<input type="checkbox" name="Feature" >images

											<input type="checkbox" name="Feature" >web pages; exports: plain text

											<input type="checkbox" name="Feature" >HTML

											<input type="checkbox" name="Feature" >Sqlite based

											<input type="checkbox" name="Feature" >zipped attachments; export to HTML; copying as LaTeX; import text files

											<input type="checkbox" name="Feature" >OpenOffice.org documents

											<input type="checkbox" name="Feature" >Internal: combination of TXT and RTF; import

											<input type="checkbox" name="Feature" >export: TXT

											<input type="checkbox" name="Feature" >Treepad

											<input type="checkbox" name="Feature" >Proprietary; export: html

											<input type="checkbox" name="Feature" >opml

											<input type="checkbox" name="Feature" >rtf

											<input type="checkbox" name="Feature" >txt

											<input type="checkbox" name="Feature" >doc

											<input type="checkbox" name="Feature" >pdf

											<input type="checkbox" name="Feature" >Notes stored as XML; both free and paid version allows notes of any file type

											<input type="checkbox" name="Feature" >Proprietary (SQL); Export to text

											<input type="checkbox" name="Feature" >XML

											<input type="checkbox" name="Feature" >CHM and HTML. Import from text

											<input type="checkbox" name="Feature" >XML and RTF

											<input type="checkbox" name="Feature" >NoteXmlFormat

											<input type="checkbox" name="Feature" >PDF

											<input type="checkbox" name="Feature" >Open

											<input type="checkbox" name="Feature" >import from web pages and other applications

											<input type="checkbox" name="Feature" >MS OneNote format

											<input type="checkbox" name="Feature" >text

											<input type="checkbox" name="Feature" >photos

											<input type="checkbox" name="Feature" >tags

											<input type="checkbox" name="Feature" >Notes stored as XML; both free and paid versions allow notes of any file type

											<input type="checkbox" name="Feature" >PS

											<input type="checkbox" name="Feature" >TIFF

											<input type="checkbox" name="Feature" >CHM

											<input type="checkbox" name="Feature" >DjVu

											<input type="checkbox" name="Feature" >DVI

											<input type="checkbox" name="Feature" >XPS

											<input type="checkbox" name="Feature" >ODF

											<input type="checkbox" name="Feature" >others; export PDF+notes for sending to other Okular users

											<input type="checkbox" name="Feature" >Zip compatible archive containing one SVG per page

											<input type="checkbox" name="Feature" >config file

											<input type="checkbox" name="Feature" >and optional background PDFs

											<input type="checkbox" name="Feature" >images; can export to txt

											<input type="checkbox" name="Feature" >html

											<input type="checkbox" name="Feature" >jpg

											<input type="checkbox" name="Feature" >Rich text; export as HTML; import text files

											<input type="checkbox" name="Feature" >Brainstorm; export to RTF and Word

											<input type="checkbox" name="Feature" >TXT (ANSI

											<input type="checkbox" name="Feature" >Unicode)

											<input type="checkbox" name="Feature" >ALX

											<input type="checkbox" name="Feature" >XML; export to PDF

											<input type="checkbox" name="Feature" >Markdown (in GUI)

											<input type="checkbox" name="Feature" >XML (data file); Export as: pdf

											<input type="checkbox" name="Feature" >md

											<input type="checkbox" name="Feature" >Stored in modified DocuWiki Markdown; export: HTML

											<input type="checkbox" name="Feature" >LaTeX

											<input type="checkbox" name="Feature" >Pandoc Markdown

											<input type="checkbox" name="Feature" >Sphinx RST (reStructuredText)

											<input type="checkbox" name="Feature" >File save

											<input type="checkbox" name="Feature" >export

											<input type="checkbox" name="Feature" >import formats

											<input type="checkbox" name="Feature" >XML; notes may include rich text or HTML

											<input type="checkbox" name="Feature" >DocBook

											<input type="checkbox" name="Feature" >Taskjuggler

											<input type="checkbox" name="Feature" >Freemind

											<input type="checkbox" name="Feature" >XOXO

											<input type="checkbox" name="Feature" >iCalendar

											<input type="checkbox" name="Feature" >Notes stored as XML; can attach any filetype

											<input type="checkbox" name="Feature" >TXT

											<input type="checkbox" name="Feature" >Proprietary; export to Unicode text

											<input type="checkbox" name="Feature" >XML and HTML

											<input type="checkbox" name="Feature" >wiki-formats

											<input type="checkbox" name="Feature" >Export to RTF

										<input type='checkbox'>autre:
<input type="text"/>

								Name :
 <input id="0" type="text" name="Feature">

								Search :

 <input type="radio" name="FeatureSearch" value="oui">Yes <input type="radio" name="FeatureSearch" value = "non">No <input type="radio" name="FeatureSearch" value = "non">Partial

											<input  style="display:none;" id ="id2Search"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Search','id2Search');">Changer type</button>

								Organizing principle(s) :
 <input id="1" type="text" name="Feature">

								Whiteboard :

 <input type="radio" name="FeatureWhiteboard" value="oui">Yes <input type="radio" name="FeatureWhiteboard" value = "non">No <input type="radio" name="FeatureWhiteboard" value = "non">Partial

											<input  style="display:none;" id ="id2Whiteboard"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Whiteboard','id2Whiteboard');">Changer type</button>

								PDF annotate and save :

 <input type="radio" name="FeaturePDF annotate and save" value="oui">Yes <input type="radio" name="FeaturePDF annotate and save" value = "non">No <input type="radio" name="FeaturePDF annotate and save" value = "non">Partial

											<input  style="display:none;" id ="id2PDF annotate and save"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1PDF annotate and save','id2PDF annotate and save');">Changer type</button>

								Tabbed sections :

 <input type="radio" name="FeatureTabbed sections" value="oui">Yes <input type="radio" name="FeatureTabbed sections" value = "non">No <input type="radio" name="FeatureTabbed sections" value = "non">Partial

											<input  style="display:none;" id ="id2Tabbed sections"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Tabbed sections','id2Tabbed sections');">Changer type</button>

								Outline bulleting with indent :

 <input type="radio" name="FeatureOutline bulleting with indent" value="oui">Yes <input type="radio" name="FeatureOutline bulleting with indent" value = "non">No <input type="radio" name="FeatureOutline bulleting with indent" value = "non">Partial

											<input  style="display:none;" id ="id2Outline bulleting with indent"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Outline bulleting with indent','id2Outline bulleting with indent');">Changer type</button>

								Handwriting recognition :

 <input type="radio" name="FeatureHandwriting recognition" value="oui">Yes <input type="radio" name="FeatureHandwriting recognition" value = "non">No <input type="radio" name="FeatureHandwriting recognition" value = "non">Partial

											<input  style="display:none;" id ="id2Handwriting recognition"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Handwriting recognition','id2Handwriting recognition');">Changer type</button>

								Spell check :

 <input type="radio" name="FeatureSpell check" value="oui">Yes <input type="radio" name="FeatureSpell check" value = "non">No <input type="radio" name="FeatureSpell check" value = "non">Partial

											<input  style="display:none;" id ="id2Spell check"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Spell check','id2Spell check');">Changer type</button>

								Ink-pen input :

 <input type="radio" name="FeatureInk-pen input" value="oui">Yes <input type="radio" name="FeatureInk-pen input" value = "non">No <input type="radio" name="FeatureInk-pen input" value = "non">Partial

											<input  style="display:none;" id ="id2Ink-pen input"type="text"/>
										    <button class="btn btn-primary btn-xs" type="button" onClick="switchFunction('id1Ink-pen input','id2Ink-pen input');">Changer type</button>

<input type="submit" class="btn btn-info" value="Ajouter un produit" />
					</form>

			</fieldset>


text:
class ProductType < ApplicationRecord
  belongs_to :provider_type

  # Optional: Override in each product type to customize product class name
  def self.product_class
    to_s.sub(/Type\z/, '').constantize
  end

  # Optional: Override in each product type
  # Properties are used to create a comparable list of properties;
  # The list of strings are turned into labels that will have values manager supplied/changed values on the products
  # example: [ {name: 'CPUs', value: '1'}, ...]
  def properties
    []
  end

  # Optional: Override in each product type
  # settings are used to create a products initial settings
  # Product.settings are later combined with a ServiceRequest.settings to create the Service.settings
  def default_settings
    # Used to initialize the product.
    {}
  end

  # Optional: Override in each product type
  def tag_list
    []
  end

  # All product types use the same serializer
  def serializer_class_name
    'ProductTypeSerializer'
  end
end


text:
#include "test.h"

#ifdef __GNUC__
#include <stdlib.h>
#endif

#include "benchtest.h"

#define ITERATIONS      1000000L

sem_t sema;
//HANDLE w32sema;

struct _timeb currSysTimeStart;
struct _timeb currSysTimeStop;
long durationMilliSecs;
long overHeadMilliSecs = 0;
int one = 1;
int zero = 0;

#define GetDurationMilliSecs(_TStart, _TStop) ((_TStop.time*1000+_TStop.millitm) \
                                               - (_TStart.time*1000+_TStart.millitm))

/*
 * Dummy use of j, otherwise the loop may be removed by the optimiser
 * when doing the overhead timing with an empty loop.
 */
#define TESTSTART \
  { int i, j = 0, k = 0; _ftime(&currSysTimeStart); for (i = 0; i < ITERATIONS; i++) { j++;

#define TESTSTOP \
  }; _ftime(&currSysTimeStop); if (j + k == i) j++; }

void
reportTest (char * testNameString)
{
  durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs;

  printf( "%-45s %15ld %15.3f\n",
          testNameString,
          durationMilliSecs,
          (float) durationMilliSecs * 1E3 / ITERATIONS);
}

int
bench_main (int argc, char *argv[])
{
  printf( "=============================================================================\n");
  printf( "\nOperations on a semaphore.\n%ld iterations\n\n",
          ITERATIONS);
  printf( "%-45s %15s %15s\n",
          "Test",
          "Total(msec)",
          "average(usec)");

  /*
   * Time the loop overhead so we can subtract it from the actual test times.
   */

  TESTSTART
  assert(1 == one);
  TESTSTOP

  durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs;
  overHeadMilliSecs = durationMilliSecs;

  /*
   * Now we can start the actual tests
   */
  assert(sem_init(&sema, 0, 0) == 0);
  TESTSTART
  assert(sem_post(&sema) == zero);
  TESTSTOP
  assert(sem_destroy(&sema) == 0);

  reportTest("POSIX Post with no waiters");

  assert(sem_init(&sema, 0, ITERATIONS) == 0);
  TESTSTART
  assert(sem_wait(&sema) == zero);
  TESTSTOP
  assert(sem_destroy(&sema) == 0);

  reportTest("POSIX Wait without blocking");

  printf( "=============================================================================\n");

  /*
   * End of tests.
   */

  return 0;
}


text:
#pragma strict

var move = false;
var hitDist = 0f;

function Start () {

}

function Update () {
	try {
		hitDist = Vector3.Distance(Vector3.zero, GameObject.FindGameObjectWithTag("Player").GetComponent(CameraScript).hit.point);
	} catch (err) {
		Debug.LogError(err);
	}
	if(move) {
		transform.LookAt(GameObject.FindGameObjectWithTag("Player").GetComponent(CameraScript).transform.forward * hitDist);
	}
}


text:
package org.karmaexchange.resources.derived;

import java.util.List;

import javax.annotation.Nullable;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.annotation.XmlRootElement;

import lombok.Data;

import org.karmaexchange.dao.Event;
import org.karmaexchange.dao.derived.EventSourceInfo;
import org.karmaexchange.resources.EventResource;
import org.karmaexchange.resources.msg.EventView;
import org.karmaexchange.util.AdminUtil;
import org.karmaexchange.util.AdminUtil.AdminSubtask;
import org.karmaexchange.util.AdminUtil.AdminTaskType;

@Path("/derived/event")
public class SourceEventResource {

  @Context
  protected UriInfo uriInfo;
  @Context
  protected Request request;
  @Context
  protected ServletContext servletContext;

  @POST
  @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public void syncEvents(
      @QueryParam("org_id") String orgId,
      @QueryParam("org_secret") String orgSecret,
      List<SyncRequest> syncRequests) {
    EventSourceInfo sourceInfo =
        EventSourceInfo.validateOrgSecret(orgId, orgSecret);

    AdminUtil.executeSubtaskAsAdmin(
      AdminTaskType.SOURCE_EVENT_UPDATE,
      new SyncEventsAdminSubtask(syncRequests, sourceInfo));
  }

  @Data
  private class SyncEventsAdminSubtask implements AdminSubtask {

    private final List<SyncRequest> syncRequests;
    private final EventSourceInfo sourceInfo;

    @Override
    public void execute() {
      // TODO(avaliani): Optimize this by doing a batch upsert / delete.
      for (SyncRequest syncRequest : syncRequests) {

        if (syncRequest.action == SyncRequest.Action.UPSERT) {

          if (syncRequest.sourceEvent != null) {
            Event event = syncRequest.sourceEvent.toEvent(sourceInfo);
            getEventResource().upsertResource(
              new EventView(event, false));
          } else if (syncRequest.sourceUser != null) {
            syncRequest.sourceUser.upsert(sourceInfo);
          } else if (syncRequest.sourceConfig != null) {
            syncRequest.sourceConfig.upsert(sourceInfo);
          }

        } else { // DELETE

          if (syncRequest.sourceEventId != null) {
            getEventResource().deleteResource(
              SourceEvent.createKey(sourceInfo, syncRequest.sourceEventId));
          }

        }

      }
    }
  }

  private EventResource getEventResource() {
    return new EventResource(uriInfo, request, servletContext);
  }

  @XmlRootElement
  @Data
  public static class SyncRequest {
    public enum Action {
      UPSERT,
      DELETE
    }

    private Action action;

    /**
     * Source db key of the event being synchronized. Only non-null for DELETE.
     */
    @Nullable
    private String sourceEventId;

    /**
     * Source db event of being synchronized. Only non-null for UPSERT.
     */
    @Nullable
    private SourceEvent sourceEvent;

    /**
     * Source db user being synchronized. Only non-null for UPSERT.
     */
    @Nullable
    private SourceUser sourceUser;

    /**
     * Source configuration info. Only non-null for UPSERT.
     */
    @Nullable
    private SourceConfig sourceConfig;
  }
}


text:
using org.xmlvm;
namespace java.util.regex {
public class NonCapFSet: global::java.util.regex.FSet {
new public void @this(int n1){
//XMLVM_BEGIN_WRAPPER[java.util.regex.NonCapFSet: void <init>(int)]
    global::System.Object _r0_o = null;
    global::org.xmlvm._nElement _r1;
    _r0_o = this;
    _r1.i = n1;
    ((global::java.util.regex.FSet) _r0_o).@this((int) _r1.i);
    return;
//XMLVM_END_WRAPPER[java.util.regex.NonCapFSet: void <init>(int)]
}

public override int matches(int n1, global::java.lang.CharSequence n2, global::java.util.regex.MatchResultImpl n3){
//XMLVM_BEGIN_WRAPPER[java.util.regex.NonCapFSet: int matches(int, java.lang.CharSequence, java.util.regex.MatchResultImpl)]
    global::org.xmlvm._nElement _r0;
    global::System.Object _r0_o = null;
    global::org.xmlvm._nElement _r1;
    global::System.Object _r2_o = null;
    global::org.xmlvm._nElement _r3;
    global::System.Object _r4_o = null;
    global::System.Object _r5_o = null;
    _r2_o = this;
    _r3.i = n1;
    _r4_o = n2;
    _r5_o = n3;
    _r0.i = ((global::java.util.regex.NonCapFSet) _r2_o).getGroupIndex();
    _r1.i = ((global::java.util.regex.MatchResultImpl) _r5_o).getConsumed((int) _r0.i);
    _r1.i = _r3.i - _r1.i;
    ((global::java.util.regex.MatchResultImpl) _r5_o).setConsumed((int) _r0.i, (int) _r1.i);
    _r0_o = ((global::java.util.regex.NonCapFSet) _r2_o)._fnext;
    _r0.i = ((global::java.util.regex.AbstractSet) _r0_o).matches((int) _r3.i, (global::java.lang.CharSequence) _r4_o, (global::java.util.regex.MatchResultImpl) _r5_o);
    return _r0.i;
//XMLVM_END_WRAPPER[java.util.regex.NonCapFSet: int matches(int, java.lang.CharSequence, java.util.regex.MatchResultImpl)]
}

public override global::System.Object getName(){
//XMLVM_BEGIN_WRAPPER[java.util.regex.NonCapFSet: java.lang.String getName()]
    global::System.Object _r0_o = null;
    global::System.Object _r1_o = null;
    _r1_o = this;
    // Value=NonCapFSet
    _r0_o = new global::java.lang.String();
    ((global::java.lang.String)_r0_o).@this(new global::org.xmlvm._nArrayAdapter<char>(new char[] {unchecked((char) unchecked((uint)78)), unchecked((char) unchecked((uint) 111)), unchecked((char) unchecked((uint) 110)), unchecked((char) unchecked((uint) 67)), unchecked((char) unchecked((uint) 97)), unchecked((char) unchecked((uint) 112)), unchecked((char) unchecked((uint) 70)), unchecked((char) unchecked((uint) 83)), unchecked((char) unchecked((uint) 101)), unchecked((char) unchecked((uint) 116))}));
    return (global::java.lang.String) _r0_o;
//XMLVM_END_WRAPPER[java.util.regex.NonCapFSet: java.lang.String getName()]
}

public override bool hasConsumed(global::java.util.regex.MatchResultImpl n1){
//XMLVM_BEGIN_WRAPPER[java.util.regex.NonCapFSet: boolean hasConsumed(java.util.regex.MatchResultImpl)]
    global::org.xmlvm._nElement _r0;
    global::System.Object _r1_o = null;
    global::System.Object _r2_o = null;
    _r1_o = this;
    _r2_o = n1;
    _r0.i = 0;
    return _r0.i!=0;
//XMLVM_END_WRAPPER[java.util.regex.NonCapFSet: boolean hasConsumed(java.util.regex.MatchResultImpl)]
}

//XMLVM_BEGIN_WRAPPER[java.util.regex.NonCapFSet]
//XMLVM_END_WRAPPER[java.util.regex.NonCapFSet]

} // end of class: NonCapFSet

} // end of namespace: java.util.regex


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#ifndef __MESOS_SLAVE_CONTAINERIZER_HPP__
#define __MESOS_SLAVE_CONTAINERIZER_HPP__

#include <string>

#include <process/shared.hpp>
#include <process/subprocess.hpp>

#include <stout/option.hpp>

// ONLY USEFUL AFTER RUNNING PROTOC.
#include <mesos/slave/containerizer.pb.h>

namespace mesos {
namespace slave {

/**
 * An abstraction around the IO classes used to redirect
 * stdin/stdout/stderr to/from a container by the containerizer.
 */
struct ContainerIO
{
  /**
   * Describes how the containerizer redirects I/O for
   * stdin/stdout/stderr of a container.
   * See `process::Subprocess::IO`.
   *
   * NOTE: This wrapper prevents the containerizer from redirecting I/O
   * via a `Subprocess::PIPE`. This is restricted because the IO of a
   * container must not be affected by the status of the agent process:
   *   * A `Subprocess::PIPE` will require the agent process to regularly
   *     read and empty the pipe. The agent does not do this. If the pipe
   *     fills up, the write-end of the pipe may become blocked on IO.
   *   * Redirection must continue even if the agent dies.
   */
  class IO
  {
  public:
    enum class Type
    {
      FD,
      PATH
    };

    static IO PATH(const std::string& path)
    {
      return IO(Type::PATH, path);
    }

    static IO FD(int_fd fd, bool closeOnDestruction = true)
    {
      return IO(Type::FD, fd, closeOnDestruction);
    }

    operator process::Subprocess::IO () const
    {
      switch (type_) {
        case Type::FD:
          return process::Subprocess::FD(*fd_->get());
        case Type::PATH:
          return process::Subprocess::PATH(path_.get());
        default:
          UNREACHABLE();
      }
    }

  private:
    // A simple abstraction to wrap an FD and (optionally) close it
    // on destruction. We know that we never copy instances of this
    // class once they are instantiated, so it's OK to call
    // `close()` in the destructor since only one reference will
    // ever exist to it.
    class FDWrapper
    {
    public:
      FDWrapper(int_fd _fd, bool _closeOnDestruction)
        : fd(_fd), closeOnDestruction(_closeOnDestruction) {}

      ~FDWrapper() {
        CHECK(fd >= 0);
        if (closeOnDestruction) {
          close(fd);
        }
      }

      operator int_fd() const { return fd; }

    private:
      FDWrapper(const FDWrapper& fd) = delete;

      int_fd fd;
      bool closeOnDestruction;
    };

    IO(Type _type, int_fd _fd, bool closeOnDestruction)
      : type_(_type),
        fd_(new FDWrapper(_fd, closeOnDestruction)),
        path_(None()) {}

    IO(Type _type, const std::string& _path)
      : type_(_type),
        fd_(None()),
        path_(_path) {}

    Type type_;
    Option<process::Shared<FDWrapper>> fd_;
    Option<std::string> path_;
  };

  /**
   * How to redirect the stdin of the executable.
   * See `process::Subprocess::IO`.
   */
  IO in = IO::FD(STDIN_FILENO, false);

  /**
   * How to redirect the stdout of the executable.
   * See `process::Subprocess::IO`.
   */
  IO out = IO::FD(STDOUT_FILENO, false);

  /**
   * Similar to `out`, except this describes how to redirect stderr.
   */
  IO err = IO::FD(STDERR_FILENO, false);
};

} // namespace slave {
} // namespace mesos {

#endif // __MESOS_SLAVE_CONTAINERIZER_HPP__


text:
from subprocess import PIPE, STDOUT
from unittest import TestCase

from .mock import call
from testfixtures import ShouldRaise, compare

from testfixtures.popen import MockPopen, PopenBehaviour
from testfixtures.compat import BytesLiteral, PY2

import signal

class Tests(TestCase):

    def test_command_min_args(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=PIPE)
        # process started, no return code
        compare(process.pid, 1234)
        compare(None, process.returncode)

        out, err = process.communicate()

        # test the rest
        compare(out, b'')
        compare(err, b'')
        compare(process.returncode, 0)
        # test call list
        compare([
                call.Popen('a command', stderr=-1, stdout=-1),
                call.Popen_instance.communicate(),
                ], Popen.mock.method_calls)

    def test_command_max_args(self):

        Popen = MockPopen()
        Popen.set_command('a command', b'out', b'err', 1, 345)

        process = Popen('a command', stdout=PIPE, stderr=PIPE)
        compare(process.pid, 345)
        compare(None, process.returncode)

        out, err = process.communicate()

        # test the rest
        compare(out, b'out')
        compare(err, b'err')
        compare(process.returncode, 1)
        # test call list
        compare([
                call.Popen('a command', stderr=-1, stdout=-1),
                call.Popen_instance.communicate(),
                ], Popen.mock.method_calls)

    def test_callable_default_behaviour(self):
        def some_callable(command, stdin):
            return PopenBehaviour(BytesLiteral(command), BytesLiteral(stdin), 1, 345, 0)

        Popen = MockPopen()
        Popen.set_default(behaviour=some_callable)

        process = Popen('a command', stdin='some stdin', stdout=PIPE, stderr=PIPE)
        compare(process.pid, 345)

        out, err = process.communicate()

        compare(out, b'a command')
        compare(err, b'some stdin')
        compare(process.returncode, 1)

    def test_command_is_sequence(self):
        Popen = MockPopen()
        Popen.set_command('a command')

        process = Popen(['a', 'command'], stdout=PIPE, stderr=PIPE)

        compare(process.wait(), 0)
        compare([
                call.Popen(['a', 'command'], stderr=-1, stdout=-1),
                call.Popen_instance.wait(),
                ], Popen.mock.method_calls)

    def test_communicate_with_input(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=PIPE, shell=True)
        out, err = process.communicate('foo')
        # test call list
        compare([
                call.Popen('a command', shell=True, stderr=-1, stdout=-1),
                call.Popen_instance.communicate('foo'),
                ], Popen.mock.method_calls)

    def test_read_from_stdout(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command', stdout=b'foo')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=PIPE, shell=True)
        self.assertTrue(isinstance(process.stdout.fileno(), int))
        compare(process.stdout.read(), b'foo')
        # test call list
        compare([
                call.Popen('a command', shell=True, stderr=-1, stdout=-1),
                ], Popen.mock.method_calls)

    def test_read_from_stderr(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command', stderr=b'foo')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=PIPE, shell=True)
        self.assertTrue(isinstance(process.stdout.fileno(), int))
        compare(process.stderr.read(), b'foo')
        # test call list
        compare([
                call.Popen('a command', shell=True, stderr=-1, stdout=-1),
                ], Popen.mock.method_calls)

    def test_read_from_stdout_with_stderr_redirected_check_stdout_contents(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command', stdout=b'foo', stderr=b'bar')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=STDOUT, shell=True)
        # test stdout contents
        compare(b'foobar', process.stdout.read())
        compare(process.stderr, None)

    def test_read_from_stdout_with_stderr_redirected_check_stdout_stderr_interleaved(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command', stdout=b'o1\no2\no3\no4\n', stderr=b'e1\ne2\n')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=STDOUT, shell=True)
        self.assertTrue(isinstance(process.stdout.fileno(), int))
        # test stdout contents
        compare(b'o1\ne1\no2\ne2\no3\no4\n', process.stdout.read())

    def test_communicate_with_stderr_redirected_check_stderr_is_none(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command', stdout=b'foo', stderr=b'bar')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=STDOUT, shell=True)
        out, err = process.communicate()
        # test stderr is None
        compare(out, b'foobar')
        compare(err, None)

    def test_read_from_stdout_and_stderr(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command', stdout=b'foo', stderr=b'bar')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=PIPE, shell=True)
        compare(process.stdout.read(), b'foo')
        compare(process.stderr.read(), b'bar')
        # test call list
        compare([
                call.Popen('a command', shell=True, stderr=PIPE, stdout=PIPE),
                ], Popen.mock.method_calls)

    def test_write_to_stdin(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command')
        # usage
        process = Popen('a command', stdin=PIPE, shell=True)
        process.stdin.write('some text')
        # test call list
        compare([
                call.Popen('a command', shell=True, stdin=PIPE),
                call.Popen_instance.stdin.write('some text'),
                ], Popen.mock.method_calls)

    def test_wait_and_return_code(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command', returncode=3)
        # usage
        process = Popen('a command')
        compare(process.returncode, None)
        # result checking
        compare(process.wait(), 3)
        compare(process.returncode, 3)
        # test call list
        compare([
                call.Popen('a command'),
                call.Popen_instance.wait(),
                ], Popen.mock.method_calls)

    def test_multiple_uses(self):
        Popen = MockPopen()
        Popen.set_command('a command', b'a')
        Popen.set_command('b command', b'b')
        process = Popen('a command', stdout=PIPE, stderr=PIPE, shell=True)
        out, err = process.communicate('foo')
        compare(out, b'a')
        process = Popen(['b', 'command'], stdout=PIPE, stderr=PIPE, shell=True)
        out, err = process.communicate('foo')
        compare(out, b'b')
        compare([
                call.Popen('a command', shell=True, stderr=-1, stdout=-1),
                call.Popen_instance.communicate('foo'),
                call.Popen(['b', 'command'], shell=True, stderr=-1, stdout=-1),
                call.Popen_instance.communicate('foo'),
                ], Popen.mock.method_calls)

    def test_send_signal(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=PIPE, shell=True)
        process.send_signal(0)
        # result checking
        compare([
                call.Popen('a command', shell=True, stderr=-1, stdout=-1),
                call.Popen_instance.send_signal(0),
                ], Popen.mock.method_calls)

    def test_terminate(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=PIPE, shell=True)
        process.terminate()
        # result checking
        compare([
                call.Popen('a command', shell=True, stderr=-1, stdout=-1),
                call.Popen_instance.terminate(),
                ], Popen.mock.method_calls)

    def test_kill(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=PIPE, shell=True)
        process.kill()
        # result checking
        compare([
                call.Popen('a command', shell=True, stderr=-1, stdout=-1),
                call.Popen_instance.kill(),
                ], Popen.mock.method_calls)

    def test_all_signals(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command')
        # usage
        process = Popen('a command')
        process.send_signal(signal.SIGINT)
        process.terminate()
        process.kill()
        # test call list
        compare([
                call.Popen('a command'),
                call.Popen_instance.send_signal(signal.SIGINT),
                call.Popen_instance.terminate(),
                call.Popen_instance.kill(),
                ], Popen.mock.method_calls)

    def test_poll_no_setup(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command')
        # usage
        process = Popen('a command', stdout=PIPE, stderr=PIPE, shell=True)
        compare(process.poll(), None)
        compare(process.poll(), None)
        compare(process.wait(), 0)
        compare(process.poll(), 0)
        # result checking
        compare([
                call.Popen('a command', shell=True, stderr=-1, stdout=-1),
                call.Popen_instance.poll(),
                call.Popen_instance.poll(),
                call.Popen_instance.wait(),
                call.Popen_instance.poll(),
                ], Popen.mock.method_calls)

    def test_poll_setup(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command', poll_count=1)
        # usage
        process = Popen('a command', stdout=PIPE, stderr=PIPE, shell=True)
        compare(process.poll(), None)
        compare(process.poll(), 0)
        compare(process.wait(), 0)
        compare(process.poll(), 0)
        # result checking
        compare([
                call.Popen('a command', shell=True, stderr=-1, stdout=-1),
                call.Popen_instance.poll(),
                call.Popen_instance.poll(),
                call.Popen_instance.wait(),
                call.Popen_instance.poll(),
                ], Popen.mock.method_calls)

    def test_poll_until_result(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command', returncode=3, poll_count=2)
        # example usage
        process = Popen('a command')
        while process.poll() is None:
            # you'd probably have a sleep here, or go off and
            # do some other work.
            pass
        # result checking
        compare(process.returncode, 3)
        compare([
                call.Popen('a command'),
                call.Popen_instance.poll(),
                call.Popen_instance.poll(),
                call.Popen_instance.poll(),
                ], Popen.mock.method_calls)

    def test_command_not_specified(self):
        Popen = MockPopen()
        with ShouldRaise(KeyError(
            "Nothing specified for command 'a command'"
        )):
            Popen('a command', stdout=PIPE, stderr=PIPE, shell=True)

    def test_default_command_min_args(self):
        # setup
        Popen = MockPopen()
        Popen.set_default()
        # usage
        process = Popen('a command', stdout=PIPE, stderr=PIPE)
        # process started, no return code
        compare(process.pid, 1234)
        compare(None, process.returncode)

        out, err = process.communicate()

        # test the rest
        compare(out, b'')
        compare(err, b'')
        compare(process.returncode, 0)
        # test call list
        compare([
            call.Popen('a command', stderr=-1, stdout=-1),
            call.Popen_instance.communicate(),
        ], Popen.mock.method_calls)

    def test_default_command_max_args(self):
        Popen = MockPopen()
        Popen.set_default(b'out', b'err', 1, 345)

        process = Popen('a command', stdout=PIPE, stderr=PIPE)
        compare(process.pid, 345)
        compare(None, process.returncode)

        out, err = process.communicate()

        # test the rest
        compare(out, b'out')
        compare(err, b'err')
        compare(process.returncode, 1)
        # test call list
        compare([
            call.Popen('a command', stderr=-1, stdout=-1),
            call.Popen_instance.communicate(),
        ], Popen.mock.method_calls)

    def test_invalid_parameters(self):
        Popen = MockPopen()
        with ShouldRaise(TypeError(
                "Popen() got an unexpected keyword argument 'foo'"
        )):
            Popen(foo='bar')

    def test_invalid_method_or_attr(self):
        Popen = MockPopen()
        Popen.set_command('command')
        process = Popen('command')
        with ShouldRaise(
                AttributeError("Mock object has no attribute 'foo'")):
            process.foo()

    def test_invalid_attribute(self):
        Popen = MockPopen()
        Popen.set_command('command')
        process = Popen('command')
        with ShouldRaise(AttributeError("Mock object has no attribute 'foo'")):
            process.foo

    def test_invalid_communicate_call(self):
        Popen = MockPopen()
        Popen.set_command('bar')
        process = Popen('bar')
        with ShouldRaise(TypeError(
                "communicate() got an unexpected keyword argument 'foo'"
        )):
            process.communicate(foo='bar')

    def test_invalid_wait_call(self):
        Popen = MockPopen()
        Popen.set_command('bar')
        process = Popen('bar')
        with ShouldRaise(TypeError(
                "wait() got an unexpected keyword argument 'foo'"
        )):
            process.wait(foo='bar')

    def test_invalid_send_signal(self):
        Popen = MockPopen()
        Popen.set_command('bar')
        process = Popen('bar')
        with ShouldRaise(TypeError(
                "send_signal() got an unexpected keyword argument 'foo'"
        )):
            process.send_signal(foo='bar')

    def test_invalid_terminate(self):
        Popen = MockPopen()
        Popen.set_command('bar')
        process = Popen('bar')
        with ShouldRaise(TypeError(
                "terminate() got an unexpected keyword argument 'foo'"
        )):
            process.terminate(foo='bar')

    def test_invalid_kill(self):
        Popen = MockPopen()
        Popen.set_command('bar')
        process = Popen('bar')
        if PY2:
            text = 'kill() takes exactly 1 argument (2 given)'
        else:
            text = 'kill() takes 1 positional argument but 2 were given'
        with ShouldRaise(TypeError(text)):
            process.kill('moo')

    def test_invalid_poll(self):
        Popen = MockPopen()
        Popen.set_command('bar')
        process = Popen('bar')
        if PY2:
            text = 'poll() takes exactly 1 argument (2 given)'
        else:
            text = 'poll() takes 1 positional argument but 2 were given'
        with ShouldRaise(TypeError(text)):
            process.poll('moo')

    def test_non_pipe(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command')
        # usage
        process = Popen('a command')
        # checks
        compare(process.stdout, expected=None)
        compare(process.stderr, expected=None)
        out, err = process.communicate()
        # test the rest
        compare(out, expected=None)
        compare(err, expected=None)
        # test call list
        compare([
                call.Popen('a command'),
                call.Popen_instance.communicate(),
                ], Popen.mock.method_calls)

    def test_use_as_context_manager(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command')
        if PY2:

            process = Popen('a command')
            with ShouldRaise(AttributeError):
                process.__enter__
            with ShouldRaise(AttributeError):
                process.__exit__

        else:

            # usage
            with Popen('a command', stdout=PIPE, stderr=PIPE) as process:
                # process started, no return code
                compare(process.pid, 1234)
                compare(None, process.returncode)

                out, err = process.communicate()

            # test the rest
            compare(out, b'')
            compare(err, b'')
            compare(process.returncode, 0)

            compare(process.stdout.closed, expected=True)
            compare(process.stderr.closed, expected=True)

            # test call list
            compare([
                call.Popen('a command', stderr=-1, stdout=-1),
                call.Popen_instance.communicate(),
                call.Popen_instance.wait(),
            ], Popen.mock.method_calls)

    def test_start_new_session(self):
        # setup
        Popen = MockPopen()
        Popen.set_command('a command')
        # usage
        Popen('a command', start_new_session=True)
        # test call list
        compare([
            call.Popen('a command', start_new_session=True),
        ], Popen.mock.method_calls)


text:
require 'puppet/ssl'
require 'puppet/ssl/certificate'

# Keep track of all of our known certificates.
class Puppet::SSL::Inventory
  attr_reader :path

  # Add a certificate to our inventory.
  def add(cert)
    cert = cert.content if cert.is_a?(Puppet::SSL::Certificate)
    Puppet.settings.setting(:cert_inventory).open("a") do |f|
      f.print format(cert)
    end
  end

  # Format our certificate for output.
  def format(cert)
    iso = '%Y-%m-%dT%H:%M:%S%Z'
    "0x%04x %s %s %s\n" % [cert.serial,  cert.not_before.strftime(iso), cert.not_after.strftime(iso), cert.subject]
  end

  def initialize
    @path = Puppet[:cert_inventory]
  end

  # Rebuild the inventory from scratch.  This should happen if
  # the file is entirely missing or if it's somehow corrupted.
  def rebuild
    Puppet.notice "Rebuilding inventory file"

    Puppet.settings.setting(:cert_inventory).open('w') do |f|
      Puppet::SSL::Certificate.indirection.search("*").each do |cert|
        f.print format(cert.content)
      end
    end
  end

  # Find the serial number for a given certificate.
  def serial(name)
    return nil unless Puppet::FileSystem.exist?(@path)

    File.readlines(@path).each do |line|
      next unless line =~ /^(\S+).+\/CN=#{name}$/

      return Integer($1)
    end

    return nil
  end
end


text:
package javax.xml.xquery;

import java.io.Serializable;

import javax.xml.namespace.QName;

/**
 * XQJ interfaces reconstructed from version 0.5 documentation
 */
public class XQStackTraceVariable implements Serializable {
    private QName qname;
    private String value;

    XQStackTraceVariable(QName qname, java.lang.String value) {
        this.qname = qname;
        this.value = value;
    }

    public QName getQName() {
        return qname;
    }

    public String getValue() {
        return value;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Web.Caching;
using Moq;
using NUnit.Framework;
using Umbraco.Core.Cache;
using Umbraco.Core.Models;

namespace Umbraco.Tests.Cache
{
    [TestFixture]
    public class DefaultCachePolicyTests
    {
        [Test]
        public void Caches_Single()
        {
            var isCached = false;
            var cache = new Mock<IRuntimeCacheProvider>();
            cache.Setup(x => x.InsertCacheItem(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(),
                It.IsAny<CacheItemPriority>(), It.IsAny<CacheItemRemovedCallback>(), It.IsAny<string[]>()))
                .Callback(() =>
                {
                    isCached = true;
                });

            var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());

            var found = defaultPolicy.Get(1, id => new AuditItem(1, "blah", AuditType.Copy, 123), o => null);
            Assert.IsTrue(isCached);
        }

        [Test]
        public void Get_Single_From_Cache()
        {
            var cache = new Mock<IRuntimeCacheProvider>();
            cache.Setup(x => x.GetCacheItem(It.IsAny<string>())).Returns(new AuditItem(1, "blah", AuditType.Copy, 123));

            var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());

            var found = defaultPolicy.Get(1, id => null, ids => null);
            Assert.IsNotNull(found);
        }

        [Test]
        public void Caches_Per_Id_For_Get_All()
        {
            var cached = new List<string>();
            var cache = new Mock<IRuntimeCacheProvider>();
            cache.Setup(x => x.InsertCacheItem(It.IsAny<string>(), It.IsAny<Func<object>>(), It.IsAny<TimeSpan?>(), It.IsAny<bool>(),
                It.IsAny<CacheItemPriority>(), It.IsAny<CacheItemRemovedCallback>(), It.IsAny<string[]>()))
                .Callback((string cacheKey, Func<object> o, TimeSpan? t, bool b, CacheItemPriority cip, CacheItemRemovedCallback circ, string[] s) =>
                {
                    cached.Add(cacheKey);
                });
            cache.Setup(x => x.GetCacheItemsByKeySearch(It.IsAny<string>())).Returns(new AuditItem[] {});

            var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());

            var found = defaultPolicy.GetAll(new object[] { }, ids => new[]
            {
                new AuditItem(1, "blah", AuditType.Copy, 123),
                new AuditItem(2, "blah2", AuditType.Copy, 123)
            });

            Assert.AreEqual(2, cached.Count);
        }

        [Test]
        public void Get_All_Without_Ids_From_Cache()
        {
            var cache = new Mock<IRuntimeCacheProvider>();
            cache.Setup(x => x.GetCacheItemsByKeySearch(It.IsAny<string>())).Returns(new[]
            {
                new AuditItem(1, "blah", AuditType.Copy, 123),
                new AuditItem(2, "blah2", AuditType.Copy, 123)
            });

            var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());

            var found = defaultPolicy.GetAll(new object[] { }, ids => new[] { (AuditItem)null });
            Assert.AreEqual(2, found.Length);
        }

        [Test]
        public void If_CreateOrUpdate_Throws_Cache_Is_Removed()
        {
            var cacheCleared = false;
            var cache = new Mock<IRuntimeCacheProvider>();
            cache.Setup(x => x.ClearCacheItem(It.IsAny<string>()))
                .Callback(() =>
                {
                    cacheCleared = true;
                });

            var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());
            try
            {
                defaultPolicy.Update(new AuditItem(1, "blah", AuditType.Copy, 123), item => { throw new Exception("blah!"); });
            }
            catch
            {
                //we need this catch or nunit throw up
            }
            finally
            {
                Assert.IsTrue(cacheCleared);
            }
        }

        [Test]
        public void If_Removes_Throws_Cache_Is_Removed()
        {
            var cacheCleared = false;
            var cache = new Mock<IRuntimeCacheProvider>();
            cache.Setup(x => x.ClearCacheItem(It.IsAny<string>()))
                .Callback(() =>
                {
                    cacheCleared = true;
                });

            var defaultPolicy = new DefaultRepositoryCachePolicy<AuditItem, object>(cache.Object, new RepositoryCachePolicyOptions());
            try
            {
                defaultPolicy.Delete(new AuditItem(1, "blah", AuditType.Copy, 123), item => { throw new Exception("blah!"); });
            }
            catch
            {
                //we need this catch or nunit throw up
            }
            finally
            {
                Assert.IsTrue(cacheCleared);
            }
        }
    }
}


text:
package com.owolp.comicsand.ui.libraries;

import com.owolp.comicsand.data.model.seed.Library;
import com.owolp.comicsand.ui.base.MvpPresenter;
import com.owolp.comicsand.ui.base.MvpView;
import java.util.List;

public interface LibrariesContracts {
  interface Presenter<V> extends MvpPresenter<LibrariesContracts.View> {
  }

  interface View extends MvpView {
    void setLibraries(List<Library> libraries);

    void showProgress();

    void hideProgress();
  }
}


text:
package com.linecorp.armeria.common.brave;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

import java.util.Collections;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;

import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.RequestContext;
import com.linecorp.armeria.common.util.SafeCloseable;
import com.linecorp.armeria.internal.common.brave.TraceContextUtil;
import com.linecorp.armeria.internal.common.brave.TraceContextUtil.PingPongExtra;
import com.linecorp.armeria.server.ServiceRequestContext;

import brave.propagation.CurrentTraceContext;
import brave.propagation.CurrentTraceContext.Scope;
import brave.propagation.TraceContext;
import io.netty.channel.EventLoop;

@MockitoSettings(strictness = Strictness.LENIENT)
class RequestContextCurrentTraceContextTest {

    RequestContext ctx;
    @Mock
    EventLoop eventLoop;

    private static final CurrentTraceContext currentTraceContext =
            RequestContextCurrentTraceContext.ofDefault();
    private static final TraceContext traceContext = TraceContext.newBuilder().traceId(1).spanId(1).build();

    @BeforeEach
    void setUp() {
        when(eventLoop.inEventLoop()).thenReturn(true);
        ctx = ServiceRequestContext.builder(HttpRequest.of(HttpMethod.GET, "/"))
                                   .eventLoop(eventLoop)
                                   .build();
    }

    @Test
    public void get_returnsNullWhenNoCurrentRequestContext() {
        assertThat(currentTraceContext.get()).isNull();
    }

    @Test
    public void get_returnsNullWhenCurrentRequestContext_hasNoTraceAttribute() {
        try (SafeCloseable requestContextScope = ctx.push()) {
            assertThat(currentTraceContext.get()).isNull();
        }
    }

    @Test
    public void newScope_appliesWhenNoCurrentRequestContext() {
        try (Scope traceContextScope = currentTraceContext.newScope(traceContext)) {
            assertThat(traceContextScope).hasToString("ThreadLocalScope");
            assertThat(currentTraceContext.get()).isEqualTo(traceContext);
        }
    }

    @Test
    public void newScope_appliesWhenCurrentRequestContext() {
        try (SafeCloseable requestContextScope = ctx.push()) {
            try (Scope traceContextScope = currentTraceContext.newScope(traceContext)) {
                assertThat(traceContextScope).hasToString("InitialRequestScope");
                assertThat(currentTraceContext.get()).isEqualTo(traceContext);
            }
        }
    }

    @Test
    public void newScope_closeDoesntClearFirstScope() {
        final TraceContext traceContext2 = TraceContext.newBuilder().traceId(1).spanId(2).build();

        try (SafeCloseable requestContextScope = ctx.push()) {
            try (Scope traceContextScope = currentTraceContext.newScope(traceContext)) {
                assertThat(traceContextScope).hasToString("InitialRequestScope");
                assertThat(currentTraceContext.get()).isEqualTo(traceContext);

                try (Scope traceContextScope2 = currentTraceContext.newScope(traceContext2)) {
                    assertThat(traceContextScope2).hasToString("RequestContextTraceContextScope");
                    assertThat(currentTraceContext.get()).isEqualTo(traceContext2);
                }
                assertThat(currentTraceContext.get()).isEqualTo(traceContext);
            }
            // the first scope is attached to the request context and cleared when that's destroyed
            assertThat(currentTraceContext.get()).isEqualTo(traceContext);
        }
    }

    @Test
    public void newScope_notOnEventLoop() {
        final TraceContext traceContext2 = TraceContext.newBuilder().traceId(1).spanId(2).build();

        try (SafeCloseable requestContextScope = ctx.push()) {
            try (Scope traceContextScope = currentTraceContext.newScope(traceContext)) {
                assertThat(traceContextScope).hasToString("InitialRequestScope");
                assertThat(currentTraceContext.get()).isEqualTo(traceContext);

                when(eventLoop.inEventLoop()).thenReturn(false);
                try (Scope traceContextScope2 = currentTraceContext.newScope(traceContext2)) {
                    assertThat(traceContextScope2).hasToString("ThreadLocalScope");
                    assertThat(currentTraceContext.get()).isEqualTo(traceContext2);
                }
                when(eventLoop.inEventLoop()).thenReturn(true);
                assertThat(currentTraceContext.get()).isEqualTo(traceContext);
            }
            // the first scope is attached to the request context and cleared when that's destroyed
            assertThat(currentTraceContext.get()).isEqualTo(traceContext);
        }
    }

    @Test
    public void newScope_canClearScope() {
        try (SafeCloseable requestContextScope = ctx.push()) {
            try (Scope traceContextScope = currentTraceContext.newScope(traceContext)) {
                try (Scope traceContextScope2 = currentTraceContext.newScope(null)) {
                    assertThat(currentTraceContext.get()).isNull();
                }
                assertThat(currentTraceContext.get()).isEqualTo(traceContext);
            }
        }
    }

    @Test
    public void newScope_respondsToPing() {
        final PingPongExtra extra = new PingPongExtra();
        final TraceContext extraContext = TraceContext.newBuilder().traceId(1).spanId(1)
                                                      .extra(Collections.singletonList(extra)).build();

        try (Scope traceContextScope = currentTraceContext.newScope(extraContext)) {
            assertThat(traceContextScope).hasToString("NoopScope");
            assertThat(extra.isPong()).isTrue();
        }
    }

    @Test
    public void shouldSetPongIfOnlyExtra() {
        final PingPongExtra extra = new PingPongExtra();

        final TraceContext context = TraceContext.newBuilder().traceId(1).spanId(1)
                                                 .extra(Collections.singletonList(extra)).build();

        TraceContextUtil.PingPongExtra.maybeSetPong(context);

        assertThat(extra.isPong()).isTrue();
    }
}


text:
package org.springframework.boot.autoconfigure.mail;

import java.util.Map;
import java.util.Properties;

import javax.activation.MimeType;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration.MailSenderCondition;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

/**
 * {@link EnableAutoConfiguration Auto configuration} for email support.
 *
 * @author Oliver Gierke
 * @author Stephane Nicoll
 * @author Eddú Meléndez
 * @since 1.2.0
 */
@Configuration
@ConditionalOnClass({ MimeMessage.class, MimeType.class })
@ConditionalOnMissingBean(MailSender.class)
@Conditional(MailSenderCondition.class)
@EnableConfigurationProperties(MailProperties.class)
@Import(JndiSessionConfiguration.class)
public class MailSenderAutoConfiguration {

	@Autowired
	private MailProperties properties;

	@Autowired(required = false)
	private Session session;

	@Bean
	public JavaMailSenderImpl mailSender() {
		JavaMailSenderImpl sender = new JavaMailSenderImpl();
		if (this.session != null) {
			sender.setSession(this.session);
		}
		else {
			applyProperties(sender);
		}
		return sender;
	}

	private void applyProperties(JavaMailSenderImpl sender) {
		sender.setHost(this.properties.getHost());
		if (this.properties.getPort() != null) {
			sender.setPort(this.properties.getPort());
		}
		sender.setUsername(this.properties.getUsername());
		sender.setPassword(this.properties.getPassword());
		sender.setProtocol(this.properties.getProtocol());
		if (this.properties.getDefaultEncoding() != null) {
			sender.setDefaultEncoding(this.properties.getDefaultEncoding().name());
		}
		if (!this.properties.getProperties().isEmpty()) {
			sender.setJavaMailProperties(asProperties(this.properties.getProperties()));
		}
	}

	private Properties asProperties(Map<String, String> source) {
		Properties properties = new Properties();
		properties.putAll(source);
		return properties;
	}

	/**
	 * Condition to trigger the creation of a {@link JavaMailSenderImpl}. This kicks in if
	 * either the host or jndi name property is set.
	 */
	static class MailSenderCondition extends AnyNestedCondition {

		MailSenderCondition() {
			super(ConfigurationPhase.PARSE_CONFIGURATION);
		}

		@ConditionalOnProperty(prefix = "spring.mail", name = "host")
		static class HostProperty {
		}

		@ConditionalOnProperty(prefix = "spring.mail", name = "jndi-name")
		static class JndiNameProperty {
		}

	}

}