text:
package aufgabe2;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;

public class Authorisation implements Serializable{
	private static final long serialVersionUID = 8460911874782499643L;
	private static HashMap<Date, String> tickets = new HashMap<Date, String>();
	private HashMap<String, String> admins = new HashMap<String, String>();
	private final String userName="admin";
	private final String password="secret";

	public Authorisation() {
		if (!admins.containsKey(userName)) admins.put(userName, password);
	}

	/**
	 * checkLogin
	 *
	 * checks if the handed over authorisation is valid
	 * @param ticket - hash of the admin
	 * @return if the hash is valid
	 */
	public boolean checkLogin(String ticket) {
		if(tickets.containsValue(ticket))
			return true;

		return false;
	}

	/**
	 * doLogin
	 *
	 * Expects username and password and returns a validation-hash if the transfered credentials are valid
	 * @param user
	 * @param password
	 * @return validation-hash
	 */
	public String doLogin(String user, String password) {
		Date timestamp =null;
		String s ="";
		if (admins.containsKey(user) && admins.get(user).equals(password)){
			timestamp = new Date(System.currentTimeMillis());
			s= getHash(timestamp.toString());
			tickets.put(timestamp, s);
		}

		return s;
	}

	/**
	 * doLogout
	 *
	 * loggs an user out
	 * @param ticket - validation-hash
	 * @return if the check out was successful
	 */
	public boolean doLogout(String ticket) {
		if (tickets.containsValue(ticket)){
			for(Date aKey : tickets.keySet()){
				String s = tickets.get(aKey);
				if (s.equals(ticket)) tickets.remove(aKey);
			}
			return true;
		}
		return false;
	}

	/**
	 * getHash
	 *
	 * generates a MD5 hash out of the transfered object
	 * @param o
	 * @return MD5 hash-string
	 */
	private String getHash(Object o) {
    	try
    	{
    		MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5");
    		ByteArrayOutputStream baos = new ByteArrayOutputStream();
    		ObjectOutputStream oos = new ObjectOutputStream(baos);
    		oos.writeObject(o);
    		mdAlgorithm.update(baos.toByteArray());

    		byte[] digest = mdAlgorithm.digest();
    		StringBuffer hexString = new StringBuffer();

    		for (int i = 0; i < digest.length; i++)
    		{
    			String x = Integer.toHexString(0xFF & digest[i]);
    			if (x.length() < 2) x = "0" + x;
    			hexString.append(x);
    		}
    		return(hexString.toString());
    	}
    	catch(NoSuchAlgorithmException e) { return(null); }
    	catch(IOException e) { return(null); }
    }
}


text:
/***************************************************************************
 * INCLUDES
 ***************************************************************************/

#include "MaxPlanesLowerBound.h"

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <fstream>
#include <iostream>

#include "BlindLBInitializer.h"
#include "MatrixUtils.h"
#include "zmdpCommonDefs.h"
#include "zmdpCommonTime.h"

#define PRUNE_PLANES_INCREMENT (10)
#define PRUNE_PLANES_FACTOR (1.1)

using namespace std;
using namespace MatrixUtils;
using namespace sla;

namespace zmdp {

struct MaxPlanesData {
  LBPlane *bestPlane;
  int lastSetPlaneNumBackups;

  MaxPlanesData(void) : bestPlane(NULL), lastSetPlaneNumBackups(-1) {}
};

/**********************************************************************
 * LOCAL HELPER FUNCTIONS
 **********************************************************************/

static std::string stripWhiteSpace(const std::string &s) {
  string::size_type p1, p2;
  p1 = s.find_first_not_of(" \t");
  if (string::npos == p1) {
    return s;
  } else {
    p2 = s.find_last_not_of(" \t") + 1;
    return s.substr(p1, p2 - p1);
  }
}

static bool dominates(const LBPlane *a, const LBPlane *b,
                      bool useMaxPlanesMasking) {
  if (useMaxPlanesMasking) {
    return mask_dominates(a->alpha, b->alpha, ZMDP_BOUNDS_PRUNE_EPS, a->mask,
                          b->mask);
  } else {
    return dominates(a->alpha, b->alpha, ZMDP_BOUNDS_PRUNE_EPS);
  }
}

/**********************************************************************
 * LBPLANE
 **********************************************************************/

LBPlane::LBPlane(void) {}

LBPlane::LBPlane(const alpha_vector &_alpha, int _action,
                 const sla::mvector &_mask)
    : alpha(_alpha), action(_action), mask(_mask) {}

void LBPlane::write(std::ostream &out, bool useMaxPlanesMasking) const {
  out << "    {" << endl;
  out << "      action => " << action << "," << endl;

  if (useMaxPlanesMasking) {
    out << "      numEntries => " << mask.filled() << "," << endl;
  } else {
    out << "      numEntries => " << alpha.size() << "," << endl;
  }

  out << "      entries => [" << endl;

  if (useMaxPlanesMasking) {
    bool firstEntry = true;
    FOR_CV(mask) {
      if (!firstEntry) {
        out << "," << endl;
      }
      int i = CV_INDEX(mask);
      out << "        " << i << ", " << alpha(i) << "";
      firstEntry = false;
    }
    out << endl;
  } else {
    int n = alpha.size();
    FOR(i, n - 1) { out << "        " << i << ", " << alpha(i) << "," << endl; }
    out << "        " << (n - 1) << ", " << alpha(n - 1) << endl;
  }

  out << "      ]" << endl;
  out << "    }";
}

/**********************************************************************
 * MAX PLANES LOWER BOUND
 **********************************************************************/

MaxPlanesLowerBound::MaxPlanesLowerBound(const MDP *_pomdp,
                                         const ZMDPConfig *_config)
    : pomdp((const Pomdp *)_pomdp),
      config(_config),
      core(NULL),
      initialized(false) {
  lastPruneNumPlanes = 0;
  lastPruneNumBackups = -1;
  useMaxPlanesMasking = config->getBool("useMaxPlanesMasking");
  useMaxPlanesSupportList = config->getBool("useMaxPlanesSupportList");
  useMaxPlanesCache = config->getBool("useMaxPlanesCache");
  useMaxPlanesExtraPruning = config->getBool("useMaxPlanesExtraPruning");

  if (useMaxPlanesSupportList) {
    supportList.resize(pomdp->getBeliefSize());
  }
}

MaxPlanesLowerBound::~MaxPlanesLowerBound(void) {
  FOR_EACH(planeP, planes) { delete *planeP; }
}

void MaxPlanesLowerBound::initialize(double targetPrecision) {
  if (initialized) return;

  BlindLBInitializer blb(pomdp, this);
  blb.initialize(targetPrecision);

  if (useMaxPlanesCache) {
    // planes from initialization should have their 'age' set appropriately
    FOR_EACH(planeP, planes) { (*planeP)->numBackupsAtCreation = 0; }
  }
  initialized = true;
}

double MaxPlanesLowerBound::getValue(const belief_vector &b,
                                     const MDPNode *cn) const {
  double v = inner_prod(getBestLBPlaneConst(b).alpha, b);
  return v;
}

// lower bound on long-term reward for taking action a (alpha vector)
void MaxPlanesLowerBound::getNewLBPlaneQ(LBPlane &result, MDPNode &cn, int a) {
  alpha_vector betaA(pomdp->getBeliefSize());
  const alpha_vector *betaAO;
  alpha_vector tmp, tmp2, tmp3;

  set_to_zero(betaA);

  bool defaultIsSet = false;
  const alpha_vector *defaultBetaAO = NULL;
  const MDPQEntry &Qa = cn.Q[a];
  alpha_vector maskedBeta;
  FOR(o, Qa.getNumOutcomes()) {
    MDPEdge *e = Qa.outcomes[o];
    if (NULL != e) {
      betaAO = &getPlaneForNode(*e->nextState).alpha;
      if (useMaxPlanesMasking) {
        // occasionally, even if the nextState belief is sparse, the
        // corresponding betaAO is one of the dense alpha vectors produced
        // by the initial blind-policy heuristic.  in that case, we can
        // speed up the matrix multiplication below by masking betaAO with
        // the nextState belief (so it becomes much sparser).
        if (betaAO->filled() > cn.s.filled()) {
          mask_copy(maskedBeta, *betaAO, e->nextState->s);
          betaAO = &maskedBeta;
        }
      }
    } else {
      // impossible to see this observation, so it doesn't make sense to
      // pick the alpha that optimizes for the next belief.  plug in a
      // default alpha (arbitrarily chosen to optimize for cn.s).
      if (!defaultIsSet) {
        defaultBetaAO = &getPlaneForNode(cn).alpha;
        defaultIsSet = true;
      }
      betaAO = defaultBetaAO;
    }

    emult_column(tmp, pomdp->O[a], o, *betaAO);
    if (useMaxPlanesMasking) {
      mult(tmp3, pomdp->T[a], tmp);
      mask_copy(tmp2, tmp3, cn.s);
    } else {
      mult(tmp2, tmp, pomdp->Ttr[a]);
    }
    betaA += tmp2;
  }

  alpha_vector Rxa;
  if (useMaxPlanesMasking) {
    copy_from_column(tmp, pomdp->R, a);
    mask_copy(Rxa, tmp, cn.s);
  } else {
    copy_from_column(Rxa, pomdp->R, a);
  }
  betaA *= pomdp->getDiscount();
  betaA += Rxa;

  result.alpha = betaA;
  result.action = a;
  if (useMaxPlanesMasking) {
    result.mask = cn.s;
  }
  result.numBackupsAtCreation = core->numBackups;
}

void MaxPlanesLowerBound::getNewLBPlane(LBPlane &result, MDPNode &cn) {
  timeval startTime;
  if (zmdpDebugLevelG >= 1) {
    startTime = getTime();
  }

  double val, maxVal = -99e+20;
  LBPlane betaA;

  FOR(a, cn.getNumActions()) {
    getNewLBPlaneQ(betaA, cn, a);
    val = inner_prod(betaA.alpha, cn.s);
    cn.Q[a].lbVal = val;
    if (val > maxVal) {
      maxVal = val;
      result = betaA;
    }
  }
  if (zmdpDebugLevelG >= 1) {
    cout << "** newLowerBound: elapsed time = "
         << timevalToSeconds(getTime() - startTime) << endl;
  }
}

void MaxPlanesLowerBound::initNodeBound(MDPNode &cn) {
  if (useMaxPlanesCache) {
    MaxPlanesData *bdata = new MaxPlanesData();
    bdata->bestPlane = NULL;
    cn.boundsData = bdata;
  }

  // note: this should also do the right thing if cn is terminal;
  // at least one of the planes from initialization should give an
  // lbVal of 0 for cn in that case.
  cn.lbVal = -99e+20;
  setPlaneForNode(cn, &getBestLBPlane(cn.s));
}

void MaxPlanesLowerBound::update(MDPNode &cn) {
  LBPlane *newPlane = new LBPlane();
  getNewLBPlane(*newPlane, cn);

  setPlaneForNode(cn, newPlane);

  addLBPlane(newPlane);
  maybePrune(core->numBackups);
}

int MaxPlanesLowerBound::chooseAction(const state_vector &b) {
  return getBestLBPlaneConst(b).action;
}

void MaxPlanesLowerBound::setPlaneForNode(MDPNode &cn, LBPlane *newPlane) {
  double newLB = inner_prod(newPlane->alpha, cn.s);
  if (useMaxPlanesCache) {
    if (newLB < cn.lbVal - ZMDP_BOUNDS_PRUNE_EPS) {
#if 0
      // debug
      LBPlane* oldPlane =
        (reinterpret_cast<MaxPlanesLowerBoundData*>(cn.boundsData))->bestPlane;
      printf("setPlaneForNode: ignoring new plane: newLB=%lf cn.lbVal=%lf "
             "diff=%lg ip=%lf\n",
             newLB, cn.lbVal, (newLB-cn.lbVal),
             inner_prod(oldPlane->alpha, cn.s));
      LBPlane* newPlane = &lowerBound->getBestLBPlane(cn.s);
      printf("setPlaneForNode: newPlane=%p oldPlane=%p\n",
             newPlane, oldPlane);
#endif
      return;
    }
    MaxPlanesData *bdata = reinterpret_cast<MaxPlanesData *>(cn.boundsData);
    LBPlane *oldPlane = bdata->bestPlane;
    if (NULL != oldPlane) {
      // remove &bdata->bestPlane from oldPlane->backPointers
      std::list<LBPlane **> &backPointers = oldPlane->backPointers;
      typeof(backPointers.begin()) eraseList = std::remove(
          backPointers.begin(), backPointers.end(), &bdata->bestPlane);
      backPointers.erase(eraseList);
    }

    cn.lbVal = newLB;
    bdata->bestPlane = newPlane;
    bdata->lastSetPlaneNumBackups = core->numBackups;
    newPlane->backPointers.push_back(&bdata->bestPlane);
  } else {
    cn.lbVal = newLB;
  }
}

const LBPlane &MaxPlanesLowerBound::getPlaneForNode(MDPNode &cn) {
  if (useMaxPlanesCache) {
#if 0
    // old version, did more harm than good
    int n = (reinterpret_cast<MaxPlanesData *>(cn.boundsData))
      ->lastSetPlaneNumBackups;
    if (numBackups >
        static_cast<int>(std::max(static_cast<double>(n + CB_CACHE_INCREMENT),
                                  n * CB_CACHE_FACTOR))) {
      LBPlane& newPlane = lowerBound->getBestLBPlane(cn.s);
      setPlaneForNode(cn, &newPlane);
      return newPlane;
    } else {
      return *(reinterpret_cast<MaxPlanesData *>(cn.boundsData))->bestPlane;
    }
#endif
    MaxPlanesData *bdata = reinterpret_cast<MaxPlanesData *>(cn.boundsData);
    return getBestLBPlaneWithCache(cn.s, bdata->bestPlane,
                                   bdata->lastSetPlaneNumBackups);
  } else {
    return getBestLBPlane(cn.s);
  }
}

// return the alpha such that alpha * b has the highest value
const LBPlane &MaxPlanesLowerBound::getBestLBPlaneConst(
    const belief_vector &b) const {
  const PlaneSet *planesToCheck;
  if (useMaxPlanesSupportList) {
    planesToCheck = &supportList[b.data[0].index];
  } else {
    planesToCheck = &planes;
  }

  double val, maxval = -99e+20;
  const LBPlane *ret = NULL;
  FOR_EACH(pr, *planesToCheck) {
    const LBPlane *al = *pr;
    if (useMaxPlanesMasking) {
      if (!mask_subset(b, al->mask)) continue;
    }
    val = inner_prod(al->alpha, b);
    if (val > maxval) {
      maxval = val;
      ret = al;
    }
  }

  assert(NULL != ret);
  return *ret;
}

LBPlane &MaxPlanesLowerBound::getBestLBPlane(const belief_vector &b) {
  // cast from 'const LBPlane&' to LBPlane&
  return (LBPlane &)getBestLBPlaneConst(b);
}

// return the alpha such that alpha * b has the highest value
LBPlane &MaxPlanesLowerBound::getBestLBPlaneWithCache(
    const belief_vector &b, LBPlane *currPlane, int lastSetPlaneNumBackups) {
  const PlaneSet *planesToCheck;
  if (useMaxPlanesSupportList) {
    planesToCheck = &supportList[b.data[0].index];
  } else {
    planesToCheck = &planes;
  }

  double val;
  LBPlane *ret = currPlane;
  double maxval = inner_prod(currPlane->alpha, b);

  FOR_EACH(pr, *planesToCheck) {
    LBPlane *al = *pr;
    if (al->numBackupsAtCreation < lastSetPlaneNumBackups) continue;
    if (useMaxPlanesMasking) {
      if (!mask_subset(b, al->mask)) continue;
    }
    val = inner_prod(al->alpha, b);
    if (val > maxval) {
      maxval = val;
      ret = al;
    }
  }
  return *ret;
}

void MaxPlanesLowerBound::addLBPlane(LBPlane *av) {
  planes.push_back(av);

  if (useMaxPlanesSupportList) {
    // add new plane to supportList
    FOR_EACH(ai, av->mask.data) { supportList[ai->index].push_back(av); }
  }
}

void MaxPlanesLowerBound::prunePlanes(int numBackups) {
  int oldNum = -1;
  int numRefCountDeletions = 0;
  if (zmdpDebugLevelG >= 1) {
    oldNum = planes.size();
  }
  typeof(planes.begin()) candidateP, memberP;

  candidateP = planes.begin();
  while (candidateP != planes.end()) {
    LBPlane *candidate = *candidateP;
    if (useMaxPlanesExtraPruning) {
      if (candidate->backPointers.empty()) {
        deleteAndForward(candidate, NULL);
        candidateP = eraseElement(planes, candidateP);
        if (zmdpDebugLevelG >= 1) {
          numRefCountDeletions++;
        }
        continue;
      }
    }
    memberP = planes.begin();
    while (memberP != candidateP) {
      LBPlane *member = *memberP;
      if (candidate->numBackupsAtCreation <= lastPruneNumBackups &&
          member->numBackupsAtCreation <= lastPruneNumBackups) {
        // candidate and member were compared the last time we pruned
        // and neither dominates the other; leave them both in
      } else if (dominates(candidate, member, useMaxPlanesMasking)) {
        // memberP is pruned
        deleteAndForward(member, candidate);
        memberP = eraseElement(planes, memberP);
        continue;
      } else if (dominates(member, candidate, useMaxPlanesMasking)) {
        // candidate is pruned
        deleteAndForward(candidate, member);
        candidateP = eraseElement(planes, candidateP);
        // as a heuristic, move the winning member to the front of planes
        eraseElement(planes, memberP);
        planes.push_front(member);
        goto nextCandidate;
      }
      memberP++;
    }
    candidateP++;
  nextCandidate : {}
  }

  if (zmdpDebugLevelG >= 1) {
    cout << "... pruned # planes from " << oldNum << " down to "
         << planes.size() << endl;
    if (useMaxPlanesExtraPruning) {
      printf("[lower bound] refCount was used for %d of %d deletions\n",
             numRefCountDeletions, static_cast<int>(oldNum - planes.size()));
    }
  }
  lastPruneNumPlanes = planes.size();
  lastPruneNumBackups = numBackups;
}

// prune points and planes if the number has grown significantly
// since the last check
void MaxPlanesLowerBound::maybePrune(int numBackups) {
  unsigned int nextPruneNumPlanes =
      max(lastPruneNumPlanes + PRUNE_PLANES_INCREMENT,
          static_cast<int>(lastPruneNumPlanes * PRUNE_PLANES_FACTOR));
  if (planes.size() > nextPruneNumPlanes) {
    prunePlanes(numBackups);
  }
}

void MaxPlanesLowerBound::deleteAndForward(LBPlane *victim,
                                           LBPlane *dominator) {
  if (useMaxPlanesSupportList) {
    // remove victim from supportList
    FOR_EACH(ai, victim->mask.data) {
      PlaneSet &pi = supportList[ai->index];
      FOR_EACH(eltP, pi) {
        if (victim == *eltP) {
          eraseElement(pi, eltP);
          break;
        }
      }
    }
  }
  if (useMaxPlanesCache) {
    // forward backPointers from victim to dominator
    FOR_EACH(bpP, victim->backPointers) {
      LBPlane **bp = *bpP;
      *bp = dominator;
      dominator->backPointers.push_back(bp);
    }
  }

  delete victim;
}

void MaxPlanesLowerBound::writeToFile(const std::string &outFileName) const {
  ofstream out(outFileName.c_str());
  if (!out) {
    cerr << "ERROR: MaxPlanesLowerBound::writeToFile: couldn't open "
         << outFileName << " for writing: " << strerror(errno) << endl;
    exit(EXIT_FAILURE);
  }

  out << "# This file is a POMDP policy, represented as a set of \"lower "
         "bound\n"
         "# planes\", each of which consists of an alpha vector and a "
         "corresponding\n"
         "# action.  Given a particular belief b, this information can be used "
         "to\n"
         "# answer two queries of interest:\n"
         "#\n"
         "#   1. What is a lower bound on the expected long-term reward "
         "starting\n"
         "#        from belief b?\n"
         "#   2. What is an action that achieves that expected reward lower "
         "bound?\n"
         "#\n"
         "# Each lower bound plane is only defined over a subset of the "
         "belief\n"
         "# simplex--it is defined for those beliefs b such that the non-zero\n"
         "# entries of b are a subset of the entries present in the plane's "
         "alpha\n"
         "# vector.  If this condition holds we say the plane is 'applicable' "
         "to b.\n"
         "#\n"
         "# Given a belief b, both of the queries above can be answered by "
         "the\n"
         "# following process: first, throw out all the planes that are not\n"
         "# applicable to b.  Then, for each of the remaining planes, take the "
         "inner\n"
         "# product of the plane's alpha vector with b.  The highest inner "
         "product\n"
         "# value is the expected long-term reward lower bound, and the action "
         "label\n"
         "# for that plane is the action that achieves the bound.\n"
         "\n";
  out << "{" << endl;
  out << "  policyType => \"MaxPlanesLowerBound\"," << endl;
  out << "  numPlanes => " << planes.size() << "," << endl;
  out << "  planes => [" << endl;

  PlaneSet::const_iterator pi = planes.begin();
  FOR(i, planes.size() - 1) {
    (*pi)->write(out, useMaxPlanesMasking);
    out << "," << endl;
    pi++;
  }
  if (planes.size() > 0) {
    (*pi)->write(out, useMaxPlanesMasking);
  }
  out << endl;

  out << "  ]" << endl;
  out << "}" << endl;

  out.close();
}

void MaxPlanesLowerBound::readFromFile(const std::string &inFileName) {
  ifstream inFile(inFileName.c_str());
  if (!inFile) {
    cerr << "ERROR: couldn't open " << inFileName
         << " for reading: " << strerror(errno) << endl;
    exit(EXIT_FAILURE);
  }

  char buf[1024];
  std::string s;
  LBPlane plane;
  int entryIndex;
  double entryVal;
  int parseState = 0;
  int lnum = 0;
  while (!inFile.eof()) {
    inFile.getline(buf, sizeof(buf));
    lnum++;

    // strip whitespace, ignore empty lines and comments
    s = stripWhiteSpace(buf);
    if (0 == s.size()) continue;
    if ('#' == s[0]) continue;

    // ignore these types of lines because they contain redundant information
    if (s == "{") continue;
    if (s == "}" || s == "},") continue;
    if (s == "[") continue;
    if (s == "]" || s == "],") continue;
    if (string::npos != s.find("numPlanes")) continue;
    if (string::npos != s.find("planes")) continue;
    if (string::npos != s.find("numEntries")) continue;
    if (string::npos != s.find("entries")) continue;

  parseLineAgain:
    switch (parseState) {
      case 0:
        /* at the beginning of the file, check that this is the right type of
         * policy */
        if (string::npos != s.find("policyType") &&
            string::npos != s.find("MaxPlanesLowerBound")) {
          parseState = 1;
        } else {
          fprintf(stderr,
                  "ERROR: %s: line %d: expected 'policyType => "
                  "\"MaxPlanesLowerBound\"'\n",
                  inFileName.c_str(), lnum);
          exit(EXIT_FAILURE);
        }
        break;
      case 1:
        /* at the start of a plane, read the action */
        if (string::npos != s.find("action") &&
            (1 == sscanf(s.c_str(), "action => %d", &plane.action))) {
          plane.alpha.resize(pomdp->numStates);
          parseState = 2;
        } else {
          fprintf(stderr, "ERROR: %s: line %d: expected 'action => <int>'\n",
                  inFileName.c_str(), lnum);
          exit(EXIT_FAILURE);
        }
        break;
      case 2:
        if (string::npos != s.find("action")) {
          /* finding the 'action' keyword indicates we are at the start of
             another plane; finish up the plane we were working on and
             reparse the current line in parse state 1 */
          mask_set_to_one(plane.mask, plane.alpha);
          addLBPlane(new LBPlane(plane));
          parseState = 1;
          goto parseLineAgain;
        } else if (2 == sscanf(s.c_str(), "%d, %lf", &entryIndex, &entryVal)) {
          /* push another entry into the plane */
          plane.alpha.push_back(entryIndex, entryVal);
        } else {
          printf("s=[%s]\n", s.c_str());
          fprintf(stderr,
                  "ERROR: %s: line %d: expected entry '<int>, <double>'\n",
                  inFileName.c_str(), lnum);
          exit(EXIT_FAILURE);
        }
        break;
      default:
        assert(0);  // never reach this point
    }
  }

  /* reached EOF, finish up the last plane */
  if (2 == parseState) {
    mask_set_to_one(plane.mask, plane.alpha);
    addLBPlane(new LBPlane(plane));
  }

  inFile.close();

  // the set of planes should have been pruned before it was written out
  lastPruneNumPlanes = planes.size();
  lastPruneNumBackups = -1;

  initialized = true;
}

void MaxPlanesLowerBound::readFromCassandraAlphaFile(
    const std::string &inFileName) {
  ifstream inFile(inFileName.c_str());
  if (!inFile) {
    cerr << "ERROR: couldn't open " << inFileName
         << " for reading: " << strerror(errno) << endl;
    exit(EXIT_FAILURE);
  }

  double val;
  LBPlane plane;

  // initialize elements that are the same for all planes
  mask_set_all(plane.mask, pomdp->numStates);
  plane.numBackupsAtCreation = -1;

  while (!inFile.eof()) {
    inFile >> plane.action;
    plane.alpha.clear();
    plane.alpha.resize(pomdp->numStates);
    for (int i = 0; i < pomdp->numStates; i++) {
      inFile >> val;
      plane.alpha.push_back(i, val);
    }
    addLBPlane(new LBPlane(plane));
  }

  inFile.close();

  // the set of planes should have been pruned before it was written out
  lastPruneNumPlanes = planes.size();
  lastPruneNumBackups = -1;

  initialized = true;
}

int MaxPlanesLowerBound::getStorage(int whichMetric) const {
  switch (whichMetric) {
    case ZMDP_S_NUM_ELTS:
      // return number of planes
      return planes.size();

    case ZMDP_S_NUM_ENTRIES: {
      // return total number of entries in all planes
      int entryCount = 0;
      FOR_EACH(planeP, planes) {
        const LBPlane &p = **planeP;
        entryCount += p.alpha.filled();
        if (useMaxPlanesMasking) {
          entryCount += p.mask.filled();
        }
      }
      return entryCount;
    }

    default:
      /* N/A */
      return 0;
  }
}

};  // namespace zmdp

redpajama_set_name: RedPajamaGithub


text:
package com.heisenberg.impl.task;

import java.util.List;

import com.heisenberg.api.task.Task;
import com.heisenberg.api.task.TaskQuery;

/**
 * @author Walter White
 */
public class TaskQueryImpl implements TaskQuery {

  TaskServiceImpl taskService;

  public TaskQueryImpl(TaskServiceImpl taskService) {
    this.taskService = taskService;
  }

  @Override
  public List<Task> asList() {
    return taskService.findTasks(this);
  }

}


text:
/*
 * This combined file was created by the DataTables downloader builder:
 *   https://datatables.net/download
 *
 * To rebuild or modify this file with the latest versions of the included
 * software please visit:
 *   https://datatables.net/download/#bs4/dt-1.10.16/b-1.5.1/b-colvis-1.5.1/cr-1.4.1/fh-3.1.3/r-2.2.1/rr-1.2.3
 *
 * Included libraries:
 *   DataTables 1.10.16, Buttons 1.5.1, Column visibility 1.5.1, ColReorder 1.4.1, FixedHeader 3.1.3, Responsive 2.2.1, RowReorder 1.2.3
 */

table.dataTable {
    clear: both;
    margin-top: 6px !important;
    margin-bottom: 6px !important;
    max-width: none !important;
    border-collapse: separate !important;
}
table.dataTable td,
table.dataTable th {
    -webkit-box-sizing: content-box;
    box-sizing: content-box;
}
table.dataTable td.dataTables_empty,
table.dataTable th.dataTables_empty {
    text-align: center;
}
table.dataTable.nowrap th,
table.dataTable.nowrap td {
    white-space: nowrap;
}

div.dataTables_wrapper div.dataTables_length label {
    font-weight: normal;
    text-align: left;
    white-space: nowrap;
}
div.dataTables_wrapper div.dataTables_length select {
    width: 75px;
    display: inline-block;
}
div.dataTables_wrapper div.dataTables_filter {
    text-align: right;
}
div.dataTables_wrapper div.dataTables_filter label {
    font-weight: normal;
    white-space: nowrap;
    text-align: left;
}
div.dataTables_wrapper div.dataTables_filter input {
    margin-left: 0.5em;
    display: inline-block;
    width: auto;
}
div.dataTables_wrapper div.dataTables_info {
    padding-top: 0.85em;
    white-space: nowrap;
}
div.dataTables_wrapper div.dataTables_paginate {
    margin: 0;
    white-space: nowrap;
    text-align: right;
}
div.dataTables_wrapper div.dataTables_paginate ul.pagination {
    margin: 2px 0;
    white-space: nowrap;
    justify-content: flex-end;
}
div.dataTables_wrapper div.dataTables_processing {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 200px;
    margin-left: -100px;
    margin-top: -26px;
    text-align: center;
    padding: 1em 0;
}

table.dataTable thead > tr > th.sorting_asc, table.dataTable thead > tr > th.sorting_desc, table.dataTable thead > tr > th.sorting,
table.dataTable thead > tr > td.sorting_asc,
table.dataTable thead > tr > td.sorting_desc,
table.dataTable thead > tr > td.sorting {
    padding-right: 30px;
}
table.dataTable thead > tr > th:active,
table.dataTable thead > tr > td:active {
    outline: none;
}
table.dataTable thead .sorting,
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting_asc_disabled,
table.dataTable thead .sorting_desc_disabled {
    cursor: pointer;
    position: relative;
}
table.dataTable thead .sorting:before, table.dataTable thead .sorting:after,
table.dataTable thead .sorting_asc:before,
table.dataTable thead .sorting_asc:after,
table.dataTable thead .sorting_desc:before,
table.dataTable thead .sorting_desc:after,
table.dataTable thead .sorting_asc_disabled:before,
table.dataTable thead .sorting_asc_disabled:after,
table.dataTable thead .sorting_desc_disabled:before,
table.dataTable thead .sorting_desc_disabled:after {
    position: absolute;
    bottom: 0.9em;
    display: block;
    opacity: 0.3;
}
table.dataTable thead .sorting:before,
table.dataTable thead .sorting_asc:before,
table.dataTable thead .sorting_desc:before,
table.dataTable thead .sorting_asc_disabled:before,
table.dataTable thead .sorting_desc_disabled:before {
    right: 1em;
    content: "\2191";
}
table.dataTable thead .sorting:after,
table.dataTable thead .sorting_asc:after,
table.dataTable thead .sorting_desc:after,
table.dataTable thead .sorting_asc_disabled:after,
table.dataTable thead .sorting_desc_disabled:after {
    right: 0.5em;
    content: "\2193";
}
table.dataTable thead .sorting_asc:before,
table.dataTable thead .sorting_desc:after {
    opacity: 1;
}
table.dataTable thead .sorting_asc_disabled:before,
table.dataTable thead .sorting_desc_disabled:after {
    opacity: 0;
}

div.dataTables_scrollHead table.dataTable {
    margin-bottom: 0 !important;
}

div.dataTables_scrollBody table {
    border-top: none;
    margin-top: 0 !important;
    margin-bottom: 0 !important;
}
div.dataTables_scrollBody table thead .sorting:after,
div.dataTables_scrollBody table thead .sorting_asc:after,
div.dataTables_scrollBody table thead .sorting_desc:after {
    display: none;
}
div.dataTables_scrollBody table tbody tr:first-child th,
div.dataTables_scrollBody table tbody tr:first-child td {
    border-top: none;
}

div.dataTables_scrollFoot > .dataTables_scrollFootInner {
    box-sizing: content-box;
}
div.dataTables_scrollFoot > .dataTables_scrollFootInner > table {
    margin-top: 0 !important;
    border-top: none;
}

@media screen and (max-width: 767px) {
    div.dataTables_wrapper div.dataTables_length,
    div.dataTables_wrapper div.dataTables_filter,
    div.dataTables_wrapper div.dataTables_info,
    div.dataTables_wrapper div.dataTables_paginate {
        text-align: center;
    }
}
table.dataTable.table-sm > thead > tr > th {
    padding-right: 20px;
}
table.dataTable.table-sm .sorting:before,
table.dataTable.table-sm .sorting_asc:before,
table.dataTable.table-sm .sorting_desc:before {
    top: 5px;
    right: 0.85em;
}
table.dataTable.table-sm .sorting:after,
table.dataTable.table-sm .sorting_asc:after,
table.dataTable.table-sm .sorting_desc:after {
    top: 5px;
}

table.table-bordered.dataTable th,
table.table-bordered.dataTable td {
    border-left-width: 0;
}
table.table-bordered.dataTable th:last-child, table.table-bordered.dataTable th:last-child,
table.table-bordered.dataTable td:last-child,
table.table-bordered.dataTable td:last-child {
    border-right-width: 0;
}
table.table-bordered.dataTable tbody th,
table.table-bordered.dataTable tbody td {
    border-bottom-width: 0;
}

div.dataTables_scrollHead table.table-bordered {
    border-bottom-width: 0;
}

div.table-responsive > div.dataTables_wrapper > div.row {
    margin: 0;
}
div.table-responsive > div.dataTables_wrapper > div.row > div[class^="col-"]:first-child {
    padding-left: 0;
}
div.table-responsive > div.dataTables_wrapper > div.row > div[class^="col-"]:last-child {
    padding-right: 0;
}

@keyframes dtb-spinner {
    100% {
        transform: rotate(360deg);
    }
}
@-o-keyframes dtb-spinner {
    100% {
        -o-transform: rotate(360deg);
        transform: rotate(360deg);
    }
}
@-ms-keyframes dtb-spinner {
    100% {
        -ms-transform: rotate(360deg);
        transform: rotate(360deg);
    }
}
@-webkit-keyframes dtb-spinner {
    100% {
        -webkit-transform: rotate(360deg);
        transform: rotate(360deg);
    }
}
@-moz-keyframes dtb-spinner {
    100% {
        -moz-transform: rotate(360deg);
        transform: rotate(360deg);
    }
}
div.dt-button-info {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 400px;
    margin-top: -100px;
    margin-left: -200px;
    background-color: white;
    border: 2px solid #111;
    box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.3);
    border-radius: 3px;
    text-align: center;
    z-index: 21;
}
div.dt-button-info h2 {
    padding: 0.5em;
    margin: 0;
    font-weight: normal;
    border-bottom: 1px solid #ddd;
    background-color: #f3f3f3;
}
div.dt-button-info > div {
    padding: 1em;
}

ul.dt-button-collection.dropdown-menu {
    display: block;
    z-index: 2002;
    -webkit-column-gap: 8px;
    -moz-column-gap: 8px;
    -ms-column-gap: 8px;
    -o-column-gap: 8px;
    column-gap: 8px;
}
ul.dt-button-collection.dropdown-menu.fixed {
    position: fixed;
    top: 50%;
    left: 50%;
    margin-left: -75px;
    border-radius: 0;
}
ul.dt-button-collection.dropdown-menu.fixed.two-column {
    margin-left: -150px;
}
ul.dt-button-collection.dropdown-menu.fixed.three-column {
    margin-left: -225px;
}
ul.dt-button-collection.dropdown-menu.fixed.four-column {
    margin-left: -300px;
}
ul.dt-button-collection.dropdown-menu > * {
    -webkit-column-break-inside: avoid;
    break-inside: avoid;
}
ul.dt-button-collection.dropdown-menu.two-column {
    width: 300px;
    padding-bottom: 1px;
    -webkit-column-count: 2;
    -moz-column-count: 2;
    -ms-column-count: 2;
    -o-column-count: 2;
    column-count: 2;
}
ul.dt-button-collection.dropdown-menu.three-column {
    width: 450px;
    padding-bottom: 1px;
    -webkit-column-count: 3;
    -moz-column-count: 3;
    -ms-column-count: 3;
    -o-column-count: 3;
    column-count: 3;
}
ul.dt-button-collection.dropdown-menu.four-column {
    width: 600px;
    padding-bottom: 1px;
    -webkit-column-count: 4;
    -moz-column-count: 4;
    -ms-column-count: 4;
    -o-column-count: 4;
    column-count: 4;
}
ul.dt-button-collection.dropdown-menu .dt-button {
    border-radius: 0;
}

ul.dt-button-collection {
    -webkit-column-gap: 8px;
    -moz-column-gap: 8px;
    -ms-column-gap: 8px;
    -o-column-gap: 8px;
    column-gap: 8px;
}
ul.dt-button-collection.fixed {
    position: fixed;
    top: 50%;
    left: 50%;
    margin-left: -75px;
    border-radius: 0;
}
ul.dt-button-collection.fixed.two-column {
    margin-left: -150px;
}
ul.dt-button-collection.fixed.three-column {
    margin-left: -225px;
}
ul.dt-button-collection.fixed.four-column {
    margin-left: -300px;
}
ul.dt-button-collection > * {
    -webkit-column-break-inside: avoid;
    break-inside: avoid;
}
ul.dt-button-collection.two-column {
    width: 300px;
    padding-bottom: 1px;
    -webkit-column-count: 2;
    -moz-column-count: 2;
    -ms-column-count: 2;
    -o-column-count: 2;
    column-count: 2;
}
ul.dt-button-collection.three-column {
    width: 450px;
    padding-bottom: 1px;
    -webkit-column-count: 3;
    -moz-column-count: 3;
    -ms-column-count: 3;
    -o-column-count: 3;
    column-count: 3;
}
ul.dt-button-collection.four-column {
    width: 600px;
    padding-bottom: 1px;
    -webkit-column-count: 4;
    -moz-column-count: 4;
    -ms-column-count: 4;
    -o-column-count: 4;
    column-count: 4;
}
ul.dt-button-collection .dt-button {
    border-radius: 0;
}
ul.dt-button-collection.fixed {
    max-width: none;
}
ul.dt-button-collection.fixed:before, ul.dt-button-collection.fixed:after {
    display: none;
}

div.dt-button-background {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
}

@media screen and (max-width: 767px) {
    div.dt-buttons {
        float: none;
        width: 100%;
        text-align: center;
        margin-bottom: 0.5em;
    }
    div.dt-buttons a.btn {
        float: none;
    }
}
div.dt-buttons button.btn.processing,
div.dt-buttons div.btn.processing,
div.dt-buttons a.btn.processing {
    color: rgba(0, 0, 0, 0.2);
}
div.dt-buttons button.btn.processing:after,
div.dt-buttons div.btn.processing:after,
div.dt-buttons a.btn.processing:after {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 16px;
    height: 16px;
    margin: -8px 0 0 -8px;
    box-sizing: border-box;
    display: block;
    content: ' ';
    border: 2px solid #282828;
    border-radius: 50%;
    border-left-color: transparent;
    border-right-color: transparent;
    animation: dtb-spinner 1500ms infinite linear;
    -o-animation: dtb-spinner 1500ms infinite linear;
    -ms-animation: dtb-spinner 1500ms infinite linear;
    -webkit-animation: dtb-spinner 1500ms infinite linear;
    -moz-animation: dtb-spinner 1500ms infinite linear;
}

table.DTCR_clonedTable.dataTable {
    position: absolute !important;
    background-color: rgba(255, 255, 255, 0.7);
    z-index: 202;
}

div.DTCR_pointer {
    width: 1px;
    background-color: #0275d8;
    z-index: 201;
}

table.dataTable.fixedHeader-floating,
table.dataTable.fixedHeader-locked {
    background-color: white;
    margin-top: 0 !important;
    margin-bottom: 0 !important;
}

table.dataTable.fixedHeader-floating {
    position: fixed !important;
}

table.dataTable.fixedHeader-locked {
    position: absolute !important;
}

@media print {
    table.fixedHeader-floating {
        display: none;
    }
}

table.dataTable.dtr-inline.collapsed > tbody > tr > td.child,
table.dataTable.dtr-inline.collapsed > tbody > tr > th.child,
table.dataTable.dtr-inline.collapsed > tbody > tr > td.dataTables_empty {
    cursor: default !important;
}
table.dataTable.dtr-inline.collapsed > tbody > tr > td.child:before,
table.dataTable.dtr-inline.collapsed > tbody > tr > th.child:before,
table.dataTable.dtr-inline.collapsed > tbody > tr > td.dataTables_empty:before {
    display: none !important;
}
table.dataTable.dtr-inline.collapsed > tbody > tr[role="row"] > td:first-child,
table.dataTable.dtr-inline.collapsed > tbody > tr[role="row"] > th:first-child {
    position: relative;
    padding-left: 30px;
    cursor: pointer;
}
table.dataTable.dtr-inline.collapsed > tbody > tr[role="row"] > td:first-child:before,
table.dataTable.dtr-inline.collapsed > tbody > tr[role="row"] > th:first-child:before {
    top: 12px;
    left: 4px;
    height: 14px;
    width: 14px;
    display: block;
    position: absolute;
    color: white;
    border: 2px solid white;
    border-radius: 14px;
    box-shadow: 0 0 3px #444;
    box-sizing: content-box;
    text-align: center;
    text-indent: 0 !important;
    font-family: 'Courier New', Courier, monospace;
    line-height: 14px;
    content: '+';
    background-color: #0275d8;
}
table.dataTable.dtr-inline.collapsed > tbody > tr.parent > td:first-child:before,
table.dataTable.dtr-inline.collapsed > tbody > tr.parent > th:first-child:before {
    content: '-';
    background-color: #d33333;
}
table.dataTable.dtr-inline.collapsed.compact > tbody > tr > td:first-child,
table.dataTable.dtr-inline.collapsed.compact > tbody > tr > th:first-child {
    padding-left: 27px;
}
table.dataTable.dtr-inline.collapsed.compact > tbody > tr > td:first-child:before,
table.dataTable.dtr-inline.collapsed.compact > tbody > tr > th:first-child:before {
    top: 5px;
    left: 4px;
    height: 14px;
    width: 14px;
    border-radius: 14px;
    line-height: 14px;
    text-indent: 3px;
}
table.dataTable.dtr-column > tbody > tr > td.control,
table.dataTable.dtr-column > tbody > tr > th.control {
    position: relative;
    cursor: pointer;
}
table.dataTable.dtr-column > tbody > tr > td.control:before,
table.dataTable.dtr-column > tbody > tr > th.control:before {
    top: 50%;
    left: 50%;
    height: 16px;
    width: 16px;
    margin-top: -10px;
    margin-left: -10px;
    display: block;
    position: absolute;
    color: white;
    border: 2px solid white;
    border-radius: 14px;
    box-shadow: 0 0 3px #444;
    box-sizing: content-box;
    text-align: center;
    text-indent: 0 !important;
    font-family: 'Courier New', Courier, monospace;
    line-height: 14px;
    content: '+';
    background-color: #0275d8;
}
table.dataTable.dtr-column > tbody > tr.parent td.control:before,
table.dataTable.dtr-column > tbody > tr.parent th.control:before {
    content: '-';
    background-color: #d33333;
}
table.dataTable > tbody > tr.child {
    padding: 0.5em 1em;
}
table.dataTable > tbody > tr.child:hover {
    background: transparent !important;
}
table.dataTable > tbody > tr.child ul.dtr-details {
    display: inline-block;
    list-style-type: none;
    margin: 0;
    padding: 0;
}
table.dataTable > tbody > tr.child ul.dtr-details > li {
    border-bottom: 1px solid #efefef;
    padding: 0.5em 0;
}
table.dataTable > tbody > tr.child ul.dtr-details > li:first-child {
    padding-top: 0;
}
table.dataTable > tbody > tr.child ul.dtr-details > li:last-child {
    border-bottom: none;
}
table.dataTable > tbody > tr.child span.dtr-title {
    display: inline-block;
    min-width: 75px;
    font-weight: bold;
}

div.dtr-modal {
    position: fixed;
    box-sizing: border-box;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    z-index: 100;
    padding: 10em 1em;
}
div.dtr-modal div.dtr-modal-display {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    width: 50%;
    height: 50%;
    overflow: auto;
    margin: auto;
    z-index: 102;
    overflow: auto;
    background-color: #f5f5f7;
    border: 1px solid black;
    border-radius: 0.5em;
    box-shadow: 0 12px 30px rgba(0, 0, 0, 0.6);
}
div.dtr-modal div.dtr-modal-content {
    position: relative;
    padding: 1em;
}
div.dtr-modal div.dtr-modal-close {
    position: absolute;
    top: 6px;
    right: 6px;
    width: 22px;
    height: 22px;
    border: 1px solid #eaeaea;
    background-color: #f9f9f9;
    text-align: center;
    border-radius: 3px;
    cursor: pointer;
    z-index: 12;
}
div.dtr-modal div.dtr-modal-close:hover {
    background-color: #eaeaea;
}
div.dtr-modal div.dtr-modal-background {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 101;
    background: rgba(0, 0, 0, 0.6);
}

@media screen and (max-width: 767px) {
    div.dtr-modal div.dtr-modal-display {
        width: 95%;
    }
}
div.dtr-bs-modal table.table tr:first-child td {
    border-top: none;
}

table.dt-rowReorder-float {
    position: absolute !important;
    opacity: 0.8;
    table-layout: fixed;
    outline: 2px solid #0275d8;
    outline-offset: -2px;
    z-index: 2001;
}

tr.dt-rowReorder-moving {
    outline: 2px solid #888;
    outline-offset: -2px;
}

body.dt-rowReorder-noOverflow {
    overflow-x: hidden;
}

table.dataTable td.reorder {
    text-align: center;
    cursor: move;
}


text:
'use strict';

//Tasks service used to communicate Tasks REST endpoints
angular.module('tasks').factory('Tasks', ['$http',
	function($http) {
		var serviceFactory = {};

		serviceFactory.saveTasks = function (req, res) {
			return $http.post('/tasks/create',req);
		};
		serviceFactory.getTasks = function (req, res) {
			return $http.get('/tasks', req);
		};
		serviceFactory.updateTask = function (req,res) {
			return $http.post('/Task/update', req);
		};
		serviceFactory.getTaskById = function (req, res) {
			return $http.get('/task/' + req.taskId);
		};
		serviceFactory.updateAssigneesList = function (req, res) {
			return $http.get('/task/deleteAssignee/' + req.taskId+'/' +req.assigneeId);
		};
        serviceFactory.getTaskByUserId = function (req, res) {
            return $http.get('/tasks/myTask');
        };
		serviceFactory.updateMilestone = function (req, res) {
            return $http.post('/tasks/updateMilestone', req);
        };

		return serviceFactory;
	}
]);


text:
namespace AngleSharp.Css.Dom
{
    /// <summary>
    /// The enumeration over all possible animation direction values.
    /// </summary>
    public enum AnimationDirection : byte
    {
        /// <summary>
        /// The animation should play forward each cycle.
        /// In other words, each time the animation cycles,
        /// the animation will reset to the beginning state
        /// and start over again. This is the default
        /// animation direction setting.
        /// </summary>
        Normal,
        /// <summary>
        /// The animation should reverse direction each cycle.
        /// When playing in reverse, the animation steps are
        /// performed backward. In addition, timing functions
        /// are also reversed; for example, an ease-in animation
        /// is replaced with an ease-out animation when played
        /// in reverse. The count to determine if it is an even
        /// or an odd iteration starts at one.
        /// </summary>
        Alternate,
        /// <summary>
        /// The animation plays backward each cycle. Each time
        /// the animation cycles, the animation resets to the
        /// end state and start over again.
        /// </summary>
        Reverse,
        /// <summary>
        /// The animation plays backward on the first
        /// play-through, then forward on the next, then
        /// continues to alternate. The count to determinate
        /// if it is an even or an odd iteration starts at one.
        /// </summary>
        AlternateReverse
    }
}


text: another chunk


text:
const fetch = require('node-fetch');
const config = require('../../config/config');
const logger = require('../../config/logger');

function options(body) {
	return {
		method: 'POST',
		headers: {
			'X-API-KEY': config.eventsServiceAuth,
			'Content-Type': 'application/json',
		},
		body: JSON.stringify(body)
	};
}

function isJsonResponse(res) {
	return res.headers.get('content-type') === 'application/json';
}

async function parseJsonResponse(res) {
	let resBody;
	try {
		resBody = await res.json();
	} catch (err) {
		logger.warn('Sent Event JSON response was invalid');
		resBody = { message: '' };
	}
	return resBody;
}

async function sendEvent(event) {
	const res = await fetch(`${config.eventsServiceHost}/webhooks/user-preferences`, options(event));
	let resBody;
	if (isJsonResponse(res)) {
		resBody = await parseJsonResponse(res);
	} else {
		resBody = { message: await res.text() };
	}
	if (!res.ok) {
		throw new Error(res.statusText);
	}
	return resBody;
}

module.exports = {
	sendEvent
};


text:
package org.anddev.andengine.util.constants;

public interface MathConstants
{
    public static final float DEG_TO_RAD = 0.017453292f;
    public static final float PI = 3.1415927f;
    public static final float RAD_TO_DEG = 57.295776f;
    public static final float _2PI = 6.2831855f;
    public static final float _HALF_PI = 1.5707964f;
}


text:
package org.sisioh.aws4s.sns.model

import com.amazonaws.services.sns.model.GetPlatformApplicationAttributesRequest
import org.sisioh.aws4s.PimpedType

object GetPlatformApplicationAttributesRequestFactory {

  def create(): GetPlatformApplicationAttributesRequest =
    new GetPlatformApplicationAttributesRequest()

}

class RichGetPlatformApplicationAttributesRequest(val underlying: GetPlatformApplicationAttributesRequest)
    extends AnyVal
    with PimpedType[GetPlatformApplicationAttributesRequest] {

  def platformApplicationArnOpt: Option[String] =
    Option(underlying.getPlatformApplicationArn)

  def platformApplicationArnOpt_=(value: Option[String]): Unit =
    underlying.setPlatformApplicationArn(value.orNull)

  def withPlatformApplicationArnOpt(value: Option[String]): GetPlatformApplicationAttributesRequest =
    underlying.withPlatformApplicationArn(value.orNull)

}


text:
module DataMapper
  module Visualizer
    module Rake
      module Rails
        module Tasks
          #
          # Disables Bundler by default.
          #
          def initialize(options={},&block)
            super({:bundle => false}.merge(options),&block)
          end

          #
          # Overrides the Rake `task` method to make sure every defined
          # task depends on `environment`.
          #
          # @param [Array] arguments
          #   The arguments of the task.
          #
          def task(*arguments)
            if arguments.first.kind_of?(Hash)
              super(*arguments)
            else
              super(arguments.first => :environment)
            end
          end
        end
      end
    end
  end
end


text:
class Library
  def initialize(name, path="", exportMacro=nil)
    @name = name
    @namespaceName = name
    @root = path
    @rootPathname = Pathname.new(@root)
    @includePaths = []
    @files = []
    @dependencies = []
    @languagesAutogenPath = { }
    @exportMacro = exportMacro ? exportMacro : name.upcase() + "_EXPORT"
    @coreInclude = "#{name}.h"
  end

  attr_reader :name, :files, :root
  attr_accessor :namespaceName, :rootPathname, :includePaths, :dependencies, :exportMacro, :coreInclude

  def setAutogenPath(lang, path)
    @languagesAutogenPath[lang] = path
  end

  # The path which should hold auto gen files for the library
  def autogenPath(lang)
    pth = @languagesAutogenPath[lang]
    if (pth)
      return pth
    end

    return "#{root}/autogen_#{name}"
  end

  def setRoot(root)
    @root = root
    @rootPathname = Pathname.new(@root)
  end

  # Add a source file path to the library
  def addFile(path)
    @files << path
  end

  # Add a source file path to the library
  def addFiles(path, pattern, recursive)
    pattern = "#{root}/#{path}/#{recursive ? "**/" : ""}#{pattern}"
    Dir.glob(pattern).each do |item|
      next if item == '.' or item == '..'
      # do work on real items

      filePath = Pathname.new(item).relative_path_from(@rootPathname)
      addFile(filePath)
    end
  end

  # add a dependency library to this library
  def addDependency(dep)
    @dependencies << dep
  end

  # add a dependency library to this library
  def addDependencies(depArr)
    @dependencies = @dependencies.concat(depArr)
  end

  # add an include path to the library
  def addIncludePath(path)
    @includePaths << path
  end

  # find an array of all the include paths this library requires, including its dependent library include paths.
  def includePaths
    localPaths = @includePaths.map{ |path| root + "/" + path + "/" }
    externalPaths = @dependencies.map{ |dep| dep.includePaths }.reduce([]) { |sum, obj| sum + obj }

    allPaths = (localPaths + externalPaths).uniq

    return allPaths
  end
end


text:
package id.ac.ui.edoocatia;

public interface ActionResolver {

	String getString(int resId);
}


text:
Debug.order('app-home/feed_post_form.js');

Template.feedPostForm.rendered = function() {
    $("body").click(function(e) {
        if (!(e.target.id == "feed-post-container" || $(e.target).parents("#feed-post-container").size())) {
            $header = $('.feed-post-form-header');
            $body = $('.feed-post-form .inner-form');

            $header.children().children('input').prop('checked', false);
            $header.children().children('label').removeClass('checked');

            $body.slideUp();
        }
    });
}

Template.feedPostFormHeader.events({
    'change input:radio': function(e) {
        var $target = $(e.currentTarget),
            $label = $('label[for=' + $target.attr('id') + ']'),
            $sell = $('.feed-post-form-sell'),
            $buy = $('.feed-post-form-buy');

        $label.siblings('label').removeClass('checked');
        $label.addClass('checked');

        var duration = 200;
        if ($target.val() == 'sell') {
            if ($buy.css('display') !== 'none') {
                $buy.velocity('slideUp', duration);
            }
            $sell.velocity('slideDown', duration);
        } else {
            if ($sell.css('display') !== 'none') {
                $sell.velocity('slideUp', duration);
            }
            $buy.velocity('slideDown', duration);
        }
    }
});

Template.feedPostFormSell.events({
    'change #sell-image': function(e) {
        Utils.readUrl(e.currentTarget, 'sell-preview');
        $('#sell-preview').toggleClass('filled uploading');
    },
    'click #sell-post': function(e) {
        if ($('input[type=feed]:checked') && $('#sell-title').val() && $('#sell-description').val()) {
            upload(e);
        }
    },
    'change #sell-fb': function(e) {
        if ($(e.currentTarget).is(':checked')) {
            if (Meteor.isClient) {
                Accounts.ui.config({
                    requestPermissions: {
                        facebook: ['publish_stream']
                    }
                });
            }
        }
    }
});

Template.feedPostFormFeedList.helpers({
    feeds: function() {
        var feeds = Feeds.find().fetch();
        return feeds;
    }
});

Template.feedPostFormFeedList.events({
    'change input:radio': function(e) {
        var $target = $(e.currentTarget),
            $label = $('label[for=' + $target.attr('id') + ']');

        $label.siblings('label').removeClass('checked');
        $label.addClass('checked');
    }
});

//whoops defining a function here...shoot me
var upload = function(e) {
    if (Session.get('uploading') == true) {
        setInterval(upload(e), 100);
    } else {
        $(e.target).css('pointer-events', 'none');
        setInterval(function() {
            $(e.target).css('pointer-events', 'auto');
        }, 1000);
        e.preventDefault();

        if (!Meteor.user()) {
            RModal.openModal($('#login-modal'));
            return -1;
        }
        $(this).css('pointer-events', 'none');

        temp = {};
        temp.title = $('#sell-title').val();
        temp.feeds = [];
        if (Session.get('uploadUrl'))
            temp.imageUrl = S3.url + Session.get('uploadUrl');
        if (Router.current().params.id) {
            temp.feeds.push(Router.current().params.id);
        } else {
            temp.feeds.push($('input[name=feed]:checked').val());
        }
        /*
           temp.so = $('input[name=so]').val();
           temp.bin = $('input[name=bin]').val();
           temp.condition = $('select[name=condition]').val();
           */
        temp.description = $('#sell-description').val();
        //temp.imageUrl = S3.imageUpload(Meteor.userId(), document.getElementById('image').files[0]);
        //temp.image = document.getElementById('image').files[0];
        Debug.feed('temp item', temp);

        // NEED A CHECK TO SEE IF THE FIELDS ARE ALL FILLED
        $('.feed-post-form-sell').slideUp();

        Meteor.call('addPost', temp, function(e, r) {
            console.log("something");
            if (e) {
                alert(e);
            } else {
                if (r == -1)
                    alert('Need an image url!');
                else if (r == -2)
                    alert('Need a title!');
                else if (r == -3)
                    alert('Need a description!');
                else if (r == -4)
                    alert('Pick a feed!');
                console.log("done");
                //	Router.go('/post/' + r);
            }
        });
    }
    return 0;
}

Template.feedPostFormBuy.events({
    'click #buy-post': function(e) {
        if (!($('input[type=feed]:checked') && $('#buy-description').val()))
            return -1;
        if (!Meteor.user()) {
            RModal.openModal($('#login-modal'));
            return -1;
        }
        $(e.target).css('pointer-events', 'none');
        setInterval(function() {
            $(e.target).css('pointer-events', 'auto');
        }, 1000);
        e.preventDefault();

        temp = {};
        temp.feeds = [];
        if (Router.current().params.id)
            temp.feeds.push(Router.current().params.id);
        else
            temp.feeds.push($('input[name=feed]:checked').val());
        /*
   temp.so = $('input[name=so]').val();
   temp.bin = $('input[name=bin]').val();
   temp.condition = $('select[name=condition]').val();
   */
        temp.description = $('#buy-description').val();
        temp.buy = true;
        Debug.feed('temp item', temp);

        //NEED A CHECK TO SEE IF THE FIELDS ARE ALL FILLED
        e.preventDefault();
        Meteor.call('addRequest', temp, function(e, r) {
            console.log("something");
            if (e) {
                alert(e);
            } else {
                console.log("done");
                Router.go('/');
            }
        });
        $('#buy-description').val('');
        $('.feed-post-form-buy').slideUp();
        $('.feed-post-form-header label').removeClass('checked');
        $('#feed-buy-radio').prop('checked', false);
    }
});


text:
export class Statistic {

  total_devices : number;
  usable_devices : number;
  busy_devices : number;
  caster : number;

  constructor( total_devices : number, usable_devices : number,busy_devices : number,caster : number){

    this.total_devices = total_devices;
    this.usable_devices=usable_devices;
    this.busy_devices=busy_devices;
    this.caster=caster;
  }

}


text:
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody2D))]
public class BallController : MonoBehaviour
{

    new Rigidbody2D rigidbody2D;

    Vector2 lastClickDir;
    int wallBoucnes = 0;

    //tempvalue for when game is paused
    Vector2 savedSpeed;

    /// <summary>
    /// ball is frozen into place
    /// </summary>
    bool frozen; //TODO Change frozen to is kinametic from ridgidbody2d

    bool useAnimator; //Enables use of the Animator if asigned

    // Use this for initialization
    void Start()
    {
        InputManager.onClick += InputManager_onClick;

        Events.GlobalEvents.AddEventListener<Events.IPause>(OnPause);
        Events.GlobalEvents.AddEventListener<Events.IResetGameState>(ResetBall);
        rigidbody2D = GetComponent<Rigidbody2D>();

        ResetBall(new Events.IResetGameState(false));

        ChangeLooks();
    }

    /// <summary>
    /// Swaps sprite of the object currently
    /// Also swaps animation controler of the ball
    /// </summary>
    public void ChangeLooks()
    {
        GetComponent<SpriteRenderer>().sprite = Menus.ShopMenuData.GetShopMenu().Characters[SaveManager.savaData.SelectedCharacter].LowRes;
        PhysicsMaterial2D temp = GetComponent<PolygonCollider2D>().sharedMaterial;
        Destroy(GetComponent<PolygonCollider2D>());
        gameObject.AddComponent<PolygonCollider2D>().sharedMaterial = temp;
    }

    public void OnDestroy()
    {
        InputManager.onClick -= InputManager_onClick;

        Events.GlobalEvents.RemoveEventListener<Events.IPause>(OnPause);
        Events.GlobalEvents.RemoveEventListener<Events.IResetGameState>(ResetBall);
    }

    /// <summary>
    /// Called when pause state has changed
    /// </summary>
    /// <param name="pause"></param>
    void OnPause(Events.IPause pause)
    {
        enabled = !pause.State;
        if (pause.State)
        {
            savedSpeed = rigidbody2D.velocity;
            rigidbody2D.velocity = Vector2.zero;
            frozen = true;
            SetConstraints();
        }
        else
        {
            frozen = false;
            SetConstraints();
            rigidbody2D.velocity = savedSpeed;

        }
    }

    /// <summary>
    /// Resets the ball called when game is reset
    /// </summary>
    /// <param name="obj"></param>
    void ResetBall(Events.IResetGameState obj)
    {
        transform.position = Vector3.zero;
        rigidbody2D.velocity = Vector2.zero;
        frozen = true;
        SetConstraints();
        //StartCoroutine(ballFreeze(0.5f, 0.0f));
    }

    /// <summary>
    /// Call in inputManager handles force adding for the ball
    /// </summary>
    /// <param name="position"></param>
    private void InputManager_onClick(Vector2 position)
    {
        if (isActiveAndEnabled)
        {
            frozen = false;
            SetConstraints();

            if (transform.position.y < 12f)
            {
                Vector2 dir;
                dir = ((Vector2)Camera.main.WorldToViewportPoint(transform.position));
                dir.Scale(new Vector2(Screen.width, Screen.height));

                if (Vector2.Distance(dir, position) > 150)
                {
                    return;
                }

                dir = dir - position;
                dir = Util.Common.AngleToVector(Util.Common.VectorToAngle(dir));

                lastClickDir = dir;

                Events.GlobalEvents.Invoke(new Events.IBallMove(dir, transform.position));

                wallBoucnes = 0;

                //dir = new Vector2(-dir.x, dir.y * Physics2D.gravity.y);
                dir *= 350 * rigidbody2D.mass; //TODO tweak with force to make the ball more reactive
                dir.y *= rigidbody2D.gravityScale *1.3f;

                rigidbody2D.AddTorque(dir.x / 10);
                if (rigidbody2D.angularVelocity > 10)
                    rigidbody2D.angularVelocity = 10;
                if (rigidbody2D.angularVelocity < -10)
                    rigidbody2D.angularVelocity = -10;

                rigidbody2D.AddForce(dir);
            }
        }
    }

    /// <summary>
    /// Unity Function
    /// </summary>
    /// <param name="collision"></param>
    public void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.transform.tag == "ScoreTarget")
        {
            Events.GlobalEvents.Invoke(new Events.IScore(wallBoucnes, lastClickDir));
            StartCoroutine(ballResetDelay(0.4f));
            StartCoroutine(ballFreeze(0.5f, 0.4f));
            rigidbody2D.velocity = Vector2.zero;
        }
    }

    public void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.transform.tag == "Bottom")
        {
            rigidbody2D.velocity = Vector2.zero;
            // StartCoroutine(ballResetDelay(0.2f));
            // StartCoroutine(ballFreeze(0.5f, 0.2f));
            Events.GlobalEvents.Invoke(new Events.IBallHitBottom());
        }
        else if (collision.transform.tag == "Side")
        {
            wallBoucnes++;
        }
        else if (collision.transform.tag == "ScoreTarget")
        {
            rigidbody2D.velocity = rigidbody2D.velocity * 0.5f;
        }
    }

    /// <summary>
    /// Used to induce a delay for when the ball resets
    /// </summary>
    /// <param name="Delay">Delay Time in seconds</param>
    /// <returns></returns>
    IEnumerator ballResetDelay(float Delay)
    {
        yield return new WaitForSeconds(Delay);

        transform.position = Vector3.zero;

    }

    /// <summary>
    /// Freezes the Ball in place for x seconds
    /// </summary>
    /// <param name="duration">time ball will befrozen</param>
    /// <param name="delay">a delay for this action to happen</param>
    /// <returns></returns>
    IEnumerator ballFreeze(float duration,float delay)
    {
        yield return new WaitForSeconds(delay);
        float d = duration;

        frozen = true;
        SetConstraints();

        while(d>0 && frozen)
        {
            d -= Time.deltaTime;
            yield return new WaitForEndOfFrame();
        }

        frozen = false;
        SetConstraints();

    }

    /// <summary>
    /// Used to change the contrians of the object easily
    /// </summary>
    void SetConstraints()
    {
        if (frozen)
        {
            rigidbody2D.constraints = RigidbodyConstraints2D.FreezeAll;
            return;
        }

            //transform.position = new Vector3(0, transform.position.y, transform.position.z);
            rigidbody2D.constraints = RigidbodyConstraints2D.None;
    }
}


text:
'use strict';

describe('Service: Books', function () {

  // load the service's module
  beforeEach(module('dashboardApp'));

  // instantiate service
  var Books;
  beforeEach(inject(function (_Books_) {
    Books = _Books_;
  }));

  it('should do something', function () {
    expect(!!Books).toBe(true);
  });

});


text:
namespace shapelens {

/// Central object representing class.
/// The purpose of this class is to faciliate the exchange of object related information
/// between different codes. By our definition, an object is a significant peak of the
/// brightness distribution, indentified by some image processing code (e.g. Frame).\n\n
/// A respresentant of this class describes an object in real (pixel) space.
/// It consists of the pixel values, the Grid, and the centroid.
/// centroid, ellipticity).
/// In addition, it can store information from the preceding image processing steps:
/// - noise characteristics (including the noise model)
/// - pixel covariance matrix
/// - detection flags
/// - processing history
/// - segmentation map
/// - Fourier transform

class Object : public Image<data_t> {
 public:
  /// Constructor.
  Object();
  /// Argumented constructor for loading an object from a Fits file.
  /// The Fits file shold have been created by Object::save().
  Object (std::string fitsfile);
  /// Copy constructor from base class.
  Object (const Image<data_t>& base);
  /// Save the object information in a Fits file.
  /// Data and SegmentationMap will go to pHDU and 1st extHDU, respectively.
  /// All other information goes to the pHDU header.
  /// If a weight map is provided, these will be stored in the extension \p WEIGTH
  /// If a correlation function is provided, these will be stored in the extension \p CORRELATION.
  void save(std::string fitsfile);

  /// Computes Object::flux and Object::centroid from pixel data.
  /// If Object::weight is non-empty, the pixel weights are considered.
  void computeCentroid();
  /// Compute correlation function Object::xi from pixel data.
  /// \p threshold is the minimum significance of the correlation to
  /// to be considered (reasonable value are around 2).
  void computeCorrelationFunction(data_t threshold);
  /// Compute Fourier transform Object::fourier from pixel data.
  void computeFFT();
  /// Convolve with given \p kernel.
  /// fourier and kernel::fourier will be used if present.
  void convolve(const Object& kernel);

  /// The \p id of the Object.
  unsigned long id;
  /// The weight (inverse variance) map in the region of this object.
  /// This map is employed when <tt>noisemodel==WEIGHT</tt>.
  Image<data_t> weight;
  /// The position of the object's centroid.
  Point<data_t> centroid;
  /// The detection flags.
  /// They indicates problems during the various procedures and are filled by a frameing class.
  /// Thus, look at Frame or SExFrame for the meaning of the individual bits.
  std::bitset<8> flags;
  /// The noise mean \f$\mu_n\f$.
  data_t noise_mean;
  /// The noise RMS \f$\sigma_n\f$.
  data_t noise_rms;
  /// The segmentation map.
  SegmentationMap segmentation;
  /// The correlation function.
  CorrelationFunction xi;
  /// The Fourier transform of the pixel data.
  FourierTransform2D fourier;
};
} // end namespace
#endif


text:
/**
 * @license Licensed under the Apache License, Version 2.0 (the "License"):
 *          http://www.apache.org/licenses/LICENSE-2.0
 */

/**
 * @fileoverview Blocks for Arduino Tone generation
 *     The Arduino function syntax can be found at
 *     https://www.arduino.cc/en/Reference/tone
 *
 */
'use strict';

goog.provide('Blockly.Blocks.tone');

goog.require('Blockly.Blocks');
goog.require('Blockly.Types');

/** Common HSV hue for all blocks in this category. */
Blockly.Blocks.tone.HUE = 250;

Blockly.Blocks['io_tone'] = {
  init: function() {
    this.appendDummyInput()
        .appendField(Blockly.Msg.ARD_SETTONE)
        .appendField(new Blockly.FieldDropdown(
            Blockly.Arduino.Boards.selected.digitalPins), "TONEPIN");
    this.appendValueInput("FREQUENCY")
        .setCheck(Blockly.Types.NUMBER.checkList)
        .appendField(Blockly.Msg.ARD_TONEFREQ);
    this.setInputsInline(true);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour(Blockly.Blocks.tone.HUE);
    this.setTooltip(Blockly.Msg.ARD_TONE_TIP);
    this.setHelpUrl('https://www.arduino.cc/en/Reference/tone');
  },
  /**
   * Called whenever anything on the workspace changes.
   * It checks frequency values and sets a warning if out of range.
   * @this Blockly.Block
   */
  onchange: function(event) {
    if (!this.workspace || event.type == Blockly.Events.MOVE ||
        event.type == Blockly.Events.UI) {
        return;  // Block deleted or irrelevant event
    }
    var freq = Blockly.Arduino.valueToCode(
        this, "FREQUENCY", Blockly.Arduino.ORDER_ATOMIC)
    if (freq < 31 || freq > 65535) {
      this.setWarningText(Blockly.Msg.ARD_TONE_WARNING, 'io_tone');
    } else {
      this.setWarningText(null, 'io_tone');
    }
  },
  /** @return {!string} The type of input value for the block, an integer. */
  getBlockType: function() {
    return Blockly.Types.NUMBER;
  }
};

Blockly.Blocks['io_notone'] = {
  init: function() {
    this.appendDummyInput()
        .appendField(Blockly.Msg.ARD_NOTONE)
        .appendField(new Blockly.FieldDropdown(
            Blockly.Arduino.Boards.selected.digitalPins), "TONEPIN");
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour(Blockly.Blocks.tone.HUE);
    this.setTooltip(Blockly.Msg.ARD_NOTONE_TIP);
    this.setHelpUrl('https://www.arduino.cc/en/Reference/noTone');
  },
    /** @return {!string} The type of input value for the block, an integer. */
  getBlockType: function() {
    return Blockly.Types.NUMBER;
  }
};


text:
<?php

namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP;

use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Config;

class SyntaxSniff implements Sniff
{

    /**
     * The path to the PHP version we are checking with.
     *
     * @var string
     */
    private $phpPath = null;

    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array
     */
    public function register()
    {
        return [T_OPEN_TAG];

    }//end register()

    /**
     * Processes this test, when one of its tokens is encountered.
     *
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
     * @param int                         $stackPtr  The position of the current token in
     *                                               the stack passed in $tokens.
     *
     * @return void
     */
    public function process(File $phpcsFile, $stackPtr)
    {
        if ($this->phpPath === null) {
            $this->phpPath = Config::getExecutablePath('php');
        }

        $fileName = escapeshellarg($phpcsFile->getFilename());
        $cmd      = escapeshellcmd($this->phpPath)." -l -d display_errors=1 -d error_prepend_string='' $fileName 2>&1";
        $output   = shell_exec($cmd);
        $matches  = [];
        if (preg_match('/^.*error:(.*) in .* on line ([0-9]+)/m', trim($output), $matches) === 1) {
            $error = trim($matches[1]);
            $line  = (int) $matches[2];
            $phpcsFile->addErrorOnLine("PHP syntax error: $error", $line, 'PHPSyntax');
        }

        // Ignore the rest of the file.
        return ($phpcsFile->numTokens + 1);

    }//end process()

}//end class


text:
import { Injectable } from '@angular/core';

@Injectable()
export class SnackbarService {
  showSnackbar(
    message: string,
    actionHandler?: () => void,
    actionText?: string
  ): void {
    document.querySelector('#menu-snackbar').MaterialSnackbar.showSnackbar({
      message,
      actionHandler,
      actionText
    });
  }
}


text:
<?php

/**
 * Doctrine_Configurable
 * the base for Doctrine_Table, Doctrine_Manager and Doctrine_Connection
 *
 * @package     Doctrine
 * @subpackage  Configurable
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.doctrine-project.org
 * @since       1.0
 * @version     $Revision: 7490 $
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 */
abstract class Doctrine_Configurable extends Doctrine_Locator_Injectable
{
    /**
     * @var array $attributes               an array of containing all attributes
     */
    protected $attributes = array();

    /**
     * @var Doctrine_Configurable $parent   the parent of this component
     */
    protected $parent;

    /**
     * @var array $_impl                    an array containing concrete implementations for class templates
     *                                      keys as template names and values as names of the concrete
     *                                      implementation classes
     */
    protected $_impl = array();

    /**
     * @var array $_params                  an array of user defined parameters
     */
    protected $_params = array();

    /**
     * setAttribute
     * sets a given attribute
     *
     * <code>
     * $manager->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_ALL);
     * </code>
     *
     * @param mixed $attribute              either a Doctrine_Core::ATTR_* integer constant or a string
     *                                      corresponding to a constant
     * @param mixed $value                  the value of the attribute
     * @see Doctrine_Core::ATTR_* constants
     * @throws Doctrine_Exception           if the value is invalid
     * @return void
     */
    public function setAttribute($attribute, $value)
    {
        switch ($attribute) {
            case Doctrine_Core::ATTR_LISTENER:
                $this->setEventListener($value);
                break;
            case Doctrine_Core::ATTR_COLL_KEY:
                if ( ! ($this instanceof Doctrine_Table)) {
                    throw new Doctrine_Exception("This attribute can only be set at table level.");
                }
                if ($value !== null && ! $this->hasField($value)) {
                    throw new Doctrine_Exception("Couldn't set collection key attribute. No such field '$value'.");
                }
                break;
            case Doctrine_Core::ATTR_CACHE:
            case Doctrine_Core::ATTR_RESULT_CACHE:
            case Doctrine_Core::ATTR_QUERY_CACHE:
                if ($value !== null) {
                    if ( ! ($value instanceof Doctrine_Cache_Interface)) {
                        throw new Doctrine_Exception('Cache driver should implement Doctrine_Cache_Interface');
                    }
                }
                break;
            case Doctrine_Core::ATTR_SEQCOL_NAME:
                if ( ! is_string($value)) {
                    throw new Doctrine_Exception('Sequence column name attribute only accepts string values');
                }
                break;
            case Doctrine_Core::ATTR_FIELD_CASE:
                if ($value != 0 && $value != CASE_LOWER && $value != CASE_UPPER)
                    throw new Doctrine_Exception('Field case attribute should be either 0, CASE_LOWER or CASE_UPPER constant.');
                break;
            case Doctrine_Core::ATTR_SEQNAME_FORMAT:
            case Doctrine_Core::ATTR_IDXNAME_FORMAT:
            case Doctrine_Core::ATTR_TBLNAME_FORMAT:
            case Doctrine_Core::ATTR_FKNAME_FORMAT:
                if ($this instanceof Doctrine_Table) {
                    throw new Doctrine_Exception('Sequence / index name format attributes cannot be set'
                                               . 'at table level (only at connection or global level).');
                }
                break;
        }

        $this->attributes[$attribute] = $value;
    }

    public function getParams($namespace = null)
    {
    	if ($namespace == null) {
    	    $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE);
    	}

    	if ( ! isset($this->_params[$namespace])) {
    	    return null;
    	}

        return $this->_params[$namespace];
    }

    public function getParamNamespaces()
    {
        return array_keys($this->_params);
    }

    public function setParam($name, $value, $namespace = null)
    {
    	if ($namespace == null) {
    	    $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE);
    	}

    	$this->_params[$namespace][$name] = $value;

    	return $this;
    }

    public function getParam($name, $namespace = null)
    {
    	if ($namespace == null) {
    	    $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE);
    	}

        if ( ! isset($this->_params[$namespace][$name])) {
            if (isset($this->parent)) {
                return $this->parent->getParam($name, $namespace);
            }
            return null;
        }

        return $this->_params[$namespace][$name];
    }

    /**
     * setImpl
     * binds given class to given template name
     *
     * this method is the base of Doctrine dependency injection
     *
     * @param string $template      name of the class template
     * @param string $class         name of the class to be bound
     * @return Doctrine_Configurable    this object
     */
    public function setImpl($template, $class)
    {
        $this->_impl[$template] = $class;

        return $this;
    }

    /**
     * getImpl
     * returns the implementation for given class
     *
     * @return string   name of the concrete implementation
     */
    public function getImpl($template)
    {
        if ( ! isset($this->_impl[$template])) {
            if (isset($this->parent)) {
                return $this->parent->getImpl($template);
            }
            return null;
        }
        return $this->_impl[$template];
    }

    public function hasImpl($template)
    {
        if ( ! isset($this->_impl[$template])) {
            if (isset($this->parent)) {
                return $this->parent->hasImpl($template);
            }
            return false;
        }
        return true;
    }

    /**
     * @param Doctrine_EventListener $listener
     * @return void
     */
    public function setEventListener($listener)
    {
        return $this->setListener($listener);
    }

    /**
     * addRecordListener
     *
     * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener
     * @return Doctrine_Configurable        this object
     */
    public function addRecordListener($listener, $name = null)
    {
        if ( ! isset($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER]) ||
             ! ($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER] instanceof Doctrine_Record_Listener_Chain)) {

            $this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER] = new Doctrine_Record_Listener_Chain();
        }
        $this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER]->add($listener, $name);

        return $this;
    }

    /**
     * getListener
     *
     * @return Doctrine_EventListener_Interface|Doctrine_Overloadable
     */
    public function getRecordListener()
    {
        if ( ! isset($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER])) {
            if (isset($this->parent)) {
                return $this->parent->getRecordListener();
            }
            return null;
        }
        return $this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER];
    }

    /**
     * setListener
     *
     * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener
     * @return Doctrine_Configurable        this object
     */
    public function setRecordListener($listener)
    {
        if ( ! ($listener instanceof Doctrine_Record_Listener_Interface)
            && ! ($listener instanceof Doctrine_Overloadable)
        ) {
            throw new Doctrine_Exception("Couldn't set eventlistener. Record listeners should implement either Doctrine_Record_Listener_Interface or Doctrine_Overloadable");
        }
        $this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER] = $listener;

        return $this;
    }

    /**
     * addListener
     *
     * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener
     * @return Doctrine_Configurable    this object
     */
    public function addListener($listener, $name = null)
    {
        if ( ! isset($this->attributes[Doctrine_Core::ATTR_LISTENER]) ||
             ! ($this->attributes[Doctrine_Core::ATTR_LISTENER] instanceof Doctrine_EventListener_Chain)) {

            $this->attributes[Doctrine_Core::ATTR_LISTENER] = new Doctrine_EventListener_Chain();
        }
        $this->attributes[Doctrine_Core::ATTR_LISTENER]->add($listener, $name);

        return $this;
    }

    /**
     * getListener
     *
     * @return Doctrine_EventListener_Interface|Doctrine_Overloadable
     */
    public function getListener()
    {
        if ( ! isset($this->attributes[Doctrine_Core::ATTR_LISTENER])) {
            if (isset($this->parent)) {
                return $this->parent->getListener();
            }
            return null;
        }
        return $this->attributes[Doctrine_Core::ATTR_LISTENER];
    }

    /**
     * setListener
     *
     * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener
     * @return Doctrine_Configurable        this object
     */
    public function setListener($listener)
    {
        if ( ! ($listener instanceof Doctrine_EventListener_Interface)
            && ! ($listener instanceof Doctrine_Overloadable)
        ) {
            throw new Doctrine_EventListener_Exception("Couldn't set eventlistener. EventListeners should implement either Doctrine_EventListener_Interface or Doctrine_Overloadable");
        }
        $this->attributes[Doctrine_Core::ATTR_LISTENER] = $listener;

        return $this;
    }

    /**
     * returns the value of an attribute
     *
     * @param integer $attribute
     * @return mixed
     */
    public function getAttribute($attribute)
    {
        if (isset($this->attributes[$attribute])) {
            return $this->attributes[$attribute];
        }

        if (isset($this->parent)) {
            return $this->parent->getAttribute($attribute);
        }
        return null;
    }

    /**
     * Unset an attribute from this levels attributes
     *
     * @param integer $attribute
     * @return void
     */
    public function unsetAttribute($attribute)
    {
        if (isset($this->attributes[$attribute])) {
            unset($this->attributes[$attribute]);
        }
    }

    /**
     * getAttributes
     * returns all attributes as an array
     *
     * @return array
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

    /**
     * Set the charset
     *
     * @param string $charset
     */
    public function setCharset($charset)
    {
        $this->setAttribute(Doctrine_Core::ATTR_DEFAULT_TABLE_CHARSET, $charset);
    }

    /**
     * Get the charset
     *
     * @return mixed
     */
    public function getCharset()
    {
        return $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_TABLE_CHARSET);
    }

    /**
     * Set the collate
     *
     * @param string $collate
     */
    public function setCollate($collate)
    {
        $this->setAttribute(Doctrine_Core::ATTR_DEFAULT_TABLE_COLLATE, $collate);
    }

    /**
     * Get the collate
     *
     * @return mixed $collate
     */
    public function getCollate()
    {
        return $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_TABLE_COLLATE);
    }

    /**
     * sets a parent for this configurable component
     * the parent must be configurable component itself
     *
     * @param Doctrine_Configurable $component
     * @return void
     */
    public function setParent(Doctrine_Configurable $component)
    {
        $this->parent = $component;
    }

    /**
     * getParent
     * returns the parent of this component
     *
     * @return Doctrine_Configurable
     */
    public function getParent()
    {
        return $this->parent;
    }
}


text:
using Xunit;
using Shouldly;

namespace AutoMapper.UnitTests.Projection
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using AutoMapper;
    using QueryableExtensions;

    public class ProjectWithFields : AutoMapperSpecBase
    {
        public class Foo
        {
            public int A;
        }

        public class FooDto
        {
            public int A;
        }

        protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<Foo, FooDto>();
        });

        [Fact]
        public void Should_work()
        {
            new[] { new Foo() }.AsQueryable().ProjectTo<FooDto>(Configuration).Single().A.ShouldBe(0);
        }
    }

    public class ProjectTest
    {
        private MapperConfiguration _config;

        public ProjectTest()
        {
            _config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Address, AddressDto>();
                cfg.CreateMap<Customer, CustomerDto>();
            });
        }

        [Fact]
        public void ProjectToWithUnmappedTypeShouldThrowException()
        {
            var customers =
                new[] { new Customer { FirstName = "Bill", LastName = "White", Address = new Address("Street1") } }
                    .AsQueryable();

            IList<Unmapped> projected = null;

            typeof(InvalidOperationException).ShouldBeThrownBy(() => projected = customers.ProjectTo<Unmapped>(_config).ToList());

            projected.ShouldBeNull();
        }

        [Fact]
        public void DynamicProjectToShouldWork()
        {
            var customers =
                new[] { new Customer { FirstName = "Bill", LastName = "White", Address = new Address("Street1") } }
                    .AsQueryable();

            IQueryable projected = customers.ProjectTo(typeof(CustomerDto), _config);

            projected.Cast<CustomerDto>().Single().FirstName.ShouldBe("Bill");
        }

        public class Customer
        {
            public string FirstName { get; set; }

            public string LastName { get; set; }

            public Address Address { get; set; }
        }

        public class Address
        {
            public Address(string street)
            {
                Street = street;
            }

            public string Street { get; set; }
        }

        public class CustomerDto
        {
            public string FirstName { get; set; }

            public AddressDto Address { get; set; }
        }

        public class AddressDto
        {
            public string Street { get; set; }
        }

        public class Unmapped
        {
            public string FirstName { get; set; }
        }
    }
}


text:
DROP TABLE IF EXISTS system_user_schema.system_users_history;

CREATE TABLE system_user_schema.system_users_history (
	sysuser_id	uuid NOT NULL,
	login	text NOT NULL,
	password_changed	text NOT NULL,
	firstname	text NOT NULL,
	lastname	text NOT NULL,
	datetime_user_change_started	timestamp without time zone NOT NULL,
	datetime_user_change_ended	timestamp without time zone NOT NULL,
	changing_user_login	text NOT NULL,
	change_type	text NOT NULL -- the change_type will be either update or delete
);


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>Comments for page "Shorty Lvl. 2"</title>
		<link>http://bvs.wikidot.com/forum/t-54729/shorty-lvl-2</link>
		<description>Posts in the discussion thread "Shorty Lvl. 2"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 03:35:21 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-54729#post-919343</guid>
				<title>Shorty lvl 2's Jutsu</title>
				<link>http://bvs.wikidot.com/forum/t-54729/shorty-lvl-2#post-919343</link>
				<description></description>
				<pubDate>Mon, 08 Nov 2010 19:50:54 +0000</pubDate>
				<wikidot:authorName>tressert</wikidot:authorName>				<wikidot:authorUserId>206985</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

Shorty lvl 2 cannot teach "kido: iron maiden" "Kido: slayer" or "kido:metalacolypse" as thee jutsu are required to be learned in order to obtain her.

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>