text:
"use strict";

var map = function(f, thing) {
  if(thing.map) {
    return thing.map(f);
  }

  throw new Error("Object given does not implement map");
};

var square = function(x) {
  return x * x;
};

console.log(map(square, [1,2,3]));

Object.prototype.map = function(f) {
  var result = {}, that = this;

  Object.keys(this).forEach(function(key) {
    result[key] = f(key, that[key]);
  });

  return result;
};

var obj = {
  "courses" : ["Programming 101", "Frontend JavaScript", "Core Java"]
};

console.log(map(function(key, value) {
  return map(function(course) {
    return course + "!";
  }, value);
}, obj));

String.prototype.map = function(f) {
  var result = this.split("");
  return map(f, result).join("");
};

console.log(map(function(ch) {
  return ch.toUpperCase();
}, "javascript"));


text:
package com.workshop.rest;

import java.util.List;

public interface UserService {
    List<User> list();

    void create(User user);
}

redpajama_set_name: RedPajamaGithub


text:
$(document).ready(function() {

  window.ga = window.ga || function() {};

  cdb.init(function() {

    if ($('.is-index-action').length > 0) {
      window.search_index = new gfw.ui.view.SearchIndex();
    }

  });

});


text:
package api.web.gw2.jsonp.v1.guilddetails;

import api.web.gw2.mapping.core.IdValue;
import api.web.gw2.mapping.core.LocalizedResource;
import api.web.gw2.mapping.v1.guilddetails.GuildDetails;
import api.web.gw2.mapping.v1.guilddetails.GuildDetailsEmblem;

/**
 * Default JSON-P implementation of the details of a guild.
 *
 * @author Fabrice Bouyé
 */
public final class JsonpGuildDetails implements GuildDetails {

    @IdValue(flavor = IdValue.Flavor.STRING)
    private String guildId = IdValue.DEFAULT_STRING_ID;
    private String guildName = LocalizedResource.DEFAULT;
    private String tag = LocalizedResource.DEFAULT;
    private GuildDetailsEmblem emblem = null;

    /**
     * Creates a new empty instance.
     */
    public JsonpGuildDetails() {
    }

    @Override
    public String getGuildId() {
        return guildId;
    }

    @Override
    public String getGuildName() {
        return guildName;
    }

    @Override
    public String getTag() {
        return tag;
    }

    @Override
    public GuildDetailsEmblem getEmblem() {
        return emblem;
    }
}


text:
module.exports = exports = function (options) {
    var users = options.users;

  // Example:
  // Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
  return function (req, res, next) {
    var header = req.get('Authorization');

    if (!header) {
      return next();
    }

    var parts = header.split(' ');

    if (parts[0] != 'Basic') {
      return next();
    }

    var buffer = new Buffer(parts[1], 'base64');
    var userPass = buffer.toString('utf8');

    var userPassArray = userPass.split(':');

    var options = {
      email: userPassArray[0],
      password: userPassArray[1]
    };

    // login attempt
    users.get(options, function (error, user) {
      if (error) next(error);

      if (!user) {
        return next(new Error('auth_failed'));
      }

      req.auth = req.auth || {};
      req.auth.user = user;
      req.auth.type = 'basic';
    });
  };
};


text:
package org.apache.hadoop.hive.ql.exec.vector.mapjoin;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.hive.ql.CompilationOpContext;
import org.apache.hadoop.hive.ql.exec.JoinUtil;
import org.apache.hadoop.hive.ql.exec.vector.VectorizationContext;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;
import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpression;
import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinHashMultiSet;
import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinHashTableResult;
import org.apache.hadoop.hive.ql.exec.vector.mapjoin.hashtable.VectorMapJoinHashMultiSetResult;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.plan.OperatorDesc;

/**
 * This class has methods for generating vectorized join results for the big table only
 * variation of inner joins.
 *
 * When an inner join does not have any small table columns in the join result, we use this
 * variation we call inner big only.  This variation uses a hash multi-set instead of hash map
 * since there are no values (just a count).
 *
 * Note that if a inner key appears in the small table results area, we use the inner join
 * projection optimization and are able to use this variation.
 */
public abstract class VectorMapJoinInnerBigOnlyGenerateResultOperator
        extends VectorMapJoinGenerateResultOperator {

  private static final long serialVersionUID = 1L;
  private static final Logger LOG = LoggerFactory.getLogger(VectorMapJoinInnerBigOnlyGenerateResultOperator.class.getName());

  //---------------------------------------------------------------------------
  // Inner big-table only join specific members.
  //

  // An array of hash multi-set results so we can do lookups on the whole batch before output result
  // generation.
  protected transient VectorMapJoinHashMultiSetResult hashMultiSetResults[];

  // Pre-allocated member for storing the (physical) batch index of matching row (single- or
  // multi-small-table-valued) indexes during a process call.
  protected transient int[] allMatchs;

  /*
   *  Pre-allocated members for storing information on single- and multi-valued-small-table matches.
   *
   *  ~ValueCounts
   *                Number of (empty) small table values.
   *  ~AllMatchIndices
   *                (Logical) indices into allMatchs to the first row of a match of a
   *                possible series of duplicate keys.
   *  ~DuplicateCounts
   *                The duplicate count for each matched key.
   *
   */
  protected transient long[] equalKeySeriesValueCounts;
  protected transient int[] equalKeySeriesAllMatchIndices;
  protected transient int[] equalKeySeriesDuplicateCounts;

  // Pre-allocated member for storing the (physical) batch index of rows that need to be spilled.
  protected transient int[] spills;

  // Pre-allocated member for storing index into the hashMultiSetResults for each spilled row.
  protected transient int[] spillHashMapResultIndices;

  /** Kryo ctor. */
  protected VectorMapJoinInnerBigOnlyGenerateResultOperator() {
    super();
  }

  public VectorMapJoinInnerBigOnlyGenerateResultOperator(CompilationOpContext ctx) {
    super(ctx);
  }

  public VectorMapJoinInnerBigOnlyGenerateResultOperator(CompilationOpContext ctx,
      VectorizationContext vContext, OperatorDesc conf) throws HiveException {
    super(ctx, vContext, conf);
  }

  /*
   * Setup our inner big table only join specific members.
   */
  protected void commonSetup(VectorizedRowBatch batch) throws HiveException {
    super.commonSetup(batch);

    // Inner big-table only join specific.
    VectorMapJoinHashMultiSet baseHashMultiSet = (VectorMapJoinHashMultiSet) vectorMapJoinHashTable;

    hashMultiSetResults = new VectorMapJoinHashMultiSetResult[batch.DEFAULT_SIZE];
    for (int i = 0; i < hashMultiSetResults.length; i++) {
      hashMultiSetResults[i] = baseHashMultiSet.createHashMultiSetResult();
    }

    allMatchs = new int[batch.DEFAULT_SIZE];

    equalKeySeriesValueCounts = new long[batch.DEFAULT_SIZE];
    equalKeySeriesAllMatchIndices = new int[batch.DEFAULT_SIZE];
    equalKeySeriesDuplicateCounts = new int[batch.DEFAULT_SIZE];

    spills = new int[batch.DEFAULT_SIZE];
    spillHashMapResultIndices = new int[batch.DEFAULT_SIZE];
  }

  //-----------------------------------------------------------------------------------------------

  /*
   * Inner big table only join (hash multi-set).
   */

  /**
   * Generate the inner big table only join output results for one vectorized row batch.
   *
   * @param batch
   *          The big table batch with any matching and any non matching rows both as
   *          selected in use.
   * @param allMatchCount
   *          Number of matches in allMatchs.
   * @param equalKeySeriesCount
   *          Number of single value matches.
   * @param spillCount
   *          Number of spills in spills.
   * @param hashTableResults
   *          The array of all hash table results for the batch. We need the
   *          VectorMapJoinHashTableResult for the spill information.
   * @param hashMapResultCount
   *          Number of entries in hashMapResults.
   *
   **/
  protected void finishInnerBigOnly(VectorizedRowBatch batch,
      int allMatchCount, int equalKeySeriesCount, int spillCount,
      VectorMapJoinHashTableResult[] hashTableResults, int hashMapResultCount)
          throws HiveException, IOException {

    // Get rid of spills before we start modifying the batch.
    if (spillCount > 0) {
      spillHashMapBatch(batch, hashTableResults,
          spills, spillHashMapResultIndices, spillCount);
    }

    /*
     * Optimize by running value expressions only over the matched rows.
     */
    if (allMatchCount > 0 && bigTableValueExpressions != null) {
      performValueExpressions(batch, allMatchs, allMatchCount);
    }

    int numSel = 0;
    for (int i = 0; i < equalKeySeriesCount; i++) {
      long count = equalKeySeriesValueCounts[i];
      int allMatchesIndex = equalKeySeriesAllMatchIndices[i];
      int duplicateCount = equalKeySeriesDuplicateCounts[i];

      if (count == 1) {
        numSel = generateHashMultiSetResultSingleValue(
            batch, allMatchs, allMatchesIndex, duplicateCount, numSel);
      } else {
        generateHashMultiSetResultMultiValue(batch,
            allMatchs, allMatchesIndex,
            duplicateCount, count);
      }
    }
    batch.size = numSel;
    batch.selectedInUse = true;
  }

  /**
   * Generate the single value match inner big table only join output results for a match.
   *
   * @param batch
   *          The big table batch.
   * @param allMatchs
   *          A subset of the rows of the batch that are matches.
   * @param allMatchesIndex
   *          The logical index into allMatchs of the first equal key.
   * @param duplicateCount
   *          The number of duplicates or equal keys.
   * @param numSel
   *          The current count of rows in the rebuilding of the selected array.
   *
   * @return
   *          The new count of selected rows.
   */
  private int generateHashMultiSetResultSingleValue(VectorizedRowBatch batch,
      int[] allMatchs, int allMatchesIndex, int duplicateCount, int numSel)
          throws HiveException, IOException {

    // LOG.debug("generateHashMultiSetResultSingleValue enter...");

    // Generate result within big table batch itself.

    // LOG.debug("generateHashMultiSetResultSingleValue with big table...");

    for (int i = 0; i < duplicateCount; i++) {

      int batchIndex = allMatchs[allMatchesIndex + i];

      // Use the big table row as output.
      batch.selected[numSel++] = batchIndex;
    }

    return numSel;
  }

  /**
   * Generate results for a N x M cross product.
   *
   * @param batch
   *          The big table batch.
   * @param allMatchs
   *          The all match selected array that contains (physical) batch indices.
   * @param allMatchesIndex
   *          The index of the match key.
   * @param duplicateCount
   *          Number of equal key rows.
   * @param count
   *          Value count.
   */
  private void generateHashMultiSetResultMultiValue(VectorizedRowBatch batch,
      int[] allMatchs, int allMatchesIndex,
      int duplicateCount, long count) throws HiveException, IOException {

    // LOG.debug("generateHashMultiSetResultMultiValue allMatchesIndex " + allMatchesIndex + " duplicateCount " + duplicateCount + " count " + count);

    // TODO: Look at repeating optimizations...

    for (int i = 0; i < duplicateCount; i++) {

      int batchIndex = allMatchs[allMatchesIndex + i];

      for (long l = 0; l < count; l++) {

        // Copy the BigTable values into the overflow batch. Since the overflow batch may
        // not get flushed here, we must copy by value.
        if (bigTableRetainedVectorCopy != null) {
          bigTableRetainedVectorCopy.copyByValue(batch, batchIndex,
                                                 overflowBatch, overflowBatch.size);
        }

        overflowBatch.size++;
        if (overflowBatch.size == overflowBatch.DEFAULT_SIZE) {
          forwardOverflow();
        }
      }
    }
  }

  /**
   * Generate the inner big table only join output results for one vectorized row batch with
   * a repeated key.
   *
   * @param batch
   *          The big table batch with any matching and any non matching rows both as
   *          selected in use.
   * @param hashMultiSetResult
   *          The hash multi-set results for the batch.
   */
  protected int generateHashMultiSetResultRepeatedAll(VectorizedRowBatch batch,
          VectorMapJoinHashMultiSetResult hashMultiSetResult) throws HiveException {

    long count = hashMultiSetResult.count();

    if (batch.selectedInUse) {
      // The selected array is already filled in as we want it.
    } else {
      int[] selected = batch.selected;
      for (int i = 0; i < batch.size; i++) {
        selected[i] = i;
      }
      batch.selectedInUse = true;
    }

    do {
      forwardBigTableBatch(batch);
      count--;
    } while (count > 0);

    // We forwarded the batch in this method.
    return 0;
  }

  protected void finishInnerBigOnlyRepeated(VectorizedRowBatch batch, JoinUtil.JoinResult joinResult,
      VectorMapJoinHashMultiSetResult hashMultiSetResult) throws HiveException, IOException {

    switch (joinResult) {
    case MATCH:

      if (bigTableValueExpressions != null) {
        // Run our value expressions over whole batch.
        for(VectorExpression ve: bigTableValueExpressions) {
          ve.evaluate(batch);
        }
      }

      // Generate special repeated case.
      int numSel = generateHashMultiSetResultRepeatedAll(batch, hashMultiSetResult);
      batch.size = numSel;
      batch.selectedInUse = true;
      break;

    case SPILL:
      // Whole batch is spilled.
      spillBatchRepeated(batch, (VectorMapJoinHashTableResult) hashMultiSetResult);
      batch.size = 0;
      break;

    case NOMATCH:
      // No match for entire batch.
      batch.size = 0;
      break;
    }
  }
}


text:
#include <DeviceLocatedSettingsTraitDataSink.h>
#include <nest/trait/located/DeviceLocatedSettingsTrait.h>
#include <nest/trait/located/LocatedTrait.h>

#include <Weave/Support/CodeUtils.h>

using namespace ::nl::Weave::TLV;
using namespace ::nl::Weave::Profiles::DataManagement;
using namespace ::Schema::Nest::Trait::Located;

DeviceLocatedSettingsTraitDataSink::DeviceLocatedSettingsTraitDataSink() : TraitDataSink(&DeviceLocatedSettingsTrait::TraitSchema)
{}

WEAVE_ERROR
DeviceLocatedSettingsTraitDataSink::SetLeafData(PropertyPathHandle aLeafHandle, TLVReader & aReader)
{
    WEAVE_ERROR err = WEAVE_NO_ERROR;

    uint32_t mFixtureMajorType = 0;
    uint32_t mFixtureMinorType = 0;

    switch (aLeafHandle)
    {
    case DeviceLocatedSettingsTrait::kPropertyHandle_FixtureType_MajorType:
        err = aReader.Get(mFixtureMajorType);
        SuccessOrExit(err);

        if (mFixtureMajorType >= LocatedTrait::LOCATED_MAJOR_FIXTURE_TYPE_DOOR &&
            mFixtureMajorType <= LocatedTrait::LOCATED_MAJOR_FIXTURE_TYPE_OBJECT)
        {
            WeaveLogDetail(Support, "<< kPropertyHandle_FixtureType_MajorType : %d\n", mFixtureMajorType);
        }
        else
        {
            WeaveLogDetail(Support, "<< kPropertyHandle_FixtureType_MajorType %d is invalid\n", mFixtureMajorType);
        }
        break;

    case DeviceLocatedSettingsTrait::kPropertyHandle_FixtureType_MinorTypeDoor:
        err = aReader.Get(mFixtureMinorType);
        SuccessOrExit(err);

        if (mFixtureMinorType >= LocatedTrait::LOCATED_MINOR_FIXTURE_TYPE_DOOR_GENERIC &&
            mFixtureMinorType <= LocatedTrait::LOCATED_MINOR_FIXTURE_TYPE_DOOR_GARAGE_SINGLE_PANEL)
        {
            WeaveLogDetail(Support, "<< kPropertyHandle_FixtureType_MinorTypeDoor : %d\n", mFixtureMinorType);
        }
        else
        {
            WeaveLogDetail(Support, "<< kPropertyHandle_FixtureType_MinorTypeDoor %d is invalid\n", mFixtureMinorType);
        }
        break;

    case DeviceLocatedSettingsTrait::kPropertyHandle_FixtureType_MinorTypeWindow:
        err = aReader.Get(mFixtureMinorType);
        SuccessOrExit(err);

        if (mFixtureMinorType >= LocatedTrait::LOCATED_MINOR_FIXTURE_TYPE_WINDOW_GENERIC &&
            mFixtureMinorType <= LocatedTrait::LOCATED_MINOR_FIXTURE_TYPE_WINDOW_ROOF)
        {
            WeaveLogDetail(Support, "<< kPropertyHandle_FixtureType_MinorTypeWindow : %d\n", mFixtureMinorType);
        }
        else
        {
            WeaveLogDetail(Support, "<< kPropertyHandle_FixtureType_MinorTypeWindow %d is invalid\n", mFixtureMinorType);
        }
        break;

    case DeviceLocatedSettingsTrait::kPropertyHandle_FixtureType_MinorTypeWall:
        err = aReader.Get(mFixtureMinorType);
        SuccessOrExit(err);

        if (mFixtureMinorType >= LocatedTrait::LOCATED_MINOR_FIXTURE_TYPE_WALL_GENERIC &&
            mFixtureMinorType <= LocatedTrait::LOCATED_MINOR_FIXTURE_TYPE_WALL_FLUSH)
        {
            WeaveLogDetail(Support, "<< kPropertyHandle_FixtureType_MinorTypeWall : %d\n", mFixtureMinorType);
        }
        else
        {
            WeaveLogDetail(Support, "<< kPropertyHandle_FixtureType_MinorTypeWall %d is invalid\n", mFixtureMinorType);
        }

        WeaveLogDetail(Support, "<< kHandle_minor_type_wall = %d\n", mFixtureMinorType);
        break;

    case DeviceLocatedSettingsTrait::kPropertyHandle_FixtureType_MinorTypeObject:
        err = aReader.Get(mFixtureMinorType);
        SuccessOrExit(err);

        if (mFixtureMinorType == LocatedTrait::LOCATED_MINOR_FIXTURE_TYPE_OBJECT_GENERIC)
        {
            WeaveLogDetail(Support, "<< kPropertyHandle_FixtureType_MinorTypeObject : %d\n", mFixtureMinorType);
        }
        else
        {
            WeaveLogDetail(Support, "<< kPropertyHandle_FixtureType_MinorTypeObject %d is invalid\n", mFixtureMinorType);
        }
        break;

    case DeviceLocatedSettingsTrait::kPropertyHandle_FixtureType:
        break;

    default:
        WeaveLogDetail(Support, "<< UNKNOWN Device Located Settings trait leaf handle : %d\n", aLeafHandle);
    }

exit:
    return err;
}


text:
package com.suscipio_solutions.consecro_mud.Abilities.Prayers;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Abilities.interfaces.MendingSkill;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMProps;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;

@SuppressWarnings("rawtypes")
public class Prayer_CureSerious extends Prayer implements MendingSkill
{
	@Override public String ID() { return "Prayer_CureSerious"; }
	private final static String localizedName = CMLib.lang().L("Cure Serious Wounds");
	@Override public String name() { return localizedName; }
	@Override public int abstractQuality(){ return Ability.QUALITY_BENEFICIAL_OTHERS;}
	@Override public int classificationCode(){return Ability.ACODE_PRAYER|Ability.DOMAIN_HEALING;}
	@Override public long flags(){return Ability.FLAG_HOLY|Ability.FLAG_HEALINGMAGIC;}
	@Override protected long minCastWaitTime(){return CMProps.getTickMillis()/2;}

	@Override
	public boolean supportsMending(Physical item)
	{
		return (item instanceof MOB)
				&&((((MOB)item).curState()).getHitPoints()<(((MOB)item).maxState()).getHitPoints());
	}

	@Override
	public int castingQuality(MOB mob, Physical target)
	{
		if(mob!=null)
		{
			if(target instanceof MOB)
			{
				if(!supportsMending(target))
					return Ability.QUALITY_INDIFFERENT;
				if(((MOB)target).charStats().getMyRace().racialCategory().equals("Undead"))
					return Ability.QUALITY_MALICIOUS;
			}
		}
		return super.castingQuality(mob,target);
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		final MOB target=this.getTarget(mob,commands,givenTarget);
		if(target==null) return false;
		final boolean undead=target.charStats().getMyRace().racialCategory().equals("Undead");

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			// it worked, so build a copy of this ability,
			// and add it to the affects list of the
			// affected MOB.  Then tell everyone else
			// what happened.
			final CMMsg msg=CMClass.getMsg(mob,target,this,(!undead?0:CMMsg.MASK_MALICIOUS)|verbalCastCode(mob,target,auto),auto?L("A soft white glow surrounds <T-NAME>."):L("^S<S-NAME> @x1, delivering a serious healing touch to <T-NAMESELF>.^?",prayWord(mob)));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				final int healing=CMLib.dice().roll(3,adjustedLevel(mob,asLevel),5);
				final int oldHP=target.curState().getHitPoints();
				CMLib.combat().postHealing(mob,target,this,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,healing,null);
				if(target.curState().getHitPoints()>oldHP)
					target.tell(L("You feel better!"));
				lastCastHelp=System.currentTimeMillis();
			}
		}
		else
			beneficialWordsFizzle(mob,target,auto?"":L("<S-NAME> @x1 for <T-NAMESELF>, but nothing happens.",prayWord(mob)));

		// return whether it worked
		return success;
	}
}


text:
package org.apache.ambari.server.actionmanager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.google.inject.persist.UnitOfWork;
import junit.framework.Assert;

import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.Role;
import org.apache.ambari.server.RoleCommand;
import org.apache.ambari.server.agent.ActionQueue;
import org.apache.ambari.server.agent.CommandReport;
import org.apache.ambari.server.controller.HostsMap;
import org.apache.ambari.server.orm.GuiceJpaInitializer;
import org.apache.ambari.server.orm.InMemoryDefaultTestModule;
import org.apache.ambari.server.orm.dao.ExecutionCommandDAO;
import org.apache.ambari.server.orm.dao.HostRoleCommandDAO;
import org.apache.ambari.server.orm.entities.HostRoleCommandEntity;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.svccomphost.ServiceComponentHostStartEvent;
import org.apache.ambari.server.utils.StageUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.persist.PersistService;

import static org.junit.Assert.*;

public class TestActionDBAccessorImpl {
  private static final Logger log = LoggerFactory.getLogger(TestActionDBAccessorImpl.class);

  private long requestId = 23;
  private long stageId = 31;
  private String hostName = "host1";
  private String clusterName = "cluster1";
  private Injector injector;
  ActionDBAccessor db;
  ActionManager am;

  @Inject
  private Clusters clusters;
  @Inject
  private ExecutionCommandDAO executionCommandDAO;
  @Inject
  private HostRoleCommandDAO hostRoleCommandDAO;

  @Before
  public void setup() throws AmbariException {
    injector = Guice.createInjector(new InMemoryDefaultTestModule());
    injector.getInstance(GuiceJpaInitializer.class);
    injector.injectMembers(this);
    clusters.addHost(hostName);
    clusters.getHost(hostName).persist();
    clusters.addCluster(clusterName);
    db = injector.getInstance(ActionDBAccessorImpl.class);

    am = new ActionManager(5000, 1200000, new ActionQueue(), clusters, db,
        new HostsMap((String) null), null, injector.getInstance(UnitOfWork.class));
  }

  @After
  public void tearDown() throws AmbariException {
    injector.getInstance(PersistService.class).stop();
  }

  @Test
  public void testActionResponse() {
    String hostname = "host1";
    populateActionDB(db, hostname, requestId, stageId);
    Stage stage = db.getAllStages(requestId).get(0);
    Assert.assertEquals(stageId, stage.getStageId());
    stage.setHostRoleStatus(hostname, "HBASE_MASTER", HostRoleStatus.QUEUED);
    db.hostRoleScheduled(stage, hostname, "HBASE_MASTER");
    List<CommandReport> reports = new ArrayList<CommandReport>();
    CommandReport cr = new CommandReport();
    cr.setTaskId(1);
    cr.setActionId(StageUtils.getActionId(requestId, stageId));
    cr.setRole("HBASE_MASTER");
    cr.setStatus("COMPLETED");
    cr.setStdErr("");
    cr.setStdOut("");
    cr.setExitCode(215);
    reports.add(cr);
    am.processTaskResponse(hostname, reports);
    assertEquals(215,
        am.getAction(requestId, stageId).getExitCode(hostname, "HBASE_MASTER"));
    assertEquals(HostRoleStatus.COMPLETED, am.getAction(requestId, stageId)
        .getHostRoleStatus(hostname, "HBASE_MASTER"));
    Stage s = db.getAllStages(requestId).get(0);
    assertEquals(HostRoleStatus.COMPLETED,s.getHostRoleStatus(hostname, "HBASE_MASTER"));
  }

  @Test
  public void testGetStagesInProgress() {
    String hostname = "host1";
    populateActionDB(db, hostname, requestId, stageId);
    populateActionDB(db, hostname, requestId, stageId+1);
    List<Stage> stages = db.getStagesInProgress();
    assertEquals(2, stages.size());
  }

  @Test
  public void testGetStagesInProgressWithFailures() {
    String hostname = "host1";
    populateActionDB(db, hostname, requestId, stageId);
    populateActionDB(db, hostname, requestId+1, stageId);
    db.abortOperation(requestId);
    List<Stage> stages = db.getStagesInProgress();
    assertEquals(1, stages.size());
    assertEquals(requestId+1, stages.get(0).getRequestId());
  }

  @Test
  public void testPersistActions() {
    populateActionDB(db, hostName, requestId, stageId);
    for (Stage stage : db.getAllStages(requestId)) {
      log.info("taskId={}" + stage.getExecutionCommands(hostName).get(0).
          getExecutionCommand().getTaskId());
      assertTrue(stage.getExecutionCommands(hostName).get(0).
          getExecutionCommand().getTaskId() > 0);
      assertTrue(executionCommandDAO.findByPK(stage.getExecutionCommands(hostName).
          get(0).getExecutionCommand().getTaskId()) != null);
    }
  }

  @Test
  public void testHostRoleScheduled() throws InterruptedException {
    populateActionDB(db, hostName, requestId, stageId);
    Stage stage = db.getAction(StageUtils.getActionId(requestId, stageId));
    assertEquals(HostRoleStatus.PENDING, stage.getHostRoleStatus(hostName, Role.HBASE_MASTER.toString()));
    List<HostRoleCommandEntity> entities=
        hostRoleCommandDAO.findByHostRole(hostName, requestId, stageId, Role.HBASE_MASTER);

    assertEquals(HostRoleStatus.PENDING, entities.get(0).getStatus());
    stage.setHostRoleStatus(hostName, Role.HBASE_MASTER.toString(), HostRoleStatus.QUEUED);

    entities = hostRoleCommandDAO.findByHostRole(hostName, requestId, stageId, Role.HBASE_MASTER);
    assertEquals(HostRoleStatus.QUEUED, stage.getHostRoleStatus(hostName, Role.HBASE_MASTER.toString()));
    assertEquals(HostRoleStatus.PENDING, entities.get(0).getStatus());
    db.hostRoleScheduled(stage, hostName, Role.HBASE_MASTER.toString());

    entities = hostRoleCommandDAO.findByHostRole(hostName, requestId, stageId, Role.HBASE_MASTER);
    assertEquals(HostRoleStatus.QUEUED, entities.get(0).getStatus());

    Thread thread = new Thread(){
      @Override
      public void run() {
        Stage stage1 = db.getAction("23-31");
        stage1.setHostRoleStatus(hostName, Role.HBASE_MASTER.toString(), HostRoleStatus.COMPLETED);
        db.hostRoleScheduled(stage1, hostName, Role.HBASE_MASTER.toString());
      }
    };

    thread.start();
    thread.join();

    entities = hostRoleCommandDAO.findByHostRole(hostName, requestId, stageId, Role.HBASE_MASTER);
    assertEquals("Concurrent update failed", HostRoleStatus.COMPLETED, entities.get(0).getStatus());

  }

  @Test
  public void testUpdateHostRole() throws Exception {
    populateActionDB(db, hostName, requestId, stageId);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 50000; i++) {
      sb.append("1234567890");
    }
    String largeString = sb.toString();

    CommandReport commandReport = new CommandReport();
    commandReport.setStatus(HostRoleStatus.COMPLETED.toString());
    commandReport.setStdOut(largeString);
    commandReport.setStdErr(largeString);
    commandReport.setExitCode(123);
    db.updateHostRoleState(hostName, requestId, stageId, Role.HBASE_MASTER.toString(), commandReport);

    List<HostRoleCommandEntity> commandEntities = hostRoleCommandDAO.findByHostRole(hostName, requestId, stageId, Role.HBASE_MASTER);
    assertEquals(1, commandEntities.size());
    HostRoleCommandEntity commandEntity = commandEntities.get(0);
    HostRoleCommand command = db.getTask(commandEntity.getTaskId());
    assertNotNull(command);

    assertEquals(largeString, command.getStdout());

  }

  @Test
  public void testGetRequestsByStatus() throws AmbariException {
    List<Long> requestIds = new ArrayList<Long>();
    requestIds.add(requestId + 1);
    requestIds.add(requestId);
    populateActionDB(db, hostName, requestId, stageId);
    clusters.addHost("host2");
    clusters.getHost("host2").persist();
    populateActionDB(db, hostName, requestId + 1, stageId);
    List<Long> requestIdsResult = db.getRequestsByStatus(null);

    assertNotNull("List of request IDs is null", requestIdsResult);
    assertEquals("Request IDs not matches", requestIds, requestIdsResult);
  }

  @Test
  public void testAbortRequest() throws AmbariException {
    Stage s = new Stage(requestId, "/a/b", "cluster1", "action db accessor test");
    s.setStageId(stageId);

    clusters.addHost("host2");
    clusters.getHost("host2").persist();
    clusters.addHost("host3");
    clusters.getHost("host3").persist();
    clusters.addHost("host4");
    clusters.getHost("host4").persist();

    s.addHostRoleExecutionCommand("host1", Role.HBASE_MASTER,
        RoleCommand.START,
        new ServiceComponentHostStartEvent(Role.HBASE_MASTER.toString(),
            "host1", System.currentTimeMillis(),
            new HashMap<String, String>()), "cluster1", "HBASE");
    s.addHostRoleExecutionCommand("host2", Role.HBASE_MASTER,
        RoleCommand.START,
        new ServiceComponentHostStartEvent(Role.HBASE_MASTER.toString(),
            "host2", System.currentTimeMillis(),
            new HashMap<String, String>()), "cluster1", "HBASE");
    s.addHostRoleExecutionCommand(
        "host3",
        Role.HBASE_REGIONSERVER,
        RoleCommand.START,
        new ServiceComponentHostStartEvent(Role.HBASE_REGIONSERVER
            .toString(), "host3", System.currentTimeMillis(),
            new HashMap<String, String>()), "cluster1", "HBASE");
    s.addHostRoleExecutionCommand(
        "host4",
        Role.HBASE_REGIONSERVER,
        RoleCommand.START,
        new ServiceComponentHostStartEvent(Role.HBASE_REGIONSERVER
            .toString(), "host4", System.currentTimeMillis(),
            new HashMap<String, String>()), "cluster1", "HBASE");
    List<Stage> stages = new ArrayList<Stage>();
    stages.add(s);
    s.getOrderedHostRoleCommands().get(0).setStatus(HostRoleStatus.PENDING);
    s.getOrderedHostRoleCommands().get(1).setStatus(HostRoleStatus.IN_PROGRESS);
    s.getOrderedHostRoleCommands().get(2).setStatus(HostRoleStatus.QUEUED);

    HostRoleCommand cmd = s.getOrderedHostRoleCommands().get(3);
    String hostName = cmd.getHostName();
    cmd.setStatus(HostRoleStatus.COMPLETED);

    db.persistActions(stages);
    db.abortOperation(requestId);

    List<HostRoleCommand> commands = db.getRequestTasks(requestId);
    for(HostRoleCommand command : commands) {
      if(command.getHostName().equals(hostName)) {
        assertEquals(HostRoleStatus.COMPLETED, command.getStatus());
      } else {
        assertEquals(HostRoleStatus.ABORTED, command.getStatus());
      }
    }
  }

  private void populateActionDB(ActionDBAccessor db, String hostname,
      long requestId, long stageId) {
    Stage s = new Stage(requestId, "/a/b", "cluster1", "action db accessor test");
    s.setStageId(stageId);
    s.addHostRoleExecutionCommand(hostname, Role.HBASE_MASTER,
        RoleCommand.START,
        new ServiceComponentHostStartEvent(Role.HBASE_MASTER.toString(),
            hostname, System.currentTimeMillis(),
            new HashMap<String, String>()), "cluster1", "HBASE");
    s.addHostRoleExecutionCommand(
        hostname,
        Role.HBASE_REGIONSERVER,
        RoleCommand.START,
        new ServiceComponentHostStartEvent(Role.HBASE_REGIONSERVER
            .toString(), hostname, System.currentTimeMillis(),
            new HashMap<String, String>()), "cluster1", "HBASE");
    List<Stage> stages = new ArrayList<Stage>();
    stages.add(s);
    db.persistActions(stages);
  }
}


text:
/*
* 21. Write a program that reads a string from the console and prints
* all different letters in the string along with information how many
* times each letter is found.
*/

using System;
using System.Collections.Generic;
using System.Linq;

class CharOccurs
{
    static void Main()
    {
        Console.Write("Enter a string: ");
        char[] letters = Console.ReadLine().ToCharArray();

        Dictionary<char, int> dict = new Dictionary<char, int>();

        for (int i = 0; i < letters.Length; i++)
            if (!dict.ContainsKey(letters[i])) dict.Add(letters[i], 1);
            else dict[letters[i]]++;

        Console.WriteLine("\nLetter occurence table:\n{0}\n",
            string.Join("\n", dict.Select(x => string.Format(@"'{0}' -> {1} time(s)", x.Key, x.Value)).ToArray()));
    }
}


text:
/* globals describe, it, afterEach, beforeEach, after, before */
'use strict';

// Imports
var chai = require('chai');
var mongoose = require('mongoose');
var assert = chai.assert;

// Load the main config so we can figure out the test db
var config = require('../../../../../config/config.js');

// Class / Object we want to test
require('../../../backend/models/Event.js');
var Event = mongoose.model('Event');

describe('Flok Component Stream: Event Model', function() {

    before(function(done) {
        // Connect to mongoose before the tests
        mongoose.connect(config.test.db, function() {
            done();
        });
    });

    beforeEach(function(done) {
        // Once we're connected drop the database to avoid interference from other tests
        mongoose.connection.db.dropDatabase(function() {
            done();
        });
    });

    it('Event objects can be created', function() {
        assert.isFunction(Event, 'Event should be a function');
        var testEvent = new Event();
        assert.isObject(testEvent, 'Expected new Event() to create object');
    });

    it('converts toJSON', function() {
        var testEvent = new Event();

        var json = testEvent.toJSON();

        assert.isObject(json, 'Expecting a JSON object');
        // TODO test the properties of the object according to schema
        // for this we could write a jsonSchema and parse it through a validator to save time.

        // for now test that it has the require properties:
        assert.property(json, 'timestamp', 'timestamp should have a default value');
        assert.property(json, 'author', 'author is a required property');
    });

    it('converts nested objects toJSON', function() {
        var testEvent = new Event({
            author: {
                name: 'test'
            }
        });

        var json = testEvent.toJSON();

        // Stringify and parse again
        // TODO: this is what happens when it's send over the API, so should probably rather be an integration test
        json = JSON.parse(JSON.stringify(json));
        assert.isObject(json, 'Expecting a JSON object');
        assert.isObject(json.author, 'author is an object');
        assert.equal(json.author.name, 'test', 'correct author name');
    });

    it('saves Events to the db', function(done) {
        var event = new Event();

        event.title = 'The Test Event';
        event.sourceId = 'TestSaveEventToDb!1';

        event.save(function(err, newEvent, numberAffected) {
            assert.isNull(err, 'save should not throw error');

            assert.equal(newEvent.title, event.title, 'The title of the created event should match');

            assert.equal(numberAffected, 1, 'only 1 object should be affected');

            done();
        });
    });

    after(function(done) {
        // Close connection after all tests
        mongoose.connection.close(function() {
            done();
        });
    });
});


text:
package com.aspose.cells.model;

import com.aspose.cells.model.DrawingArea;
import com.aspose.cells.model.DrawingLine;
import com.aspose.cells.model.LinkElement;
import java.util.*;
import com.aspose.cells.model.Font;
import com.aspose.cells.model.Link;

public class ChartsTitle   {

  private Boolean isVisible = null;
  private String linkedSource = null;
  private Integer rotationAngle = null;
  private String text = null;
  private String textDirection = null;
  private String textHorizontalAlignment = null;
  private String textVerticalAlignment = null;
  private DrawingArea area = null;
  private Boolean autoScaleFont = null;
  private String backgroundMode = null;
  private DrawingLine border = null;
  private Font font = null;
  private Boolean isAutomaticSize = null;
  private Boolean isInnerMode = null;
  private Boolean shadow = null;
  private List<LinkElement> shapeProperties = new ArrayList<LinkElement>();
  private Integer width = null;
  private Integer height = null;
  private Integer X = null;
  private Integer Y = null;
  private Link link = null;

  public Boolean getIsVisible() {
    return isVisible;
  }
  public void setIsVisible(Boolean isVisible) {
    this.isVisible = isVisible;
  }

  public String getLinkedSource() {
    return linkedSource;
  }
  public void setLinkedSource(String linkedSource) {
    this.linkedSource = linkedSource;
  }

  public Integer getRotationAngle() {
    return rotationAngle;
  }
  public void setRotationAngle(Integer rotationAngle) {
    this.rotationAngle = rotationAngle;
  }

  public String getText() {
    return text;
  }
  public void setText(String text) {
    this.text = text;
  }

  public String getTextDirection() {
    return textDirection;
  }
  public void setTextDirection(String textDirection) {
    this.textDirection = textDirection;
  }

  public String getTextHorizontalAlignment() {
    return textHorizontalAlignment;
  }
  public void setTextHorizontalAlignment(String textHorizontalAlignment) {
    this.textHorizontalAlignment = textHorizontalAlignment;
  }

  public String getTextVerticalAlignment() {
    return textVerticalAlignment;
  }
  public void setTextVerticalAlignment(String textVerticalAlignment) {
    this.textVerticalAlignment = textVerticalAlignment;
  }

  public DrawingArea getArea() {
    return area;
  }
  public void setArea(DrawingArea area) {
    this.area = area;
  }

  public Boolean getAutoScaleFont() {
    return autoScaleFont;
  }
  public void setAutoScaleFont(Boolean autoScaleFont) {
    this.autoScaleFont = autoScaleFont;
  }

  public String getBackgroundMode() {
    return backgroundMode;
  }
  public void setBackgroundMode(String backgroundMode) {
    this.backgroundMode = backgroundMode;
  }

  public DrawingLine getBorder() {
    return border;
  }
  public void setBorder(DrawingLine border) {
    this.border = border;
  }

  public Font getFont() {
    return font;
  }
  public void setFont(Font font) {
    this.font = font;
  }

  public Boolean getIsAutomaticSize() {
    return isAutomaticSize;
  }
  public void setIsAutomaticSize(Boolean isAutomaticSize) {
    this.isAutomaticSize = isAutomaticSize;
  }

  public Boolean getIsInnerMode() {
    return isInnerMode;
  }
  public void setIsInnerMode(Boolean isInnerMode) {
    this.isInnerMode = isInnerMode;
  }

  public Boolean getShadow() {
    return shadow;
  }
  public void setShadow(Boolean shadow) {
    this.shadow = shadow;
  }

  public List<LinkElement> getShapeProperties() {
    return shapeProperties;
  }
  public void setShapeProperties(List<LinkElement> shapeProperties) {
    this.shapeProperties = shapeProperties;
  }

  public Integer getWidth() {
    return width;
  }
  public void setWidth(Integer width) {
    this.width = width;
  }

  public Integer getHeight() {
    return height;
  }
  public void setHeight(Integer height) {
    this.height = height;
  }

  public Integer getX() {
    return X;
  }
  public void setX(Integer X) {
    this.X = X;
  }

  public Integer getY() {
    return Y;
  }
  public void setY(Integer Y) {
    this.Y = Y;
  }

  public Link getLink() {
    return link;
  }
  public void setLink(Link link) {
    this.link = link;
  }

  @Override
  public String toString()  {
    StringBuilder sb = new StringBuilder();
    sb.append("class ChartsTitle {\n");

    sb.append("  isVisible: ").append(isVisible).append("\n");
    sb.append("  linkedSource: ").append(linkedSource).append("\n");
    sb.append("  rotationAngle: ").append(rotationAngle).append("\n");
    sb.append("  text: ").append(text).append("\n");
    sb.append("  textDirection: ").append(textDirection).append("\n");
    sb.append("  textHorizontalAlignment: ").append(textHorizontalAlignment).append("\n");
    sb.append("  textVerticalAlignment: ").append(textVerticalAlignment).append("\n");
    sb.append("  area: ").append(area).append("\n");
    sb.append("  autoScaleFont: ").append(autoScaleFont).append("\n");
    sb.append("  backgroundMode: ").append(backgroundMode).append("\n");
    sb.append("  border: ").append(border).append("\n");
    sb.append("  font: ").append(font).append("\n");
    sb.append("  isAutomaticSize: ").append(isAutomaticSize).append("\n");
    sb.append("  isInnerMode: ").append(isInnerMode).append("\n");
    sb.append("  shadow: ").append(shadow).append("\n");
    sb.append("  shapeProperties: ").append(shapeProperties).append("\n");
    sb.append("  width: ").append(width).append("\n");
    sb.append("  height: ").append(height).append("\n");
    sb.append("  X: ").append(X).append("\n");
    sb.append("  Y: ").append(Y).append("\n");
    sb.append("  link: ").append(link).append("\n");
    sb.append("}\n");
    return sb.toString();
  }
}


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class GetIncident(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the GetIncident Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(GetIncident, self).__init__(temboo_session, '/Library/PagerDuty/Incidents/GetIncident')

    def new_input_set(self):
        return GetIncidentInputSet()

    def _make_result_set(self, result, path):
        return GetIncidentResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return GetIncidentChoreographyExecution(session, exec_id, path)

class GetIncidentInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the GetIncident
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    def set_APIKey(self, value):
        """
        Set the value of the APIKey input for this Choreo. ((required, string) The API Key provided by PagerDuty.)
        """
        super(GetIncidentInputSet, self)._set_input('APIKey', value)
    def set_IncidentID(self, value):
        """
        Set the value of the IncidentID input for this Choreo. ((required, string) An incident ID, or an incident number.)
        """
        super(GetIncidentInputSet, self)._set_input('IncidentID', value)
    def set_SubDomain(self, value):
        """
        Set the value of the SubDomain input for this Choreo. ((required, string) The subdomain of your PagerDuty site address.)
        """
        super(GetIncidentInputSet, self)._set_input('SubDomain', value)

class GetIncidentResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the GetIncident Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Response(self):
        """
        Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from PagerDuty.)
        """
        return self._output.get('Response', None)

class GetIncidentChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return GetIncidentResultSet(response, path)