text:
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <ctime>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
#include <Eigen/Dense>

using Eigen::MatrixXd;
using Eigen::VectorXd;
using namespace std;

const int MATCH_MIN = 0;
const int MATCH_MAX = 1;

/*
 * readMatrix
 * read a file into a matrix object
 * file must have matrix dimension as first line
 * matrix must be square
 */
void readMatrix(const char* filename, MatrixXd& m) {
  ifstream fin(filename);

  if (!fin) {
    cout << "Cannot open file." << endl;
    return;
  }

  // read in matrix dimensions and
  // create a matrix of that size
  int n_rows, n_cols;
  fin >> n_rows >> n_cols;
  MatrixXd temp(n_rows, n_cols);

  // read elements into the temporary matrix
  for (int i=0; i<n_rows; i++) {
    for (int j=0; j<n_cols; j++) {
      fin >> temp(i,j);
    }
  }
  fin.close();

  // if the dimensions are equal (square matrix), we're done
  // else, have to figure out larger dimension and pad with matrix max
  if (n_rows == n_cols) {
    m = temp;
  }
  else {
    float max_elem = temp.maxCoeff(); // find the max element
    float dim = max(n_rows, n_cols); // find the dimension for the new, square matrix
    m.resize(dim,dim);
    // fill the matrix with the elements from temp and pad with max element
    for (int i=0; i < dim; i++) {
      for (int j=0; j < dim; j++) {
        if (i >= n_rows || j >= n_cols) m(i,j) = max_elem;
        else m(i,j) = temp(i,j);
      }
    }
  }
}

/*
 * reduce
 * reduces matrix based on row and column minimums
 */
void reduce(MatrixXd& m) {
  // subtract row minimum from each row
  for (int i=0; i<m.rows(); i++) {
    float minElement = m.row(i).minCoeff();
    VectorXd rMinusMin(m.rows());
    rMinusMin.fill(-minElement);
    m.row(i) += rMinusMin;
  }
}

/*
 * hasMark
 * if there is a starred/primed zero in the given row/col, returns it's index
 * else, returns -1
 */
int hasMark(VectorXd& v) {
  for (int i=0; i<v.size(); i++) {
    if (v(i)) {
      return i;
    }
  }
  return -1;
}

/*
 * swapStarsAndPrimes
 * Swap stars and primes based on step 5 of Hungarian algorithm
 * Z0 is uncovered primed zero we've found
 * Z1 is the stared zero in the column of Z0 (if any)
 * Z2 is the primed zero in the row of Z1 (will always be one)
 * ...continue series until we reach a primed zero with no starred zero in its column
 * Unstar each starred zero, star each primed zero, erase all primes and uncover every line in the matrix
 */
void swapStarsAndPrimes(int i, int j, MatrixXd& stars, MatrixXd& primes) {
  int primeRow = i;
  int primeCol = j;

  bool done = false;
  while (!done) {
    // find row index of row that has a 0* in the same col as the current 0'
    VectorXd col = stars.col(primeCol);
    int starInPrimeColRow = hasMark(col);

    if (starInPrimeColRow < 0) {
      // star the prime we're looking at
      primes(primeRow, primeCol) = 0;
      stars(primeRow, primeCol) = 1;
      done = true;
    }
    else {
      // find which col has a 0' in the same row as z1
      VectorXd row = primes.row(starInPrimeColRow);
      int primeInStarRowCol = hasMark(row);

      // star first primed zero
      primes(primeRow, primeCol) = 0;
      stars(primeRow, primeCol) = 1;
      //primes(starInPrimeColRow, primeInStarRowCol) = 0;
      //stars(starInPrimeColRow, primeInStarRowCol) = 1;

      // unstar starred zero
      stars(starInPrimeColRow, primeCol) = 0;

      // set index of last prime, will check it's column for 0*s next
      primeRow = starInPrimeColRow;
      primeCol = primeInStarRowCol;
    }
  }
  // clear primes
  primes.fill(0);
}

/*
 * findMatching
 * implementation of the Hungarian matching algorithm
 * referenced from: http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html
 */
void findMatching(MatrixXd& m, MatrixXd& result, int type) {
  MatrixXd n = m; // make a copy of m for reducing
  int dim = n.rows(); // dimension of matrix, used for checking if we've reduced
                      // the matrix enough yet

  MatrixXd stars(m.rows(), m.cols()); // matrix for storing our "starred" 0s (0*)
  stars.fill(0);
  MatrixXd primes(m.rows(), m.cols()); // matrix for storing our "primed" 0s (0')
  primes.fill(0);
  VectorXd rowCover(m.rows()); // keep track of which rows are "covered"
  rowCover.fill(0);
  VectorXd colCover(m.cols()); // keep track of which columns are "covered"
  colCover.fill(0);

  // to do maximization rather than minimization, we have to
  // transform the matrix by subtracting every value from the maximum
  if (type == MATCH_MAX) {
    float max = n.maxCoeff();
    MatrixXd maxMat(n.rows(), n.cols());
    maxMat.fill(max);
    n = maxMat - n;
  }

  // Step 1
  // Reduce matrix
  reduce(n);

  // Step 2
  // Find a zero in the matrix. If there is no starred zero in
  // its row or column, star Z. Repeat for each element in the matrix.
  for (int i=0; i<n.rows(); i++) {
    for (int j=0; j<n.cols(); j++) {
      if (n(i,j) == 0 && !rowCover(i) && !colCover(j)) {
        stars(i,j) = 1;
        rowCover(i) = 1;
        colCover(j) = 1;
      }
    }
  }
  // covers need to be cleared for following steps
  rowCover.fill(0);
  colCover.fill(0);

  while (true) {
    // Step 3
    // Cover all columns that have a starred zero
    // If the number of columns with starred zeroes equals the matrix
    // dimensions, we are done! Otherwise, move on to step 4.
    step3:
    for (int j=0; j<n.cols(); j++) {
      VectorXd col = stars.col(j);
      if (hasMark(col) >= 0) {
        colCover(j) = 1;
      }
    }
    if (colCover.sum() == dim) {
      result = stars;
      return;
    }

    // Step 4
    // Find a non-covered zero and prime it
    step4:
    for (int i=0; i<n.rows(); i++) {
      for (int j=0; j<n.cols(); j++) {
        if (n(i,j) == 0 && !rowCover(i) && !colCover(j)) {
          primes(i,j) = 1;
          // if no starred zero in the row...
          VectorXd row = stars.row(i);
          if (hasMark(row) < 0) {
            // Step 5
            // swap stars and primes
            swapStarsAndPrimes(i, j, stars, primes);

            // clear lines
            rowCover.fill(0);
            colCover.fill(0);

            goto step3;
          }
          else {
            // cover row
            rowCover(i) = 1;

            // uncover column of the starred zero in the same row
            int col = hasMark(row);
            colCover(col) = 0;
          }
        }
      }
    }

    // Step 6
    // Should now be no more uncovered zeroes
    // Get the minimum uncovered element
    float min = 1000000;
    for (int i=0; i<n.rows(); i++) {
      for (int j=0; j<n.cols(); j++) {
        if (!rowCover(i) && !colCover(j) && n(i,j) < min) {
          min = n(i,j);
        }
      }
    }

    // Subtract minimum from uncovered elements, add it to elements covered twice
    for (int i=0; i<n.rows(); i++) {
      for (int j=0; j<n.cols(); j++) {
        if (!rowCover(i) && !colCover(j)) {
          n(i,j) -= min;
        }
        else if (rowCover(i) && colCover(j)) {
          n(i,j) += min;
        }
      }
    }

    goto step4;
  }
}

/*
 * main()
 */
int main(int argc, char *argv[])
{
  if (argc != 2) {
    cout << "Usage: ./a.out [matrixfile]" << endl;
    return 0;
  }

  // times
	clock_t start, end;
  float elapsedTime;

  // random seed
  srand((unsigned)time(0));

	// start time
  start = clock();

  // read in the matrix file
  MatrixXd m(1,1);
  readMatrix(argv[1], m);

  // create an empty matrix to put the result in
  MatrixXd result(m.rows(), m.cols());
  result.fill(0);

  // run the Hungarian (Munkres) algorithm to find the maximal matching
  findMatching(m, result, MATCH_MIN);

  MatrixXd mask = m.cwiseProduct(result);
  int sum = mask.sum();

  cout << "ORIGINAL MATRIX" << endl;
  cout << m << endl;
  cout << endl;
  cout << "ASSIGNMENT RESULT" << endl;
  cout << result << endl;
  cout << endl;
  cout << "FINAL SUM" << endl;
  cout << sum << endl;

  // stop time
  end = clock();
	elapsedTime = (float)(end - start) / CLOCKS_PER_SEC;
  cout << "Completed in: " << elapsedTime << " s" << endl;

  return 0;
}

max_stars_repo_name: emstresh/HungarianAlgorithm

max_issues_repo_name: emstresh/HungarianAlgorithm

max_forks_repo_name: emstresh/HungarianAlgorithm


text:
// Copyright (c) 2011 by BBNT Solutions LLC
// All Rights Reserved.

#include "Generic/common/leak_detection.h" // This must be the first #include
#include "Generic/common/SessionLogger.h"

#include "ProfileGenerator/TeaserBiography.h"
#include "ProfileGenerator/Profile.h"
#include "ProfileGenerator/ProfileSlot.h"
#include "ProfileGenerator/EmploymentHypothesis.h"
#include "ProfileGenerator/NameHypothesis.h"

#include "boost/foreach.hpp"
#include <boost/algorithm/string.hpp>
#include <list>
#include <iostream>

TeaserBiography::TeaserBiography(Profile_ptr profile) {

	_biography = L"";
	_profile = profile;
	_name_hypothesis = profile->getProfileNameHypothesis();
	_bio_mentions = 0;
	if (profile->getProfileType() == Profile::PER) {
		_biography += getLeadPersonSentence(profile);
		_biography += getFamilySentence(profile);
		_biography += getEducationSentence(profile);
		_biography += getDescriptionSentence(profile);
	} else if (profile->getProfileType() == Profile::ORG) {
		_biography += getLeadOrganizationSentence(profile);
		_biography += getDescriptionSentence(profile);
	} else if (profile->getProfileType() == Profile::GPE) {
		// TODO
	}

}
std::wstring TeaserBiography::repeatReference(NameHypothesis::PronounRole role, bool capitalize){
	std::wstring ref = _name_hypothesis->getRepeatReference(_bio_mentions, role);
	if (ref != L"" && capitalize)
		ref.at(0) = towupper(ref.at(0));
	return ref;
}

std::wstring TeaserBiography::getLeadPersonSentence(Profile_ptr profile) {

	std::wstring birth_clause = getDateDisplayValue(profile->getExistingSlot(ProfileSlot::BIRTHDATE_UNIQUE_ID));
	std::wstring death_clause = getDateDisplayValue(profile->getExistingSlot(ProfileSlot::DEATHDATE_UNIQUE_ID));
	std::wstring nationality = L"";
	std::wstring job_title = L"";
	std::wstring employer = L"";
	ProfileSlot_ptr nat_slot = profile->getExistingSlot(ProfileSlot::NATIONALITY_UNIQUE_ID);
	if (nat_slot != ProfileSlot_ptr() && nat_slot->getOutputHypotheses().size() != 0)
		nationality = nat_slot->getOutputHypotheses().front()->getDisplayValue();
	ProfileSlot_ptr employer_slot = profile->getExistingSlot(ProfileSlot::EMPLOYER_UNIQUE_ID);
	EmploymentHypothesis::status_tense_t employment_tense;
	if (employer_slot != ProfileSlot_ptr() && employer_slot->getOutputHypotheses().size() != 0) {
		EmploymentHypothesis_ptr empHypoth = boost::dynamic_pointer_cast<EmploymentHypothesis>(employer_slot->getOutputHypotheses().front());
		if (empHypoth->getNamedArgument() != NameHypothesis_ptr()) {
			employer = empHypoth->getNamedArgument()->getDisplayValue();
			job_title = empHypoth->getJobTitle();
			if (job_title == L"ceo" || job_title == L"cio" || job_title == L"coo" || job_title == L"cto" || job_title == L"mp")
				std::transform(job_title.begin(), job_title.end(), job_title.begin(), towupper);
			employment_tense = empHypoth->getTense(true); // temporarily print debug info
		}
	}

	if (nationality == L"" && employer == L"") {
		std::wstring ref = repeatReference(NameHypothesis::SUBJECT, true);
		if (birth_clause != L"" && death_clause != L"") {
			return ref + L" was born " + birth_clause + L" and died " + death_clause + L". ";
		} else if (birth_clause != L"") {
			return ref + L" was born " + birth_clause + L". ";
		} else if (death_clause != L"") {
			return ref + L" died " + death_clause + L". ";
		}
		_bio_mentions--; // we didn't use this references, so decrement the counter
		return L"";
	}

	bool is_alive = (death_clause == L"");
	bool dangling = false;

	std::wstring ret_value = L"";
	if (birth_clause != L"") {
		// We know there is either a nationality or employer coming, since they aren't both null
		ret_value += L"Born " + birth_clause + L", " + repeatReference(NameHypothesis::SUBJECT, false);
		dangling = true;
	}

	if (nationality != L"") {
		if (employer == L"") {
			// All we have is nationality and possibly death, so fix up the sentence and return.
			if (!dangling) {
				ret_value = repeatReference(NameHypothesis::SUBJECT, true);
				dangling = true;
			}
			if (death_clause != L"")
				ret_value += L" was a citizen of " + nationality + L" who died " + death_clause + L". ";
			else ret_value += L" is a citizen of " + nationality + L". ";
			dangling = false; // not that it matters
			return ret_value;
		} else if (nationality != employer) {
			// We know we have employment coming, so mention nationality and continue
			if (!dangling) {
				ret_value += L"A citizen of " + nationality + L", " + repeatReference(NameHypothesis::SUBJECT, false);
				dangling = true;
			} else {
				if (is_alive)
					ret_value += L" is";
				else ret_value += L" was";
				ret_value += L" a citizen of " + nationality + L" and ";
				dangling = true;
			}
		}
	}

	// We know we have an employer, otherwise we would have returned above
	if (!dangling){
		ret_value += repeatReference(NameHypothesis::SUBJECT, true);
		dangling = true;
	}

	if (job_title != L"") {
		if (!is_alive || employment_tense == EmploymentHypothesis::PAST)
			ret_value += L" was ";
		else if (employment_tense == EmploymentHypothesis::FUTURE)
			ret_value += L" is reportedly the future ";
		else
			ret_value += L" is ";
		ret_value += getJobTitleArticle(job_title) + L" " + job_title + L" of " + modifyEmployerName(employer);
	} else {
		if (!is_alive || employment_tense == EmploymentHypothesis::PAST)
			ret_value += L" used to work for ";
		else if (employment_tense == EmploymentHypothesis::FUTURE)
			ret_value += L" reportedly will work for ";
		else
			ret_value += L" works for ";
		ret_value += modifyEmployerName(employer);
	}
	ret_value += L". ";

	if (death_clause != L"") {
		ret_value += repeatReference(NameHypothesis::SUBJECT, true) + L" died " + death_clause + L". ";
	}

	return ret_value;
}

std::wstring TeaserBiography::modifyEmployerName(std::wstring employer) {
	// TODO_IDEA: case?
	if (employer == L"United States" || employer == L"Senate" || employer == L"House of Representatives" ||
		employer == L"House" ||
		employer == L"United Kingdom" || employer == L"United Nations")
		return L"the " + employer;
	if (employer == L"UN")
		return L"the United Nations";
	if (employer == L"State")
		return L"the State Department";
	if (employer == L"Defense")
		return L"the Defense Department";
	return employer;
}

bool TeaserBiography::isSingularJobTitle(std::wstring title) {
	if (title == L"president" || title == L"vice president" || title == L"chancellor" || title == L"leader" || title == L"ceo" ||
		title == L"chairman" || title == L"head" || title == L"premier" || title == L"dictator" || title == L"treasurer" ||
		title == L"governor" || title == L"mayor" || title == L"coo" || title == L"chairwoman" || title == L"chairperson" ||
		title == L"chair" || title == L"co-chair" || title == L"founder" || title == L"provost" || title == L"chancellor" ||
		title == L"dean" || title == L"speaker" || title == L"commissioner" || title == L"commissar" || title == L"commander in chief" ||
		title == L"cio" || title == L"cto" ||
		title == L"CEO" || title == L"CIO" || title == L"COO" || title == L"CTO" || title == L"MP")
		return true;

	if (title.find(L"minister") != std::wstring::npos ||
		title.find(L"president") != std::wstring::npos ||
		title.find(L"executive") != std::wstring::npos ||
		title.find(L"director") != std::wstring::npos ||
		title.find(L"head") != std::wstring::npos ||
		title.find(L"chief") != std::wstring::npos ||
		title.find(L"general") != std::wstring::npos ||
		title.find(L"co-") != std::wstring::npos ||
		title.find(L"vice") != std::wstring::npos ||
		title.find(L"deputy") != std::wstring::npos)
		return true;

	return false;
}

std::wstring TeaserBiography::getJobTitleArticle(std::wstring title) {
	if (isSingularJobTitle(title))
		return L"the";

	if (title.at(0) == L'a' || title.at(0) == L'e' || title.at(0) == L'i' || title.at(0) == L'o' || title.at(0) == L'u')
		return L"an";

	if (title == L"mp")
		return L"an";

	return L"a";
}

std::wstring TeaserBiography::getFamilySentence(Profile_ptr profile) {
	std::wstring spouse_list = getPrintableList(profile->getExistingSlot(ProfileSlot::SPOUSE_UNIQUE_ID), 1, false);
	std::wstring family_list = getPrintableList(profile->getExistingSlot(ProfileSlot::FAMILY_UNIQUE_ID), 3, false);
	std::wstring death_date = getDateDisplayValue(profile->getExistingSlot(ProfileSlot::DEATHDATE_UNIQUE_ID));
	bool is_alive = death_date == L"";
	std::wstring to_be_tensed = is_alive ? L" is " : L" was ";
	if (spouse_list == L"" && family_list == L"") {
		return L"";
	} else if (spouse_list == L"") {
		return L"Family members include " + family_list + L". ";
	} else if (family_list == L"") {
		return repeatReference(NameHypothesis::SUBJECT, true) + to_be_tensed + L"married to " + spouse_list + L". ";
	} else {
		return repeatReference(NameHypothesis::SUBJECT, true) + to_be_tensed + L"married to " + spouse_list + L"; other family members include " + family_list + L". ";
	}
	return L"";
}

std::wstring TeaserBiography::getEducationSentence(Profile_ptr profile) {
	std::wstring schools = getPrintableList(profile->getExistingSlot(ProfileSlot::EDUCATION_UNIQUE_ID), 3, false);
	if (schools != L"")
		return repeatReference(NameHypothesis::SUBJECT, true) + L" was educated at " + schools + L". ";
	else return L"";
}

std::wstring TeaserBiography::getLeadOrganizationSentence(Profile_ptr profile) {
	std::wstring hq = getPrintableList(profile->getExistingSlot(ProfileSlot::HEADQUARTERS_UNIQUE_ID), 3, false);
	std::wstring founder = getPrintableList(profile->getExistingSlot(ProfileSlot::FOUNDER_UNIQUE_ID), 1, false);
	std::wstring founding_date = getDateDisplayValue(profile->getExistingSlot(ProfileSlot::FOUNDINGDATE_UNIQUE_ID));

	// Separate out former and current leaders
	std::list<GenericHypothesis_ptr> leader_hypotheses;
	std::list<GenericHypothesis_ptr> former_leader_hypotheses;
	ProfileSlot_ptr leaders_slot = profile->getExistingSlot(ProfileSlot::LEADER_UNIQUE_ID);
	if (leaders_slot != ProfileSlot_ptr()) {
		BOOST_FOREACH(GenericHypothesis_ptr hypoth, leaders_slot->getOutputHypotheses()) {
			EmploymentHypothesis::status_tense_t tense = getEmploymentTense(hypoth);
			if (tense == EmploymentHypothesis::CURRENT)
				leader_hypotheses.push_back(hypoth);
			else if (tense == EmploymentHypothesis::PAST)
				former_leader_hypotheses.push_back(hypoth);
		}
	}
	std::wstring leader_list = getPrintableList(leader_hypotheses, 2, true, false);
	std::wstring former_leader_list = getPrintableList(former_leader_hypotheses, 2, true, false);
	boost::replace_all(former_leader_list, L")", L"");
	boost::replace_all(former_leader_list, L"(", L"");

	// Separate out former and current employees
	std::list<GenericHypothesis_ptr> employee_hypotheses;
	std::list<GenericHypothesis_ptr> former_employee_hypotheses;
	ProfileSlot_ptr employees_slot = profile->getExistingSlot(ProfileSlot::EMPLOYEE_UNIQUE_ID);
	if (employees_slot != ProfileSlot_ptr()) {
		BOOST_FOREACH(GenericHypothesis_ptr hypoth, employees_slot->getOutputHypotheses()) {
			EmploymentHypothesis::status_tense_t tense = getEmploymentTense(hypoth);
			if (tense == EmploymentHypothesis::CURRENT)
				employee_hypotheses.push_back(hypoth);
			else if (tense == EmploymentHypothesis::PAST)
				former_employee_hypotheses.push_back(hypoth);
		}
	}
	std::wstring employee_list = getPrintableList(employee_hypotheses, 5, false, false);
	std::wstring former_employee_list = getPrintableList(former_employee_hypotheses, 3, false, false);

	std::wstring ret_value = L"";

	ProfileSlot_ptr employeeSlot = profile->getExistingSlot(ProfileSlot::EMPLOYEE_UNIQUE_ID);
	int n_employees = 0;
	if (employeeSlot != ProfileSlot_ptr())
		n_employees = static_cast<int>(employeeSlot->getOutputHypotheses().size());

	if (leader_list == L"" && former_leader_list == L"" && employee_list == L"")
		return getSimpleFoundingHQSentence(founder, founding_date, hq);

	bool has_preceding_clause = true;
	if (founder != L"" && founding_date != L"")
		ret_value += L"Founded by " + founder + L" " + founding_date + L", ";
	else if (founder != L"")
		ret_value += L"Founded by " + founder + L", ";
	else if (founding_date != L"")
		ret_value += L"Founded " + founding_date + L", ";
	else has_preceding_clause = false;

	// Just do leaders if we have some
	if (leader_list != L"") {
		ret_value += repeatReference(NameHypothesis::SUBJECT, !has_preceding_clause) + L" is led by " + leader_list + L". ";
		if (former_leader_list != L"")
			ret_value += L"(Former leaders include " + former_leader_list + L".) ";
	} else if (former_leader_list != L"") {
		ret_value += repeatReference(NameHypothesis::SUBJECT, !has_preceding_clause) + L" has been led by " + former_leader_list + L". ";
	} else if (employee_list != L"") {
		ret_value += repeatReference(NameHypothesis::POSSESSIVE_MOD, !has_preceding_clause) + L" employees/members include " + employee_list + L". ";
		if (former_employee_list != L"")
			ret_value += L"(Additional former employees/members: " + former_employee_list + L".) ";
	}

	if (hq != L"")
		ret_value += repeatReference(NameHypothesis::SUBJECT, true) + L" has headquarters in " + hq + L". ";

	return ret_value;
}

std::wstring TeaserBiography::getSimpleFoundingHQSentence(std::wstring founder, std::wstring founding_date, std::wstring hq) {
	std::wstring founding_sentence = L"";
	if (founder != L"" && founding_date != L"")
		founding_sentence = repeatReference(NameHypothesis::SUBJECT, true) + L" was founded by " + founder + L" " + founding_date ;
	else if (founder != L"")
		founding_sentence = repeatReference(NameHypothesis::SUBJECT, true) + L" was founded by " + founder;
	else if (founding_date != L"")
		founding_sentence = repeatReference(NameHypothesis::SUBJECT, true) + L" was founded " + founding_date;

	if (hq != L"") {
		if (founding_sentence != L"")
			return founding_sentence + L" and has headquarters in " + hq + L". ";
		else return repeatReference(NameHypothesis::SUBJECT, true) + L" has headquarters in " + hq + L". ";
	} else if (founding_sentence != L"") {
		return founding_sentence + L". ";
	}

	return L"";
}

std::wstring TeaserBiography::getDescriptionSentence(Profile_ptr profile) {
	ProfileSlot_ptr slot = profile->getExistingSlot(ProfileSlot::DESCRIPTION_UNIQUE_ID);
	if (slot == ProfileSlot_ptr())
		return L"";
	std::list<GenericHypothesis_ptr> hypotheses;
	BOOST_FOREACH(GenericHypothesis_ptr hypoth, slot->getOutputHypotheses()) {
		if (hypoth->getDisplayValue().size() <= 100)
			hypotheses.push_back(hypoth);
	}
	std::wstring descriptions = getPrintableList(hypotheses, 4, false, true);
	if (descriptions != L"") {
		descriptions = profile->stripOfResolutionsToThisActor(descriptions);
		return repeatReference(NameHypothesis::SUBJECT, true) + L" has been described as " + descriptions + L". ";
	}
	else return L"";
}

std::wstring TeaserBiography::getPrintableList(ProfileSlot_ptr slot, int max_to_print, bool include_titles) {
	if (slot == ProfileSlot_ptr())
		return L"";
	return getPrintableList(slot->getOutputHypotheses(), max_to_print, include_titles, false);
}

std::wstring TeaserBiography::getPrintableList(std::list<GenericHypothesis_ptr>& hypotheses, int max_to_print, bool include_titles, bool is_description) {

	if (hypotheses.size() == 0 || max_to_print == 0) {
		return L"";
	} else if (hypotheses.size() == 1 || max_to_print == 1) {
		return getDisplayValue(hypotheses.front(), include_titles, is_description);
	} else if (hypotheses.size() == 2  || max_to_print == 2) {
		std::wstring ret_value = L"";
		int counter = 0;
		for (std::list<GenericHypothesis_ptr>::iterator iter = hypotheses.begin(); iter != hypotheses.end(); iter++) {
			GenericHypothesis_ptr hypoth = *iter;
			ret_value += getDisplayValue(hypoth, include_titles, is_description);
			if (counter == 0)
				ret_value += L" and ";
			else if (counter == 1)
				break;
			counter++;
		}
		return ret_value;
	} else {
		std::wstring ret_value = L"";
		size_t max = max_to_print;
		if (hypotheses.size() < max)
			max = hypotheses.size();
		size_t counter = 0;
		for (std::list<GenericHypothesis_ptr>::iterator iter = hypotheses.begin(); iter != hypotheses.end(); iter++) {
			GenericHypothesis_ptr hypoth = *iter;
			ret_value += getDisplayValue(hypoth, include_titles, is_description);
			if (counter < max - 2)
				ret_value += L", ";
			else if (counter < max - 1)
				ret_value += L", and ";
			counter++;
			if (counter == max)
				break;
		}
		return ret_value;
	}
}

std::wstring TeaserBiography::getDisplayValue(GenericHypothesis_ptr hypo, bool include_titles, bool use_quotes) {

	std::wstring ret_value = hypo->getDisplayValue();

	// Special handling for employees
	EmploymentHypothesis_ptr empHypoth = boost::dynamic_pointer_cast<EmploymentHypothesis>(hypo);
	if (empHypoth != EmploymentHypothesis_ptr()) {
		if (empHypoth->getNamedArgument() == NameHypothesis_ptr())
			return L""; // this should never happen
		ret_value = empHypoth->getNamedArgument()->getDisplayValue();
		if (include_titles) {
			std::wstring title = empHypoth->getJobTitle();
			if (title.size() != 0) {
				if (title == L"ceo" || title == L"cio" || title == L"coo" || title == L"cto" || title == L"mp")
					std::transform(title.begin(), title.end(), title.begin(), towupper);
				if (title != L"leader" && title != L"head" && title != L"leaders" && title != L"heads") {
					if (isSingularJobTitle(title))
						ret_value += L" (as " + title + L")";
					else ret_value += L" (as " + getJobTitleArticle(title) + L" " + title + L")";
				}
			}
		}
	}

	if (use_quotes)
		return L"\"" + ret_value + L"\"";
	else return ret_value;
}

EmploymentHypothesis::status_tense_t TeaserBiography::getEmploymentTense(GenericHypothesis_ptr hypo) {

	EmploymentHypothesis_ptr empHypoth = boost::dynamic_pointer_cast<EmploymentHypothesis>(hypo);
	if (empHypoth != EmploymentHypothesis_ptr()) {
		return empHypoth->getTense(true); // temporarily print debug info
	}
	return EmploymentHypothesis::CURRENT;
}

std::wstring TeaserBiography::getDateDisplayValue(ProfileSlot_ptr slot) {
	if (slot == ProfileSlot_ptr() || slot->getOutputHypotheses().size() == 0)
		return L"";
	std::wstring value = slot->getOutputHypotheses().front()->getDisplayValue();
	if (value.length() == 4)
		return L"in " + value;
	else if (value.length() == 7)
		return L"in " + monthFromIntWString(value.substr(5,2)) + L" of " + value.substr(0,4);
	else if (value.length() == 8 && value.at(5) == L'W')
		return L"in " + value.substr(0,4);
	else if (value.length() == 10){
		std::wstring dayStr = value.substr(8,2);
		if (dayStr.substr(0,1) == L"0")
			dayStr = dayStr.substr(1,1);
		return L"on " + monthFromIntWString(value.substr(5,2)) + L" " + dayStr + L", " + value.substr(0,4);
	}
	//this one is not supposed  to happen, but ....
	SessionLogger::warn("unrecog_date_0") << L"unrecognized datestring " << value;
	return value;
}
std::wstring TeaserBiography::monthFromIntWString(std::wstring monthInt) {
	if (monthInt == L"01")
		return L"January";
	else if (monthInt == L"02")
		return L"February";
	else if (monthInt == L"03")
		return L"March";
	else if (monthInt == L"04")
		return L"April";
	else if (monthInt == L"05")
		return L"May";
	else if (monthInt == L"06")
		return L"June";
	else if (monthInt == L"07")
		return L"July";
	else if (monthInt == L"08")
		return L"August";
	else if (monthInt == L"09")
		return L"September";
	else if (monthInt == L"10")
		return L"October";
	else if (monthInt == L"11")
		return L"November";
	else if (monthInt == L"12")
		return L"December";

	// might as well log the bug
	SessionLogger::warn("unrecog_date_0") << L"unrecognized datestring for month integer" << monthInt;
	return monthInt;

}

ext: cpp

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Zen Enterprise Framework
//
// Copyright (C) 2001 - 2016 Raymond A. Richards
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#ifndef ZEN_ENTERPRISE_I_MESSAGE_HPP_INCLUDED
#define ZEN_ENTERPRISE_I_MESSAGE_HPP_INCLUDED

#include "Configuration.hpp"

#include <memory>

#include <Zen/Enterprise/I_ResourceLocation.hpp>

#include <boost/noncopyable.hpp>
#include <boost/cstdint.hpp>

namespace boost {
namespace archive {
    class polymorphic_iarchive;
    class polymorphic_oarchive;
} // namespace archive
} // namespace boost

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace Enterprise {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
class I_MessageHeader;
class I_MessageType;
class I_Endpoint;

/// I_Message interface.
class ENTERPRISE_DLL_LINK I_Message
:   boost::noncopyable
{
    /// @name Types
    /// @{
public:
    typedef std::shared_ptr<I_Endpoint>                 pEndpoint_type;
    typedef std::shared_ptr<I_ResourceLocation>         pResourceLocation_type;
    typedef std::shared_ptr<I_MessageHeader>            pMessageHeader_type;
    typedef std::shared_ptr<I_MessageType>              pMessageType_type;
    /// @}

    /// @name I_Message interface.
    /// @{
public:
    /// Get the source endpoint of this message
    /// @return The destination endpoint, or invalid() if this message originated from
    ///     the current process.
    virtual pEndpoint_type getSourceEndpoint() = 0;

    /// Get the destination endpiont of this message
    /// @return The destination endpoint, or invalid() if this message is destined for
    ///     the current process.
    virtual pEndpoint_type getDestinationEndpoint() = 0;

    /// Get the source resource of this message.
    virtual pResourceLocation_type getSourceLocation() = 0;

    /// Get the destination resource of this message.
    virtual pResourceLocation_type getDestinationLocation() = 0;

    /// Get the message header.
    virtual pMessageHeader_type getMessageHeader() const = 0;

    /// Get the message Id of this message.
    virtual boost::uint64_t getMessageId() const = 0;

    /// This method returns the message type.
    virtual pMessageType_type getMessageType() const = 0;

    /// Deserialize this message from an input archive.
    /// The protocol adapter deserializes the header, creates the appropriate message
    /// using the message registry, and then deserializes the rest of the message using
    /// this method.
    virtual void serialize(pMessageHeader_type _pHeader, boost::archive::polymorphic_iarchive& _archive, const int _version) = 0;

    /// Serialize this message to an output archive.
    /// The protocol adapter serializes the header and then call this
    /// method to serialize the rest of the message.
    virtual void serialize(boost::archive::polymorphic_oarchive& _archive, const int _version) = 0;
    /// @}

    /// @name Events
    /// @{
public:
    /// @}

    /// @name 'Structors
    /// @{
protected:
             I_Message();
    virtual ~I_Message();
    /// @}

};  // interface I_Message

//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
}   // namespace Enterprise
}   // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~

#endif // ZEN_ENTERPRISE_I_MESSAGE_HPP_INCLUDED

ext: hpp

max_stars_repo_name: indie-zen/zen-enterprise

max_issues_repo_name: indie-zen/zen-enterprise

max_forks_repo_name: indie-zen/zen-enterprise


text:
/////////////////////////////////////////////////////////////
//                                                         //
// Copyright (c) 2003-2017 by The University of Queensland //
// Centre for Geoscience Computing                         //
// http://earth.uq.edu.au/centre-geoscience-computing      //
//                                                         //
// Primary Business: Brisbane, Queensland, Australia       //
// Licensed under the Open Software License version 3.0    //
// http://www.apache.org/licenses/LICENSE-2.0              //
//                                                         //
/////////////////////////////////////////////////////////////

#include <boost/version.hpp>
#include <boost/python.hpp>
#include "Python/esys/lsm/MeshBuildParamsPy.h"

namespace esys
{
  namespace lsm
  {
    /*!
      constructor for MeshTagBuildPrmsPy

      \param tag
      \param mask
    */
    MeshTagBuildPrmsPy::MeshTagBuildPrmsPy(int tag, int mask) : MeshTagBuildPrms(tag, mask)
    {
    }

    /*!
      constructor for MeshGapBuildPrmsPy

      \param maxGap
    */
    MeshGapBuildPrmsPy::MeshGapBuildPrmsPy(double maxGap) : MeshGapBuildPrms(maxGap)
    {
    }

    using boost::python::arg;
    void exportMeshBuildPrms()
    {
      // Disable autogeneration of C++ signatures (Boost 1.34.0 and higher)
      // for Epydoc which stumbles over indentation in the automatically generated strings.
      boost::python::docstring_options no_autogen(true,false);

      boost::python::class_<MeshTagBuildPrmsPy>(
        "MeshTagBuildPrms",
        "Parameters for bonding particles to a mesh which uses\n"
        "particle-tags as the criterion for creating bonds.",
        boost::python::init<int, int>(
          (
            arg("tag"),
            arg("mask")
          ),
	  "Build parameters for particles with a specified tag\n"
          "@type tag: int\n"
          "@kwarg tag: particle tag, particles with this tag will be\n"
          " bonded to the specified mesh.\n"
          "@type mask: int\n"
          "@kwarg mask: mask applied (anded) to particle tag before"
          " being compared with C{tag}.\n"
        )
      );

      boost::python::class_<MeshGapBuildPrmsPy>(
        "MeshGapBuildPrms",
        "Parameters for bonding particles to a mesh which uses\n"
        "distance-to-mesh criterion for creating bonds.",
        boost::python::init<double>(
          (arg("maxDistance")),
	  "Build parameters for particles within a specified distance of a mesh wall\n"
          "@type maxDistance: float\n"
          "@kwarg maxDistance: Particles which are closer than C{maxDistance}"
          " to the mesh get bonded to the mesh.\n"
        )
      );
    }
  }
}

max_stars_repo_name: danielfrascarelli/esys-particle

max_issues_repo_name: danielfrascarelli/esys-particle

max_forks_repo_name: danielfrascarelli/esys-particle


text:
//------------------------------------------------------------------------------
/*
    This file is part of rippled: https://github.com/ripple/rippled
    Copyright (c) 2012, 2013 Ripple Labs Inc.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose  with  or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include "../../beast/beast/unit_test/suite.h"

#include <boost/regex.hpp>

#include <cstdarg>

namespace ripple {

// VFALCO TODO Replace these with something more robust and without macros.
//
#if ! BEAST_MSVC
#define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d)
#endif

std::string strprintf (const char* format, ...)
{
    char buffer[50000];
    char* p = buffer;
    int limit = sizeof (buffer);
    int ret;

    for (;;)
    {
        va_list arg_ptr;
        va_start (arg_ptr, format);
        ret = _vsnprintf (p, limit, format, arg_ptr);
        va_end (arg_ptr);

        if (ret >= 0 && ret < limit)
            break;

        if (p != buffer)
            delete[] p;

        limit *= 2;
        p = new char[limit];

        if (p == nullptr)
            throw std::bad_alloc ();
    }

    std::string str (p, p + ret);

    if (p != buffer)
        delete[] p;

    return str;
}

// NIKB NOTE: This function is only used by strUnHex (const std::string& strSrc)
// which results in a pointless copy from std::string into std::vector. Should
// we just scrap this function altogether?
int strUnHex (std::string& strDst, const std::string& strSrc)
{
    std::string tmp;

    tmp.reserve ((strSrc.size () + 1) / 2);

    auto iter = strSrc.cbegin ();

    if (strSrc.size () & 1)
    {
        int c = charUnHex (*iter);

        if (c < 0)
            return -1;

        tmp.push_back(c);
        ++iter;
    }

    while (iter != strSrc.cend ())
    {
        int cHigh = charUnHex (*iter);
        ++iter;

        if (cHigh < 0)
            return -1;

        int cLow = charUnHex (*iter);
        ++iter;

        if (cLow < 0)
            return -1;

        tmp.push_back (static_cast<char>((cHigh << 4) | cLow));
    }

    strDst = std::move(tmp);

    return strDst.size ();
}

std::pair<Blob, bool> strUnHex (const std::string& strSrc)
{
    std::string strTmp;

    if (strUnHex (strTmp, strSrc) == -1)
        return std::make_pair (Blob (), false);

    return std::make_pair(strCopy (strTmp), true);
}

uint64_t uintFromHex (const std::string& strSrc)
{
    uint64_t uValue (0);

    if (strSrc.size () > 16)
        throw std::invalid_argument("overlong 64-bit value");

    for (auto c : strSrc)
    {
        int ret = charUnHex (c);

        if (ret == -1)
            throw std::invalid_argument("invalid hex digit");

        uValue = (uValue << 4) | ret;
    }

    return uValue;
}

//
// Misc string
//

Blob strCopy (const std::string& strSrc)
{
    Blob vucDst;

    vucDst.resize (strSrc.size ());

    std::copy (strSrc.begin (), strSrc.end (), vucDst.begin ());

    return vucDst;
}

std::string strCopy (Blob const& vucSrc)
{
    std::string strDst;

    strDst.resize (vucSrc.size ());

    std::copy (vucSrc.begin (), vucSrc.end (), strDst.begin ());

    return strDst;

}

extern std::string urlEncode (const std::string& strSrc)
{
    std::string strDst;
    int         iOutput = 0;
    int         iSize   = strSrc.length ();

    strDst.resize (iSize * 3);

    for (int iInput = 0; iInput < iSize; iInput++)
    {
        unsigned char c = strSrc[iInput];

        if (c == ' ')
        {
            strDst[iOutput++]   = '+';
        }
        else if (isalnum (c))
        {
            strDst[iOutput++]   = c;
        }
        else
        {
            strDst[iOutput++]   = '%';
            strDst[iOutput++]   = charHex (c >> 4);
            strDst[iOutput++]   = charHex (c & 15);
        }
    }

    strDst.resize (iOutput);

    return strDst;
}

//
// IP Port parsing
//
// <-- iPort: "" = -1
// VFALCO TODO Make this not require boost... and especially boost::asio
bool parseIpPort (const std::string& strSource, std::string& strIP, int& iPort)
{
    boost::smatch   smMatch;
    bool            bValid  = false;

    static boost::regex reEndpoint ("\\`\\s*(\\S+)(?:\\s+(\\d+))?\\s*\\'");

    if (boost::regex_match (strSource, smMatch, reEndpoint))
    {
        boost::system::error_code   err;
        std::string                 strIPRaw    = smMatch[1];
        std::string                 strPortRaw  = smMatch[2];

        boost::asio::ip::address    addrIP      = boost::asio::ip::address::from_string (strIPRaw, err);

        bValid  = !err;

        if (bValid)
        {
            strIP   = addrIP.to_string ();
            iPort   = strPortRaw.empty () ? -1 : beast::lexicalCastThrow <int> (strPortRaw);
        }
    }

    return bValid;
}

// VFALCO TODO Callers should be using beast::URL and beast::ParsedURL, not this home-brew.
//
bool parseUrl (const std::string& strUrl, std::string& strScheme, std::string& strDomain, int& iPort, std::string& strPath)
{
    // scheme://username:password@hostname:port/rest
    static boost::regex reUrl ("(?i)\\`\\s*([[:alpha:]][-+.[:alpha:][:digit:]]*)://([^:/]+)(?::(\\d+))?(/.*)?\\s*?\\'");
    boost::smatch   smMatch;

    bool    bMatch  = boost::regex_match (strUrl, smMatch, reUrl);          // Match status code.

    if (bMatch)
    {
        std::string strPort;

        strScheme   = smMatch[1];
        strDomain   = smMatch[2];
        strPort     = smMatch[3];
        strPath     = smMatch[4];

        boost::algorithm::to_lower (strScheme);

        iPort   = strPort.empty () ? -1 : beast::lexicalCast <int> (strPort);
        // Log::out() << strUrl << " : " << bMatch << " : '" << strDomain << "' : '" << strPort << "' : " << iPort << " : '" << strPath << "'";
    }

    // Log::out() << strUrl << " : " << bMatch << " : '" << strDomain << "' : '" << strPath << "'";

    return bMatch;
}

//
// Quality parsing
// - integers as is.
// - floats multiplied by a billion
bool parseQuality (const std::string& strSource, std::uint32_t& uQuality)
{
    uQuality    = beast::lexicalCast <std::uint32_t> (strSource);

    if (!uQuality)
    {
        float   fQuality    = beast::lexicalCast <float> (strSource);

        if (fQuality)
            uQuality    = (std::uint32_t) (QUALITY_ONE * fQuality);
    }

    return !!uQuality;
}

beast::StringPairArray parseDelimitedKeyValueString (beast::String parameters,
                                                   beast::beast_wchar delimiter)
{
    beast::StringPairArray keyValues;

    while (parameters.isNotEmpty ())
    {
        beast::String pair;

        {
            int const delimiterPos = parameters.indexOfChar (delimiter);

            if (delimiterPos != -1)
            {
                pair = parameters.substring (0, delimiterPos);

                parameters = parameters.substring (delimiterPos + 1);
            }
            else
            {
                pair = parameters;

                parameters = beast::String::empty;
            }
        }

        int const equalPos = pair.indexOfChar ('=');

        if (equalPos != -1)
        {
            beast::String const key = pair.substring (0, equalPos);
            beast::String const value = pair.substring (equalPos + 1, pair.length ());

            keyValues.set (key, value);
        }
    }

    return keyValues;
}

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

class StringUtilities_test : public beast::unit_test::suite
{
public:
    void testUnHexSuccess (std::string strIn, std::string strExpected)
    {
        std::string strOut;

        expect (strUnHex (strOut, strIn) == strExpected.length (),
            "strUnHex: parsing correct input failed");

        expect (strOut == strExpected,
            "strUnHex: parsing doesn't produce expected result");
    }

    void testUnHexFailure (std::string strIn)
    {
        std::string strOut;

        expect (strUnHex (strOut, strIn) == -1,
            "strUnHex: parsing incorrect input succeeded");

        expect (strOut.empty (),
            "strUnHex: parsing incorrect input returned data");
    }

    void testUnHex ()
    {
        testcase ("strUnHex");

        testUnHexSuccess ("526970706c6544", "RippleD");
        testUnHexSuccess ("A", "\n");
        testUnHexSuccess ("0A", "\n");
        testUnHexSuccess ("D0A", "\r\n");
        testUnHexSuccess ("0D0A", "\r\n");
        testUnHexSuccess ("200D0A", " \r\n");
        testUnHexSuccess ("282A2B2C2D2E2F29", "(*+,-./)");

        // Check for things which contain some or only invalid characters
        testUnHexFailure ("123X");
        testUnHexFailure ("V");
        testUnHexFailure ("STR");
    }

    void testParseUrl ()
    {
        testcase ("parseUrl");

        std::string strScheme;
        std::string strDomain;
        int         iPort;
        std::string strPath;

        unexpected (!parseUrl ("lower://domain", strScheme, strDomain, iPort, strPath),
            "parseUrl: lower://domain failed");

        unexpected (strScheme != "lower",
            "parseUrl: lower://domain : scheme failed");

        unexpected (strDomain != "domain",
            "parseUrl: lower://domain : domain failed");

        unexpected (iPort != -1,
            "parseUrl: lower://domain : port failed");

        unexpected (strPath != "",
            "parseUrl: lower://domain : path failed");

        unexpected (!parseUrl ("UPPER://domain:234/", strScheme, strDomain, iPort, strPath),
            "parseUrl: UPPER://domain:234/ failed");

        unexpected (strScheme != "upper",
            "parseUrl: UPPER://domain:234/ : scheme failed");

        unexpected (iPort != 234,
            boost::str (boost::format ("parseUrl: UPPER://domain:234/ : port failed: %d") % iPort));

        unexpected (strPath != "/",
            "parseUrl: UPPER://domain:234/ : path failed");

        unexpected (!parseUrl ("Mixed://domain/path", strScheme, strDomain, iPort, strPath),
            "parseUrl: Mixed://domain/path failed");

        unexpected (strScheme != "mixed",
            "parseUrl: Mixed://domain/path tolower failed");

        unexpected (strPath != "/path",
            "parseUrl: Mixed://domain/path path failed");
    }

    void testStringConcat ()
    {
        testcase ("stringConcat");
        auto result = stringConcat({});
        expect(result == "", result);

        result = stringConcat({"hello, ", std::string("world.")});
        expect(result == "hello, world.", result);

        result = stringConcat({"hello, ", 23});
        expect(result == "hello, 23", result);

        result = stringConcat({"hello, ", true});
        expect(result == "hello, true", result);

        result = stringConcat({"hello, ", 'x'});
        expect(result == "hello, x", result);
    }

    void testToString ()
    {
        testcase ("toString");
        auto result = toString("hello");
        expect(result == "hello", result);
    }

    void run ()
    {
        testParseUrl ();
        testUnHex ();
        testStringConcat ();
        testToString ();
    }
};

BEAST_DEFINE_TESTSUITE(StringUtilities, ripple_basics, ripple);

} // ripple

max_stars_repo_name: softwaredeveloper/stellard

max_issues_repo_name: softwaredeveloper/stellard

max_forks_repo_name: softwaredeveloper/stellard


text:
// Copyright 2010 Dean Michael Berris.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#define BOOST_TEST_MODULE utils thread pool test
#include <boost/config/warning_disable.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/network/utils/thread_pool.hpp>
#include <boost/bind.hpp>

using namespace boost::network;

// This test specifies the requirements for a thread pool interface. At the
// very least any thread pool implementation should be able to pass the simple
// tests that this unit test requires of thread pools. Ultimately the
// requirements will show up in the Concept documentation, but this test is the
// canonical definition of what a thread pool should look like at least
// syntactically.
//

BOOST_AUTO_TEST_CASE( default_constructor ) {
    utils::thread_pool pool;
    BOOST_CHECK_EQUAL(pool.thread_count(), std::size_t(1));
}

struct foo {
    foo() : val_(0) {}
    void bar(int val) {
        val_ += val;
    }
    int const val() const {
        return val_;
    }
protected:
    int val_;
};

BOOST_AUTO_TEST_CASE( post_work ) {
    foo instance;
    {
        utils::thread_pool pool;
        BOOST_CHECK_NO_THROW(pool.post(boost::bind(&foo::bar, &instance, 1)));
        BOOST_CHECK_NO_THROW(pool.post(boost::bind(&foo::bar, &instance, 2)));
        // require that pool is destroyed here, RAII baby
    }
    BOOST_CHECK_EQUAL(instance.val(), 3);
}

max_stars_repo_name: antoinelefloch/cpp-netlib

max_issues_repo_name: antoinelefloch/cpp-netlib

max_forks_repo_name: antoinelefloch/cpp-netlib


text:
// Copyright (C) 2010-2015 Joshua Boyce
// See the file COPYING for copying permission.

#include <hadesmem/process_list.hpp>
#include <hadesmem/process_list.hpp>

#include <utility>

#include <hadesmem/detail/warning_disable_prefix.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <hadesmem/detail/warning_disable_suffix.hpp>

#include <hadesmem/config.hpp>
#include <hadesmem/process_entry.hpp>

void TestProcessList()
{
  using ProcessListIterCat =
    std::iterator_traits<hadesmem::ProcessList::iterator>::iterator_category;
  HADESMEM_DETAIL_STATIC_ASSERT(
    std::is_base_of<std::input_iterator_tag, ProcessListIterCat>::value);
  using ProcessListConstIterCat = std::iterator_traits<
    hadesmem::ProcessList::const_iterator>::iterator_category;
  HADESMEM_DETAIL_STATIC_ASSERT(
    std::is_base_of<std::input_iterator_tag, ProcessListConstIterCat>::value);

  hadesmem::ProcessList const process_list_1;
  hadesmem::ProcessList process_list_2(process_list_1);
  hadesmem::ProcessList process_list_3(std::move(process_list_2));
  process_list_2 = std::move(process_list_3);
  BOOST_TEST(std::begin(process_list_2) != std::end(process_list_2));

  auto iter = std::begin(process_list_1);
  BOOST_TEST(iter != std::end(process_list_1));
  BOOST_TEST(++iter != std::end(process_list_1));
  BOOST_TEST_NE(iter->GetId(), 0U);
  DWORD const second_id = iter->GetId();
  BOOST_TEST(++iter != std::end(process_list_1));
  DWORD const third_id = iter->GetId();
  BOOST_TEST_NE(second_id, third_id);
}

void TestProcessListAlgorithm()
{
  hadesmem::ProcessList const process_list_1;

  for (auto const& entry : process_list_1)
  {
    BOOST_TEST(!entry.GetName().empty());
  }

  auto const this_iter = std::find_if(std::begin(process_list_1),
                                      std::end(process_list_1),
                                      [](hadesmem::ProcessEntry const& entry)
                                      {
    return entry.GetId() == ::GetCurrentProcessId();
  });
  BOOST_TEST(this_iter != std::end(process_list_1));
}

int main()
{
  TestProcessList();
  TestProcessListAlgorithm();
  return boost::report_errors();
}


text:
//============================================================================
// Name        :
// Author      : Avi
// Revision    : $Revision: #10 $
//
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description :
//============================================================================
#include "ServerTestHarness.hpp"
#include "TestFixture.hpp"

#include "Defs.hpp"
#include "Suite.hpp"
#include "Family.hpp"
#include "Task.hpp"
#include "DurationTimer.hpp"
#include "VerifyAttr.hpp"

#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>

#include <iostream>
#include <fstream>
#include <stdlib.h>

using namespace std;
using namespace ecf;
namespace fs = boost::filesystem;

BOOST_AUTO_TEST_SUITE( TestSuite )

// Test the abort command. This will test the abort command and the
// retry behaviour. i.e if a task is aborted, and the variable ECF_TRIES
// is defined. Then providing its value is less the the task's try number
// we should do an immediate job submission.
BOOST_AUTO_TEST_CASE( test_ )
{
	DurationTimer timer;
	cout << "Test:: ...test_abort_cmd "<< flush;
   TestClean clean_at_start_and_end;

	// Create the defs file corresponding to the text below
	// ECF_HOME variable is automatically added by the test harness.
	// ECF_INCLUDE variable is automatically added by the test harness.
	// SLEEPTIME variable is automatically added by the test harness.
	// ECF_CLIENT_EXE_PATH variable is automatically added by the test harness.
	//                     This is substituted in ecf includes
	//                     Allows test to run without requiring installation

 	//# Note: we have to use relative paths, since these tests are relocatable
	//	suite test_task_abort_cmd
	//    edit ECF_TRIES '4'
	//	  family family0
	// 		task abort
 	//	   endfamily
	//	endsuite
   	Defs theDefs;
 	{
      suite_ptr suite = theDefs.add_suite("test_abort_cmd");
 		suite->addVariable( Variable("ECF_TRIES","4") );
 		family_ptr fam0 = suite->add_family("family0");
 		task_ptr abort = fam0->add_task("abort");
 		abort->addVerify( VerifyAttr(NState::ABORTED,3) ); // task should abort 3 times & succeed on 4th attempt
 		abort->addVerify( VerifyAttr(NState::COMPLETE,1) );// task should complete 1 times
 	}

	// Create a custom ecf file for test_task_abort_cmd/family0/abort to invoke the child abort command
	std::string templateEcfFile;
 	templateEcfFile += "%include <head.h>\n";
	templateEcfFile += "\n";
	templateEcfFile += "echo do some work\n";
	templateEcfFile += "if [ %ECF_TRYNO% -le 3 ] ; then\n";
 	templateEcfFile += "   %ECF_CLIENT_EXE_PATH% --abort=\"expected abort at task try no %ECF_TRYNO%\"\n";
	templateEcfFile += "   trap 0       # Remove all traps\n";
	templateEcfFile += "   exit 0       # End the shell before child command complete\n";
 	templateEcfFile += "fi\n";
	templateEcfFile += "\n";
	templateEcfFile += "%include <tail.h>\n";

 	// The test harness will create corresponding directory structure
 	// Override the default ECF file, with our custom ECF_ file
 	std::map<std::string,std::string> taskEcfFileMap;
 	taskEcfFileMap.insert(std::make_pair(TestFixture::taskAbsNodePath(theDefs,"abort"),templateEcfFile));

    // Avoid standard verification since we expect to abort many times
   ServerTestHarness serverTestHarness;
	serverTestHarness.run(theDefs,ServerTestHarness::testDataDefsLocation("test_abort_cmd.def"), taskEcfFileMap);

	cout << timer.duration() << " update-calendar-count(" << serverTestHarness.serverUpdateCalendarCount() << ")\n";
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: mpartio/ecflow

max_issues_repo_name: mpartio/ecflow

max_forks_repo_name: mpartio/ecflow


text:
#include <algorithm>

#include <boost/numeric/mtl/mtl.hpp>

#include "DOFMatrix.hpp"
#include "QPsiPhi.hpp"
#include "BasisFunction.hpp"
#include "Boundary.hpp"
#include "DOFAdmin.hpp"
#include "ElInfo.hpp"
#include "FiniteElemSpace.hpp"
#include "Mesh.hpp"
#include "DOFVector.hpp"
#include "Operator.hpp"
#include "BoundaryCondition.hpp"
#include "BoundaryManager.hpp"
#include "Assembler.hpp"

namespace AMDiS
{
  using namespace mtl;

  DOFMatrix::DOFMatrix()
    : rowFeSpace(NULL),
      colFeSpace(NULL),
      elementMatrix(3, 3),
      nRow(0),
      nCol(0),
      nnzPerRow(0),
      inserter(NULL)
  {}

  DOFMatrix::DOFMatrix(const FiniteElemSpace* rowSpace,
                       const FiniteElemSpace* colSpace,
                       std::string n)
    : rowFeSpace(rowSpace),
      colFeSpace(colSpace),
      name(n),
      coupleMatrix(false),
      nnzPerRow(0),
      inserter(NULL)
  {
    FUNCNAME("DOFMatrix::DOFMatrix()");

    TEST_EXIT(rowFeSpace)("No fe space for row!\n");

    if (!colFeSpace)
      colFeSpace = rowFeSpace;
    boundaryManager = new BoundaryManager(rowFeSpace);

    nRow = rowFeSpace->getBasisFcts()->getNumber();
    nCol = colFeSpace->getBasisFcts()->getNumber();
    elementMatrix.change_dim(nRow, nCol);
    rowIndices.resize(nRow);
    colIndices.resize(nCol);
  }

  DOFMatrix::DOFMatrix(const DOFMatrix& rhs)
    : name(rhs.name + "copy")
  {
    FUNCNAME("DOFMatrix::DOFMatrix()");

    *this = rhs;
    TEST_EXIT(rhs.inserter == 0)("Cannot copy during insertion!\n");
    inserter = 0;
  }

  DOFMatrix::~DOFMatrix()
  {
    if (boundaryManager)
      delete boundaryManager;
    if (inserter)
      delete inserter;
  }

  void DOFMatrix::print() const
  {
    if (inserter)
      inserter->print();
  }

  int DOFMatrix::getUsedSize() const
  {
    return rowFeSpace->getAdmin()->getUsedSize();
  }

  DOFMatrix& DOFMatrix::operator=(const DOFMatrix& rhs)
  {
    rowFeSpace = rhs.rowFeSpace;
    colFeSpace = rhs.colFeSpace;
    operators = rhs.operators;
    operatorFactor = rhs.operatorFactor;
    coupleMatrix = rhs.coupleMatrix;

    /// The matrix values may only be copyed, if there is no active insertion.
    if (rhs.inserter == 0 && inserter == 0)
      matrix = rhs.matrix;

    if (rhs.boundaryManager)
      boundaryManager = new BoundaryManager(*rhs.boundaryManager);
    else
      boundaryManager = NULL;

    nRow = rhs.nRow;
    nCol = rhs.nCol;
    elementMatrix.change_dim(nRow, nCol);

    return *this;
  }

  void DOFMatrix::addElementMatrix(const ElementMatrix& elMat,
                                   const BoundaryType* bound,
                                   ElInfo* rowElInfo,
                                   ElInfo* colElInfo)
  {
    FUNCNAME_DBG("DOFMatrix::addElementMatrix()");

    TEST_EXIT_DBG(inserter)("DOFMatrix is not in insertion mode\n");
    TEST_EXIT_DBG(rowFeSpace)("Have now rowFeSpace!\n");

    inserter_type& ins= *inserter;

    // === Get indices mapping from local to global matrix indices. ===

    rowFeSpace->getBasisFcts()->getLocalIndices(rowElInfo->getElement(),
        rowFeSpace->getAdmin(),
        rowIndices);
    if (rowFeSpace == colFeSpace)
    {
      colIndices = rowIndices;
    }
    else
    {
      if (colElInfo)
      {
        colFeSpace->getBasisFcts()->getLocalIndices(colElInfo->getElement(),
            colFeSpace->getAdmin(),
            colIndices);
      }
      else
      {
        // If there is no colElInfo pointer, use rowElInfo the get the indices.
        colFeSpace->getBasisFcts()->getLocalIndices(rowElInfo->getElement(),
            colFeSpace->getAdmin(),
            colIndices);
      }
    }

    for (int i = 0; i < nRow; i++)
    {
      DegreeOfFreedom row = rowIndices[i];

      BoundaryCondition* condition =
        bound ? boundaryManager->getBoundaryCondition(bound[i]) : NULL;

      if (condition && condition->isDirichlet())
      {
        if (condition->applyBoundaryCondition())
          dirichletDofs.insert(row);
      }
      else
      {
        for (int j = 0; j < nCol; j++)
        {
          DegreeOfFreedom col = colIndices[j];
          ins[row][col] += elMat[i][j];
        }
      }
    }
  }

  void DOFMatrix::assembleOperator(Operator& op)
  {
    FUNCNAME("DOFMatrix::assembleOperator()");

    TEST_EXIT(rowFeSpace->getMesh() == colFeSpace->getMesh())
    ("This function does not support for multi mesh procedure!\n");
    TEST_EXIT(op.getRowFeSpace() == rowFeSpace)
    ("Row FE spaces do not fit together!\n");
    TEST_EXIT(op.getColFeSpace() == colFeSpace)
    ("Column FE spaces do not fit together!\n");

    clearOperators();
    addOperator(&op);

    matrix.change_dim(rowFeSpace->getAdmin()->getUsedSize(),
                      colFeSpace->getAdmin()->getUsedSize());

    Mesh* mesh = rowFeSpace->getMesh();
    mesh->dofCompress();
    const BasisFunction* basisFcts = rowFeSpace->getBasisFcts();

    Flag assembleFlag = getAssembleFlag() |
                        Mesh::CALL_LEAF_EL                        |
                        Mesh::FILL_COORDS                         |
                        Mesh::FILL_DET                            |
                        Mesh::FILL_GRD_LAMBDA |
                        Mesh::FILL_NEIGH |
                        Mesh::FILL_BOUND;

    BoundaryType* bound = new BoundaryType[basisFcts->getNumber()];

    calculateNnz();
    if (getBoundaryManager())
      getBoundaryManager()->initMatrix(this);

    startInsertion(getNnz());

    TraverseStack stack;
    ElInfo* elInfo = stack.traverseFirst(mesh, -1, assembleFlag);
    while (elInfo)
    {
      basisFcts->getBound(elInfo, bound);

      assemble(1.0, elInfo, bound);

      if (getBoundaryManager())
        getBoundaryManager()->fillBoundaryConditions(elInfo, this);

      elInfo = stack.traverseNext(elInfo);
    }

    clearDirichletRows();
    finishAssembling();
    finishInsertion();
    getBoundaryManager()->exitMatrix(this);

    delete [] bound;
  }

  void DOFMatrix::assemble(double factor,
                           ElInfo* elInfo,
                           const BoundaryType* bound)
  {
    set_to_zero(elementMatrix);

    std::vector<Operator*>::iterator it = operators.begin();
    std::vector<double*>::iterator factorIt = operatorFactor.begin();
    for (; it != operators.end(); ++it, ++factorIt)
      if ((*it)->getNeedDualTraverse() == false &&
          (*factorIt == NULL ||** factorIt != 0.0))
        (*it)->getElementMatrix(elInfo,	elementMatrix, *factorIt ? **factorIt : 1.0);

    if (factor != 1.0)
      elementMatrix *= factor;

    if (operators.size())
      addElementMatrix(elementMatrix, bound, elInfo, NULL);
  }

  void DOFMatrix::assemble(double factor,
                           ElInfo* elInfo,
                           const BoundaryType* bound,
                           Operator* op)
  {
    FUNCNAME_DBG("DOFMatrix::assemble()");

    TEST_EXIT_DBG(op)("No operator!\n");

    set_to_zero(elementMatrix);
    op->getElementMatrix(elInfo, elementMatrix, factor);

    if (factor != 1.0)
      elementMatrix *= factor;

    addElementMatrix(elementMatrix, bound, elInfo, NULL);
  }

  void DOFMatrix::finishAssembling()
  {
    // call the operators cleanup procedures
    for (std::vector<Operator*>::iterator it = operators.begin();
         it != operators.end(); ++it)
      (*it)->finishAssembling();
  }

  // Should work as before
  Flag DOFMatrix::getAssembleFlag()
  {
    Flag fillFlag(0);
    for (std::vector<Operator*>::iterator op = operators.begin();
         op != operators.end(); ++op)
      fillFlag |= (*op)->getFillFlag();

    return fillFlag;
  }

  void DOFMatrix::addOperator(Operator* op, double* factor, double* estFactor)
  {
    operators.push_back(op);
    operatorFactor.push_back(factor);
    operatorEstFactor.push_back(estFactor);
  }

  void DOFMatrix::clearOperators()
  {
    operators.clear();
    operatorFactor.clear();
    operatorEstFactor.clear();
  }

  void DOFMatrix::copy(const DOFMatrix& rhs)
  {
    matrix = rhs.matrix;
  }

  void DOFMatrix::clearDirichletRows()
  {
    // Do the following only in sequential code. In parallel mode, the specific
    // solver method must care about dirichlet boundary conditions.
    inserter_type& ins = *inserter;
    for (std::set<DegreeOfFreedom>::iterator it = dirichletDofs.begin();
         it != dirichletDofs.end(); ++it)
      ins[(*it)][(*it)] = 1.0;
  }

  size_t DOFMatrix::memsize() const
  {
    return (num_rows(matrix) + matrix.nnz()) * sizeof(base_matrix_type::size_type)
           + matrix.nnz() * sizeof(base_matrix_type::value_type);
  }

  void DOFMatrix::startInsertion(int nnz_per_row)
  {
    if (inserter)
    {
      delete inserter;
      inserter = NULL;
    }

    inserter = new inserter_type(matrix, nnz_per_row);

    dirichletDofs.clear();
  }

} // end namespace AMDiS


text:
/**
 * $Id$
 *
 * Copyright (C)
 * 2015 - $Date$
 *     Martin Wolf <ndhist@martin-wolf.org>
 *
 * This file is distributed under the BSD 2-Clause Open Source License
 * (See LICENSE file).
 *
 */
#ifndef NDHIST_DETAIL_FULL_MULTI_AXIS_INDEX_ITER_HPP_INCLUDED
#define NDHIST_DETAIL_FULL_MULTI_AXIS_INDEX_ITER_HPP_INCLUDED 1

#include <vector>

#include <boost/assert.hpp>

#include <ndhist/detail/axis.hpp>

namespace ndhist {
namespace detail {

/**
 * @brief The full_multi_axis_index_iter struct provides a n-dimensional index
 *        iterator over the full range of each axis. Each axis can be fixed to
 *        certain value if needed.
 */
struct full_multi_axis_index_iter
{
    full_multi_axis_index_iter(
        std::vector<intptr_t> const & arr_shape
    )
      : is_end_point_(false)
      , arr_shape_(arr_shape)
    {
        uintptr_t const nd = arr_shape_.size();
        fixed_axes_mask_.resize(nd);
        indices_.resize(nd);
    }

    /**
     * @brief Initializes the iteration over the array (including OOR bins)
     *        for the given fixed axes indices (*fixed_axes_indices*).
     *        All vectors must be of
     *        length *nd* -- the dimensionality of the array.
     */
    void
    init_iteration(std::vector<intptr_t> const & fixed_axes_indices)
    {
        uintptr_t const nd = arr_shape_.size();
        indices_.assign(nd, axis::OOR_UNDERFLOW);
        n_iterations_ = 1;
        last_iter_axis_ = -1;
        for(uintptr_t i=0; i<nd; ++i)
        {
            fixed_axes_mask_[i] = (fixed_axes_indices[i] != axis::FLAGS_FLOATING_INDEX);
            if(! fixed_axes_mask_[i])
            {
                last_iter_axis_ = i;
                n_iterations_ *= arr_shape_[i]+2;
            }
            else
            {
                indices_[i] = fixed_axes_indices[i];
            }
        }

        if(last_iter_axis_ == -1)
        {
            throw AssertionError("No iteration axes specified for oor multi-axis iteration!");
        }

        p_ = last_iter_axis_;
        iter_index_ = 0;
        is_end_point_ = false;
    }

    std::vector<intptr_t> const &
    get_indices() const
    {
        return indices_;
    }

    void increment()
    {
        // Increment the indices values for the next value.
        if(iter_index_ == n_iterations_-1)
        {
            is_end_point_ = true;
            return;
        }

        // Move the index pointer to the next non-fixed outer-axis if the index
        // of the current axis has reached its maximum. Then increase
        // the index and reset all indices to the right of this
        // increased index to zero. After this operation, the index
        // pointer points to the inner-most axis (excluding the
        // fixed axes).
        while((indices_[p_] == axis::OOR_OVERFLOW) || fixed_axes_mask_[p_])
        {
            --p_;
        }
        BOOST_ASSERT(p_ >= 0);
        if(indices_[p_] == arr_shape_[p_]-1) {
            indices_[p_] = axis::OOR_OVERFLOW;
        }
        else {
            ++indices_[p_];
        }
        while(p_ < last_iter_axis_)
        {
            ++p_;
            if(! fixed_axes_mask_[p_]) {
                indices_[p_] = axis::OOR_UNDERFLOW;
            }
        }

        ++iter_index_;
    }

    bool is_end() const
    {
        return is_end_point_;
    }

    bool is_oor_bin() const
    {
        uintptr_t const nd = arr_shape_.size();
        for(uintptr_t i=0; i<nd; ++i)
        {
            if((indices_[i] == axis::OOR_UNDERFLOW) ||
               (indices_[i] == axis::OOR_OVERFLOW))
            {
                return true;
            }
        }
        return false;
    }

    uintptr_t
    get_oor_array_index() const
    {
        uintptr_t idx = 0;
        uintptr_t const nd = arr_shape_.size();
        for(uintptr_t i=0; i<nd; ++i)
        {
            if(! ((indices_[i] == axis::OOR_UNDERFLOW) || (indices_[i] == axis::OOR_OVERFLOW)))
            {
                // Mark the axis i as available.
                idx |= (1<<i);
            }
        }
        return idx;
    }

    bool is_end_point_;
    std::vector<intptr_t> const & arr_shape_;
    std::vector<bool> fixed_axes_mask_;
    std::vector<intptr_t> indices_;
    intptr_t last_iter_axis_;
    intptr_t n_iterations_;
    intptr_t p_;
    intptr_t iter_index_;
};

}// namespace detail
}// namespace ndhist

#endif  // !NDHIST_DETAIL_FULL_MULTI_AXIS_INDEX_ITER_HPP_INCLUDED

max_stars_repo_name: martwo/ndhist

max_issues_repo_name: martwo/ndhist

max_forks_repo_name: martwo/ndhist


text:
/*
 *  reads.cpp
 *  TopHat
 *
 *  Created by Cole Trapnell on 9/2/48.
 *  Copyright 2448 Cole Trapnell. All rights reserved.
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <iostream>
#include <cassert>
#include <string>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <boost/smart_ptr/make_shared.hpp>

#include <seqan/find.h>
#include <seqan/file.h>
#include <seqan/modifier.h>

#include "reads.h"
#include "bwt_map.h"
#include "tokenize.h"

using namespace std;

QReadData QReadDataValue::Null;

char* FLineReader::nextLine() {
   if(!file) return NULL;
   if (pushed) { pushed=false; return buf; }
   //reads a char at a time until \n and/or \r are encountered
   len=0;
   int c=0;
   while ((c=getc(file))!=EOF) {
     if (len>=allocated-1) {
        allocated+=512;
        buf=(char*)realloc(buf,allocated);
     }
     if (c=='\n' || c=='\r') {
       buf[len]='\0';
       if (c=='\r') { //DOS file: double-char line terminator, skip the second one
          if ((c=getc(file))!='\n')
              ungetc(c,file);
          }
       lcount++;
       return buf;
       }
     buf[len]=(char)c;
     len++;
     }
   if (c==EOF) {
     isEOF=true;
     if (len==0) return NULL;
     }
   buf[len]='\0';
   lcount++;
   return buf;
}

ReadFormat skip_lines(FLineReader& fr)
{
  if (fr.fhandle() == NULL) return FASTX_AUTO;
  char* buf = NULL;
  ReadFormat rfmt=FASTX_AUTO;
  int lcount=0;
  while ((buf = fr.nextLine()) != NULL) {
	++lcount;
	int i=0;
    while (buf[i]!=0 && buf[i]==' ') ++i;
    if (buf[i] == '\0') continue; //skip empty lines
    if (buf[0] == '>') rfmt=FASTA;
    if (buf[0] == '@') rfmt=FASTQ;
    if (rfmt) {
	   fr.pushBack();
	   break;
    }
  /*
  if (lcount==500) { //skipped 500 lines already, something is wrong here (large header?!?)
	warn_msg("Warning: cannot determine file format! (large header?)\n");
	break;
   }
 */
  }

  return rfmt;
}

bool next_fastx_read(FLineReader& fr, Read& read, ReadFormat rd_format,
                        FLineReader* frq) {
  /*
  if (fr.pushed_read)
    {
      read = fr.last_read;
      fr.pushed_read = false;
      return true;
    }
  */
  read.clear();
  char* buf=NULL;
  while ((buf=fr.nextLine())!=NULL) {
    if (buf[0]==0) continue; //skip empty lines
    if ((rd_format == FASTA && buf[0] == '>') ||
          (rd_format == FASTQ && (buf[0] == '+' || buf[0] == '@'))) { //next record
        if (read.seq.length()>0) { //current record ending
           fr.pushBack();
           break;
           }
        read.name=buf+1;
        string::size_type space_pos = read.name.find_first_of(" \t");
        if (space_pos != string::npos) {
            read.name.resize(space_pos);
            }
        continue;
        } //defline
    // sequence line
    read.seq.append(buf);
    } //line reading loop

  replace(read.seq.begin(), read.seq.end(), '.', color ? '4' : 'N'); //shouldn't really be needed for FASTA files
  if (rd_format != FASTQ && frq==NULL)
      return (!read.seq.empty());
  if (frq==NULL) frq=&fr; //FASTQ
  //FASTQ or quals in a separate file -- now read quality values
  buf=frq->nextLine();
  if (buf==NULL) return false;
  while (buf[0]==0) { //skip empty lines
    buf=frq->nextLine();
    if (buf==NULL) return false;
    }
  //must be on '+' line here
  if (buf==NULL || (rd_format == FASTQ && buf[0] != '+') ||
           (rd_format == FASTA && buf[0] != '>')) {
     err_exit("Error: beginning of quality values record not found! (%s)\n",buf);
     return false;
     }
  read.alt_name=buf+1;
  string::size_type space_pos = read.alt_name.find_first_of(" \t");
  if (space_pos != string::npos) read.alt_name.resize(space_pos);
   //read qv line(s) now:
  while ((buf=frq->nextLine())!=NULL) {
    if (integer_quals)
      {
        vector<string> integer_qual_values;
        tokenize(string(buf), " ", integer_qual_values);
        string temp_qual;
        for (size_t i = 0; i < integer_qual_values.size(); ++i)
          {
            int qual_value = atoi(integer_qual_values[i].c_str());
            if (qual_value < 0) qual_value = 0;
            temp_qual.push_back((char)(qual_value + 33));
          }
        read.qual.append(temp_qual);
      }
    else {
        read.qual.append(buf);
      }
    if (read.qual.length()>=read.seq.length()-1)
          break;
    } //while qv lines

  // final check
  if (color) {
     if (read.seq.length()==read.qual.length()) {
        //discard first qv
        read.qual=read.qual.substr(1);
        }
     if (read.seq.length()!=read.qual.length()+1) {
        err_exit("Error: length of quality string does not match sequence length (%d) for color read %s!\n",
            read.seq.length(), read.alt_name.c_str());
        }
     }
  else {
   if (read.seq.length()!=read.qual.length()) {
           err_exit("Error: qual length (%d) differs from seq length (%d) for fastq record %s!\n",
               read.qual.length(), read.seq.length(), read.alt_name.c_str());
           return false;
           }
    }

  //fr.last_read = read;
  return !(read.seq.empty());
}

// This could be faster.
void reverse_complement(string& seq)
{
	//fprintf(stderr,"fwd: %s\n", seq.c_str());
	for (string::size_type i = 0; i < seq.length(); ++i)
	{
		switch(seq[i])
		{
			case 'A' : seq[i] = 'T'; break;
			case 'T' : seq[i] = 'A'; break;
			case 'C' : seq[i] = 'G'; break;
			case 'G' : seq[i] = 'C'; break;
			default: seq[i]   = 'N'; break;
		}
	}
	reverse(seq.begin(), seq.end());
	//fprintf(stderr, "rev: %s\n", seq.c_str());
}

string str_convert_color_to_bp(const string& color)
{
  if (color.length() <= 0)
    return "";

  char base = color[0];
  string bp;
  for (string::size_type i = 1; i < color.length(); ++i)
    {
      char next = color[i];
      switch(base)
	{
	  // 'A0':'A', 'A1':'C', 'A2':'G', 'A3':'T', 'A4':'N', 'A.':'N',
	case 'A':
	  {
	    switch(next)
	      {
	      case '0': next = 'A'; break;
	      case '1': next = 'C'; break;
	      case '2': next = 'G'; break;
	      case '3': next = 'T'; break;
	      default: next = 'N'; break;
	      }
	  }
	  break;
	case 'C':
	  {
	    // 'C0':'C', 'C1':'A', 'C2':'T', 'C3':'G', 'C4':'N', 'C.':'N',
	     switch(next)
	      {
	      case '0': next = 'C'; break;
	      case '1': next = 'A'; break;
	      case '2': next = 'T'; break;
	      case '3': next = 'G'; break;
	      default: next = 'N'; break;
	      }
	  }
	  break;
	case 'G':
	  {
	    // 'G0':'G', 'G1':'T', 'G2':'A', 'G3':'C', 'G4':'N', 'G.':'N',
	     switch(next)
	      {
	      case '0': next = 'G'; break;
	      case '1': next = 'T'; break;
	      case '2': next = 'A'; break;
	      case '3': next = 'C'; break;
	      default: next = 'N'; break;
	      }
	  }
	  break;
	case 'T':
	  {
	    // 'T0':'T', 'T1':'G', 'T2':'C', 'T3':'A', 'T4':'N', 'T.':'N',
	     switch(next)
	      {
	      case '0': next = 'T'; break;
	      case '1': next = 'G'; break;
	      case '2': next = 'C'; break;
	      case '3': next = 'A'; break;
	      default: next = 'N'; break;
	      }
	  }
	  break;
	default: next = 'N'; break;
	}

      bp.push_back(next);
      base = next;
    }

  return bp;
}

// daehwan - reduce code redundancy!
seqan::String<char> convert_color_to_bp(char base, const seqan::String<char>& color)
{
  if (seqan::length(color) <= 0)
    return "";

  string bp;
  for (string::size_type i = 0; i < seqan::length(color); ++i)
    {
      char next = color[i];
      switch(base)
	{
	  // 'A0':'A', 'A1':'C', 'A2':'G', 'A3':'T', 'A4':'N', 'A.':'N',
	case 'A':
	  {
	    switch(next)
	      {
	      case '0': next = 'A'; break;
	      case '1': next = 'C'; break;
	      case '2': next = 'G'; break;
	      case '3': next = 'T'; break;
	      default: next = 'N'; break;
	      }
	  }
	  break;
	case 'C':
	  {
	    // 'C0':'C', 'C1':'A', 'C2':'T', 'C3':'G', 'C4':'N', 'C.':'N',
	     switch(next)
	      {
	      case '0': next = 'C'; break;
	      case '1': next = 'A'; break;
	      case '2': next = 'T'; break;
	      case '3': next = 'G'; break;
	      default: next = 'N'; break;
	      }
	  }
	  break;
	case 'G':
	  {
	    // 'G0':'G', 'G1':'T', 'G2':'A', 'G3':'C', 'G4':'N', 'G.':'N',
	     switch(next)
	      {
	      case '0': next = 'G'; break;
	      case '1': next = 'T'; break;
	      case '2': next = 'A'; break;
	      case '3': next = 'C'; break;
	      default: next = 'N'; break;
	      }
	  }
	  break;
	case 'T':
	  {
	    // 'T0':'T', 'T1':'G', 'T2':'C', 'T3':'A', 'T4':'N', 'T.':'N',
	     switch(next)
	      {
	      case '0': next = 'T'; break;
	      case '1': next = 'G'; break;
	      case '2': next = 'C'; break;
	      case '3': next = 'A'; break;
	      default: next = 'N'; break;
	      }
	  }
	  break;
	default: next = 'N'; break;
	}

      bp.push_back(next);
      base = next;
    }

  return bp;
}

#define check_color(b1, b2, c1, c2) ((b1 == c1 && b2 == c2) || (b1 == c2 && b2 == c1))

#define two_bps_to_color(b1, b2, c)				      \
  if (((b1) == 'A' || (b1) == 'G' || (b1) == 'C' || (b1) == 'T') && (b1) == (b2)) \
  c = '0'; \
  else if (check_color((b1), (b2), 'A', 'C') || check_color((b1), (b2), 'G', 'T')) \
  c = '1'; \
  else if (check_color((b1), (b2), 'A', 'G') || check_color((b1), (b2), 'C', 'T')) \
  c = '2'; \
  else if (check_color((b1), (b2), 'A', 'T') || check_color((b1), (b2), 'C', 'G')) \
  c = '3'; \
  else \
  c = '4';

string convert_bp_to_color(const string& bp, bool remove_primer)
{
  if (bp.length() <= 1)
    return "";

  char base = toupper(bp[0]);
  string color;
  if (!remove_primer)
    color.push_back(base);

  for (string::size_type i = 1; i < bp.length(); ++i)
    {
      char next = toupper(bp[i]);

      char c = '0';
      two_bps_to_color(base, next, c);
      color.push_back(c);

      base = next;
    }

  return color;
}

// daehwan - check this -
seqan::String<char> convert_bp_to_color(const seqan::String<char>& bp, bool remove_primer)
{
  if (seqan::length(bp) <= 1)
    return "";

  char base = toupper(bp[0]);
  string color;
  if (!remove_primer)
    color.push_back(base);

  for (string::size_type i = 1; i < seqan::length(bp); ++i)
    {
      char next = toupper(bp[i]);

      char c = '0';
      two_bps_to_color(base, next, c);
      color.push_back(c);

      base = next;
    }

  return color;
}

/*
 */
void BWA_decode(const string& color, const string& qual, const string& ref, string& decode)
{
  assert(color.length() == ref.length() - 1);

  static const size_t max_length = MAX_READ_LEN;
  const unsigned int max_value = max_length * 0xff;
  size_t length = color.length();
  if (length < 1 || length + 1 > max_length)
    {
      return;
    }

  unsigned int f[max_length * 4];
  char ptr[max_length * 4];

  unsigned int q_prev = 0;
  for (unsigned int i = 0; i < length + 1; ++i)
    {
      unsigned int q = (unsigned int) (qual.length() <= i ? 'I' : qual[i]) - 33;
      for (unsigned int j = 0; j < 4; ++j)
	{
	  size_t i_j = i * 4 + j;
	  if (i == 0)
	    {
	      f[i_j] = "ACGT"[j] == ref[i] ? 0 : q;
	      ptr[i_j] = 4;
	      continue;
	    }

	  f[i_j] = max_value;
	  char base = "ACGT"[j];
	  for (unsigned int k = 0; k < 4; ++k)
	    {
	      char base_prev = "ACGT"[k];
	      char ref_color;
	      two_bps_to_color(base_prev, base, ref_color);

	      char base_prev_prev = "ACGTN"[(int)ptr[(i-1)*4 + k]];
	      char ref_color_prev;
	      two_bps_to_color(base_prev_prev, base_prev, ref_color_prev);

	      char color_curr = color[i-1];
	      char color_prev = i >= 2 ? color[i-2] : '4';

	      int q_hat = 0;
	      if (color_prev == ref_color_prev && color_prev != '4')
		{
		  if (color_curr == ref_color)
		    q_hat = q + q_prev;
		  else
		    q_hat = q_prev - q;
		}
	      else if (color_curr == ref_color)
		{
		  q_hat = q - q_prev;
		}

	      unsigned int f_k = f[(i-1) * 4 + k] +
		(base == ref[i] ? 0 : q_hat) +
		(color_curr == ref_color ? 0 : q);

	      if (f_k < f[i_j])
		{
		  f[i_j] = f_k;
		  ptr[i_j] = k;
		}
	    }
	}

      q_prev = q;
    }

  unsigned int min_index = 0;
  unsigned int min_f = f[length * 4];
  for (unsigned int i = 1; i < 4; ++i)
    {
      unsigned int temp_f = f[length * 4 + i];
      if (temp_f < min_f)
	{
	  min_f = temp_f;
	  min_index = i;
	}
    }

  decode.resize(length + 1);
  decode[length] = "ACGT"[min_index];
  for (unsigned int i = length; i > 0; --i)
    {
      min_index = ptr[i * 4 + min_index];
      decode[i-1] = "ACGT"[min_index];
    }
}

void bam2Read(bam1_t *b, Read& rd, bool alt_name=false) {
  GBamRecord bamrec(b);
  rd.clear();
  rd.seq=bamrec.seqData(&rd.qual);
  rd.name=bam1_qname(b);
  if (alt_name)
    rd.alt_name=bamrec.tag_str("ZN");
}

bool ReadStream::next_read(QReadData& rdata) {
  while (read_pq.size()<ReadBufSize && !r_eof) {
    //keep the queue topped off
    Read rf;
    if (get_direct(rf)) {
      uint64_t id = (uint64_t)atol(rf.name.c_str());
      QReadData rdata=boost::make_shared<QReadDataValue>(id, rf, last_b());
      read_pq.push(rdata);
      }
    }
  if (read_pq.size()==0)
     return false;
  const QReadData& t = read_pq.top();
  rdata=t; //copy strings and duplicate b pointer!
  read_pq.pop();
  return true;
}

bool ReadStream::get_direct(Read& r) {
  if (fstream.file==NULL) return false;
  if (fstream.is_bam) {
	 bool got_read=false;
	 while (!got_read) {
       if (samread(fstream.bam_file, b) < 0) {
          r_eof=true;
          return false;
       }
       else {
    	if (bam_ignoreQC || (b->core.flag & BAM_FQCFAIL)==0)
            got_read=true;
       }
	 }
     bam2Read(b, r, bam_alt_name);
     return true;
   }
   if (!next_fastx_read(*flseqs, r, read_format, flquals)) {
        r_eof=true;
        return false;
        }
  return true;
}

// reads must ALWAYS be requested in increasing order of their ID
bool ReadStream::getRead(uint64_t r_id,
		Read& read,
		bool strip_slash,
		uint64_t begin_id,
		uint64_t end_id,
		/*
		GBamWriter* um_out, //unmapped reads output
		char um_code, //if non-zero, write the found read to um_out with this code
		int64_t* unmapped_counter, //update this counter for unmapped/skipped reads *only*
		int64_t* multimapped_counter //update this counter for too multi-mapped reads
		*/
		GetReadProc* rProc,
		bool is_unmapped )
 {
	if (!fstream.file)
		err_die("Error: calling ReadStream::getRead() with no file handle!");
	if (r_id<last_id)
		err_die("Error: ReadStream::getRead() called with out-of-order id#!");
	last_id=r_id;
	bool found=false;
	read.clear();
	while (!found) {
		QReadData rdata;
		if (!next_read(rdata))
			break;
		/*
    if (strip_slash) {
       string::size_type slash = rdata.read.name.rfind("/");
       if (slash != string::npos)
          rdata.read.name.resize(slash);
       }
    uint64_t id = (uint64_t)atol(read.name.c_str());
		 */
		if (rdata->id >= end_id)
			return false;

		if (rdata->id < begin_id)
			continue; //silently skip until begin_id found
		//does not trigger rProc->process() until begin_id

		if (rdata->id == r_id)
		{
			read=rdata->read; //it will be returned
			found=true;
		}
		else if (rdata->id > r_id)
		{ //can't find it, went too far
			//only happens when reads [mates] were removed for some reason
			//read_pq.push(make_pair(id, read));
			read_pq.push(rdata);
			break;
		}
		if (rProc) { //skipped read processing (unmapped reads)
			if (!rProc->process(rdata, found)) //, is_unmapped))
				//  rProc->process() should normally return TRUE
				return false; //abort search for r_id, return "not found"
		}
	} //while target read id not found
	return found;
}

bool ReadStream::getQRead(uint64_t r_id,
		QReadData& qread,
		uint64_t begin_id,
		uint64_t end_id,
		GetReadProc* rProc,
		bool is_unmapped )
 {
	if (!fstream.file)
		err_die("Error: calling ReadStream::getRead() with no file handle!");
	if (r_id<last_id)
		err_die("Error: ReadStream::getRead() called with out-of-order id#!");
	last_id=r_id;
	bool found=false;
	//qread.clear();
	qread.reset();
	while (!found) {
		QReadData rdata;
		if (!next_read(rdata))
			break;
		if (rdata->id >= end_id)
			return false;

		if (rdata->id < begin_id)
			continue; //silently skip until begin_id found
		//does not trigger rProc->process() until begin_id
		if (rdata->id == r_id)
		{
			qread=rdata; //it will be returned
			found=true;
		}
		else if (rdata->id > r_id)
		{ //can't find it, went too far
			//only happens when reads [mates] were removed for some reason
			//read_pq.push(make_pair(id, read));
			read_pq.push(rdata);
			break;
		}
		if (rProc) { //skipped read processing (unmapped reads)
			if (!rProc->process(rdata, found)) //, is_unmapped))
				//  rProc->process() should normally return TRUE
				return false; //abort search for r_id, return "not found"
		}
	} //while target read id not found
	return found;
}

max_stars_repo_name: infphilo/tophat

max_issues_repo_name: infphilo/tophat

max_forks_repo_name: infphilo/tophat


text:
// Copyright (c) 2013, Thomas Goyne <plorkyeran@aegisub.org>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// Aegisub Project http://www.aegisub.org/

/// @file text_file_writer.cpp
/// @brief Write plain text files line by line
/// @ingroup utility
///

#include "config.h"

#include "text_file_writer.h"

#include "options.h"

#include <libaegisub/io.h>
#include <libaegisub/charset_conv.h>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <fstream>

TextFileWriter::TextFileWriter(agi::fs::path const& filename, std::string encoding)
: file(new agi::io::Save(filename, true))
, conv()
{
	if (encoding.empty())
		encoding = OPT_GET("App/Save Charset")->GetString();
	if (boost::iequals(encoding, "utf-8"))
		conv.reset(new agi::charset::IconvWrapper("utf-8", encoding.c_str(), true));

	try {
		// Write the BOM
		WriteLineToFile("\xEF\xBB\xBF", false);
	}
	catch (agi::charset::ConversionFailure&) {
		// If the BOM could not be converted to the target encoding it isn't needed
	}
}

TextFileWriter::~TextFileWriter() {
	// Explicit empty destructor required with a unique_ptr to an incomplete class
}

void TextFileWriter::WriteLineToFile(std::string&& line, bool addLineBreak) {
	if (addLineBreak)
#ifdef _WIN32
		line += "\r\n";
#else
		line += "\n";
#endif

	if (conv)
		line = conv->Convert(line);
	file->Get().write(line.data(), line.size());
}

max_stars_repo_name: rcombs/Aegisub

max_issues_repo_name: rcombs/Aegisub

max_forks_repo_name: rcombs/Aegisub


text:
/*
 * extrema_bow_extractor.hpp
 *
 *  Created on: Aug 15, 2013
 *      Author: mdantone
 */

#ifndef SURF_BOW_EXTRACTOR_HPP_
#define SURF_BOW_EXTRACTOR_HPP_
#include "bow_extractor.hpp"
#include "cpp/vision/features/low_level_features.hpp"

#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>

namespace vision {
namespace features {

class ExtremaBowExtractor : boost::noncopyable {

public:

  ExtremaBowExtractor(std::string feature_typestr,
                      const cv::Mat_<float>& vocabulary);

  ExtremaBowExtractor(const vision::features::feature_type::T feature_type,
                      const cv::Mat_<float>& vocabulary);

  void extract(const cv::Mat& image,
               cv::Mat_<int>& histogram,
               const cv::Mat_<uchar>& mask = cv::Mat_<char>() );
private:

  BowExtractor bow_extractor_;
  boost::scoped_ptr<vision::features::LowLevelFeatureExtractor> extractor;

};

} /* namespace features */
} /* namespace vision */
#endif /* SURF_BOW_EXTRACTOR_HPP_ */


text:
///////////////////////////////////////////////////////////////////////////////
// independence.hpp                                                          //
//                                                                           //
//  Copyright 2010 Erwann Rogard. Distributed under the Boost                //
//  Software License, Version 1.0. (See accompanying file                    //
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //
///////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_INCLUDE_PEARSON_CHISQ_INDEPENDENCE_HPP_ER_2010
#define BOOST_STATISTICS_DETAIL_NON_PARAMETRIC_CONTINGENCY_TABLE_INCLUDE_PEARSON_CHISQ_INDEPENDENCE_HPP_ER_2010

#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/feature.hpp>
#include <boost/statistics/detail/non_parametric/contingency_table/pearson_chisq/independence/null_hypothesis.hpp>

#endif


text:
/*
 * L2ProductRightHandSide.cc
 *
 *  Created on: 29.06.2017
 *      Author: thies
 */

#include <deal.II/base/quadrature.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/lac/vector.h>

#include <forward/L2ProductRightHandSide.h>

namespace wavepi {
namespace forward {
using namespace dealii;
using namespace wavepi::base;

template <int dim>
L2ProductRightHandSide<dim>::L2ProductRightHandSide(std::shared_ptr<DiscretizedFunction<dim>> f1,
                                                    std::shared_ptr<DiscretizedFunction<dim>> f2)
    : func1(f1), func2(f2) {}

template <int dim>
L2ProductRightHandSide<dim>::AssemblyScratchData::AssemblyScratchData(const FiniteElement<dim> &fe,
                                                                      const Quadrature<dim> &quad)
    : fe_values(fe, quad, update_values | update_quadrature_points | update_JxW_values) {}

template <int dim>
L2ProductRightHandSide<dim>::AssemblyScratchData::AssemblyScratchData(const AssemblyScratchData &scratch_data)
    : fe_values(scratch_data.fe_values.get_fe(), scratch_data.fe_values.get_quadrature(),
                update_values | update_quadrature_points | update_JxW_values) {}

template <int dim>
void L2ProductRightHandSide<dim>::copy_local_to_global(Vector<double> &result, const AssemblyCopyData &copy_data) {
  for (unsigned int i = 0; i < copy_data.local_dof_indices.size(); ++i)
    result(copy_data.local_dof_indices[i]) += copy_data.cell_rhs(i);
}

template <int dim>
void L2ProductRightHandSide<dim>::local_assemble(const Vector<double> &f1, const Vector<double> &f2,
                                                 const typename DoFHandler<dim>::active_cell_iterator &cell,
                                                 AssemblyScratchData &scratch_data, AssemblyCopyData &copy_data) {
  const unsigned int dofs_per_cell = scratch_data.fe_values.get_fe().dofs_per_cell;
  const unsigned int n_q_points    = scratch_data.fe_values.get_quadrature().size();

  copy_data.cell_rhs.reinit(dofs_per_cell);
  copy_data.local_dof_indices.resize(dofs_per_cell);
  scratch_data.fe_values.reinit(cell);

  cell->get_dof_indices(copy_data.local_dof_indices);

  for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)
    for (unsigned int i = 0; i < dofs_per_cell; ++i)
      for (unsigned int k1 = 0; k1 < dofs_per_cell; ++k1)
        for (unsigned int k2 = 0; k2 < dofs_per_cell; ++k2)
          copy_data.cell_rhs(i) -=
              f1[copy_data.local_dof_indices[k1]] * scratch_data.fe_values.shape_value(k1, q_point) *
              f2[copy_data.local_dof_indices[k2]] * scratch_data.fe_values.shape_value(k2, q_point) *
              scratch_data.fe_values.shape_value(i, q_point) * scratch_data.fe_values.JxW(q_point);
}

template <int dim>
void L2ProductRightHandSide<dim>::create_right_hand_side(const DoFHandler<dim> &dof, const Quadrature<dim> &quad,
                                                         Vector<double> &rhs) const {
  func1->set_time(this->get_time());
  func2->set_time(this->get_time());

  Vector<double> coeffs1 = func1->get_function_coefficients(func1->get_time_index());
  Assert(coeffs1.size() == dof.n_dofs(), ExcDimensionMismatch(coeffs1.size(), dof.n_dofs()));

  Vector<double> coeffs2 = func2->get_function_coefficients(func2->get_time_index());
  Assert(coeffs2.size() == dof.n_dofs(), ExcDimensionMismatch(coeffs2.size(), dof.n_dofs()));

  WorkStream::run(
      dof.begin_active(), dof.end(),
      std::bind(&L2ProductRightHandSide<dim>::local_assemble, *this, std::ref(coeffs1), std::ref(coeffs2),
                std::placeholders::_1, std::placeholders::_2, std::placeholders::_3),
      std::bind(&L2ProductRightHandSide<dim>::copy_local_to_global, *this, std::ref(rhs), std::placeholders::_1),
      AssemblyScratchData(dof.get_fe(), quad), AssemblyCopyData());
}

template <int dim>
std::shared_ptr<DiscretizedFunction<dim>> L2ProductRightHandSide<dim>::get_func1() const {
  return func1;
}

template <int dim>
void L2ProductRightHandSide<dim>::set_func1(std::shared_ptr<DiscretizedFunction<dim>> func1) {
  this->func1 = func1;
}

template <int dim>
std::shared_ptr<DiscretizedFunction<dim>> L2ProductRightHandSide<dim>::get_func2() const {
  return func2;
}

template <int dim>
void L2ProductRightHandSide<dim>::set_func2(std::shared_ptr<DiscretizedFunction<dim>> func2) {
  this->func2 = func2;
}

template class L2ProductRightHandSide<1>;
template class L2ProductRightHandSide<2>;
template class L2ProductRightHandSide<3>;

} /* namespace forward */
} /* namespace wavepi */

max_stars_repo_name: thiesgerken/wavepi

max_issues_repo_name: thiesgerken/wavepi

max_forks_repo_name: thiesgerken/wavepi