Ejemplo n.º 1
0
Res FillTemplate(const string& template_string,
                 const map<string, string>& vars,
                 bool tolerate_missing_vars,
                 string* out) {
  assert(out);
  out->clear();

  const char* p = template_string.c_str();

  for (;;) {
    const char* begin = strstr(p, "${");
    if (!begin) {
      // Done.
      *out += p;
      break;
    }
    const char* end = strchr(p, '}');
    if (!end) {
      // Done.
      *out += p;
      break;
    }

    string varname(begin + 2, end - (begin + 2));
    if (IsValidVarname(varname)) {
      // See if we can replace this slot.
      map<string, string>::const_iterator it =
        vars.find(varname);
      if (it == vars.end()) {
        if (tolerate_missing_vars) {
          // Pass the variable through, without replacing it.
          out->append(p, end + 1 - p);
          p = end + 1;
          continue;
        } else {
          out->clear();
          return Res(ERR, "Template contained varname '" + varname +
                     "' but no variable of that name is defined.");
        }
      }
      // Insert text up to the var.
      out->append(p, begin - p);
      // Insert the replacement text.
      out->append(it->second);
      p = end + 1;
    } else {
      // Non-varname character; don't replace anything here.
      out->append(p, end + 1 - p);
      p = end + 1;
    }
  }
  return Res(OK);
}
Ejemplo n.º 2
0
bool CEngSynthes::try_adj_node(int node_no)
{
	if(!_node_is_adj (E.m_Nodes[node_no])) return false;
	vector<long> rels;
	get_out_rels(node_no, rels);
	sort(rels.begin(), rels.end(), rel_pos_less(*this));


	if (Node(node_no).m_MainWordNo != -1)
	{
		CEngSemWord& e_word = Node(node_no).m_Words[Node(node_no).m_MainWordNo];
		if(e_word.HasOneGrammem(eSupremum))
		{ 
			Res(node_no).m_Article = DefArticle;
		};
		int parent_rel = get_in_rel(node_no);
		translate_option_t main_option;
		if(parent_rel != -1){
			int parent = Rel(parent_rel).m_SourceNodeNo;
			long id = Res(parent).m_EngParadigmId;
			if(id != -1){
				main_option.dual_freq_dict = &helper.m_pData->m_AdjNounDualFreq;
				main_option.dual_id1 = -1; // ADJ
				main_option.dual_id2 = id; // NOUN id
			}
		}
		
		helper.synthesize_by_node(E.m_Nodes[node_no]);

		if (Node(node_no).HasRelOperator ("AntiMagn"))
			e_word.m_Word =   "the least "+ e_word.m_Word;


		Res(node_no).m_WordForms.push_back(e_word.m_Word);

	}


	// sons are here
	for(long i = 0; i < rels.size(); i++){
		translate_node(Rel(rels[i]).m_TargetNodeNo);
	}	


	handle_colloc_words(node_no, Res(node_no));
	handle_rel_operators(node_no);
	return true;
}
Ejemplo n.º 3
0
void PtexTriangleFilter::buildKernel(PtexTriangleKernel& k, float u, float v,
                                     float uw1, float vw1, float uw2, float vw2,
                                     float width, float blur, Res faceRes)
{
    const float sqrt3 = 1.7320508075688772f;

    // compute ellipse coefficients, A*u^2 + B*u*v + C*v^2 == AC - B^2/4
    float scaleAC = 0.25f * width*width;
    float scaleB = -2.0f * scaleAC;
    float A = (vw1*vw1 + vw2*vw2) * scaleAC;
    float B = (uw1*vw1 + uw2*vw2) * scaleB;
    float C = (uw1*uw1 + uw2*uw2) * scaleAC;

    // convert to cartesian domain
    float Ac = 0.75f * A;
    float Bc = float(sqrt3/2) * (B-A);
    float Cc = 0.25f * A - 0.5f * B + C;

    // compute min blur for eccentricity clamping
    const float maxEcc = 15.0f; // max eccentricity
    const float eccRatio = (maxEcc*maxEcc + 1.0f) / (maxEcc*maxEcc - 1.0f);
    float X = sqrtf(squared(Ac - Cc) + squared(Bc));
    float b_e = 0.5f * (eccRatio * X - (Ac + Cc));

    // compute min blur for texel clamping
    // (ensure that ellipse is no smaller than a texel)
    float b_t = squared(0.5f / (float)faceRes.u());

    // add blur
    float b_b = 0.25f * blur * blur;
    float b = PtexUtils::max(b_b, PtexUtils::max(b_e, b_t));
    Ac += b;
    Cc += b;

    // compute minor radius
    float m = sqrtf(2.0f*(Ac*Cc - 0.25f*Bc*Bc) / (Ac + Cc + X));

    // choose desired resolution
    int reslog2 = PtexUtils::max(0, PtexUtils::calcResFromWidth(2.0f*m));

    // convert back to triangular domain
    A = float(4/3.0) * Ac;
    B = float(2/sqrt3) * Bc + A;
    C = -0.25f * A + 0.5f * B + Cc;

    // scale by kernel width
    float scale = PtexTriangleKernelWidth * PtexTriangleKernelWidth;
    A *= scale;
    B *= scale;
    C *= scale;

    // find u,v,w extents
    float uw = PtexUtils::min(sqrtf(C), 1.0f);
    float vw = PtexUtils::min(sqrtf(A), 1.0f);
    float ww = PtexUtils::min(sqrtf(A-B+C), 1.0f);

    // init kernel
    float w = 1.0f - u - v;
    k.set(Res((int8_t)reslog2, (int8_t)reslog2), u, v, u-uw, v-vw, w-ww, u+uw, v+vw, w+ww, A, B, C);
}
Ejemplo n.º 4
0
WorldObject::ModelSkeletonPtr
WorldObject::LoadSkeleton(
	__in const NWN::ResRef32 & ResRef
	)
/*++

Routine Description:

	This routine loads a GR2 file from disk and parses the contents out.  The
	first skeleton in the file is then loaded and returned to the caller.

Arguments:

	ResRef - Supplies the resource reference identifying the name of the
	         resource to load.

Return Value:

	The routine returns a ModelSkeleton instance pointer (owned by the caller)
	on success.  On failure, an std::exception is raised.

Environment:

	User mode, game state lock held.

--*/
{
	Gr2FileReader::Ptr Gr2Object;
	DemandResource32   Res( m_ResMan, ResRef, NWN::ResGR2 );

	Gr2Object = m_ResMan.OpenGr2File( Res );

	return Gr2Object->LoadModelSkeleton( );
}
Ejemplo n.º 5
0
/*
	произведение вектора-строки на матрицу. 
	в результат уходит вектор-строка длиной 
	по количеству колонок в матрице
*/
CVector CVector::operator * (const CMatrix &arg){
	UINT size = this->getSize(), n = arg.getColCount();

	if (arg.getRowCount() == size) // равна ли длина вектора высоте матрицы?
	{
		CVector Res(n);
		for (UINT i = 0; i < n; i++)
		{
			for (UINT j = 0; j < size; j++)
			{
				Res[i] += (*this)[j] * arg[j][i];
			}
		}
		return Res;
	}

	// длина не равна высоте
	{
		std::string 
			error, msg, place, 
			reason, arg_reason, object;
		error = "Error: length_error: ";
		place = "CVector::operator * (const CMatrix), size = ";
		reason = std::to_string(size);
		arg_reason = std::to_string(arg.getRowCount());
		object = std::to_string(UINT(this));

		msg = 
			error + place + reason + ", arg.size = " + 
			arg_reason + ", Object = " + object;
		throw std::length_error(msg);
		//return CVector(size); // в результат сбрасывается нулевой вектор
	}
}
Ejemplo n.º 6
0
CVector CVector::operator * (const TYPE num) const{
	auto size = getSize();
	CVector Res(size);
	for (int i = 0; i < size; i++)
		Res[i] = (*this)[i] * num;
	return Res;
}
Ejemplo n.º 7
0
// векторное произведение
CVector CVector::crossProduct(const CVector &b) const{
	if (size != 3 || b.getSize() != 3)
	{
		std::string 
			error, msg, place, reason,
			arg_reason, object;
		error = "Error: length_error: ";
		place = "CVector::crossProduct(), size = ";
		reason = std::to_string(size);
		arg_reason = std::to_string(b.getSize());
		object = std::to_string(UINT(this));

		msg = 
			error + place + reason + ", arg.size = " +
			arg_reason + ", Object = " + object;
		throw std::length_error(msg);
	}

	SINT n = 3;
	CVector Res(n), a = *this;
	Res[0] = a[1] * b[2] - a[2] * b[1];
	Res[1] = a[2] * b[0] - a[0] * b[2];
	Res[2] = a[0] * b[1] - a[1] * b[0];
	return Res;
}
Ejemplo n.º 8
0
CMatrix CMatrix::operator + (const CMatrix &arg){
	UINT n = arg.getRowCount(), m = arg.getColCount();

	if (n != rowCount && m != colCount)
	{
		std::string 
			error, msg, place, reason,
			arg_reason, object;
		error = "Error: length_error: ";
		place = "CMatrix::operator + (), size = (";
		reason = std::to_string(rowCount) + ", " + std::to_string(colCount);
		arg_reason = std::to_string(n) + ", " + std::to_string(m);
		object = std::to_string(UINT(this));

		msg = 
			error + place + reason + "), arg.size = (" +
			arg_reason + "), Object = " + object;
		throw std::length_error(msg);
	}

	CMatrix Res(n, m);
	for (UINT i = 0; i < n; i++)
	{
		for (UINT j = 0; j < n; j++)
		{
			// первые [] перегружены нами, а вторые берутся из CVector
			Res[i][j] = (*this)[i][j] + arg[i][j];
		}
	}
	return Res;
}
Ejemplo n.º 9
0
CMatrix CMatrix::operator * (const CMatrix &arg)
{
	auto rows = getRowCount(), cols = arg.getColCount(),
		p = getColCount(), // = RowCount у второй матрицы
		p2 = arg.getRowCount();

	/* избыточно, ввести обработчик */
	if (p == p2) // ширина первой матрицы равна высоте второй?
	{
		CMatrix Res(rows, cols);
			for (auto i = 0; i < rows; i++)
			{
				for (auto j = 0; j < cols; j++)
				{
					for (auto k = 0; k < p; k++)
					{
						Res[i][j] += (*this)[i][k] * arg[k][j];
					}
				}
			}
			return Res;
	}
	else // не равна
	{
		return CMatrix(rows, cols); // возвращаем нулевую матрицу
	}
	
}
void FuseProb::saveFusedImage(Mat& M, string outpath, int id)
{
	Mat image(m_rows*10, m_cols*10, m_type);
	Mat Res(m_size, CV_64F);
	M.copyTo(Res);
//	normalize(Res);
	for(int i=0; i<m_rows; ++i)
		for(int j=0; j<m_cols; ++j)
		{
			int B=0, G=255, R=255, v=0;
			Point P1, P2;
			P1.x = j*SCALE; P1.y = i*SCALE;
			P2.x = (j+1)*SCALE-1; P2.y = (i+1)*SCALE-1;
			double val = Prob[0].at<double>(i, j);
			if(isNavigable(Prob[0], i, j))
				v = roundup(255*(Res.at<double>(i, j)));
			else if(val==999)
				B = G = R = 205;
			else if(val==888)
				B = G = R = 0;
			else if(val==555)
			{
				B = R = 0; G = 255;
			}
			else if(val==777)
			{
				B = R = 255; G = 0;
			}
			rectangle(image, P1, P2, Scalar(B, G-v, R), -1);
		}
	stringstream ss;
	ss<<id;
	string path = outpath+"ResultFuseProb"+ss.str()+".png";
	imwrite(path, image);
}
Ejemplo n.º 11
0
// векторное произведение
CVector CVector::crossProduct(const CVector &b) const{
	auto n = 3;
	CVector Res(n), a = *this;
	Res[0] = a[1] * b[2] - a[2] * b[1];
	Res[1] = a[2] * b[0] - a[0] * b[2];
	Res[2] = a[0] * b[1] - a[1] * b[0];
	return Res;
}
Ejemplo n.º 12
0
Res ParseValueStringOrMap(const Context* ctx,
                          Config* cfg,
                          const Json::Value& val,
                          const string& equals_string,
                          const string& separator_string,
                          string* out) {
  if (val.isString()) {
    *out = val.asString();
  } else if (val.isArray()) {
    // Evaluate as a lisp expression.
    Res err = EvalToString(ctx, cfg, val, out);
    if (!err.Ok()) {
      err.AppendDetail("in ParseValueStringOrMap(): array eval of '" +
                       val.toStyledString() + "'");
      return err;
    }
  } else if (val.isObject()) {
    // Evaluate as a named-value map.
    bool done_first = false;
    out->clear();
    for (Json::Value::iterator it = val.begin(); it != val.end(); ++it) {
      if (!it.key().isString()) {
        return Res(ERR_PARSE,
                   "ParseValueStringOrMap(): key is not a string: '" +
                   it.key().toStyledString());
      }
      const Json::Value& map_val = *it;
      string result;
      Res err = EvalToString(ctx, cfg, map_val, &result);
      if (!err.Ok()) {
        err.AppendDetail("in ParseValueStringOrMap(): key '" +
                         it.key().toStyledString() + "'");
        return err;
      }
      if (done_first) {
        *out += separator_string;
      }
      *out += it.key().asString();
      *out += equals_string;
      *out += result;
      done_first = true;
    }
  }
  return Res(OK);
}
Ejemplo n.º 13
0
const Point Point::operator*(float l) const
{
  Point Res(*this);
  for (unsigned i = 0; i < size(); i++) {
    Res[i] *= l;
  }
  Res.m_score = kMaxFloat;
  return Res;
}
Ejemplo n.º 14
0
Res Object::Init(const Context* context, const string& name,
                 const Json::Value& value) {
  name_ = name;
  name_dir_ = FilenamePathPart(name_);
  base_dir_ = name_dir_;
  context->LogVerbose(StringPrintf("Object::Init(): %s\n", name_.c_str()));

  return Res(OK);
}
Ejemplo n.º 15
0
Array<COMPLEX,2> TailGF::eval(COMPLEX omega) const {
  const int omin(OrderMin()), omax(OrderMax());
  Array<COMPLEX,2> Res(N1,N2);
  COMPLEX z= pow(omega , -omin);
  Res = 0;
  for (int u =omin; u<= omax;u++,z /=omega ) 
    Res += z* (*this)[u];
  return Res;
}
Ejemplo n.º 16
0
DWORD CSerialPort::Read(LPVOID Buffer, DWORD BufferSize)
  {
    DWORD Res(0);
    if (m_PortHandle != INVALID_HANDLE_VALUE)
      {
        ReadFile(m_PortHandle, Buffer, BufferSize, &Res, NULL);
      }
    return Res;  
  }
Ejemplo n.º 17
0
CVector CVector::operator + (const CVector &arg){
	// избыточно, добавить обработчки приёма значения
	/*int s = std::min<int>
		(getSize(), arg.getSize());*/
	auto size = this->getSize();
	CVector Res(size);
	for (int i = 0; i < size; i++)
		Res[i] = (*this)[i] + arg[i];
	return Res;
}
Ejemplo n.º 18
0
Res ExternalLibTarget::Process(const Context* context) {
  dep_hash_ << "external_lib_dep_hash" << name();
  dep_hash_ << dep();
  dep_hash_ << linker_flags();
  dep_hash_ << inc_dirs();
  dep_hash_was_set_ = true;

  processed_ = true;
  return Res(OK);
}
Ejemplo n.º 19
0
Res ReadFileHash(const string& out_dir,
                 const string& file_path,
                 Hash* hash) {
    string hash_fname = PathJoin(out_dir, LocalFileStemFromPath(file_path));
    hash_fname += ".hash";

    hash->Reset();
    FILE* f = fopen(hash_fname.c_str(), "rb");
    if (f) {
        if (fread((void*) hash->data(), hash->size(), 1, f)) {
            fclose(f);
            return Res(OK);
        } else {
            fclose(f);
            hash->Reset();
            return Res(ERR_FILE_ERROR, "ReadFileHash: " + hash_fname);
        }
    }
    return Res(ERR_FILE_ERROR, "ReadFileHash: file open failed: " + hash_fname);
}
Ejemplo n.º 20
0
const Point Point::operator+(const Point& p2) const
{
  CHECK(p2.size() == size());
  Point Res(*this);
  for (unsigned i = 0; i < size(); i++) {
    Res[i] += p2[i];
  }

  Res.m_score = kMaxFloat;
  return Res;
}
Ejemplo n.º 21
0
CMatrix CMatrix::operator * (const TYPE num){
	UINT n = getRowCount(), m = getColCount();
	CMatrix Res(n, m);
	for (UINT i = 0; i < n; i++)
	{
		for (UINT j = 0; j < m; j++)
		{
			Res[i][j] = (*this)[i][j] * num;
		}
	}
	return Res;
}
Ejemplo n.º 22
0
cElHomographie cElHomographie::operator * (const cElHomographie & H2) const
{
    ElMatrix<REAL> M1(3,3);
    ElMatrix<REAL> M2(3,3);
    ElMatrix<REAL> Res(3,3);

     this->ToMatrix(M1);
     H2.ToMatrix(M2);

    Res.mul(M1,M2);
    return FromMatrix(Res);
}
Ejemplo n.º 23
0
CMatrix CMatrix::flip(){
	int Col = getColCount(), Row = getRowCount();
	CMatrix Res(Col, Row);
	for (int i = 0; i < Col; i++)
	{
		for (int j = 0; j < Row; j++)
		{ 
			Res[i][j] = (*this)[j][i];
		}
	}
	return Res;
}
Ejemplo n.º 24
0
// Assign weights to each function.
// General principles:
//   * any uncovered function gets weight 0.
//   * a function with lots of uncovered blocks gets bigger weight.
//   * a function with a less frequently executed code gets bigger weight.
Vector<double> BlockCoverage::FunctionWeights(size_t NumFunctions) const {
  Vector<double> Res(NumFunctions);
  for (auto It : Functions) {
    auto FunctionID = It.first;
    auto Counters = It.second;
    assert(FunctionID < NumFunctions);
    auto &Weight = Res[FunctionID];
    Weight = 1000.;  // this function is covered.
    Weight /= SmallestNonZeroCounter(Counters);
    Weight *= NumberOfUncoveredBlocks(Counters) + 1;  // make sure it's not 0.
  }
  return Res;
}
Ejemplo n.º 25
0
CMatrix CMatrix::flip(){
	UINT Col = getColCount(), Row = getRowCount();
	CMatrix Res(Row, Col);

	for (UINT i = 0; i < Row; i++)
	{
		for (UINT j = 0; j < Col; j++)
		{ 
			Res[i][j] = (*this)[j][i];
		}
	}
	return Res;
}
Ejemplo n.º 26
0
CMatrix CMatrix::operator * (const TYPE num)
{
	auto rows = getRowCount(), cols = getColCount();
	CMatrix Res(rows, cols);
	for (auto i = 0; i < rows; i++)
	{
		for (auto j = 0; j < cols; j++)
		{
			Res[i][j] = (*this)[i][j] * num;
		}
	}
	return Res;
}
Ejemplo n.º 27
0
// Recurse over a set of phi uses to eliminate the trivial ones
MemoryAccess *MemorySSAUpdater::recursePhi(MemoryAccess *Phi) {
  if (!Phi)
    return nullptr;
  TrackingVH<MemoryAccess> Res(Phi);
  SmallVector<TrackingVH<Value>, 8> Uses;
  std::copy(Phi->user_begin(), Phi->user_end(), std::back_inserter(Uses));
  for (auto &U : Uses) {
    if (MemoryPhi *UsePhi = dyn_cast<MemoryPhi>(&*U)) {
      auto OperRange = UsePhi->operands();
      tryRemoveTrivialPhi(UsePhi, OperRange);
    }
  }
  return Res;
}
Ejemplo n.º 28
0
Res WriteFileHash(const string& out_dir,
                  const string& file_path,
                  const Hash& hash) {
    string hash_fname = PathJoin(out_dir, LocalFileStemFromPath(file_path));
    hash_fname += ".hash";

    FILE* f = fopen(hash_fname.c_str(), "wb");
    if (!f) {
        return Res(ERR_FILE_ERROR, "WriteFileHash can't open file " + hash_fname);
    } else {
        size_t wrote = fwrite(hash.data(), hash.size(), 1, f);
        if (wrote != 1) {
            return Res(ERR_FILE_ERROR, "WriteFileHash couldn't write to file " +
                       hash_fname);
        }
        int closed_code = fclose(f);
        if (closed_code != 0) {
            return Res(ERR_FILE_ERROR, "WriteFileHash couldn't close " + hash_fname);
        }
    }

    return Res(OK);
}
Ejemplo n.º 29
0
/*
	Перегрузки операторов
*/
CMatrix CMatrix::operator + (const CMatrix &arg)
{
	auto rows = arg.getRowCount(), cols = arg.getColCount();
	CMatrix Res(rows, cols);
	for (auto i = 0; i < rows; i++)
	{
		for (auto j = 0; j < cols; j++)
		{
			// первые [] перегружены нами, а вторые берутся из BaseVector
			Res[i][j] = (*this)[i][j] + arg[i][j];
		}
	}
	return Res;
}
Ejemplo n.º 30
0
Unit FileToVector(const std::string &Path, size_t MaxSize) {
  std::ifstream T(Path);
  if (!T) {
    Printf("No such directory: %s; exiting\n", Path.c_str());
    exit(1);
  }
  if (MaxSize) {
    Unit Res(MaxSize);
    T.read(reinterpret_cast<char*>(Res.data()), MaxSize);
    Res.resize(T.gcount());
    return Res;
  }
  return Unit((std::istreambuf_iterator<char>(T)),
              std::istreambuf_iterator<char>());
}