text:
#include <grpc/support/port_platform.h>

#include "src/core/lib/iomgr/port.h"

#include <limits.h>
#include <string.h>

#include <grpc/slice_buffer.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>

#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/iomgr_custom.h"
#include "src/core/lib/iomgr/resource_quota.h"
#include "src/core/lib/iomgr/tcp_client.h"
#include "src/core/lib/iomgr/tcp_custom.h"
#include "src/core/lib/iomgr/tcp_server.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/slice/slice_string_helpers.h"

#define GRPC_TCP_DEFAULT_READ_SLICE_SIZE 8192

extern grpc_core::TraceFlag grpc_tcp_trace;

grpc_socket_vtable* grpc_custom_socket_vtable = nullptr;
extern grpc_tcp_server_vtable custom_tcp_server_vtable;
extern grpc_tcp_client_vtable custom_tcp_client_vtable;

void grpc_custom_endpoint_init(grpc_socket_vtable* impl) {
  grpc_custom_socket_vtable = impl;
  grpc_set_tcp_client_impl(&custom_tcp_client_vtable);
  grpc_set_tcp_server_impl(&custom_tcp_server_vtable);
}

typedef struct {
  grpc_endpoint base;
  gpr_refcount refcount;
  grpc_custom_socket* socket;

  grpc_closure* read_cb;
  grpc_closure* write_cb;

  grpc_slice_buffer* read_slices;
  grpc_slice_buffer* write_slices;

  grpc_resource_user* resource_user;
  grpc_resource_user_slice_allocator slice_allocator;

  bool shutting_down;

  char* peer_string;
} custom_tcp_endpoint;

static void tcp_free(grpc_custom_socket* s) {
  custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)s->endpoint;
  grpc_resource_user_unref(tcp->resource_user);
  gpr_free(tcp->peer_string);
  gpr_free(tcp);
  s->refs--;
  if (s->refs == 0) {
    grpc_custom_socket_vtable->destroy(s);
    gpr_free(s);
  }
}

#ifndef NDEBUG
#define TCP_UNREF(tcp, reason) tcp_unref((tcp), (reason), __FILE__, __LINE__)
#define TCP_REF(tcp, reason) tcp_ref((tcp), (reason), __FILE__, __LINE__)
static void tcp_unref(custom_tcp_endpoint* tcp, const char* reason,
                      const char* file, int line) {
  if (grpc_tcp_trace.enabled()) {
    gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
    gpr_log(file, line, GPR_LOG_SEVERITY_ERROR,
            "TCP unref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp->socket, reason,
            val, val - 1);
  }
  if (gpr_unref(&tcp->refcount)) {
    tcp_free(tcp->socket);
  }
}

static void tcp_ref(custom_tcp_endpoint* tcp, const char* reason,
                    const char* file, int line) {
  if (grpc_tcp_trace.enabled()) {
    gpr_atm val = gpr_atm_no_barrier_load(&tcp->refcount.count);
    gpr_log(file, line, GPR_LOG_SEVERITY_ERROR,
            "TCP   ref %p : %s %" PRIdPTR " -> %" PRIdPTR, tcp->socket, reason,
            val, val + 1);
  }
  gpr_ref(&tcp->refcount);
}
#else
#define TCP_UNREF(tcp, reason) tcp_unref((tcp))
#define TCP_REF(tcp, reason) tcp_ref((tcp))
static void tcp_unref(custom_tcp_endpoint* tcp) {
  if (gpr_unref(&tcp->refcount)) {
    tcp_free(tcp->socket);
  }
}

static void tcp_ref(custom_tcp_endpoint* tcp) { gpr_ref(&tcp->refcount); }
#endif

static void call_read_cb(custom_tcp_endpoint* tcp, grpc_error* error) {
  grpc_closure* cb = tcp->read_cb;
  if (grpc_tcp_trace.enabled()) {
    gpr_log(GPR_INFO, "TCP:%p call_cb %p %p:%p", tcp->socket, cb, cb->cb,
            cb->cb_arg);
    size_t i;
    const char* str = grpc_error_string(error);
    gpr_log(GPR_INFO, "read: error=%s", str);

    for (i = 0; i < tcp->read_slices->count; i++) {
      char* dump = grpc_dump_slice(tcp->read_slices->slices[i],
                                   GPR_DUMP_HEX | GPR_DUMP_ASCII);
      gpr_log(GPR_INFO, "READ %p (peer=%s): %s", tcp, tcp->peer_string, dump);
      gpr_free(dump);
    }
  }
  TCP_UNREF(tcp, "read");
  tcp->read_slices = nullptr;
  tcp->read_cb = nullptr;
  GRPC_CLOSURE_SCHED(cb, error);
}

static void custom_read_callback(grpc_custom_socket* socket, size_t nread,
                                 grpc_error* error) {
  grpc_core::ExecCtx exec_ctx;
  grpc_slice_buffer garbage;
  custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)socket->endpoint;
  if (error == GRPC_ERROR_NONE && nread == 0) {
    error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("EOF");
  }
  if (error == GRPC_ERROR_NONE) {
    // Successful read
    if ((size_t)nread < tcp->read_slices->length) {
      /* TODO(murgatroid99): Instead of discarding the unused part of the read
       * buffer, reuse it as the next read buffer. */
      grpc_slice_buffer_init(&garbage);
      grpc_slice_buffer_trim_end(
          tcp->read_slices, tcp->read_slices->length - (size_t)nread, &garbage);
      grpc_slice_buffer_reset_and_unref_internal(&garbage);
    }
  } else {
    grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices);
  }
  call_read_cb(tcp, error);
}

static void tcp_read_allocation_done(void* tcpp, grpc_error* error) {
  custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)tcpp;
  if (grpc_tcp_trace.enabled()) {
    gpr_log(GPR_INFO, "TCP:%p read_allocation_done: %s", tcp->socket,
            grpc_error_string(error));
  }
  if (error == GRPC_ERROR_NONE) {
    /* Before calling read, we allocate a buffer with exactly one slice
     * to tcp->read_slices and wait for the callback indicating that the
     * allocation was successful. So slices[0] should always exist here */
    char* buffer = (char*)GRPC_SLICE_START_PTR(tcp->read_slices->slices[0]);
    size_t len = GRPC_SLICE_LENGTH(tcp->read_slices->slices[0]);
    grpc_custom_socket_vtable->read(tcp->socket, buffer, len,
                                    custom_read_callback);
  } else {
    grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices);
    call_read_cb(tcp, GRPC_ERROR_REF(error));
  }
  if (grpc_tcp_trace.enabled()) {
    const char* str = grpc_error_string(error);
    gpr_log(GPR_INFO, "Initiating read on %p: error=%s", tcp->socket, str);
  }
}

static void endpoint_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices,
                          grpc_closure* cb) {
  custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
  GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();
  GPR_ASSERT(tcp->read_cb == nullptr);
  tcp->read_cb = cb;
  tcp->read_slices = read_slices;
  grpc_slice_buffer_reset_and_unref_internal(read_slices);
  TCP_REF(tcp, "read");
  grpc_resource_user_alloc_slices(&tcp->slice_allocator,
                                  GRPC_TCP_DEFAULT_READ_SLICE_SIZE, 1,
                                  tcp->read_slices);
}

static void custom_write_callback(grpc_custom_socket* socket,
                                  grpc_error* error) {
  grpc_core::ExecCtx exec_ctx;
  custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)socket->endpoint;
  grpc_closure* cb = tcp->write_cb;
  tcp->write_cb = nullptr;
  if (grpc_tcp_trace.enabled()) {
    const char* str = grpc_error_string(error);
    gpr_log(GPR_INFO, "write complete on %p: error=%s", tcp->socket, str);
  }
  TCP_UNREF(tcp, "write");
  GRPC_CLOSURE_SCHED(cb, error);
}

static void endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* write_slices,
                           grpc_closure* cb, void* arg) {
  custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
  GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD();

  if (grpc_tcp_trace.enabled()) {
    size_t j;

    for (j = 0; j < write_slices->count; j++) {
      char* data = grpc_dump_slice(write_slices->slices[j],
                                   GPR_DUMP_HEX | GPR_DUMP_ASCII);
      gpr_log(GPR_INFO, "WRITE %p (peer=%s): %s", tcp->socket, tcp->peer_string,
              data);
      gpr_free(data);
    }
  }

  if (tcp->shutting_down) {
    GRPC_CLOSURE_SCHED(cb, GRPC_ERROR_CREATE_FROM_STATIC_STRING(
                               "TCP socket is shutting down"));
    return;
  }

  GPR_ASSERT(tcp->write_cb == nullptr);
  tcp->write_slices = write_slices;
  GPR_ASSERT(tcp->write_slices->count <= UINT_MAX);
  if (tcp->write_slices->count == 0) {
    // No slices means we don't have to do anything,
    // and libuv doesn't like empty writes
    GRPC_CLOSURE_SCHED(cb, GRPC_ERROR_NONE);
    return;
  }
  tcp->write_cb = cb;
  TCP_REF(tcp, "write");
  grpc_custom_socket_vtable->write(tcp->socket, tcp->write_slices,
                                   custom_write_callback);
}

static void endpoint_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) {
  // No-op. We're ignoring pollsets currently
  (void)ep;
  (void)pollset;
}

static void endpoint_add_to_pollset_set(grpc_endpoint* ep,
                                        grpc_pollset_set* pollset) {
  // No-op. We're ignoring pollsets currently
  (void)ep;
  (void)pollset;
}

static void endpoint_delete_from_pollset_set(grpc_endpoint* ep,
                                             grpc_pollset_set* pollset) {
  // No-op. We're ignoring pollsets currently
  (void)ep;
  (void)pollset;
}

static void endpoint_shutdown(grpc_endpoint* ep, grpc_error* why) {
  custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
  if (!tcp->shutting_down) {
    if (grpc_tcp_trace.enabled()) {
      const char* str = grpc_error_string(why);
      gpr_log(GPR_INFO, "TCP %p shutdown why=%s", tcp->socket, str);
    }
    tcp->shutting_down = true;
    // GRPC_CLOSURE_SCHED(tcp->read_cb, GRPC_ERROR_REF(why));
    // GRPC_CLOSURE_SCHED(tcp->write_cb, GRPC_ERROR_REF(why));
    // tcp->read_cb = nullptr;
    // tcp->write_cb = nullptr;
    grpc_resource_user_shutdown(tcp->resource_user);
    grpc_custom_socket_vtable->shutdown(tcp->socket);
  }
  GRPC_ERROR_UNREF(why);
}

static void custom_close_callback(grpc_custom_socket* socket) {
  socket->refs--;
  if (socket->refs == 0) {
    grpc_custom_socket_vtable->destroy(socket);
    gpr_free(socket);
  } else if (socket->endpoint) {
    grpc_core::ExecCtx exec_ctx;
    custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)socket->endpoint;
    TCP_UNREF(tcp, "destroy");
  }
}

static void endpoint_destroy(grpc_endpoint* ep) {
  custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
  grpc_custom_socket_vtable->close(tcp->socket, custom_close_callback);
}

static char* endpoint_get_peer(grpc_endpoint* ep) {
  custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
  return gpr_strdup(tcp->peer_string);
}

static grpc_resource_user* endpoint_get_resource_user(grpc_endpoint* ep) {
  custom_tcp_endpoint* tcp = (custom_tcp_endpoint*)ep;
  return tcp->resource_user;
}

static int endpoint_get_fd(grpc_endpoint* ep) { return -1; }

static bool endpoint_can_track_err(grpc_endpoint* ep) { return false; }

static grpc_endpoint_vtable vtable = {endpoint_read,
                                      endpoint_write,
                                      endpoint_add_to_pollset,
                                      endpoint_add_to_pollset_set,
                                      endpoint_delete_from_pollset_set,
                                      endpoint_shutdown,
                                      endpoint_destroy,
                                      endpoint_get_resource_user,
                                      endpoint_get_peer,
                                      endpoint_get_fd,
                                      endpoint_can_track_err};

grpc_endpoint* custom_tcp_endpoint_create(grpc_custom_socket* socket,
                                          grpc_resource_quota* resource_quota,
                                          char* peer_string) {
  custom_tcp_endpoint* tcp =
      (custom_tcp_endpoint*)gpr_malloc(sizeof(custom_tcp_endpoint));
  grpc_core::ExecCtx exec_ctx;

  if (grpc_tcp_trace.enabled()) {
    gpr_log(GPR_INFO, "Creating TCP endpoint %p", socket);
  }
  memset(tcp, 0, sizeof(custom_tcp_endpoint));
  socket->refs++;
  socket->endpoint = (grpc_endpoint*)tcp;
  tcp->socket = socket;
  tcp->base.vtable = &vtable;
  gpr_ref_init(&tcp->refcount, 1);
  tcp->peer_string = gpr_strdup(peer_string);
  tcp->shutting_down = false;
  tcp->resource_user = grpc_resource_user_create(resource_quota, peer_string);
  grpc_resource_user_slice_allocator_init(
      &tcp->slice_allocator, tcp->resource_user, tcp_read_allocation_done, tcp);

  return &tcp->base;
}


text:
package com.icegreen.greenmail.imap.commands;

import com.icegreen.greenmail.imap.*;
import com.icegreen.greenmail.store.FolderException;
import com.icegreen.greenmail.store.FolderListener;

import javax.mail.Flags;

/**
 * Handles processeing for the STORE imap command.
 *
 * @author Darrell DeBoer <darrell@apache.org>
 * @version $Revision: 109034 $
 */
class StoreCommand extends SelectedStateCommand implements UidEnabledCommand {
    public static final String NAME = "STORE";
    public static final String ARGS = "<Message-set> ['+'|'-']FLAG[.SILENT] <flag-list>";

    private final StoreCommandParser parser = new StoreCommandParser();

    StoreCommand() {
        super(NAME, ARGS);
    }

    @Override
    protected void doProcess(ImapRequestLineReader request,
                             ImapResponse response,
                             ImapSession session)
            throws ProtocolException, FolderException {
        doProcess(request, response, session, false);
    }

    @Override
    public void doProcess(ImapRequestLineReader request,
                          ImapResponse response,
                          ImapSession session,
                          boolean useUids)
            throws ProtocolException, FolderException {
        IdRange[] idSet = parser.parseIdRange(request);
        StoreDirective directive = parser.storeDirective(request);
        Flags flags = parser.flagList(request);
        parser.endLine(request);

        ImapSessionFolder mailbox = session.getSelected();
//        IdRange[] uidSet;
//        if (useUids) {
//           uidSet = idSet;
//        } else {
//            uidSet = mailbox.msnsToUids(idSet);
//        }
//        if (directive.getSign() < 0) {
//            mailbox.setFlags(flags, false, uidSet, directive.isSilent());
//        }
//        else if (directive.getSign() > 0) {
//            mailbox.setFlags(flags, true, uidSet, directive.isSilent());
//        }
//        else {
//            mailbox.replaceFlags(flags, uidSet, directive.isSilent());
//        }

        FolderListener silentListener = null;
        if (directive.isSilent()) {
            silentListener = mailbox;
        }

        // TODO do this in one hit.
        long[] uids = mailbox.getMessageUids();
        for (long uid : uids) {
            int msn = mailbox.getMsn(uid);

            if ((useUids && includes(idSet, uid)) ||
                    (!useUids && includes(idSet, msn))) {
                if (directive.getSign() < 0) {
                    mailbox.setFlags(flags, false, uid, silentListener, useUids);
                } else if (directive.getSign() > 0) {
                    mailbox.setFlags(flags, true, uid, silentListener, useUids);
                } else {
                    mailbox.replaceFlags(flags, uid, silentListener, useUids);
                }
            }
        }

        boolean omitExpunged = !useUids;
        session.unsolicitedResponses(response, omitExpunged);
        response.commandComplete(this);
    }

    private static class StoreCommandParser extends CommandParser {
        StoreDirective storeDirective(ImapRequestLineReader request) throws ProtocolException {
            int sign = 0;
            boolean silent = false;

            char next = request.nextWordChar();
            if (next == '+') {
                sign = 1;
                request.consume();
            } else if (next == '-') {
                sign = -1;
                request.consume();
            } else {
                sign = 0;
            }

            String directive = consumeWord(request, new NoopCharValidator());
            if ("FLAGS".equalsIgnoreCase(directive)) {
                silent = false;
            } else if ("FLAGS.SILENT".equalsIgnoreCase(directive)) {
                silent = true;
            } else {
                throw new ProtocolException("Invalid Store Directive: '" + directive + '\'');
            }
            return new StoreDirective(sign, silent);
        }
    }

    private static class StoreDirective {
        private int sign;
        private boolean silent;

        public StoreDirective(int sign, boolean silent) {
            this.sign = sign;
            this.silent = silent;
        }

        public int getSign() {
            return sign;
        }

        public boolean isSilent() {
            return silent;
        }
    }
}

/*
6.4.6.  STORE Command

   Arguments:  message set
               message data item name
               value for message data item

   Responses:  untagged responses: FETCH

   Result:     OK - store completed
               NO - store error: can't store that data
               BAD - command unknown or arguments invalid

      The STORE command alters data associated with a message in the
      mailbox.  Normally, STORE will return the updated value of the
      data with an untagged FETCH response.  A suffix of ".SILENT" in
      the data item name prevents the untagged FETCH, and the server
      SHOULD assume that the client has determined the updated value
      itself or does not care about the updated value.

         Note: regardless of whether or not the ".SILENT" suffix was
         used, the server SHOULD send an untagged FETCH response if a
         change to a message's flags from an external source is
         observed.  The intent is that the status of the flags is
         determinate without a race condition.

      The currently defined data items that can be stored are:

      FLAGS <flag list>
                     Replace the flags for the message with the
                     argument.  The new value of the flags are returned
                     as if a FETCH of those flags was done.

      FLAGS.SILENT <flag list>
                     Equivalent to FLAGS, but without returning a new
                     value.

      +FLAGS <flag list>
                     Add the argument to the flags for the message.  The
                     new value of the flags are returned as if a FETCH
                     of those flags was done.

      +FLAGS.SILENT <flag list>
                     Equivalent to +FLAGS, but without returning a new
                     value.

      -FLAGS <flag list>
                     Remove the argument from the flags for the message.
                     The new value of the flags are returned as if a
                     FETCH of those flags was done.

      -FLAGS.SILENT <flag list>
                     Equivalent to -FLAGS, but without returning a new
                     value.

   Example:    C: A003 STORE 2:4 +FLAGS (\Deleted)
               S: * 2 FETCH FLAGS (\Deleted \Seen)
               S: * 3 FETCH FLAGS (\Deleted)
               S: * 4 FETCH FLAGS (\Deleted \Flagged \Seen)
               S: A003 OK STORE completed

*/

redpajama_set_name: RedPajamaGithub


text:
package com.dremio.service.commandpool;

import java.time.Duration;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

import org.awaitility.Awaitility;
import org.junit.Assert;
import org.junit.Test;

import com.dremio.common.util.Closeable;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;

import io.opentracing.noop.NoopTracerFactory;

/**
 * Tests for {@link ReleasableBoundCommandPool}
 */
public class TestReleasableBoundCommandPool extends TestBoundCommandPool {
  private final AtomicInteger counter = new AtomicInteger(0);

  @Override
  CommandPool newTestCommandPool() {
    return createReleasableCommandPool(1);
  }

  ReleasableBoundCommandPool createReleasableCommandPool(int size) {
    return new ReleasableBoundCommandPool(size, NoopTracerFactory.create());
  }

  // This tests for the following:
  // A max of poolSize threads are scheduled at any point of time. The remaining are queued
  // The set of threadIds tracked by the ReleasableBoundCommandPool tracks the threadIds correctly
  @Test
  public void testPoolSizeAndThreadIds() throws Exception {
    // create a command pool of size 2
    ReleasableBoundCommandPool commandPool = createReleasableCommandPool(2);

    // create block commands that can be unblocked one by one
    List<CommandPool.Command<?>> allCommands = Lists.newArrayList();
    List<CommandPool.Command<?>> thread1Commands = Lists.newArrayList();
    List<CommandPool.Command<?>> thread2Commands = Lists.newArrayList();
    List<CommandPool.Command<?>> thread3Commands = Lists.newArrayList();

    BlockingCommand command;
    CountMaxAndCheckThreadIds countMax = new CountMaxAndCheckThreadIds(commandPool);
    for(int i = 0; i < 10; i++) {
      command = new BlockingCommand(countMax);
      allCommands.add(command);
      thread1Commands.add(command);

      command = new BlockingCommand(countMax);
      allCommands.add(command);
      thread2Commands.add(command);

      command = new BlockingCommand(countMax);
      allCommands.add(command);
      thread3Commands.add(command);
    }

    TaskSubmissionThread taskSubmissionThread1 = new TaskSubmissionThread(thread1Commands, commandPool, 1);
    TaskSubmissionThread taskSubmissionThread2 = new TaskSubmissionThread(thread2Commands, commandPool, 2);
    TaskSubmissionThread taskSubmissionThread3 = new TaskSubmissionThread(thread3Commands, commandPool, 3);

    // start all 3 threads
    taskSubmissionThread1.start();
    taskSubmissionThread2.start();
    taskSubmissionThread3.start();

    for(CommandPool.Command<?> task : allCommands) {
      BlockingCommand blockingCommand = (BlockingCommand)task;
      blockingCommand.unblock();
      Assert.assertTrue(countMax.maxCount <= 2);
      try {
        Thread.sleep(2);
      } catch (InterruptedException ie) {
      }
    }

    taskSubmissionThread1.join();
    taskSubmissionThread2.join();
    taskSubmissionThread3.join();
  }

  // This test tests releaseAndReacquireSlot API. The thread holding the slot releases and waits for a event
  @Test
  public void testReleaseAndWait() {
    ReleasableBoundCommandPool releasableBoundCommandPool = createReleasableCommandPool(1);

    ReleaseAndWaitCommand releaseAndWaitCommand = new ReleaseAndWaitCommand(releasableBoundCommandPool, new StartAndStop());
    CompletableFuture<?> future = releasableBoundCommandPool.submit(CommandPool.Priority.HIGH, "release-and-block", releaseAndWaitCommand, false);
    releaseAndWaitCommand.firstUnblock();
    releaseAndWaitCommand.secondUnblock();
    try {
      future.get();
    } catch (InterruptedException | ExecutionException | CancellationException e) {
      throw new RuntimeException(e);
    }
  }

  // This test tests releaseAndReacquireSlot API. The thread holding the slot releases and submits a task to
  // the command pool and waits for it to complete
  @Test
  public void testReleaseAndSubmitTask() {
    ReleasableBoundCommandPool releasableBoundCommandPool = createReleasableCommandPool(1);

    ReleaseAndResubmitTask releaseAndResubmitTask = new ReleaseAndResubmitTask(releasableBoundCommandPool, new StartAndStop());
    CompletableFuture<?> future = releasableBoundCommandPool.submit(CommandPool.Priority.HIGH, "release-and-submit", releaseAndResubmitTask, false);
    releaseAndResubmitTask.firstUnblock();
    releaseAndResubmitTask.secondUnblock();
    try {
      future.get();
    } catch (InterruptedException | ExecutionException | CancellationException e) {
      throw new RuntimeException(e);
    }
  }

  // test to ensure that the reacquiring waiter has higher priority than a regular task
  @Test
  public void testOrderingOfReAcquiringWaiters() throws Exception {
    ReleasableBoundCommandPool releasableBoundCommandPool = createReleasableCommandPool(1);

    counter.set(0);
    ReleaseAndResubmitTask releaseAndResubmitTask = new ReleaseAndResubmitTask(releasableBoundCommandPool, new StartAndStop());
    CompletableFuture<Integer> future = releasableBoundCommandPool.submit(CommandPool.Priority.HIGH, "release-and-submit", releaseAndResubmitTask, false);

    Thread.sleep(2);

    SimpleBlockingCommand blockingCommand1 = new SimpleBlockingCommand(releasableBoundCommandPool, new StartAndStop());
    CompletableFuture<Integer> future1 = releasableBoundCommandPool.submit(CommandPool.Priority.MEDIUM, "simple1", blockingCommand1, false);

    Thread.sleep(2);

    SimpleBlockingCommand blockingCommand2 = new SimpleBlockingCommand(releasableBoundCommandPool, new StartAndStop());
    CompletableFuture<Integer> future2 = releasableBoundCommandPool.submit(CommandPool.Priority.MEDIUM, "simple2", blockingCommand2, false);

    Thread.sleep(2);

    SimpleBlockingCommand blockingCommand3 = new SimpleBlockingCommand(releasableBoundCommandPool, new StartAndStop());
    CompletableFuture<Integer> future3 = releasableBoundCommandPool.submit(CommandPool.Priority.MEDIUM, "simple3", blockingCommand3, false);

    // will release the slot and submit a job
    // blockingCommand1 should run now
    releaseAndResubmitTask.firstUnblock();

    // wait till the new job submission is done
    Awaitility.await()
      .pollInterval(Duration.ofSeconds(1))
      .atMost(Duration.ofSeconds(50))
      .until(() -> releasableBoundCommandPool.getNumWaiters() == 3);

    // simpleBlockingCommand1 is done
    // 3 waiters: blockingCommand2, blockingCommand3 (MEDIUM priority) and the job submitted by releaseAndResubmitTask (HIGH priority)
    // after this unblock submitted task should run
    blockingCommand1.firstUnblock();

    // 2 waiters now: blockingCommand2 and blockingCommand3. blockingCommand2 should run
    // releaseAndResubmitTask is still not a waiter since close is not invoked
    releaseAndResubmitTask.secondUnblock();

    // ensure that releaseAndResubmitTask is in the waiter queue
    Awaitility.await()
      .pollInterval(Duration.ofSeconds(1))
      .atMost(Duration.ofSeconds(50))
      .until(() -> releasableBoundCommandPool.getReacquireWaiters() == 1);

    // this should give control to releaseAndResubmitTask
    blockingCommand2.firstUnblock();

    blockingCommand3.firstUnblock();

    Assert.assertEquals(1, (int)Futures.getUnchecked(future1));
    Assert.assertEquals(2, (int)Futures.getUnchecked(future2));
    Assert.assertEquals(3, (int)Futures.getUnchecked(future));
    Assert.assertEquals(4, (int)Futures.getUnchecked(future3));
  }

  List<ReleasingCommand> create3RandomTasks(int i, ReleasableBoundCommandPool commandPool, StartAndStop startAndStop) {
    ReleasingCommand cmd1;
    ReleasingCommand cmd2;
    ReleasingCommand cmd3;

    int reminder = (i % 3);
    if (reminder == 0) {
      cmd1 = new SimpleBlockingCommand(commandPool, startAndStop);
      cmd2 = new ReleaseAndResubmitTask(commandPool, startAndStop);
      cmd3 = new ReleaseAndWaitCommand(commandPool, startAndStop);
    } else if (reminder == 1) {
      cmd2 = new SimpleBlockingCommand(commandPool, startAndStop);
      cmd3 = new ReleaseAndResubmitTask(commandPool, startAndStop);
      cmd1 = new ReleaseAndWaitCommand(commandPool, startAndStop);
    } else {
      cmd3 = new SimpleBlockingCommand(commandPool, startAndStop);
      cmd1 = new ReleaseAndResubmitTask(commandPool, startAndStop);
      cmd2 = new ReleaseAndWaitCommand(commandPool, startAndStop);
    }

    return Lists.newArrayList(cmd1, cmd2, cmd3);
  }

  // test to ensure that when the API releaseAndReacquireSlot API is used, the number of active threads does not increase
  @Test
  public void testActiveThreads() throws Exception {
    ReleasableBoundCommandPool commandPool = createReleasableCommandPool(2);

    // create command that release and reacquire the slot
    List<CommandPool.Command<?>> allCommands = Lists.newArrayList();
    List<CommandPool.Command<?>> thread1Commands = Lists.newArrayList();
    List<CommandPool.Command<?>> thread2Commands = Lists.newArrayList();
    List<CommandPool.Command<?>> thread3Commands = Lists.newArrayList();

    CountMaxAndCheckThreadIds countMaxAndCheckThreadIds = new CountMaxAndCheckThreadIds(commandPool);
    for(int i = 0; i < 10; i++) {
      List<ReleasingCommand> tasks = create3RandomTasks(i, commandPool, countMaxAndCheckThreadIds);

      allCommands.addAll(tasks);
      thread1Commands.add(tasks.get(0));
      thread2Commands.add(tasks.get(1));
      thread3Commands.add(tasks.get(2));
    }

    TaskSubmissionThread thread1 = new TaskSubmissionThread(thread1Commands, commandPool, 1);
    TaskSubmissionThread thread2 = new TaskSubmissionThread(thread2Commands, commandPool, 2);
    TaskSubmissionThread thread3 = new TaskSubmissionThread(thread3Commands, commandPool, 3);

    // start all threads
    thread1.start();
    thread2.start();
    thread3.start();

    ReleasingCommand prevCmd = null;
    for(CommandPool.Command<?> cmd : allCommands) {
      ReleasingCommand currCmd = (ReleasingCommand) cmd;

      currCmd.firstUnblock();
      try {
        Thread.sleep(2);
      } catch (InterruptedException e) {
      }

      if (prevCmd != null) {
        prevCmd.secondUnblock();
        try {
          Thread.sleep(2);
        } catch (InterruptedException e) {
        }
      }

      prevCmd = currCmd;
      Assert.assertTrue(countMaxAndCheckThreadIds.maxCount <= 2);
    }

    prevCmd.secondUnblock();
    thread1.join();
    thread2.join();
    thread3.join();
  }

  // test jobs submitted using the same thread
  @Test
  public void testSubmitInSameThread() throws Exception {
    ReleasableBoundCommandPool releasableBoundCommandPool = createReleasableCommandPool(1);
    SubmitInSameThread submitInSameThread = new SubmitInSameThread(releasableBoundCommandPool);

    CompletableFuture<?> future = releasableBoundCommandPool.submit(CommandPool.Priority.HIGH, "submit-same-thread", submitInSameThread, false);
    Thread.sleep(2);
    submitInSameThread.firstUnblock();
    Thread.sleep(10);
    submitInSameThread.secondUnblock();

    future.get();
  }

  private static class TaskSubmissionThread extends Thread {
    private final List<CommandPool.Command<?>> commands;
    private final ReleasableCommandPool commandPool;
    private final int threadId;

    TaskSubmissionThread(List<CommandPool.Command<?>> commands, ReleasableCommandPool commandPool, int threadId) {
      this.commands = commands;
      this.commandPool = commandPool;
      this.threadId = threadId;
    }

    @Override
    public void run() {
      for(CommandPool.Command<?> command : commands) {
        try {
          commandPool.submit(CommandPool.Priority.HIGH, "thread-" + threadId, command, false).get();
        } catch (InterruptedException | ExecutionException | CancellationException e) {
          throw new RuntimeException(e);
        }
      }
    }
  }

  private class CountMaxAndCheckThreadIds extends StartAndStop {
    private int count = 0;
    private int maxCount = 0;
    private final ReleasableBoundCommandPool commandPool;

    CountMaxAndCheckThreadIds(ReleasableBoundCommandPool commandPool) {
      this.commandPool = commandPool;
    }

    @Override
    void start() {
      long threadId = Thread.currentThread().getId();
      Assert.assertTrue(commandPool.getThreadsHoldingSlots().contains(threadId));
      synchronized (this) {
        count++;
        if (count > maxCount) {
          maxCount = count;
        }
      }
    }

    @Override
    void stop() {
      long threadId = Thread.currentThread().getId();
      Assert.assertTrue(commandPool.getThreadsHoldingSlots().contains(threadId));
      synchronized (this) {
        count--;
      }
    }
  }

  private interface ReleasingCommand extends CommandPool.Command<Integer> {
    void firstUnblock();
    default void secondUnblock() {}
  }

  private class SimpleBlockingCommand implements ReleasingCommand {
    private Semaphore first = new Semaphore(0);
    private ReleasableBoundCommandPool releasableBoundCommandPool;
    private final StartAndStop startAndStop;

    SimpleBlockingCommand(ReleasableBoundCommandPool releasableBoundCommandPool, StartAndStop startAndStop) {
      this.releasableBoundCommandPool = releasableBoundCommandPool;
      this.startAndStop = startAndStop;
    }

    @Override
    public Integer get(long waitInMillis) throws Exception {
      startAndStop.start();
      first.acquire();
      startAndStop.stop();
      return counter.incrementAndGet();
    }

    @Override
    public void firstUnblock() {
      first.release();
    }
  }

  private class ReleaseAndWaitCommand implements ReleasingCommand {
    private Semaphore first = new Semaphore(0);
    private Semaphore second = new Semaphore(0);
    private ReleasableBoundCommandPool releasableBoundCommandPool;
    private StartAndStop startAndStop;

    ReleaseAndWaitCommand(ReleasableBoundCommandPool releasableBoundCommandPool, StartAndStop startAndStop) {
      this.releasableBoundCommandPool = releasableBoundCommandPool;
      this.startAndStop = startAndStop;
    }

    @Override
    public Integer get(long waitInMillis) throws Exception {
      try {
        startAndStop.start();
        long threadId = Thread.currentThread().getId();
        first.acquire();
        Assert.assertTrue(releasableBoundCommandPool.getThreadsHoldingSlots().contains(threadId));
        startAndStop.stop();
        try(Closeable closeable = releasableBoundCommandPool.releaseAndReacquireSlot()) {
          Assert.assertFalse(releasableBoundCommandPool.getThreadsHoldingSlots().contains(threadId));
          second.acquire();
        }
        startAndStop.start();
        Assert.assertTrue(releasableBoundCommandPool.getThreadsHoldingSlots().contains(threadId));
        startAndStop.stop();
        return counter.incrementAndGet();
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }

    @Override
    public void firstUnblock() {
      first.release();
    }

    @Override
    public void secondUnblock() {
      second.release();
    }
  }

  private class ReleaseAndResubmitTask implements ReleasingCommand {
    private Semaphore first = new Semaphore(0);
    private BlockingCommand commandToSubmit;
    private ReleasableBoundCommandPool releasableBoundCommandPool;
    private StartAndStop startAndStop;

    ReleaseAndResubmitTask(ReleasableBoundCommandPool releasableBoundCommandPool, StartAndStop startAndStop) {
      this.releasableBoundCommandPool = releasableBoundCommandPool;
      this.startAndStop = startAndStop;
      this.commandToSubmit = new BlockingCommand(startAndStop);
    }

    @Override
    public Integer get(long waitInMillis) throws Exception {
      try {
        startAndStop.start();
        long threadId = Thread.currentThread().getId();
        first.acquire();
        Assert.assertTrue(releasableBoundCommandPool.getThreadsHoldingSlots().contains(threadId));
        startAndStop.stop();
        try(Closeable closeable = releasableBoundCommandPool.releaseAndReacquireSlot()) {
          Assert.assertFalse(releasableBoundCommandPool.getThreadsHoldingSlots().contains(threadId));
          releasableBoundCommandPool.submit(CommandPool.Priority.HIGH, "submitted-task", commandToSubmit, false).get();
        }
        startAndStop.start();
        Assert.assertTrue(releasableBoundCommandPool.getThreadsHoldingSlots().contains(threadId));
        startAndStop.stop();
        return counter.incrementAndGet();
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }

    @Override
    public void firstUnblock() {
      first.release();
    }

    @Override
    public void secondUnblock() {
      commandToSubmit.unblock();
    }
  }

  private class SubmitInSameThread implements ReleasingCommand {
    private final Semaphore first = new Semaphore(0);
    private final BlockingCommand cmd = new BlockingCommand(new StartAndStop());
    private final ReleasableBoundCommandPool releasableBoundCommandPool;

    SubmitInSameThread(ReleasableBoundCommandPool releasableBoundCommandPool) {
      this.releasableBoundCommandPool = releasableBoundCommandPool;
    }

    @Override
    public Integer get(long waitInMillis) throws Exception {
      first.acquire();
      releasableBoundCommandPool.submit(CommandPool.Priority.HIGH, "task-same-thread", cmd, true).get();
      return 0;
    }

    @Override
    public void firstUnblock() {
      first.release();
    }

    @Override
    public void secondUnblock() {
      cmd.unblock();
    }
  }
}


text:
package facebook

import (
	"github.com/stretchr/gomniauth/common"
	"github.com/stretchr/gomniauth/oauth2"
	"github.com/stretchr/gomniauth/test"
	"github.com/stretchr/objx"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"testing"
)

func TestUserInterface(t *testing.T) {

	var user common.User = new(User)

	assert.NotNil(t, user)

}

func TestNewUser(t *testing.T) {

	testProvider := new(test.TestProvider)
	testProvider.On("Name").Return("providerName")

	data := objx.MSI(
		facebookKeyID, "123435467890",
		facebookKeyName, "Mathew",
		facebookKeyEmail, "my@email.com",
		facebookKeyNickname, "Mat",
		"picture", objx.MSI("url", "http://www.myface.com/"))
	creds := &common.Credentials{Map: objx.MSI(oauth2.OAuth2KeyAccessToken, "ABC123")}

	user := NewUser(data, creds, testProvider)

	if assert.NotNil(t, user) {

		assert.Equal(t, data, user.Data())

		assert.Equal(t, "Mathew", user.Name())
		assert.Equal(t, "my@email.com", user.Email())
		assert.Equal(t, "Mat", user.Nickname())
		assert.Equal(t, "http://www.myface.com/", user.AvatarURL())

		// check provider credentials
		creds := user.ProviderCredentials()[testProvider.Name()]
		if assert.NotNil(t, creds) {
			assert.Equal(t, "ABC123", creds.Get(oauth2.OAuth2KeyAccessToken).Str())
			assert.Equal(t, "123435467890", creds.Get(common.CredentialsKeyID).Str())
		}

	}

	mock.AssertExpectationsForObjects(t, testProvider.Mock)

}

func TestIDForProvider(t *testing.T) {

	user := new(User)
	user.data = objx.MSI(
		common.UserKeyProviderCredentials,
		map[string]*common.Credentials{
			"github": &common.Credentials{Map: objx.MSI(common.CredentialsKeyID, "githubid")},
			"google": &common.Credentials{Map: objx.MSI(common.CredentialsKeyID, "googleid")}})

	assert.Equal(t, "githubid", user.IDForProvider("github"))
	assert.Equal(t, "googleid", user.IDForProvider("google"))

}


text:
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- page-footer-ad -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-7331066809382251"
     data-ad-slot="5924127880"
     data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>


text:
<?php

namespace MwbExporter\Formatter\Zend\DbTable\Model;

use MwbExporter\Core\Model\Columns as Base;

class Columns extends Base
{
    /**
     *
     * @param SimpleXMLElement $data
     * @param type $parent
     */
    public function __construct($data, $parent)
    {
        parent::__construct($data, $parent);
    }

    /**
     *
     * @return string
     */
    public function display()
    {
        $return = array();

        foreach($this->columns as $column){
            $return[] = $column->display();
        }

        return implode("\n", $return);
    }

    /**
     *
     * @return string
     */
    public function displayArrayCollections()
    {
        $return = array();

        foreach($this->columns as $column){
            if (true == $arrayCollection = $column->displayArrayCollection()){
                $return[] = $arrayCollection;
            }
        }

        return implode("\n", $return);
    }

    /**
     *
     * @return string
     */
    public function displayGetterAndSetter()
    {
        $return = array();

        foreach($this->columns as $column){
            $return[] = $column->displayGetterAndSetter();
        }

        return implode("\n", $return);
    }

        /**
     *
     * @return string
     */
    public function displayPrimary()
    {
        $return = '';

        foreach($this->columns as $column){
            if($column->isPrimary())
                $return .= "'".$column->getColumnName()."',";
        }

        return $return;
    }
}


text:
<?php namespace Arcanedev\Stripe\Contracts\Resources;

/**
 * Interface  BankAccount
 *
 * @package   Arcanedev\Stripe\Contracts\Resources
 * @author    ARCANEDEV <arcanedev.maroc@gmail.com>
 */
interface BankAccount
{
    /* ------------------------------------------------------------------------------------------------
     |  Main Functions
     | ------------------------------------------------------------------------------------------------
     */
    /**
     * Get the verified bank account.
     *
     * @param  array|null         $params
     * @param  array|string|null  $options
     *
     * @return self
     */
    public function verify($params = [], $options = null);
}


text:
@interface SSColors : NSObject

#define COLOR_PRIMARY @"0459BE"
#define COLOR_SECONDARY @"FF1300"
#define COLOR_BACKGROUND_OFF_WHITE @"F8F8F8"
#define COLOR_TEXT_TITLE @"555555"
#define COLOR_TEXT_DARK @"444444"
#define COLOR_TEXT_LIGHT @"939399"
#define COLOR_SEPARATOR @"DDDDDD"

@end


text:
package com.example.bigtable;

import static org.junit.Assert.assertThat;

import java.io.IOException;
import org.hamcrest.CoreMatchers;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class WritesTest extends MobileTimeSeriesBaseTest {

  @BeforeClass
  public static void beforeClass() throws IOException {
    initializeVariables();
    createTable();
  }

  @AfterClass
  public static void afterClass() throws IOException {
    cleanupTable();
  }

  @Test
  public void test1_WriteSimple() {
    WriteSimple.writeSimple(projectId, instanceId, TABLE_ID);

    String output = bout.toString();
    assertThat(output, CoreMatchers.containsString("Successfully wrote row"));
  }

  @Test
  public void test2_WriteBatch() {
    WriteBatch.writeBatch(projectId, instanceId, TABLE_ID);

    String output = bout.toString();
    assertThat(output, CoreMatchers.containsString("Successfully wrote 2 rows"));
  }

  @Test
  public void test3_WriteConditionally() {
    WriteConditionally.writeConditionally(projectId, instanceId, TABLE_ID);

    String output = bout.toString();
    assertThat(output, CoreMatchers.containsString("Successfully updated row's os_name: true"));
  }

  @Test
  public void test4_WriteIncrement() {
    WriteIncrement.writeIncrement(projectId, instanceId, TABLE_ID);

    String output = bout.toString();
    assertThat(
        output, CoreMatchers.containsString("Successfully updated row phone#4c410523#20190501"));
  }
}


text:
package org.apache.hadoop.hbase.client;

import java.io.IOException;

import org.apache.hadoop.hbase.HBaseClusterTestCase;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TimestampTestBase;

/**
 * Tests user specifiable time stamps putting, getting and scanning.  Also
 * tests same in presence of deletes.  Test cores are written so can be
 * run against an HRegion and against an HTable: i.e. both local and remote.
 */
public class TestTimestamp extends HBaseClusterTestCase {
  public static String COLUMN_NAME = "colfamily1";

  /** constructor */
  public TestTimestamp() {
    super();
  }

  /**
   * Basic test of timestamps.
   * Do the above tests from client side.
   * @throws IOException
   */
  public void testTimestamps() throws IOException {
    HTable t = createTable();
    Incommon incommon = new HTableIncommon(t);
    TimestampTestBase.doTestDelete(incommon, new FlushCache() {
      public void flushcache() throws IOException {
        cluster.flushcache();
      }
     });

    // Perhaps drop and readd the table between tests so the former does
    // not pollute this latter?  Or put into separate tests.
    TimestampTestBase.doTestTimestampScanning(incommon, new FlushCache() {
      public void flushcache() throws IOException {
        cluster.flushcache();
      }
    });
  }

  /*
   * Create a table named TABLE_NAME.
   * @return An instance of an HTable connected to the created table.
   * @throws IOException
   */
  private HTable createTable() throws IOException {
    HTableDescriptor desc = new HTableDescriptor(getName());
    desc.addFamily(new HColumnDescriptor(COLUMN_NAME));
    HBaseAdmin admin = new HBaseAdmin(conf);
    admin.createTable(desc);
    return new HTable(conf, getName());
  }
}


text:
`route53` responder supports `dns-01` challenge type. This assumes domain NS are managed under Route53 hosted zone.

```yaml
challenge_responders:
  - route53:
      ### AWS Access key (optional, default to aws-sdk standard)
      aws_access_key:
        access_key_id:
        secret_access_key:
        # session_token:

      ### Assume IAM role to access Route 53
      # Available options are https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/AssumeRoleCredentials.html
      assume_role:
        role_arn: "arn:aws:iam:::..."

      ### Hosted zone map (optional)
      ##  This specifies an exact hosted zone ID for each domain name.
      ##  Required when you have multiple hosted zones for the same domain name.
      hosted_zone_map:
        "example.org.": "/hostedzone/DEADBEEF"

      # Restore to original records on cleanup (after domain authorization). Default to false.
      # Useful when you need to keep existing record as long as possible.
      restore_to_original_records: false

      ### Substitution record names map (optional)
      ## This specifies alias for specific _acme-challenge record. For instance the following example
      ## updates _acme-challenge.test-example-com.example.org instead of _acme-challenge.test.example.com.
      ##
      ## This eases using the route53 responder for domains not managed in route53, by registering CNAME record to
      ## the alias record name on the original record name in advance. This is called delegation.
      substitution_map:
        "test.example.com.": "test-example-com.example.org."
```

## IAM Policy

- [docs/vendor/aws.md](../vendor/aws.md): IAM and KMS key policies, and some tips


text:
/*
|--------------------------------------------------------------------------
| Production config file
|--------------------------------------------------------------------------
|
| This is the default webpack production config.
|
*/

const path = require('path')
const webpack = require('webpack')
const manifest = require('./manifest.json')
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const CopyWebpackPlugin = require('copy-webpack-plugin')
const autoprefixer = require('autoprefixer')

console.log("\n ----------------------------")
console.log(" Plugin production build ")
console.log(" ----------------------------\n")

module.exports = {
		entry: "./src/js/main.js",
		output: {
			filename: "index.js",
			path: "dist",
		},
		externals: [
			"Dashboard",
			"React"
		],
		postcss: [
			autoprefixer({
				browsers: ['last 2 versions']
			})
		],
		module: {
			loaders: [
				{
					test: /\.(png|woff|woff2|eot|ttf|svg)$/,
					loader: 'url-loader?limit=100000'
				},
				{
					test: /\.scss$/,
					loader: ExtractTextPlugin.extract('style', 'css!postcss!sass')
				},
				{
					test: /\.jsx?$/,
					exclude: /(node_modules)/,
					loaders: [
						'babel?presets[]=stage-0,presets[]=react,presets[]=es2015'
					]
				}
			],
			preLoaders: [
				{
					test: /\.jsx?$/,
					loader: 'eslint',
					exclude: /node_modules/
				},
				{
					test: /index\.jsx$/,
					loader: 'string-replace',
					query: {
						multiple: [
							{
								search: '@plugin_bundle_class',
								replace: manifest.bundle.replace(/\./g, '-'),
								flags: 'g'
							},
							{
								search: '@plugin_bundle',
								replace: manifest.bundle,
								flags: 'g'
							}
						]
					},
					flags: 'g'
				},
				{
					test: /style\.scss$/,
					loader: 'string-replace',
					query: {
						multiple: [
							{
								search: '@plugin_bundle_class',
								replace: manifest.bundle.replace(/\./g, '-'),
								flags: 'g'
							}
						]
					},
					flags: 'g'
				}
			]
		},
		cssLoader: {
			modules: false,
			importLoaders: 1,
			sourceMap: false
		},
		eslint: {
			failOnWarning: false,
			failOnError: true
		},
		plugins: [
			new ExtractTextPlugin("style.css"),
			new webpack.DefinePlugin({
				'process.env': {
					'NODE_ENV': JSON.stringify('production')
				}
			}),
			new webpack.optimize.UglifyJsPlugin({
				minimize: true,
				sourceMap: false,
				output: {
					comments: false
				},
				compress: {
					warnings: false
				}
			}),
			new CopyWebpackPlugin([
					{ from: 'manifest.json', to: '.' }
			])
		]
}


text:
package api

import "github.com/google/gapid/core/data/deep"

// CmdExtra is the interface implemented by command 'extras' - additional
// information that can be placed inside a command.
type CmdExtra interface{}

// CmdExtras is a list of CmdExtra objects.
type CmdExtras []CmdExtra

func (e *CmdExtras) All() CmdExtras {
	if e == nil {
		return nil
	}
	return *e
}

// Add appends one or more CmdExtras to the list of CmdExtras.
func (e *CmdExtras) Add(es ...CmdExtra) {
	if e != nil {
		*e = append(*e, es...)
	}
}

// MustClone clones on or more CmdExtras to the list of CmdExtras,
// if there was an error, a panic is raised
func (e *CmdExtras) MustClone(es ...CmdExtra) {
	if e != nil {
		for _, ex := range es {
			i, err := deep.Clone(ex)
			if err != nil {
				panic(err)
			}
			*e = append(*e, i)
		}
	}
}

// Aborted returns a pointer to the ErrCmdAborted structure in the CmdExtras, or
// nil if not found.
func (e *CmdExtras) Aborted() *ErrCmdAborted {
	for _, e := range e.All() {
		if e, ok := e.(*ErrCmdAborted); ok {
			return e
		}
	}
	return nil
}

// Observations returns a pointer to the CmdObservations structure in the
// CmdExtras, or nil if there are no observations in the CmdExtras.
func (e *CmdExtras) Observations() *CmdObservations {
	for _, o := range e.All() {
		if o, ok := o.(*CmdObservations); ok {
			return o
		}
	}
	return nil
}

// GetOrAppendObservations returns a pointer to the existing Observations
// structure in the CmdExtras, or appends and returns a pointer to a new
// observations structure if the CmdExtras does not already contain one.
func (e *CmdExtras) GetOrAppendObservations() *CmdObservations {
	if o := e.Observations(); o != nil {
		return o
	}
	o := &CmdObservations{}
	e.Add(o)
	return o
}

// WithExtras adds the given extras to a command and returns it.
func WithExtras(a Cmd, extras ...CmdExtra) Cmd {
	a.Extras().Add(extras...)
	return a
}


text:
package uk.ac.aber.mwg2.cs123.patience.cards;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

import uk.ac.aber.mwg2.cs123.patience.gui.PackDialog;

/**
 * This class initialy represents an ordered 52 cards pack. User can shuffle it
 * and remove cards from it, using provided methods.
 *
 * @author mwg2
 * @since 26 March 2015
 *
 */
public class Pack extends CardsCollection {

	private PackDialog packDialog;
	private boolean shuffled = false;
	private BufferedImage img;

	private final String PACK_FILE = "pack.txt";
	private final String IMG_FILE = "res/bb.gif";

	/**
	 * Creates a sorted 52 cards pack
	 */
	public Pack() {
		super();

		// load the image of a reversed card
		loadImage();

		try {
			loadCards();
		} catch (IOException e) {
			// Notify the user and crash as there would be no point to
			// carry on.
			JOptionPane.showMessageDialog(null,
					"Unable to load cards to the pack", null,
					JOptionPane.ERROR_MESSAGE);
			System.exit(-1);
		}
	}

	/**
	 * Returns an image of a reversed playing card. It represents the whole
	 * pack placed on the table upside down.
	 * @return Image of the reversed pack
	 */
	public BufferedImage getImage() {
		return img;
	}

	/**
	 * Returns and removes the first card from the pack. Note that a null will
	 * be returned if the pack is empty.
	 * @return Card from the 'head' of the pack or a null if the pack is empty
	 */
	public Card dealCard() {
		if (!getCards().isEmpty()) {
			return getCards().remove(0);
		} else {
			return null;
		}
	}

	/**
	 * Creates a modal dialog which displays current pack
	 */
	public void diplayPack() {
		if (packDialog == null) {
			packDialog = new PackDialog(this);
		}
		packDialog.repaint();
		packDialog.setVisible(true);
	}

	/**
	 * Shuffles the pack of cards when called for the first time. Every other
	 * attept to use it will fail and notify the user.
	 */
	public void shuffle() {
		if (!shuffled) {
			Collections.shuffle(getCards());
			shuffled = true;
		} else {
			JOptionPane.showMessageDialog(packDialog,
					"This pack has been already shuffled.");
		}
	}

	// Loads the image of a reversed card, as pack will be upside down
	private void loadImage() {
		try {
			img = ImageIO.read(new File(IMG_FILE));
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "Unable to load the image of a "
					+ "reversed card into deck", "Error", JOptionPane.ERROR_MESSAGE);
		}
	}

	// Loads 52 cards into the 'cards' list.
	private void loadCards() throws IOException {
		try (Scanner in = new Scanner(new File(PACK_FILE))) {
			int num = Integer.parseInt(in.nextLine());
			for (int i = 0; i < num; i++) {
				String[] cardInfo = in.nextLine().split(":");
				addCard(new Card(Suit.fromString(cardInfo[0]), Value
						.fromString(cardInfo[1])));
			}
		}
	}
}


text:
START_ATF_NAMESPACE
    namespace ATL
    {
        struct  Win32ThreadTraits
        {
        };
    }; // end namespace ATL
END_ATF_NAMESPACE


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Bytescout.PDF;

namespace FillFormExample
{
    /// <summary>
    /// This example demonstrates how to fill PDF form programmatically.
    /// </summary>
    class Program
    {
        static void Main()
        {
            // Map of form fields and sample values to set
            Dictionary<string, object> fieldMap = new Dictionary<string, object>()
            {
                { "f1_1[0]", "John J Smith" }, // Name
                { "f1_2[0]", "12 Palm st., Hill Valley, CA 12345" } // Business address
           };

            // Load PDF form
            Document pdfDocument = new Document(@".\W-9.pdf");
            pdfDocument.RegistrationName = "demo";
            pdfDocument.RegistrationKey = "demo";

            // Get first page
            Page page = pdfDocument.Pages[0];

            // Get widget by its name and change value
            foreach (KeyValuePair<string, object> keyValuePair in fieldMap)
            {
                Annotation annotation = page.Annotations[keyValuePair.Key];

                if (annotation is CheckBox)
                {
                    ((CheckBox)annotation).Checked = Convert.ToBoolean(keyValuePair.Value);
                }
                else if (annotation is EditBox)
                {
                    ((EditBox)annotation).Text = (string)keyValuePair.Value;
                }
            }

            // Save modified document
            pdfDocument.Save("result.pdf");

            // Cleanup
            pdfDocument.Dispose();

            // Open result document in default associated application (for demo purpose)
            ProcessStartInfo processStartInfo = new ProcessStartInfo("result.pdf");
            processStartInfo.UseShellExecute = true;
            Process.Start(processStartInfo);
        }
    }
}


text:
package org.apache.usergrid.rest.management.organizations;

import com.fasterxml.jackson.jaxrs.json.annotation.JSONP;
import org.apache.amber.oauth2.common.exception.OAuthSystemException;
import org.apache.commons.lang.NullArgumentException;
import org.apache.usergrid.exception.NotImplementedException;
import org.apache.usergrid.management.ActivationState;
import org.apache.usergrid.management.OrganizationConfig;
import org.apache.usergrid.management.OrganizationInfo;
import org.apache.usergrid.management.export.ExportService;
import org.apache.usergrid.persistence.entities.Export;
import org.apache.usergrid.rest.AbstractContextResource;
import org.apache.usergrid.rest.ApiResponse;
import org.apache.usergrid.rest.applications.ServiceResource;
import org.apache.usergrid.rest.exceptions.RedirectionException;
import org.apache.usergrid.rest.management.organizations.applications.ApplicationsResource;
import org.apache.usergrid.rest.management.organizations.users.UsersResource;
import org.apache.usergrid.rest.security.annotations.RequireOrganizationAccess;
import org.apache.usergrid.rest.security.annotations.RequireSystemAccess;
import org.apache.usergrid.rest.utils.JSONPUtils;
import org.apache.usergrid.security.oauth.ClientCredentialsInfo;
import org.apache.usergrid.security.tokens.exceptions.TokenException;
import org.apache.usergrid.services.ServiceResults;
import org.glassfish.jersey.server.mvc.Viewable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.util.*;

import static javax.servlet.http.HttpServletResponse.*;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;

@Component("org.apache.usergrid.rest.management.organizations.OrganizationResource")
@Scope("prototype")
@Produces({
        MediaType.APPLICATION_JSON, "application/javascript", "application/x-javascript", "text/ecmascript",
        "application/ecmascript", "text/jscript"
})
public class OrganizationResource extends AbstractContextResource {

    private static final Logger logger = LoggerFactory.getLogger( OrganizationsResource.class );

    //@Autowired
    //protected ExportService exportService;

    OrganizationInfo organization;

    public OrganizationResource() {
        if (logger.isTraceEnabled()) {
            logger.trace("OrganizationResource created");
        }
    }

    public OrganizationResource init( OrganizationInfo organization ) {
        this.organization = organization;
        if (logger.isTraceEnabled()) {
            logger.trace("OrganizationResource initialized for org {}", organization.getName());
        }
        return this;
    }

    @Path("users")
    public UsersResource getOrganizationUsers( @Context UriInfo ui ) throws Exception {
        return getSubResource( UsersResource.class ).init( organization );
    }

    @Path("applications")
    public ApplicationsResource getOrganizationApplications( @Context UriInfo ui ) throws Exception {
        return getSubResource( ApplicationsResource.class ).init( organization );
    }

    @Path("apps")
    public ApplicationsResource getOrganizationApplications2( @Context UriInfo ui ) throws Exception {
        return getSubResource( ApplicationsResource.class ).init( organization );
    }

    @GET
    @JSONP
    @RequireOrganizationAccess
    @Produces({MediaType.APPLICATION_JSON, "application/javascript"})
    public ApiResponse getOrganizationDetails( @Context UriInfo ui,
                                                   @QueryParam("callback") @DefaultValue("callback") String callback )
            throws Exception {

        if (logger.isTraceEnabled()) {
            logger.trace("Get details for organization: {}", organization.getUuid());
        }

        ApiResponse response = createApiResponse();
        response.setProperty( "organization", management.getOrganizationData( organization ) );

        return response;
    }

    @GET
    @Path("activate")
    @Produces(MediaType.TEXT_HTML)
    public Viewable activate( @Context UriInfo ui, @QueryParam("token") String token ) {

        try {
            management.handleActivationTokenForOrganization( organization.getUuid(), token );
            return handleViewable( "activate", this, organization.getName() );
        }
        catch ( TokenException e ) {
            return handleViewable( "bad_activation_token", this, organization.getName() );
        }
        catch ( RedirectionException e ) {
            throw e;
        }
        catch ( Exception e ) {
            return handleViewable( "error", e, organization.getName() );
        }
    }

    @GET
    @Path("confirm")
    @Produces(MediaType.TEXT_HTML)
    public Viewable confirm( @Context UriInfo ui, @QueryParam("token") String token ) {

        try {
            ActivationState state = management.handleActivationTokenForOrganization( organization.getUuid(), token );
            if ( state == ActivationState.CONFIRMED_AWAITING_ACTIVATION ) {
                return handleViewable( "confirm", this, organization.getName() );
            }
            return handleViewable( "activate", this, organization.getName() );
        }
        catch ( TokenException e ) {
            return handleViewable( "bad_activation_token", this, organization.getName() );
        }
        catch ( RedirectionException e ) {
            throw e;
        }
        catch ( Exception e ) {
            return handleViewable( "error", e, organization.getName() );
        }
    }

    @GET
    @Path("reactivate")
    @JSONP
    @Produces({MediaType.APPLICATION_JSON, "application/javascript"})
    public ApiResponse reactivate( @Context UriInfo ui,
                                       @QueryParam("callback") @DefaultValue("callback") String callback )
            throws Exception {

        logger.info("Send activation email for organization: {}", organization.getUuid());

        ApiResponse response = createApiResponse();

        management.startOrganizationActivationFlow( organization );

        response.setAction( "reactivate organization" );
        return response;
    }

    @RequireOrganizationAccess
    @GET
    @Path("feed")
    @JSONP
    @Produces({MediaType.APPLICATION_JSON, "application/javascript"})
    public ApiResponse getFeed( @Context UriInfo ui,
                                    @QueryParam("callback") @DefaultValue("callback") String callback )
            throws Exception {

        ApiResponse response = createApiResponse();
        response.setAction( "get organization feed" );

        ServiceResults results = management.getOrganizationActivity( organization );
        response.setEntities( results.getEntities() );
        response.setSuccess();

        return response;
    }

    @RequireOrganizationAccess
    @GET
    @Path("credentials")
    @JSONP
    @Produces({MediaType.APPLICATION_JSON, "application/javascript"})
    public ApiResponse getCredentials( @Context UriInfo ui,
                                           @QueryParam("callback") @DefaultValue("callback") String callback )
            throws Exception {

        ApiResponse response = createApiResponse();
        response.setAction( "get organization client credentials" );

        ClientCredentialsInfo keys =
                new ClientCredentialsInfo( management.getClientIdForOrganization( organization.getUuid() ),
                        management.getClientSecretForOrganization( organization.getUuid() ) );

        response.setCredentials( keys );
        return response;
    }

    @RequireOrganizationAccess
    @POST
    @Path("credentials")
    @JSONP
    @Produces({MediaType.APPLICATION_JSON, "application/javascript"})
    public ApiResponse generateCredentials( @Context UriInfo ui,
                                                @QueryParam("callback") @DefaultValue("callback") String callback )
            throws Exception {

        ApiResponse response = createApiResponse();
        response.setAction( "generate organization client credentials" );

        ClientCredentialsInfo credentials =
                new ClientCredentialsInfo( management.getClientIdForOrganization( organization.getUuid() ),
                        management.newClientSecretForOrganization( organization.getUuid() ) );

        response.setCredentials( credentials );
        return response;
    }

    public OrganizationInfo getOrganization() {
        return organization;
    }

    @RequireOrganizationAccess
    @Consumes(MediaType.APPLICATION_JSON)
    @PUT
    @JSONP
    @Produces({MediaType.APPLICATION_JSON, "application/javascript"})
    public ApiResponse executePut( @Context UriInfo ui, Map<String, Object> json,
                                       @QueryParam("callback") @DefaultValue("callback") String callback )
            throws Exception {

        if (logger.isTraceEnabled()) {
            logger.trace("executePut");
        }

        ApiResponse response = createApiResponse();
        response.setAction( "put" );

        response.setParams( ui.getQueryParameters() );

        Map customProperties = ( Map ) json.get( OrganizationsResource.ORGANIZATION_PROPERTIES );
        organization.setProperties( customProperties );
        management.updateOrganization( organization );

        return response;
    }

//    @POST
//    @Path("export")
//    @Consumes(APPLICATION_JSON)
//    @RequireOrganizationAccess
//    public Response exportPostJson( @Context UriInfo ui,Map<String, Object> json,
//                                    @QueryParam("callback") @DefaultValue("") String callback )
//            throws OAuthSystemException {
//
//        if (logger.isTraceEnabled()) {
//            logger.trace("executePostJson");
//        }
//
//        Map<String, String> uuidRet = new HashMap<>();
//
//        try {
//            Object propertiesObj = json.get("properties");
//            if (propertiesObj == null) {
//                throw new NullArgumentException("Could not find 'properties'");
//            }
//            if (!(propertiesObj instanceof Map)) {
//                throw new IllegalArgumentException("'properties' not a map");
//            }
//
//            @SuppressWarnings("unchecked")
//            Map<String,Object> properties = (Map<String,Object>)propertiesObj;
//
//            String storage_provider = ( String ) properties.get( "storage_provider" );
//            if(storage_provider == null) {
//                throw new NullArgumentException( "Could not find field 'storage_provider'" );
//            }
//
//            Object storageInfoObj = properties.get("storage_info");
//            if(storageInfoObj == null) {
//                throw new NullArgumentException( "Could not find field 'storage_info'" );
//            }
//            @SuppressWarnings("unchecked")
//            Map<String,Object> storage_info = (Map<String, Object>)storageInfoObj;
//
//            String bucketName = ( String ) storage_info.get( "bucket_location" );
//            String accessId = ( String ) storage_info.get( "s3_access_id" );
//            String secretKey = ( String ) storage_info.get( "s3_key" );
//
//            if ( bucketName == null ) {
//                throw new NullArgumentException( "Could not find field 'bucketName'" );
//            }
//            if ( accessId == null ) {
//                throw new NullArgumentException( "Could not find field 's3_access_id'" );
//            }
//            if ( secretKey == null ) {
//
//                throw new NullArgumentException( "Could not find field 's3_key'" );
//            }
//
//            json.put( "organizationId",organization.getUuid());
//
//            UUID jobUUID = exportService.schedule( json );
//            uuidRet.put( "Export Entity", jobUUID.toString() );
//        }
//        catch ( NullArgumentException e ) {
//            return Response.status( SC_BAD_REQUEST ).type( JSONPUtils.jsonMediaType( callback ) )
//                           .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build();
//        }
//        catch ( Exception e ) {
//            //TODO:throw descriptive error message and or include on in the response
//            //TODO:fix below, it doesn't work if there is an exception. Make it look like the OauthResponse.
//            return Response.status(  SC_INTERNAL_SERVER_ERROR ).type( JSONPUtils.jsonMediaType( callback ) )
//                           .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build();
//        }
//        return Response.status( SC_ACCEPTED ).entity( uuidRet ).build();
//    }

//    @GET
//    @RequireOrganizationAccess
//    @Path("export/{exportEntity: [A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}")
//    public Response exportGetJson( @Context UriInfo ui, @PathParam("exportEntity") UUID exportEntityUUIDStr,
//                                   @QueryParam("callback") @DefaultValue("") String callback ) throws Exception {
//
//        Export entity;
//        try {
//            entity = smf.getServiceManager( emf.getManagementAppId() ).getEntityManager()
//                        .get( exportEntityUUIDStr, Export.class );
//        }
//        catch ( Exception e ) { //this might not be a bad request and needs better error checking
//            return Response.status( SC_BAD_REQUEST ).type( JSONPUtils.jsonMediaType( callback ) )
//                           .entity( ServiceResource.wrapWithCallback( e.getMessage(), callback ) ).build();
//        }
//
//        if ( entity == null ) {
//            return Response.status( SC_BAD_REQUEST ).build();
//        }
//
//        return Response.status( SC_OK ).entity( entity).build();
//    }

    protected Set<String> getSetFromCommaSeparatedString(String input) {
        Set<String> ret = new HashSet<>();
        StringTokenizer tokenizer = new StringTokenizer(input, ",");

        while (tokenizer.hasMoreTokens()) {
            ret.add(tokenizer.nextToken());
        }

        return ret;
    }

    protected Map<String, Object> getConfigData(OrganizationConfig orgConfig, String itemsParam,
                                                boolean includeDefaults, boolean includeOverrides) {
        boolean itemsParamEmpty = itemsParam == null || itemsParam.isEmpty() || itemsParam.equals("*");
        return orgConfig.getOrgConfigCustomMap(itemsParamEmpty ? null : getSetFromCommaSeparatedString(itemsParam),
                includeDefaults, includeOverrides);
    }

    @JSONP
    @RequireSystemAccess
    @GET
    @Path("config")
    public ApiResponse getConfig( @Context UriInfo ui,
                                  @QueryParam("items") @DefaultValue("") String itemsParam,
                                  @QueryParam("separate_defaults") @DefaultValue("false") boolean separateDefaults,
                                  @QueryParam("callback") @DefaultValue("callback") String callback )
            throws Exception {

        if (logger.isTraceEnabled()) {
            logger.trace("Get configuration for organization: {}", organization.getUuid());
        }

        ApiResponse response = createApiResponse();
        response.setAction( "get organization configuration" );
        //response.setParams(ui.getQueryParameters());

        OrganizationConfig orgConfig =
                management.getOrganizationConfigByUuid( organization.getUuid() );

        if (separateDefaults) {
            response.setProperty("orgConfiguration", getConfigData(orgConfig, itemsParam, false, true));
            response.setProperty("defaults", getConfigData(orgConfig, itemsParam, true, false));
        } else {
            response.setProperty("configuration", getConfigData(orgConfig, itemsParam, true, true));
        }

        return response;
    }

    @RequireSystemAccess
    @Consumes(MediaType.APPLICATION_JSON)
    @JSONP
    @PUT
    @Path("config")
    public ApiResponse putConfig( @Context UriInfo ui,
                                  Map<String, Object> json,
                                  @QueryParam("separate_defaults") @DefaultValue("false") boolean separateDefaults,
                                  @QueryParam("only_changed") @DefaultValue("false") boolean onlyChanged,
                                  @QueryParam("callback") @DefaultValue("callback") String callback )
            throws Exception {

        if (logger.isTraceEnabled()) {
            logger.trace("Put configuration for organization: {}", organization.getUuid());
        }

        ApiResponse response = createApiResponse();
        response.setAction("put organization configuration");
        //response.setParams(ui.getQueryParameters());

        OrganizationConfig orgConfig =
                management.getOrganizationConfigByUuid( organization.getUuid() );

        // validates JSON and throws IllegalArgumentException if invalid
        // exception will be handled up the chain
        orgConfig.addProperties(json, true);

        management.updateOrganizationConfig(orgConfig);

        // refresh orgConfig -- to pick up removed entries and defaults
        orgConfig = management.getOrganizationConfigByUuid( organization.getUuid() );

        String itemsToReturn = "";
        if (onlyChanged) {
            itemsToReturn = String.join(",", json.keySet());
        }

        if (separateDefaults) {
            response.setProperty("orgConfiguration", getConfigData(orgConfig, itemsToReturn, false, true));
            response.setProperty("defaults", getConfigData(orgConfig, itemsToReturn, true, false));
        } else {
            response.setProperty( "configuration", getConfigData(orgConfig, itemsToReturn, true, true));
        }

        return response;
    }

    /** Delete organization is not yet supported */
    //@RequireSystemAccess
    @DELETE
    public ApiResponse deleteOrganization() throws Exception {
        throw new NotImplementedException();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gear.Model
{
    /// <summary>
    /// Represents a material; something that a block or component is made from.
    /// </summary>
    public class Material
    {
        public Guid MaterialId { get; set; }

        public string Name { get; set; }
    }
}


text:
Test xmp_load_module_from_memory
--CREDITS--
Boro Sitnikovski <buritomath@yahoo.com>
--SKIPIF--
<?php if (!extension_loaded("xmp")) print "skip"; ?>
--FILE--
<?php
$filename = dirname(__FILE__)."/../3d.mod";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

$ctx = xmp_create_context();
$mod = xmp_load_module_from_memory($ctx, $contents);
var_dump($mod);
xmp_release_module($ctx);
xmp_free_context($ctx);
?>
--EXPECT--
int(0)


text:
`notify_package_added` -> `bulk_add_pkgs`

This makes rewrites of packages O(A/P) vs O(A) where A == number of
package versions and P == number of packages. Also tried to limit the
number of times the data file was serialized and written to once per
bulk update, vs. once for every package added.

 0. 76s start
 1. 48s batch leaf rebuild
 2. 43 batch index.json writes
 3. 26.5 turn off index writing
 4. 24.5 turn off pip sync


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BtrieveWrapper
{
    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
    public class KeyTypeAttribute : Attribute
    {
        public KeyTypeAttribute(string name, ushort defaultLength, params ushort[] lengthList) {
            this.Name = name;
            this.DefaultLength = defaultLength;
            this.LengthList = lengthList;
        }

        public string Name { get; private set; }
        public ushort DefaultLength { get; private set; }
        public IEnumerable<ushort> LengthList { get; private set; }

        public bool ValidateLength(ushort length) {
            if (this.LengthList.Count() == 0) {
                return true;
            } else {
                return this.LengthList.Any(l => l == length);
            }
        }
    }
}


text:
require "import"
import "android.widget.*"
import "android.content.*"
local AlertBuilder = import "android.app.AlertDialog$Builder"

local layout = require "text.layout_text"

function onCreate(savedInstanceState)
    activity.setTitle('Test Text')
    activity.setContentView(loadlayout(layout))
    btn_1.onClick = function(v)
        AlertBuilder(activity)
            .setTitle('LuaTitle')
            .setMessage('from lua script')
            .setPositiveButton('OK',luajava.createProxy("android.content.DialogInterface$OnClickListener",{
                onClick = function(dialog,witch)
                    activity.toast("click ok")
                end
            }))
            .setNegativeButton('Cancel', nil)
            .show()
    end
end


text:
<dc:title>HOLMES GROUP, INC. v. VORNADO AIRCIRCULATION SYSTEMS, INC.</dc:title>
<dc:language>en-US</dc:language>
<dc:creator opf:file-as="NYPL" opf:role="aut">NYPL</dc:creator>
<dc:publisher>NYPL</dc:publisher>
<dc:date opf:event="publication">2015-01-15</dc:date>
<dc:rights>Copyright ©2015 by Cornell Law and NYPL</dc:rights>


text:
class CreateAdmins < ActiveRecord::Migration[5.0]
  def change
    create_table :admins do |t|
      t.string :name

      t.timestamps
    end
  end
end


text:
import {LOGIN_REQUEST, LOGIN_REQUEST_SUCCESS, LOGIN_REQUEST_FAIL} from '../actions/login'

const initialState = {
  isLogin: false
};

export default function update(state = initialState, action) {
  switch (action.type) {
    case LOGIN_REQUEST:
      return state;
    case LOGIN_REQUEST_SUCCESS:
      if (action.data.errno) {
        return Object.assign({}, state, {
          isLogin: false
        });
      } else {
        return Object.assign({}, state, action.data, {
          isLogin: true
        });
      }
    case LOGIN_REQUEST_FAIL:
      return Object.assign({}, state, {
        isLogin: false
      });
    default:
      return state;
  }
}


text:
//---------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2015-2018 Sergej Zuyev (sergej.zuyev - at - zz-systems.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------------

#pragma once
#include <string>
#include <algorithm>
#include <vector>

namespace zacc {
    /**
     * @brief Simple commandline option parser
     * @authors iain, s.zuyev
     * @remark taken from http://stackoverflow.com/a/868894/1261537 and adapted
     */
    class option_parser
    {
    public:
        /**
         * @brief accepts main() args
         * @param argc argument count
         * @param argv argument array
         */
        option_parser(const int argc, char** argv)
            : _options(argv + 1, argv + argc)
        { }

        /**
         * @brief checks if an option is set
         * @param option option name
         * @return true if the option exists, false otherwise
         */
        bool has_option(const std::string& option) const
        {
            return std::find(_options.begin(), _options.end(), option) != _options.end();
        }

        /**
         * @brief gets the option value
         * @param option
         * @return option value if option exists, otherwise an empty string
         */
        const std::string& get_option(const std::string& option) const
        {
            auto iter = std::find(_options.begin(), _options.end(), option);

            if(iter != _options.end() && ++ iter != _options.end())
                return *iter;

            return _empty;
        }

    private:
        std::vector<std::string> _options;
        const std::string _empty;
    };
}


text:
using RKT_WPF_POSTFlightBooking.Contexts;

namespace RKT_WPF_POSTFlightBooking.Helpers
{
    static class RegistrationHelper
    {
        public static async void DeleteRegistration()
        {
            // this method should not be awaitable therefore using async void
            await Globals.LogonCore.UnregisterAsync();
            SharedContext.Context.Store.Dispose();
            SharedContext.Context = null;
            NavigateToLogonPage();
        }

        public static void NavigateToLogonPage()
        {
            new LogonWindow().Show();
        }
    }
}


text:
package app.config;

import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpMethod;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import javax.servlet.MultipartConfigElement;
import javax.sql.DataSource;

/**
 * The @EnableResourceServer annotation adds a filter of type OAuth2AuthenticationProcessingFilter automatically
 * to the Spring Security filter chain.
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/v1/users/verify/*").permitAll()
                .antMatchers(HttpMethod.POST, "/v1/users").permitAll()
                .antMatchers(HttpMethod.GET,"/v1/users/heroku/awake").permitAll()
                .antMatchers(HttpMethod.POST, "/v1/img/**").access("hasRole('ADMIN') or hasRole('USER')")
                .antMatchers(HttpMethod.GET, "/v1/img/**").permitAll()
                .antMatchers("/v1/users/**").authenticated()
                .antMatchers("/v1/books/**").authenticated()
                .antMatchers("/v1/authors/admin/**").authenticated()
                .antMatchers(HttpMethod.DELETE, "/post/**").hasAuthority("ROLE_ADMIN")
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());

    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(getDataSource());
    }

    @Bean(name = "commonsMultipartResolver")
    public MultipartResolver multipartResolver() {
        return new StandardServletMultipartResolver();
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();

        factory.setMaxFileSize("5MB");
        factory.setMaxRequestSize("5MB");

        return factory.createMultipartConfig();
    }

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setCorePoolSize(5);
        pool.setMaxPoolSize(10);
        pool.setWaitForTasksToCompleteOnShutdown(true);
        return pool;
    }

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource getDataSource() {
        return DataSourceBuilder.create().build();
    }

}


text:
package org.handwerkszeug.riak.model;

import static org.handwerkszeug.riak.util.Validation.notNull;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author taichi
 */
public abstract class AbstractRiakObject<T> implements RiakObject<T> {

	private Location location;
	private String vectorClock;
	private String contentType = DEFAULT_CONTENT_TYPE;
	private String charset;
	private String contentEncoding;
	private String vtag;
	private List<Link> links = Collections.emptyList();
	private Date lastModified;
	private Map<String, String> userMetadata = Collections.emptyMap();

	protected AbstractRiakObject() {
	}

	public AbstractRiakObject(Location location) {
		notNull(location, "location");
		this.location = location;
	}

	@Override
	public Location getLocation() {
		return this.location;
	}

	@Override
	public void setLocation(Location location) {
		this.location = location;
	}

	@Override
	public String getVectorClock() {
		return this.vectorClock;
	}

	@Override
	public void setVectorClock(String clock) {
		this.vectorClock = clock;
	}

	@Override
	public String getContentType() {
		return this.contentType;
	}

	@Override
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	@Override
	public String getCharset() {
		return this.charset;
	}

	@Override
	public void setCharset(String charset) {
		this.charset = charset;
	}

	@Override
	public String getContentEncoding() {
		return this.contentEncoding;
	}

	@Override
	public void setContentEncoding(String encoding) {
		this.contentEncoding = encoding;
	}

	@Override
	public String getVtag() {
		return this.vtag;
	}

	@Override
	public void setVtag(String vtag) {
		this.vtag = vtag;
	}

	@Override
	public List<Link> getLinks() {
		return this.links;
	}

	@Override
	public void setLinks(List<Link> links) {
		this.links = links;
	}

	@Override
	public Date getLastModified() {
		return this.lastModified;
	}

	@Override
	public void setLastModified(Date date) {
		this.lastModified = date;
	}

	@Override
	public Map<String, String> getUserMetadata() {
		return this.userMetadata;
	}

	@Override
	public void setUserMetadata(Map<String, String> metadata) {
		this.userMetadata = metadata;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("AbstractRiakObject [location=");
		builder.append(this.location);
		builder.append(", vectorClock=");
		builder.append(this.vectorClock);
		builder.append(", contentType=");
		builder.append(this.contentType);
		builder.append(", charset=");
		builder.append(this.charset);
		builder.append(", contentEncoding=");
		builder.append(this.contentEncoding);
		builder.append(", vtag=");
		builder.append(this.vtag);
		builder.append(", links=");
		builder.append(this.links);
		builder.append(", lastModified=");
		builder.append(this.lastModified);
		builder.append(", userMetadata=");
		builder.append(this.userMetadata);
		builder.append("]");
		return builder.toString();
	}
}


text:
package com.silver.dan.castdemo.settingsFragments;

/**
 * Created by dan on 5/26/16.
 */

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.afollestad.materialdialogs.MaterialDialog;
import com.silver.dan.castdemo.R;
import com.silver.dan.castdemo.WidgetOption;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CountdownSettings extends WidgetSettingsFragment {

    @BindView(R.id.countdown_date)
    TwoLineSettingItem countdownDate;

    @BindView(R.id.countdown_time)
    TwoLineSettingItem countdownTime;

    @BindView(R.id.countdown_text)
    TwoLineSettingItem countdownText;

    WidgetOption dateOption, textOption;

    public static String COUNTDOWN_DATE = "COUNTDOWN_DATE";
    public static String COUNTDOWN_TEXT = "COUNTDOWN_TEXT";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.countdown_settings, container, false);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }

    public void updateCountdownTextLabel() {
        countdownText.setSubHeaderText(textOption.value);
    }

    public void updateCountdownDateAndTimeText() {
        Date countdownTarget = dateOption.getDate();

        DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getContext());
        DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);

        String dateString = dateFormat.format(countdownTarget);
        String timeString = timeFormat.format(countdownTarget);

        countdownDate.setSubHeaderText(dateString);
        countdownTime.setSubHeaderText(timeString);
    }

    @OnClick(R.id.countdown_text)
    public void updateCountdownText() {
        new MaterialDialog.Builder(getContext())
                .title(R.string.countdown_timer_text)
                .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES)
                .input(getString(R.string.countdown_timer_text), textOption.value, new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                        textOption.update(input.toString());
                        updateWidgetProperty(COUNTDOWN_TEXT, textOption.value);
                        updateCountdownTextLabel();
                    }
                }).show();
    }

    @OnClick(R.id.countdown_date)
    public void updateCountdownDate() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateOption.getDate());
        DatePickerDialog dpd = DatePickerDialog.newInstance(
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
                        Calendar curDate = Calendar.getInstance();
                        curDate.setTime(dateOption.getDate());

                        curDate.set(year, monthOfYear, dayOfMonth);

                        dateOption.setValue(curDate.getTime());
                        dateOption.save();
                        updateWidgetProperty(COUNTDOWN_DATE, dateOption.value);
                        updateCountdownDateAndTimeText();
                    }
                },
                cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH)
        );

        dpd.show(getActivity().getFragmentManager(), "Datepickerdialog");

    }

    @OnClick(R.id.countdown_time)
    public void updateCountdownTime() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateOption.getDate());
        TimePickerDialog dpd = TimePickerDialog.newInstance(
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
                        Calendar curDate = Calendar.getInstance();
                        curDate.setTime(dateOption.getDate());

                        curDate.set(curDate.get(Calendar.YEAR), curDate.get(Calendar.MONTH), curDate.get(Calendar.DAY_OF_MONTH), hourOfDay, minute, second);

                        dateOption.setValue(curDate.getTime());
                        dateOption.save();
                        updateWidgetProperty(COUNTDOWN_DATE, dateOption.value);
                        updateCountdownDateAndTimeText();

                    }
                },
                cal.get(Calendar.HOUR_OF_DAY),
                cal.get(Calendar.MINUTE),
                false
        );

        dpd.show(getActivity().getFragmentManager(), "timepickerdialog");

    }

    @Override
    public void initView() {

        dateOption = loadOrInitOption(COUNTDOWN_DATE);
        textOption = loadOrInitOption(COUNTDOWN_TEXT);

        updateCountdownTextLabel();
        updateCountdownDateAndTimeText();
    }
}