text:
package energy.usef.core.service.notification;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import energy.usef.core.config.Config;
import energy.usef.core.config.ConfigParam;
import energy.usef.core.data.xml.bean.message.Message;
import energy.usef.core.data.xml.bean.message.MessageMetadata;
import energy.usef.core.data.xml.bean.message.MessagePrecedence;
import energy.usef.core.model.MessageType;
import energy.usef.core.service.business.MessageService;
import energy.usef.core.service.helper.JMSHelperService;
import energy.usef.core.service.helper.NotificationHelperService;
import energy.usef.core.util.DateTimeUtil;

/**
 * Simple implementation of the failed message notification hook.
 */
@Stateless
public class NotificationHelperServiceImpl implements NotificationHelperService {
    private static final Logger LOGGER = LoggerFactory.getLogger(NotificationHelperServiceImpl.class);

    private static final double MILLIS_PER_MINUTE = 60000.0;

    @Resource
    private TimerService timerService;

    @Inject
    private MessageService ingoingMessageService;

    @Inject
    private JMSHelperService jmsService;

    @Inject
    private Config config;

    /**
     * {@inheritDoc}
     */
    public void notifyMessageNotSent(String xml, Message message) {
        MessageMetadata messageMetadata = message.getMessageMetadata();
        if (MessagePrecedence.CRITICAL.equals(messageMetadata.getPrecedence())) {
            LOGGER.warn("CRITICAL MESSAGE IS NOT SENT, MESSAGE ID: {}", messageMetadata.getMessageID());
            jmsService.sendMessageToNotSentQueue(xml);
        } else if (MessagePrecedence.TRANSACTIONAL.equals(messageMetadata.getPrecedence())) {
            jmsService.sendMessageToNotSentQueue(xml);
            LOGGER.warn("TRANSACTIONAL MESSAGE IS NOT SENT, MESSAGE ID: {}", messageMetadata.getMessageID());
        }
    }

    /**
     * {@inheritDoc}
     */
    public void notifyNoMessageResponse(String xml, Message message) {
        MessageMetadata messageMetadata = message.getMessageMetadata();
        // The number of milliseconds per minute, for conversion to a Timer's delay
        long delay;
        int ptuDuration = config.getIntegerProperty(ConfigParam.PTU_DURATION);
        double criticalMessageNotificationFactor = config.getDoubleProperty(ConfigParam.CRITICAL_MESSAGE_NOTIFICATION_FACTOR);
        double transactionalMessageNotificationFactor = config
                .getDoubleProperty(ConfigParam.TRANSACTIONAL_MESSAGE_NOTIFICATION_FACTOR);
        if (MessagePrecedence.CRITICAL.equals(messageMetadata.getPrecedence())) {
            delay = Math.round(MILLIS_PER_MINUTE * ptuDuration * criticalMessageNotificationFactor);
            setTimer(delay, messageMetadata, xml);
        } else if (MessagePrecedence.TRANSACTIONAL.equals(messageMetadata.getPrecedence())) {
            delay = Math.round(MILLIS_PER_MINUTE * ptuDuration * transactionalMessageNotificationFactor);
            setTimer(delay, messageMetadata, xml);
        }
    }

    private void setTimer(long delay, MessageMetadata messageMetadata, String xml) {
        LOGGER.info("Setting a programmatic timeout for {} milliseconds from now.", delay);
        NotificationInfo info = new NotificationInfo(MessageType.fromValue(messageMetadata.getPrecedence()),
                messageMetadata.getConversationID(), xml);
        long factoredDelay = delay / DateTimeUtil.getTimeFactor();
        timerService.createTimer(factoredDelay, info);
    }

    /**
     * Action to perform when timer expires.
     *
     * @param timer a s{@link Timer}.
     *
     */
    @Timeout
    public void timeoutAction(Timer timer) {
        NotificationInfo info = (NotificationInfo) timer.getInfo();
        if (ingoingMessageService.getMessageResponseByConversationId(info.getConversationId()) != null) {
            LOGGER.info("HOOK: Response for {} message with Conversation Id {} received", info.getMessageType(),
                    info.getConversationId());
            return;
        }
        jmsService.sendMessageToNotSentQueue(info.getXml());
        LOGGER.warn("HOOK: No response found for {} message with Conversation Id {} received", info.getMessageType(),
                info.getConversationId());
    }

}


text:
<?php namespace Barryvdh\TranslationManager\Console;

use Barryvdh\TranslationManager\Manager;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;

class ImportCommand extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'translations:import';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import translations from the PHP sources';

    /** @var  \Barryvdh\TranslationManager\Manager  */
    protected $manager;

    public function __construct(Manager $manager)
    {
        $this->manager = $manager;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $replace = $this->option('replace');
        $counter = $this->manager->importTranslations($replace);
        $this->info('Done importing, processed '.$counter. ' items!');

    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('replace', "R", InputOption::VALUE_NONE, 'Replace existing keys'),
        );
    }

}

redpajama_set_name: RedPajamaGithub


text:
module KnapsackPro
  module Config
    module CI
      class Buildkite < Base
        def node_total
          ENV['BUILDKITE_PARALLEL_JOB_COUNT']
        end

        def node_index
          ENV['BUILDKITE_PARALLEL_JOB']
        end

        def node_build_id
          ENV['BUILDKITE_BUILD_NUMBER']
        end

        def node_retry_count
          ENV['BUILDKITE_RETRY_COUNT']
        end

        def commit_hash
          ENV['BUILDKITE_COMMIT']
        end

        def branch
          ENV['BUILDKITE_BRANCH']
        end

        def project_dir
          ENV['BUILDKITE_BUILD_CHECKOUT_PATH']
        end
      end
    end
  end
end


text:
require 'erb'
require 'rubygems/dependency_installer'

module Bundler
  class Installer < Environment
    class << self
      attr_accessor :post_install_messages
    end

    # Begins the installation process for Bundler.
    # For more information see the #run method on this class.
    def self.install(root, definition, options = {})
      installer = new(root, definition)
      installer.run(options)
      installer
    end

    # Runs the install procedures for a specific Gemfile.
    #
    # Firstly, this method will check to see if Bundler.bundle_path exists
    # and if not then will create it. This is usually the location of gems
    # on the system, be it RVM or at a system path.
    #
    # Secondly, it checks if Bundler has been configured to be "frozen"
    # Frozen ensures that the Gemfile and the Gemfile.lock file are matching.
    # This stops a situation where a developer may update the Gemfile but may not run
    # `bundle install`, which leads to the Gemfile.lock file not being correctly updated.
    # If this file is not correctly updated then any other developer running
    # `bundle install` will potentially not install the correct gems.
    #
    # Thirdly, Bundler checks if there are any dependencies specified in the Gemfile using
    # Bundler::Environment#dependencies. If there are no dependencies specified then
    # Bundler returns a warning message stating so and this method returns.
    #
    # Fourthly, Bundler checks if the default lockfile (Gemfile.lock) exists, and if so
    # then proceeds to set up a defintion based on the default gemfile (Gemfile) and the
    # default lock file (Gemfile.lock). However, this is not the case if the platform is different
    # to that which is specified in Gemfile.lock, or if there are any missing specs for the gems.
    #
    # Fifthly, Bundler resolves the dependencies either through a cache of gems or by remote.
    # This then leads into the gems being installed, along with stubs for their executables,
    # but only if the --binstubs option has been passed or Bundler.options[:bin] has been set
    # earlier.
    #
    # Sixthly, a new Gemfile.lock is created from the installed gems to ensure that the next time
    # that a user runs `bundle install` they will receive any updates from this process.
    #
    # Finally: TODO add documentation for how the standalone process works.
    def run(options)
      # Create the BUNDLE_PATH directory
      begin
        Bundler.bundle_path.mkpath unless Bundler.bundle_path.exist?
      rescue Errno::EEXIST
        raise PathError, "Could not install to path `#{Bundler.settings[:path]}` " +
          "because of an invalid symlink. Remove the symlink so the directory can be created."
      end

      if Bundler.settings[:frozen]
        @definition.ensure_equivalent_gemfile_and_lockfile(options[:deployment])
      end

      if dependencies.empty?
        Bundler.ui.warn "The Gemfile specifies no dependencies"
        lock
        return
      end

      if Bundler.default_lockfile.exist? && !options["update"]
        real_ui, Bundler.ui = Bundler.ui, Bundler::UI.new
        begin
          tmpdef = Definition.build(Bundler.default_gemfile, Bundler.default_lockfile, nil)
          local = true unless tmpdef.new_platform? || tmpdef.missing_specs.any?
        rescue BundlerError
        end
        Bundler.ui = real_ui
      end

      # Since we are installing, we can resolve the definition
      # using remote specs
      unless local
        options["local"] ?
          @definition.resolve_with_cache! :
          @definition.resolve_remotely!
      end

      # Must install gems in the order that the resolver provides
      # as dependencies might actually affect the installation of
      # the gem.
      Installer.post_install_messages = {}
      specs.each do |spec|
        install_gem_from_spec(spec, options[:standalone])
      end

      lock
      generate_standalone(options[:standalone]) if options[:standalone]
    end

    def install_gem_from_spec(spec, standalone = false)
      # Download the gem to get the spec, because some specs that are returned
      # by rubygems.org are broken and wrong.
      Bundler::Fetcher.fetch(spec) if spec.source.is_a?(Bundler::Source::Rubygems)

      # Fetch the build settings, if there are any
      settings = Bundler.settings["build.#{spec.name}"]
      Bundler.rubygems.with_build_args [settings] do
        spec.source.install(spec)
        Bundler.ui.debug "from #{spec.loaded_from} "
      end

      # newline comes after installing, some gems say "with native extensions"
      Bundler.ui.info ""
      if Bundler.settings[:bin] && standalone
        generate_standalone_bundler_executable_stubs(spec)
      elsif Bundler.settings[:bin]
        generate_bundler_executable_stubs(spec, :force => true)
      end

      FileUtils.rm_rf(Bundler.tmp)
    rescue Exception => e
      # install hook failed
      raise e if e.is_a?(Bundler::InstallHookError) || e.is_a?(Bundler::SecurityError)

      # other failure, likely a native extension build failure
      Bundler.ui.info ""
      Bundler.ui.warn "#{e.class}: #{e.message}"
      msg = "An error occurred while installing #{spec.name} (#{spec.version}),"
      msg << " and Bundler cannot continue.\nMake sure that `gem install"
      msg << " #{spec.name} -v '#{spec.version}'` succeeds before bundling."
      Bundler.ui.debug e.backtrace.join("\n")
      raise Bundler::InstallError, msg
    end

    def generate_bundler_executable_stubs(spec, options = {})
      if options[:binstubs_cmd] && spec.executables.empty?
        options = {}
        spec.runtime_dependencies.each do |dep|
          bins = Bundler.definition.specs[dep].first.executables
          options[dep.name] = bins unless bins.empty?
        end
        if options.any?
          Bundler.ui.warn "#{spec.name} has no executables, but you may want " +
            "one from a gem it depends on."
          options.each{|name,bins| Bundler.ui.warn "  #{name} has: #{bins.join(', ')}" }
        else
          Bundler.ui.warn "There are no executables for the gem #{spec.name}."
        end
        return
      end

      # double-assignment to avoid warnings about variables that will be used by ERB
      bin_path = bin_path = Bundler.bin_path
      template = template = File.read(File.expand_path('../templates/Executable', __FILE__))
      relative_gemfile_path = relative_gemfile_path = Bundler.default_gemfile.relative_path_from(bin_path)
      ruby_command = ruby_command = Thor::Util.ruby_command

      exists = []
      spec.executables.each do |executable|
        next if executable == "bundle"

        binstub_path = "#{bin_path}/#{executable}"
        if File.exists?(binstub_path) && !options[:force]
          exists << executable
          next
        end

        File.open(binstub_path, 'w', 0755) do |f|
          f.puts ERB.new(template, nil, '-').result(binding)
        end
      end

      if options[:binstubs_cmd] && exists.any?
        case exists.size
        when 1
          Bundler.ui.warn "Skipped #{exists[0]} since it already exists."
        when 2
          Bundler.ui.warn "Skipped #{exists.join(' and ')} since they already exist."
        else
          items = exists[0...-1].empty? ? nil : exists[0...-1].join(', ')
          skipped = [items, exists[-1]].compact.join(' and ')
          Bundler.ui.warn "Skipped #{skipped} since they already exist."
        end
        Bundler.ui.warn "If you want to overwrite skipped stubs, use --force."
      end
    end

  private

    def generate_standalone_bundler_executable_stubs(spec)
      # double-assignment to avoid warnings about variables that will be used by ERB
      bin_path = Bundler.bin_path
      template = File.read(File.expand_path('../templates/Executable.standalone', __FILE__))
      ruby_command = ruby_command = Thor::Util.ruby_command

      spec.executables.each do |executable|
        next if executable == "bundle"
        standalone_path = standalone_path = Pathname(Bundler.settings[:path]).expand_path.relative_path_from(bin_path)
        executable_path = executable_path = Pathname(spec.full_gem_path).join(spec.bindir, executable).relative_path_from(bin_path)
        File.open "#{bin_path}/#{executable}", 'w', 0755 do |f|
          f.puts ERB.new(template, nil, '-').result(binding)
        end
      end
    end

    def generate_standalone(groups)
      standalone_path = Bundler.settings[:path]
      bundler_path = File.join(standalone_path, "bundler")
      FileUtils.mkdir_p(bundler_path)

      paths = []

      if groups.empty?
        specs = Bundler.definition.requested_specs
      else
        specs = Bundler.definition.specs_for groups.map { |g| g.to_sym }
      end

      specs.each do |spec|
        next if spec.name == "bundler"

        spec.require_paths.each do |path|
          full_path = File.join(spec.full_gem_path, path)
          gem_path = Pathname.new(full_path).relative_path_from(Bundler.root.join(bundler_path))
          paths << gem_path.to_s.sub("#{SystemRubyVersion.new.engine}/#{RbConfig::CONFIG['ruby_version']}", '#{ruby_engine}/#{ruby_version}')
        end
      end

      File.open File.join(bundler_path, "setup.rb"), "w" do |file|
        file.puts "# ruby 1.8.7 doesn't define RUBY_ENGINE"
        file.puts "ruby_engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'"
        file.puts "ruby_version = RbConfig::CONFIG[\"ruby_version\"]"
        file.puts "path = File.expand_path('..', __FILE__)"
        paths.each do |path|
          file.puts %{$:.unshift File.expand_path("\#{path}/#{path}")}
        end
      end
    end
  end
end


text:
import math

nth_prime = 10001

n_counter = 2
prime_counter = 0

# count the number of primes, break on nth
while (True):
    prime = True
    # only go up to the sqare root to speed up algorithm
    for i in range (2, math.floor(math.sqrt(n_counter)) + 1):
        if n_counter % i == 0:
            prime = False
    if prime:
        prime_counter = prime_counter + 1
        if prime_counter == nth_prime:
            print (prime_counter)
            print (n_counter)
            break
    n_counter = n_counter + 1


text:
package org.broadinstitute.hellbender.tools.picard.illumina.parser.readers;

import org.broadinstitute.hellbender.tools.picard.illumina.parser.BclData;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.File;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class BclReaderTest {

    public static final File TestDataDir = new File("src/test/resources/org/broadinstitute/hellbender/tools/picard/illumina/readerTests");
    public static final File PASSING_BCL_FILE = new File(TestDataDir, "bcl_passing.bcl");
    public static final File QUAL_0FAILING_BCL_FILE = new File(TestDataDir, "bcl_failing.bcl");
    public static final File QUAL_1FAILING_BCL_FILE = new File(TestDataDir, "bcl_failing2.bcl");
    public static final File FILE_TOO_LONG = new File(TestDataDir, "bcl_tooLong.bcl");
    public static final File FILE_TOO_SHORT = new File(TestDataDir, "bcl_tooShort.bcl");

    public static final char[] expectedBases = new char[]{
            'C', 'A', 'A', 'A', 'T', 'C', 'T', 'G', 'T', 'A', 'A', 'G', 'C', 'C', 'A', 'A',
            'C', 'A', 'C', 'C', 'A', 'A', 'C', 'G', 'A', 'T', 'A', 'C', 'A', 'A', 'C', 'A',
            'T', 'G', 'C', 'A', 'C', 'A', 'A', 'C', 'G', 'C', 'A', 'A', 'G', 'T', 'G', 'C',
            'A', 'C', 'G', 'T', 'A', 'C', 'A', 'A', 'C', 'G', 'C', 'A', 'C', 'A', 'T', 'T',
            'T', 'A', 'A', 'G', 'C', 'G', 'T', 'C', 'A', 'T', 'G', 'A', 'G', 'C', 'T', 'C',
            'T', 'A', 'C', 'G', 'A', 'A', 'C', 'C', 'C', 'A', 'T', 'A', 'T', 'G', 'G', 'G',
            'C', 'T', 'G', 'A', 'A', '.', '.', 'G', 'A', 'C', 'C', 'G', 'T', 'A', 'C', 'A',
            'G', 'T', 'G', 'T', 'A', '.'
    };

    public static final int[] expectedQuals = new int[]{
            18, 29, 8, 17, 27, 25, 28, 27, 9, 29, 8, 20, 25, 24, 27, 27,
            30, 8, 19, 24, 29, 29, 25, 28, 8, 29, 26, 24, 29, 8, 18, 8,
            29, 28, 26, 29, 25, 8, 26, 25, 28, 25, 8, 28, 28, 27, 29, 26,
            25, 26, 27, 25, 8, 18, 8, 26, 24, 29, 25, 8, 24, 8, 25, 27,
            27, 25, 8, 28, 24, 27, 25, 25, 8, 27, 25, 8, 16, 24, 28, 25,
            28, 8, 24, 27, 25, 8, 20, 29, 24, 27, 28, 8, 23, 10, 23, 11,
            15, 11, 10, 12, 12, 2, 2, 31, 24, 8, 4, 36, 12, 17, 21, 4,
            8, 12, 18, 23, 27, 2
    };

    public byte[] qualsAsBytes() {
        final byte[] byteVals = new byte[expectedQuals.length];
        for (int i = 0; i < byteVals.length; i++) {
            byteVals[i] = (byte) expectedQuals[i];
        }
        return byteVals;
    }

    @Test
    public void readValidFile() {
        final BclQualityEvaluationStrategy bclQualityEvaluationStrategy = new BclQualityEvaluationStrategy(BclQualityEvaluationStrategy.ILLUMINA_ALLEGED_MINIMUM_QUALITY);
        final BclReader reader = new BclReader(PASSING_BCL_FILE, bclQualityEvaluationStrategy, false);
        final byte[] quals = qualsAsBytes();

        Assert.assertEquals(reader.numClustersPerCycle[0], expectedBases.length);

        int readNum = 0;
        while (readNum < reader.numClustersPerCycle[0]) {
            final BclData bv = reader.next();
            Assert.assertEquals(bv.bases[0][0], expectedBases[readNum], " On num cluster: " + readNum);
            Assert.assertEquals(bv.qualities[0][0], quals[readNum], " On num cluster: " + readNum);
            ++readNum;
        }
        bclQualityEvaluationStrategy.assertMinimumQualities();
        reader.close();
    }

    @DataProvider(name = "failingFiles")
    public Object[][] failingFiles() {
        return new Object[][]{
                {QUAL_0FAILING_BCL_FILE},
                {QUAL_1FAILING_BCL_FILE},
                {new File(TestDataDir, "SomeNoneExistentFile.bcl")},
                {FILE_TOO_LONG},
                {FILE_TOO_SHORT}
        };
    }

    @Test(expectedExceptions = IlluminaReaderException.class, dataProvider = "failingFiles")
    public void failingFileTest(final File failingFile) {
        final BclQualityEvaluationStrategy bclQualityEvaluationStrategy = new BclQualityEvaluationStrategy(BclQualityEvaluationStrategy.ILLUMINA_ALLEGED_MINIMUM_QUALITY);
        final BclReader reader = new BclReader(failingFile, bclQualityEvaluationStrategy, false);
        Assert.assertEquals(reader.numClustersPerCycle[0], expectedBases.length);
        while (reader.hasNext()) {
            reader.next();
        }
        reader.close();
        bclQualityEvaluationStrategy.assertMinimumQualities();
    }

    /**
     * Asserts appropriate functionality of a quality-minimum-customized BLC reader, such that (1) if sub-Q2 qualities are found, the BCL
     * reader does not throw an exception, (2) sub-minimum calls are set to quality 1 and (3) sub-minimum calls are counted up properly.
     */
    @Test
    public void lowQualityButPassingTest() throws ExecutionException, InterruptedException {
        final BclQualityEvaluationStrategy bclQualityEvaluationStrategy = new BclQualityEvaluationStrategy(1);

        // Build a list of callables, then submit them and check for errors.
        final Collection<Callable<Void>> callables = new LinkedList<Callable<Void>>();
        for (int i = 0; i < 10; i++) {
            final boolean even_i = i % 2 == 0;
            callables.add(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    final BclReader reader = new BclReader(even_i ? QUAL_1FAILING_BCL_FILE : QUAL_0FAILING_BCL_FILE,
                            bclQualityEvaluationStrategy, false);
                    Assert.assertEquals(reader.numClustersPerCycle[0], expectedBases.length);
                    while (reader.hasNext()) {
                        reader.next();
                    }
                    reader.close();
                    return null;
                }
            });
        }
        final ExecutorService executorService = Executors.newFixedThreadPool(callables.size());
        final Collection<Future<Void>> futures = new LinkedList<Future<Void>>();
        for (final Callable<Void> callable : callables) {
            futures.add(executorService.submit(callable));
        }
        for (final Future<Void> future : futures) {
            future.get();
        }
        bclQualityEvaluationStrategy.assertMinimumQualities();
        Assert.assertEquals((int) bclQualityEvaluationStrategy.getPoorQualityFrequencies().get((byte) 0), 25);
        Assert.assertEquals((int) bclQualityEvaluationStrategy.getPoorQualityFrequencies().get((byte) 1), 25);
    }

    @Test(expectedExceptions = IlluminaReaderException.class)
    public void lowQualityAndFailingTest() throws ExecutionException, InterruptedException {
        final BclQualityEvaluationStrategy bclQualityEvaluationStrategy = new BclQualityEvaluationStrategy(BclQualityEvaluationStrategy.ILLUMINA_ALLEGED_MINIMUM_QUALITY);

        // Build a list of callables, then submit them and check for errors.
        final Collection<Callable<Void>> callables = new LinkedList<Callable<Void>>();
        for (int i = 0; i < 10; i++) {
            final boolean even_i = i % 2 == 0;
            callables.add(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    final BclReader reader = new BclReader(even_i ? QUAL_1FAILING_BCL_FILE : QUAL_0FAILING_BCL_FILE,
                            bclQualityEvaluationStrategy, false);
                    Assert.assertEquals(reader.numClustersPerCycle[0], expectedBases.length);
                    while (reader.hasNext()) {
                        reader.next();
                    }
                    reader.close();
                    return null;
                }
            });
        }
        final ExecutorService executorService = Executors.newFixedThreadPool(callables.size());
        final Collection<Future<Void>> futures = new LinkedList<Future<Void>>();
        for (final Callable<Void> callable : callables) {
            futures.add(executorService.submit(callable));
        }
        for (final Future<Void> future : futures) {
            future.get();
        }
        Assert.assertEquals((int) bclQualityEvaluationStrategy.getPoorQualityFrequencies().get((byte) 0), 25);
        Assert.assertEquals((int) bclQualityEvaluationStrategy.getPoorQualityFrequencies().get((byte) 1), 25);
        bclQualityEvaluationStrategy.assertMinimumQualities();
    }
}


text:
'use strict';
const common = require('../common');
const assert = require('assert');
const fs = require('fs');

const tmpdir = require('../common/tmpdir');
tmpdir.refresh();

const stream = fs.createWriteStream(`${tmpdir.path}/out`, {
  highWaterMark: 10
});
const err = new Error('BAM');

const write = fs.write;
let writeCalls = 0;
fs.write = function() {
  switch (writeCalls++) {
    case 0:
      console.error('first write');
      // First time is ok.
      return write.apply(fs, arguments);
    case 1:
      // Then it breaks.
      console.error('second write');
      const cb = arguments[arguments.length - 1];
      return process.nextTick(function() {
        cb(err);
      });
    default:
      // It should not be called again!
      throw new Error('BOOM!');
  }
};

fs.close = common.mustCall(function(fd_, cb) {
  console.error('fs.close', fd_, stream.fd);
  assert.strictEqual(fd_, stream.fd);
  fs.closeSync(fd_);
  process.nextTick(cb);
});

stream.on('error', common.mustCall(function(err_) {
  console.error('error handler');
  assert.strictEqual(stream.fd, null);
  assert.strictEqual(err_, err);
}));

stream.write(Buffer.allocUnsafe(256), function() {
  console.error('first cb');
  stream.write(Buffer.allocUnsafe(256), common.mustCall(function(err_) {
    console.error('second cb');
    assert.strictEqual(err_, err);
  }));
});


text:
package uk.sky.cqlmigrate;

import com.datastax.oss.driver.api.core.ConsistencyLevel;
import com.datastax.oss.driver.api.core.CqlSession;

import java.time.Duration;

public class CassandraLockConfig extends LockConfig {

    private final ConsistencyLevel consistencyLevel;
    private final String lockKeyspace;

    private CassandraLockConfig(Duration pollingInterval, Duration timeout, String clientId, boolean unlockOnFailure, ConsistencyLevel consistencyLevel, String lockKeyspace) {
        super(pollingInterval, timeout, clientId, unlockOnFailure);
        this.consistencyLevel = consistencyLevel;
        this.lockKeyspace = lockKeyspace;
    }

    @Override
    public LockingMechanism getLockingMechanism(CqlSession session, String keySpace) {
        return new CassandraLockingMechanism(session, keySpace, consistencyLevel, lockKeyspace);
    }

    public static CassandraLockConfigBuilder builder() {
        return new CassandraLockConfigBuilder();
    }

    public ConsistencyLevel getConsistencyLevel() {
        return this.consistencyLevel;
    }

    public static class CassandraLockConfigBuilder extends LockConfig.LockConfigBuilder {
        private ConsistencyLevel consistencyLevel = ConsistencyLevel.LOCAL_ONE;
        private String lockKeyspace = "cqlmigrate";

        private CassandraLockConfigBuilder() {}

        @Override
        public CassandraLockConfigBuilder withPollingInterval(Duration pollingInterval) {
            super.withPollingInterval(pollingInterval);
            return this;
        }

        @Override
        public CassandraLockConfigBuilder withTimeout(Duration timeout) {
            super.withTimeout(timeout);
            return this;
        }

        @Override
        public CassandraLockConfigBuilder unlockOnFailure() {
            super.unlockOnFailure();
            return this;
        }

        public CassandraLockConfigBuilder withConsistencyLevel(ConsistencyLevel consistencyLevel) {
            this.consistencyLevel = consistencyLevel;
            return this;
        }

        public CassandraLockConfigBuilder withLockKeyspace(String lockKeyspace) {
            this.lockKeyspace = lockKeyspace;
            return this;
        }

        public CassandraLockConfig build() {
            return new CassandraLockConfig(pollingInterval, timeout, clientId, unlockOnFailure, consistencyLevel, lockKeyspace);
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>MOD.core.dom - Mod JS</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.7.0/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="stylesheet" href="../assets/css/custom.css">
    <link rel="stylesheet" href="../assets/vendor/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="../assets/vendor/bootstrap/css/bootstrap-responsive.css">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        Toggle navigation

      </button>

Getting Started

Docs

Code

Issues

APIs

Classes

Modules

            <input type="search" placeholder="Type to filter APIs">

MOD.app

MOD.core

MOD.core.dom

MOD.core.util

MOD.form

MOD.form.check

MOD.sandbox

MOD.template

MOD.ui

MOD

                <form id="options-form" class="form-inline pull-right">
        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

    </form>

MOD.core.dom Class

            Defined in: src/core.js:343

            Module: MOD

The MOD.core.dom object handles all DOM interaction, if it affects the page it should happen here. These functions should only be accessed by the sandbox, never in the module!!

Index

Methods

Item Index

Methods

                                add_class

                                append_elems

                                apply_attrs

                                bind

                                create

                                has_class

                                next_element

                                offset

                                onload

                                onready

                                prepend_elems

                                previous_element

                                prop

                                query

                                remove_class

                                style

                                unbind

Methods

add_class

            (

                        el

                        class_to_add

)

            None

        private

                Defined in

        src/core.js:653

Add a class to an elment within the module

MOD.core.dom.add_class( el, 'class-to-add' );

Parameters:

                        el
                        Object

the element to add the class to

                        class_to_add
                        String

the class to add

Returns:

                        None:

append_elems

            (

                        el

                        elems

)

            None

        private

                Defined in

        src/core.js:738

Append elements within the scope of the module, accepts DOM elements or html

var el = MOD.core.dom.create( config );

MOD.core.dom.append_elems( el_to_append_to, el );

Parameters:

                        el
                        Object

the element to append into

                        elems
                        Array

the elements to append

Returns:

                        None:

apply_attrs

            (

                        el

                        attrs

)

            None

        private

                Defined in

        src/core.js:525

Add attributes to an element like src, href, etc...

var attrs = {
    'src' : http://someurl.com/awesome/image.jpg,
    'class' : 'awesome-img'
};

MOD.core.dom.apply_attrs( img, attrs );

Parameters:

                        el
                        Object

the element to apply the attrs to

                        attrs
                        Object

the attrs to apply

Returns:

                        None:

bind

            (

                        elem

                        evt

                        fn

)

            None

        private

                Defined in

        src/core.js:388

Attach events to elements within the module such as 'click', 'mouseenter', etc...

MOD.core.dom.bind( btn, 'click', someFunction );

Parameters:

                        elem
                        String

the element that we are attaching to

                        evt
                        String

the event type we want to attach

                        fn
                        Function

the function we want to execute

Returns:

                        None:

create

            (

                        config

)

            Object

        private

                Defined in

        src/core.js:434

Create a new DOM element and apply any attributes or create any child elements

var config = {
    el : 'div',
    attrs : {
        'id' : 'awesome',
        'class' : 'framework'
    },
    children : [
        {
            el : 'p',
            text : 'This framework is awesome!!',
            attrs : {
                'class' : 'shout-it-out'
            }
        }
    ]
};

var el = MOD.core.dom.create( config );

Parameters:

                        config
                        Object

element type to create

Returns:

                        Object:

DOM object that was created

has_class

            (

                        el

                        class_to_find

)

            Boolean

        private

                Defined in

        src/core.js:711

Checks a DOM element for a specified class

if ( MOD.core.dom.has_class( el, 'some-class' ) ) {
    // do something if has class
} else {
    // do something if doesn't have class
}

Parameters:

                        el
                        Object

the DOM element to check

                        class_to_find
                        String

the class to look for

Returns:

                        Boolean:

true if has class / else false

next_element

            (

                        el

)

            Object

        private

                Defined in

        src/core.js:782

Gets the next element that is not a text node, script tag, or style tag

var next = MOD.core.dom.next_element( el );

Parameters:

                        el
                        Object

the object whos next sibling you require

Returns:

                        Object:

the next sibling

offset

            (

                        el

)

            Object

        private

                Defined in

        src/core.js:577

returns x and y coords of the offset of the element relative to the document

var offset = PIX.core.dom.offset( el );

window.scrollTo( 0, offset.y );

Parameters:

                        el
                        Object

the DOM element you want the offset of

Returns:

                        Object:

object containing x and y coords

onload

            (

                        fn

)

            None

        private

                Defined in

        src/core.js:874

Handles running any code that needs to be run only after the window has loaded

Used by the MOD.app object

MOD.core.dom.onload( function () {
    // do some stuff when the window is loaded
});

Parameters:

                        fn
                        Function

the function(s) to run

Returns:

                        None:

onready

            (

                        fn

)

            None

        private

                Defined in

        src/core.js:854

Handles running any code that needs to be run only after the document has loaded

Used by the MOD.app object

MOD.core.dom.onready( function () {
    // do some stuff when the document is loaded
});

Parameters:

                        fn
                        Function

the function(s) to run

Returns:

                        None:

prepend_elems

            (

                        el

                        elems

)

            None

        private

                Defined in

        src/core.js:760

Prepend elements within the scope of the module, accepts DOM elements or html

var el = MOD.core.dom.create( config );

MOD.core.dom.prepend_elems( el_to_append_to, el );

Parameters:

                        el
                        Object

the element to prepend into

                        elems
                        Array

the elements to prepend

Returns:

                        None:

previous_element

            (

                        el

)

            Object

        private

                Defined in

        src/core.js:816

Gets the previous element that is not a text node, script tag, or style tag

var prev = MOD.core.dom.previous_element( el );

Parameters:

                        el
                        Object

the object whos previous sibling you require

Returns:

                        Object:

the previous sibling

prop

            (

                        el

                        prop

                        value

)

            None

        private

                Defined in

        src/core.js:558

Gets or sets a single property on an element

Parameters:

                        el
                        Object

the DOM element to update

                        prop
                        String

the property or attribute to update/retrieve

                        value
                        String

if setting, the value to apply to the property/attribute

Returns:

                        None:

query

            (

                        selector

                        context

)

            Object

        private

                Defined in

        src/core.js:350

The main query function, ties in to base to find elements. This function is the base for all DOM searching

var CONTAINER = MOD.dom.query( '#' + moduleID );

Parameters:

                        selector
                        String

the CSS selector of the requested elements

                        context
                        Object

the object to look within for the selected items

Returns:

                        Object:

jQuery like object of the DOM elements, just with less power

remove_class

            (

                        el

                        class_to_remove

)

            None

        private

                Defined in

        src/core.js:684

Remove a class from an element within the module

MOD.core.dom.remove_class( el, 'class-to-remove' );

Parameters:

                        el
                        Object

the element to remove the class from

                        class_to_remove
                        String

the class to remove

Returns:

                        None:

style

            (

                        el

                        css

                        if

)

            String / null

        private

                Defined in

        src/core.js:615

Update styles on a DOM element

Parameters:

                        el
                        Object

the element to style

                        css
                        Object / string

the key/value object of css properties / or css property string

                        if
                        String

set, should be string value of style to set on element

Returns:

                        String / null:

if calling for property returns property value as string

unbind

            (

                        elem

                        evt

                        fn

)

            None

        private

                Defined in

        src/core.js:411

Remove events on elements within the module such as 'click', 'mouseenter', etc...

MOD.core.dom.unbind( btn, 'click', someFunction );

Parameters:

                        elem
                        String

the element that we are removing the event on

                        evt
                        String

the event type we want to remove

                        fn
                        Function

the function we want to remove

Returns:

                        None:


text:
package alien4cloud.audit.annotation;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

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

@Target({ METHOD, TYPE })
@Retention(RUNTIME)
public @interface Audit {

    boolean enabledByDefault() default true;

    String category() default "";

    String action() default "";

    String[] bodyHiddenFields() default {};
}


text: <link rel="stylesheet" type="text/css" href="css/filepreview.css" />


text:
$(document).ready(function(){
	//global vars
	var inputUser = $("#nick");
	var inputMessage = $("#message");
	var loading = $("#loading");
	var messageList = $("#derniers_message");

	//functions
	function updateShoutbox(){
		//just for the fade effect
		loading.hide();

		$.ajax({
			type: "POST", url: "fonctions/shoutbox.php", data: "action=update",
			complete: function(data){
				messageList.html(data.responseText);
			}
		});
		 setTimeout(updateShoutbox, 5000);
	}
	//check if all fields are filled
	function checkForm(){
		if(inputMessage.attr("value"))
			return true;
		else
			return false;
	}

	//Load for the first time the shoutbox data
	updateShoutbox();

	//on submit event
	$("#form").submit(function(){
		if(checkForm()){
			var nick = inputUser.attr("value");
			var message = inputMessage.attr("value");
			//we deactivate submit button while sending
			$("#send").attr({ disabled:true, value:"Envoi en cours..." });
			$("#send").blur();
			//send the post to fonctions/shoutbox.phpshoutbox.php
			$.ajax({
				type: "POST", url: "fonctions/shoutbox.php", data: "action=insert&nick=" + nick + "&message=" + message,
				complete: function(data){
					messageList.html(data.responseText);
					updateShoutbox();
					        //On efface le champ d'envoi, et on lui redonne le focus
        document.getElementById("message").value="";//Vider le champ
        document.getElementById("message").focus();

					//reactivate the send button
					$("#send").attr({ disabled:false, value:"Envoyer" });
				}
			 });
		}
		else alert("Vous n'avez pas mis de message , c'est pas facile pour parler :-°");
		//we prevent the refresh of the page after submitting the form
		return false;
	});
});


text:
 function mass = xray_read_atomic_mass(mtype, varargin)
%function mass = xray_read_atomic_mass(mtype)
%
% Read atomic mass for a given material type.
%
% in
%	mtype			'aluminum', 'copper', 2, '2', '02-helium', ...
%				See xray_material_file_name.m
%		(Optionally mtype can be a cell array of several materials.
%		If so, kev_in is mandatory and the output will be an array.)
%
% out
%	mass	[M,1]	atomic mass
%
% Copyright 2008-04-27, Jeff Fessler, The University of Michigan

% default is to show example
if nargin < 1, help(mfilename), error(mfilename), end
if nargin == 1 && streq(mtype, 'test'), xray_read_atomic_mass_test, return, end

if isnumeric(mtype) && length(mtype) > 1
	mtype = num2cell(mtype);
end

if iscell(mtype)
	mass = zeros(size(mtype)); % array
	for ll=1:length(mtype)
		mass(ll) = xray_read_atomic_mass(mtype{ll}, varargin{:});
	end
return
end

% defaults
arg.units = '';
arg = vararg_pair(arg, varargin);

% trick: mass file near is near material file, and name parsing
if isnumeric(mtype)
	file = xray_material_file_name(1); % trick to allow z > 92
	zz = mtype; % atomic number
else
	file = xray_material_file_name(mtype);

	% atomic number:
	zz = regexprep(file, '/.*\/', '');
	zz = regexprep(zz, '-.*', '');
	zz = str2num(zz);
end

% atomic mass file
file = regexprep(file, 'element.*', 'atomic-mass/atomic-mass-list');

tmp = load_ascii_skip_header(file); % read uncommented lines
if zz < 1 || zz > length(tmp)
	fail('bad element %d', zz)
end
tmp = tmp(zz,:);
if tmp(1) ~= zz, fail('bug %d', zz), end

mass = tmp(2);

%
% xray_read_atomic_mass_test()
% example usage
%
function xray_read_atomic_mass_test
mtypes = {'lead', 2, '02-helium'};
mass = xray_read_atomic_mass(mtypes);

zz = 1:118;
mass = xray_read_atomic_mass(zz);
if im
	plot(zz, zz ./ mass, '-o')
	xlabel 'Z'
	ylabel 'Z/A'
%	savefig fig-z-a
end


text:
package dynamicloaders.plugin.sample;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.Map;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import dynamicloaders.core.plugin.Plugin;
import dynamicloaders.core.plugin.PluginManager;
import dynamicloaders.core.plugin.PluginManagerCompanion;

public class TimePluginTest {

	static PluginManager pmGlobal = null;

	@Before
	public void setUp() throws Exception {
		synchronized (this) {
			pmGlobal = new PluginManager();
		}

	}

	@After
	public void tearDown() throws Exception {
		synchronized (this) {
			pmGlobal = null;
		}
	}

	@Test
	public void testCreatePluginFromClass_TimePlugin() {
		System.out.println("testCreatePluginFromClass: should load a plugin from the given class name ...");
		System.out.println("testCreatePluginFromClass: plugin in this project ...");
		String name =
			"dynamicloaders.core.plugin.sample.TimePlugin";
		System.out.println("testCreatePluginFromClass: try to load plugin with name: \"" + name + "\"");
		Plugin p = PluginManagerCompanion.createPluginFromClass(name, null);
		System.out.println("testCreatePluginFromClass: Plugin loaded: name: \"" + name + "\", class instance: " + p);
		assertNotNull(p);

		System.out.println("testCreatePluginFromClass: plugin in dependency project ...");
		String name2 =
			"dynamicloaders.core.plugin.sample.TimePlugin";
		System.out.println("testCreatePluginFromClass: try to load plugin with name: \"" + name2 + "\"");
		Plugin p2 = PluginManagerCompanion.createPluginFromClass(name2, null);
		System.out.println("testCreatePluginFromClass: Plugin loaded: name: \"" + name2 + "\", class instance: " + p2);
		assertNotNull(p2);
	}

	@Test
	public void testCreatePluginWithCustomPluginApi() {
		System.out.println("testCreatePluginWithCustomPluginApi: should load the plugin from two manifest files (but without failing on duplicates), one in this project and one in dependency project too ...");
		System.out.println("testCreatePluginWithCustomPluginApi: try to retrieve a PluginManager instance ...");
		Class<? extends Plugin> api = dynamicloaders.core.plugin.sample.TimePlugin.class;
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		int namingStrategy = 0;
		// boolean failOnDuplicates = true;
		boolean failOnDuplicates = false;
		System.out.println("testCreatePluginWithCustomPluginApi: failOnDuplicates = " + failOnDuplicates);
		PluginManager pm = PluginManagerCompanion.createWithAll(api, loader, namingStrategy, failOnDuplicates);
		System.out.println("testCreatePluginWithCustomPluginApi: created a PluginManager instance: \"" + pm + "\"");
		assertNotNull(pm);
		int numberOfPlugins = pm.getPlugins().size();
		System.out.println("testCreatePluginWithCustomPluginApi: PluginManager instance contains " + numberOfPlugins + " plugins");
		// important test:
		// should load 1 plugin from the manifest in this project,
		// and 1 from the manifest in the other project (as dependency for this project),
		// but with failOnDuplicates false the last should update existing one ...
		// assertTrue(numberOfPlugins > 0);
		assertTrue(numberOfPlugins == 1);
	}

	@Test
	public void testCreatePluginOneWithCustomPluginApi() {
		System.out.println("testCreatePluginOneWithCustomPluginApi: should load the plugin from manifest files and chose the first ...");
		System.out.println("testCreatePluginWOneithCustomPluginApi: try to retrieve a PluginManager instance ...");
		Class<? extends Plugin> api = dynamicloaders.core.plugin.sample.TimePlugin.class;
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		int namingStrategy = 0;
		PluginManager pm = PluginManagerCompanion.createWithOne(api, loader, namingStrategy);
		System.out.println("testCreatePluginOneWithCustomPluginApi: created a PluginManager instance: \"" + pm + "\"");
		assertNotNull(pm);
		int numberOfPlugins = pm.getPlugins().size();
		System.out.println("testCreatePluginWithCustomPluginApi: PluginManager instance contains " + numberOfPlugins + " plugins");
		assertTrue(numberOfPlugins == 1);
	}

	@Test
	public void testPluginDefaults() {
		System.out.println("testPluginDefaults: testing plugin manager defaults, after creation with default constructor ...");
		assertNotNull(pmGlobal);
		assertNotNull(pmGlobal.getApi());
		assertTrue(pmGlobal.getApi() == Plugin.class);
		assertNotNull(pmGlobal.getLoader());
		assertNotNull(pmGlobal.getConfig());
		assertNotNull(pmGlobal.getPlugins());
		assertTrue(pmGlobal.getPlugins().size() == 0);
	}

	@Test
	public void testGetPluginInfo() {
		System.out.println("testGetPluginInfo: check plugin info for a created plugin under test here ...");
		System.out.println("testGetPluginInfo: try to retrieve a PluginManager instance ...");
		Class<? extends Plugin> api = dynamicloaders.core.plugin.sample.TimePlugin.class;
		String pluginDefaultKey = api.getName();
		PluginManager pm = PluginManagerCompanion.createWithOne(api, null);
		System.out.println("testGetPluginInfo: created a PluginManager instance: \"" + pm + "\"");
		assertNotNull(pm);
		int numberOfPlugins = pm.getPlugins().size();
		System.out.println("testGetPluginInfo: PluginManager instance contains " + numberOfPlugins + " plugins");
		assertTrue(numberOfPlugins == 1);

		assertNotNull(pm.getPlugin(pluginDefaultKey));
		assertNotNull(pm.getPlugin(pluginDefaultKey).getPluginInfo());
		assertNotNull(pm.getPlugin(pluginDefaultKey).getPluginInfo().getName());
		assertTrue(pm.getPlugin(pluginDefaultKey).getPluginInfo().getName() == "timePlugin");
		assertTrue(pm.getPlugin(pluginDefaultKey).getPluginInfo().getVersion() == "1.0.0");
	}

	@Test
	public void testGetPluginFeatures() {
		System.out.println("testGetPluginFeatures: check plugin features for a created plugin under test here ...");
		System.out.println("testGetPluginFeatures: try to retrieve a PluginManager instance ...");
		Class<? extends Plugin> api = dynamicloaders.core.plugin.sample.TimePlugin.class;
		String pluginDefaultKey = api.getName();
		PluginManager pm = PluginManagerCompanion.createWithOne(api, null);
		System.out.println("testGetPluginFeatures: created a PluginManager instance: \"" + pm + "\"");
		assertNotNull(pm);
		int numberOfPlugins = pm.getPlugins().size();
		System.out.println("testGetPluginFeatures: PluginManager instance contains " + numberOfPlugins + " plugins");
		assertTrue(numberOfPlugins == 1);

		assertNotNull(pm.getPlugin(pluginDefaultKey));
		assertNotNull(pm.getPlugin(pluginDefaultKey).getPluginFeatures());
		assertTrue(pm.getPlugin(pluginDefaultKey).getPluginFeatures().size() == 1);
	}

	@Test
	public void testGetPluginStatus() {
		System.out.println("testGetPluginStatus: check plugin status for a created plugin under test here ...");
		System.out.println("testGetPluginStatus: try to retrieve a PluginManager instance ...");
		Class<? extends Plugin> api = dynamicloaders.core.plugin.sample.TimePlugin.class;
		String pluginDefaultKey = api.getName();
		PluginManager pm = PluginManagerCompanion.createWithOne(api, null);
		System.out.println("testGetPluginStatus: created a PluginManager instance: \"" + pm + "\"");
		assertNotNull(pm);
		int numberOfPlugins = pm.getPlugins().size();
		System.out.println("testGetPluginStatus: PluginManager instance contains " + numberOfPlugins + " plugins");
		assertTrue(numberOfPlugins == 1);

		assertNotNull(pm.getPlugin(pluginDefaultKey));
		assertTrue(pm.getPlugin(pluginDefaultKey).getPluginStatus() == 0);
	}

	@Test
	public void testDoExecute() {
		System.out.println("testDoExecute: check plugin info for a loaded plugin under test here ...");
		System.out.println("testDoExecute: try to retrieve a PluginManager instance ...");
		Class<? extends Plugin> api = dynamicloaders.core.plugin.sample.TimePlugin.class;
		String pluginDefaultKey = api.getName();
		PluginManager pm = PluginManagerCompanion.createWithOne(api, null);
		System.out.println("testDoExecute: created a PluginManager instance: \"" + pm + "\"");
		assertNotNull(pm);
		int numberOfPlugins = pm.getPlugins().size();
		System.out.println("testDoExecute: PluginManager instance contains " + numberOfPlugins + " plugins");
		assertTrue(numberOfPlugins == 1);

		Plugin p = pm.getPlugin(pluginDefaultKey);
		System.out.println("testDoExecute: Plugin instance is " + p);
		assertNotNull(p);
		Map<String, String> params = null;
		System.out.println("testDoExecute: Plugin params (for execution) are: " + params);
		Map<String, ?> results = p.doExecute(params);
		System.out.println("testDoExecute: Plugin results (of execution) are: " + results);
		assertNotNull(results);
		assertNotNull(results.get("time"));
		Long l = new Long((String) results.get("time"));
		assertNotNull(l);
		// another execution
		results = p.doExecute(params);
		System.out.println("testDoExecute: Plugin results (of execution) are: " + results);
		Long l2 = new Long((String) results.get("time"));
		assertNotNull(l2);
		assertTrue(l.longValue() <= l2.longValue());
	}

	// TODO: add more tests on pmGlobal, like addPlugin() etc ...

}


text:
var util = require("../util");
var logger = require("../logger");

// https://github.com/ankane/ahoy#javascript
module.exports = function (eventData) {
  var name     = "ahoy";
  var logLabel = "Bighorn.track ahoy";
  var tracker  = self[name];

  try {
    if (!util.isObject(tracker)) {
      logger.log("SKIP", logLabel, "tracker not found", eventData);
      return false;
    }
    if (!util.isFunction(tracker.track)) {
      logger.log("SKIP", logLabel, "track method not found", eventData);
      return false;
    }
    if (!util.isValidString(eventData.name)) {
      logger.log("SKIP", logLabel, "event name missing", eventData);
      return false;
    }

    tracker.track(eventData.name, eventData);
    logger.log("SUCCESS", logLabel, eventData);
    return true;
  } catch (e) {
    logger.log("ERROR", logLabel, e.message, eventData);
    return false;
  }
};


text:
using System.Collections.Generic;

namespace HaloOnline.Server.Model.GameStatistics
{
    public class UserChallenges
    {
        public int Version { get; set; }
        public List<UserChallenge> Challenges { get; set; }
    }
}