Exemplo n.º 1
0
void DumpUnfreed()
{
	AllocList::iterator i;
	unsigned int totalSize = 0;

	if(!allocList)
		return;

	CFile f("/tmp/enigma2_mem.out", "w");
	if (!f)
		return;
	size_t len = 1024;
	char *buffer = (char*)malloc(1024);
	for(i = allocList->begin(); i != allocList->end(); i++)
	{
		unsigned int tmp;
		fprintf(f, "%s\tLINE %d\tADDRESS %p\t%d unfreed\ttype %d (btcount %d)\n",
			i->second.file, i->second.line, (void*)i->second.address, i->second.size, i->second.type, i->second.btcount);
		totalSize += i->second.size;

		char **bt_string = backtrace_symbols( i->second.backtrace, i->second.btcount );
		for ( tmp=0; tmp < i->second.btcount; tmp++ )
		{
			if ( bt_string[tmp] )
			{
				char *beg = strchr(bt_string[tmp], '(');
				if ( beg )
				{
					std::string tmp1(beg+1);
					int pos1=tmp1.find('+'), pos2=tmp1.find(')');
					if ( pos1 != std::string::npos && pos2 != std::string::npos )
					{
						std::string tmp2(tmp1.substr(pos1,(pos2-pos1)));
						tmp1.erase(pos1);
						if (tmp1.length())
						{
							int state;
							abi::__cxa_demangle(tmp1.c_str(), buffer, &len, &state);
							if (!state)
								fprintf(f, "%d %s%s\n", tmp, buffer,tmp2.c_str());
							else
								fprintf(f, "%d %s\n", tmp, bt_string[tmp]);
						}
					}
				}
				else
					fprintf(f, "%d %s\n", tmp, bt_string[tmp]);
			}
		}
		free(bt_string);
		if (i->second.btcount)
			fprintf(f, "\n");
	}
	free(buffer);

	fprintf(f, "-----------------------------------------------------------\n");
	fprintf(f, "Total Unfreed: %d bytes\n", totalSize);
	fflush(f);
};
Exemplo n.º 2
0
int DFInstanceLinux::write_raw(const VIRTADDR &addr, const int &bytes,
                               void *buffer) {
    // try to attach, will be ignored if we're already attached
    attach();

    /* Since most kernels won't let us write to /proc/<pid>/mem, we have to poke
     * out data in n bytes at a time. Good thing we read way more than we write.
     *
     * On x86-64 systems, the size that POKEDATA writes is 8 bytes instead of
     * 4, so we need to use the sizeof( long ) as our step size.
     */

    // TODO: Should probably have a global define of word size for the
    // architecture being compiled on. For now, sizeof(long) is consistent
    // on most (all?) linux systems so we'll keep this.
    uint stepsize = sizeof( long );
    uint bytes_written = 0; // keep track of how much we've written
    uint steps = bytes / stepsize;
    if (bytes % stepsize)
        steps++;
    LOGD << "WRITE_RAW: WILL WRITE" << bytes << "bytes over" << steps << "steps, with stepsize " << stepsize;

    // we want to make sure that given the case where (bytes % stepsize != 0) we don't
    // clobber data past where we meant to write. So we're first going to read
    // the existing data as it is, and then write the changes over the existing
    // data in the buffer first, then write the buffer with stepsize bytes at a time 
    // to the process. This should ensure no clobbering of data.
    QByteArray existing_data(steps * stepsize, 0);
    read_raw(addr, (steps * stepsize), existing_data);
    LOGD << "WRITE_RAW: EXISTING OLD DATA     " << existing_data.toHex();

    // ok we have our insurance in place, now write our new junk to the buffer
    memcpy(existing_data.data(), buffer, bytes);
    QByteArray tmp2(existing_data);
    LOGD << "WRITE_RAW: EXISTING WITH NEW DATA" << tmp2.toHex();

    // ok, now our to be written data is in part or all of the exiting data buffer
    long tmp_data;
    for (uint i = 0; i < steps; ++i) {
        int offset = i * stepsize;
        // for each step write a single word to the child
        memcpy(&tmp_data, existing_data.mid(offset, stepsize).data(), stepsize);
        QByteArray tmp_data_str((char*)&tmp_data, stepsize);
        LOGD << "WRITE_RAW:" << hex << addr + offset << "HEX" << tmp_data_str.toHex();
        if (ptrace(PTRACE_POKEDATA, m_pid, addr + offset, tmp_data) != 0) {
            perror("write word");
            break;
        } else {
            bytes_written += stepsize;
        }
        long written = ptrace(PTRACE_PEEKDATA, m_pid, addr + offset, 0);
        QByteArray foo((char*)&written, stepsize);
        LOGD << "WRITE_RAW: WE APPEAR TO HAVE WRITTEN" << foo.toHex();
    }
    // attempt to detach, will be ignored if we're several layers into an attach chain
    detach();
    // tell the caller how many bytes we wrote
    return bytes_written;
}
Exemplo n.º 3
0
void ompl::base::ProjectionMatrix::project(const double *from, EuclideanProjection &to) const
{
    namespace nu = boost::numeric::ublas;
    // create a temporary uBLAS vector from a C-style array without copying data
    nu::shallow_array_adaptor<const double> tmp1(mat.size2(), from);
    nu::vector<double, nu::shallow_array_adaptor<const double>> tmp2(mat.size2(), tmp1);
    to = prod(mat, tmp2);
}
Exemplo n.º 4
0
void findPairTree(message &M1, message &M2, const difference &D, const DifferentialPath &P, int max_clique_size, ofstream& changes, int counter, message &M1_old, message &M2_old){
	if (counter > 10)
		return;
	vector<vector<int>> neutral_vectors;
	vector<vector<int>> tmp_neutral_vectors;
	vector<vector<int>> first_level, second_level;
	construct_neutral_set(M1, M2, D, P);
	read(neutral_vectors);
	set<int> clique;
	vector<vector<int>> best_bits;
	for (auto i = neutral_vectors.begin(); i != neutral_vectors.end(); i++){
		message tmp1(M1);
		message tmp2(M2);
		xor(tmp1.W, *i);
		xor(tmp2.W, *i);
		D.modify(tmp1, tmp2);
		construct_neutral_set(tmp1, tmp2, D, P);
		read(tmp_neutral_vectors);
		adj_matrix adj(tmp_neutral_vectors.size());
		adj.fill(tmp_neutral_vectors, tmp1, tmp2, D, P);
		kerbosh(adj.adj, adj.adj[1].size(), clique, tmp_neutral_vectors);
		if (clique.size() == max_clique_size){
			first_level.push_back({ (*i)[0], (*i)[1], (*i)[2], (*i)[3], (*i)[4] });
		}
		if (clique.size() > max_clique_size){
			max_clique_size = clique.size();
			first_level.clear();
			first_level.push_back({ (*i)[0], (*i)[1], (*i)[2], (*i)[3], (*i)[4] });
			if (clique.size() >= 35){
				printGoodBits(M1_old, tmp1, changes);
			}
		}
		tmp_neutral_vectors.clear();
		clique.clear();
	}

	for (auto i = first_level.begin(); i != first_level.end(); i++){
		message tmp1(M1);
		message tmp2(M2);
		xor(tmp1.W, *i);
		xor(tmp2.W, *i);
		D.modify(tmp1, tmp2);
		findPairTree(tmp1, tmp2, D, P, max_clique_size, changes, ++counter, M1_old, M2_old);
	}
	return;
}
Exemplo n.º 5
0
void vernama()
{

    std::ifstream msg("example", std::ios::binary | std::ios::in);
    if (!msg.is_open()) {
        std::cerr << "File not found" << std::endl;
    }

    // Get size of file in chars
    msg.seekg (0, std::ios_base::end);
    int size = msg.tellg();
    msg.seekg (0, std::ios_base::beg);

    std::default_random_engine gen;
    std::uniform_int_distribution<llong> random(0, 255);

    // Create keys
    std::ofstream keys_out("vernama_keys", std::ios::binary | std::ios::out);
    for (size_t i = 0; i < static_cast<size_t>(size); ++i) {
        llong tmp = random(gen);
        keys_out.write((char*)&tmp, sizeof(llong));
    }
    keys_out.close();

    llong tmp;
    llong buf;
    std::ofstream out("vernama_encode", std::ios::binary | std::ios::out);
    std::ifstream keys_in("vernama_keys", std::ios::binary | std::ios::in);

    for (int i = 0; msg.read((char*)&buf, sizeof(char)); ++i) {
        llong key;
        keys_in.read((char*)&key, sizeof(llong));
        tmp = buf ^ key;
        out.write((char*)&tmp, sizeof(llong));
    }
    msg.close();
    out.close();
    // Move pointer in begin of file
    keys_in.seekg(0, std::ios::beg);

    std::ofstream decmsg("vernama_decode", std::ios::binary | std::ios::out);
    std::ifstream tmp2("vernama_encode", std::ios::binary | std::ios::in);
    if (!tmp2.is_open()) {
        std::cerr << "File with name ""vernama_encode"" not found" << std::endl;
        exit(1);
    }

    for (int i = 0; tmp2.read((char*)&buf, sizeof(llong)); ++i) {
        llong key;
        keys_in.read((char*)&key, sizeof(llong));
        tmp = buf ^ key;
        decmsg.write((char*)&tmp, sizeof(char));
    }
    keys_in.close();
    decmsg.close();
    tmp2.close();
}
Exemplo n.º 6
0
  MechanicsResidual<EvalT, Traits>::
  MechanicsResidual(Teuchos::ParameterList& p,
                    const Teuchos::RCP<Albany::Layouts>& dl) :
    stress_   (p.get<std::string>("Stress Name"),dl->qp_tensor),
    def_grad_ (p.get<std::string>("DefGrad Name"),dl->qp_tensor),
    w_grad_bf_(p.get<std::string>("Weighted Gradient BF Name"),dl->node_qp_vector),
    w_bf_     (p.get<std::string>("Weighted BF Name"),dl->node_qp_scalar),
    residual_ (p.get<std::string>("Residual Name"),dl->node_vector),
    have_pore_pressure_(p.get<bool>("Have Pore Pressure",false)),
    have_body_force_   (p.get<bool>("Have Body Force",false)),
    have_strain_ (false)
  {
    this->addDependentField(stress_);
    this->addDependentField(def_grad_);
    this->addDependentField(w_grad_bf_);
    this->addDependentField(w_bf_);

    this->addEvaluatedField(residual_);

    this->setName("MechanicsResidual"+PHX::TypeString<EvalT>::value);

    // logic to modify stress in the presence of a pore pressure
    if (have_pore_pressure_) {
      // grab the pore pressure
      PHX::MDField<ScalarT,Cell,QuadPoint> 
        tmp(p.get<std::string>("Pore Pressure Name"), dl->qp_scalar);
      pore_pressure_ = tmp;
      // grab Boit's coefficient
      PHX::MDField<ScalarT,Cell,QuadPoint> 
        tmp2(p.get<std::string>("Biot Coefficient Name"), dl->qp_scalar);
      biot_coeff_ = tmp2;
      this->addDependentField(pore_pressure_);
      this->addDependentField(biot_coeff_);
    }

    if (have_body_force_) {
      // grab the pore pressure
      PHX::MDField<ScalarT,Cell,QuadPoint,Dim> 
        tmp(p.get<std::string>("Body Force Name"), dl->qp_vector);
      body_force_ = tmp;
      this->addDependentField(body_force_);
    }

    if ( p.isType<bool>("Strain Flag") )
      have_strain_ = p.get<bool>("Strain Flag");

    std::vector<PHX::DataLayout::size_type> dims;
    w_grad_bf_.fieldTag().dataLayout().dimensions(dims);
    num_nodes_ = dims[1];
    num_pts_   = dims[2];
    num_dims_  = dims[3];
    int worksetSize = dims[0];

    Teuchos::RCP<ParamLib> paramLib = 
      p.get< Teuchos::RCP<ParamLib> >("Parameter Library");
  }
Exemplo n.º 7
0
void stimulus::entry() {

    reset.write(true);
    wait();
    reset.write(false);

    sc_signed       tmp1(8);
    sc_signed       tmp2(8);
    long            tmp3;
    int             tmp4;
    short           tmp5;
    char            tmp6;
    char            tmp7;
    bool            tmp8;
    sc_unsigned     tmp9(4);
    sc_unsigned     tmp10(4);

    tmp1 = "0b01010101";
    tmp2 = "0b00000010";
    tmp3 = 12345678;
    tmp4 = -123456;
    tmp5 = 20000;
    tmp6 = '$'; 
    tmp7 = 'A';
    tmp8 = "0";
    tmp9 = "0b0001";
    tmp10 = "0b0010";

    while(true){
       out_valid.write(true);
       out_value1.write(tmp1);
       out_value2.write(tmp2);
       out_value3.write(tmp3);
       out_value4.write(tmp4);
       out_value5.write(tmp5);
       out_value6.write(tmp6);
       out_value7.write(tmp7);
       out_value8.write(tmp8);
       out_value9.write(tmp9);
       out_value10.write(tmp10);
       cout << "Stimuli: " << tmp1 << " " << tmp2 << " " << tmp3 << " " << tmp4 << " "
	    << tmp5 << " " << tmp6 << " " << tmp7 << " " << tmp8 << " " << tmp9  << " " << tmp10 <<endl;
       tmp1 = tmp1 + 2;
       tmp2 = tmp2 + 1;
       tmp3 = tmp3 + 5;
       tmp4 = tmp4 + 3;
       tmp5 = tmp5 + 6;
       tmp7 = tmp7 + 1;
       tmp8 = !tmp8;
       tmp9 = tmp9 + 1;
       tmp10 = tmp10 + 1;
       do { wait(); } while (in_ack==false);
       out_valid.write(false);
       wait();
    }
}
void head_callback(const geometry_msgs::Point::ConstPtr& msg){
	//if in automode and estop is not set, it's good to 
	if(auto_mode == 1 && estop == 0){
		std_msgs::String result;
		//if send out velocity command to control the robot
		if(start_flag == 1){
			float theta = atan2(-1*(msg->x),msg->z);//our model has the opposite coordinates frame with the kinect frame, so negative the x value
			printf("theta:%f\n",theta);
			printf("head x %f\n",msg->x);
			printf("head y %f\n",msg->y);
			printf("head z %f\n",msg->z);
			if(fabs(theta) >= 0.5){
				printf("Out of the range of the kinect\n");
				result.data = "A00B00";
				printf("velocity A00 B00\n");
			} else {
				if(msg->z <= 1200){
					printf("in the 1.5m\n");
					result.data = "A00B00";
					printf("velocity A00 B00\n");
				}else{
					if(fabs(theta) > 0.05){
						printf("Turn\n");
						float k=10.0;
						float Vmax = 20.0;
						int left_vel = -1 * k*theta + Vmax/2;
						int right_vel = Vmax/2 + k*theta;
						char tmp[7];
						if(left_vel < 16 && right_vel > 16){
							sprintf(tmp,"A0%xB%x",left_vel, right_vel);
						}else if(right_vel < 16 && left_vel > 16){
							sprintf(tmp,"A%xB0%x",left_vel, right_vel);
						}else if(left_vel < 16 && right_vel < 16){
							sprintf(tmp,"A0%xB0%x",left_vel, right_vel);
						}else{
							sprintf(tmp,"A%xB%x",left_vel, right_vel);
						}
						printf("Velocity Command %s\n",tmp);
						std::string tmp2(tmp);
						result.data = tmp2;
					} else {
						printf("Move Straight\n");
						result.data = "A10B10";//set constant moving speed
						printf("velocity A10 B10\n");
					}
				}
			}

		}else{
			printf("Stop Gesture\n");
			result.data = "A00B00";
			printf("velocity A00 B00\n");
		}
		cmd_vel_pub.publish(result);
	}
}
Exemplo n.º 9
0
	bool operator()(std::string const& s1, std::string const& s2)
	{
		std::string tmp1(s1);
		std::sort(tmp1.begin(), tmp1.end());
		
		std::string tmp2(s2);
		std::sort(tmp2.begin(), tmp2.end());

		return tmp1 < tmp2;
	}
Exemplo n.º 10
0
Expression NonsmoothOperator::operator*( const Operator& arg ) const{

    Expression tmp2(arg);


    Expression tmp1(*this);


    return tmp1*tmp2;
}
Exemplo n.º 11
0
void P_graded(vector<double> &P, const vector<double> &par,
    const NumericMatrix &Theta, const NumericVector &ot, const int &N,
    const int &nfact, const int &nint, const int &itemexp, const int &israting)
{
    const int parsize = par.size();
    vector<double> a(nfact);
    for(int i = 0; i < nfact; ++i) a[i] = par[i];
    vector<double> d(nint, 0.0);
    if(israting){
        const double t = par[parsize-1];
        for(int i = nfact; i < parsize - 1; ++i)
            d[i - nfact] = par[i] + t;
    } else {
        for(int i = nfact; i < parsize; ++i)
            d[i - nfact] = par[i];
    }
    int notordered = 0;
    for(int i = 1; i < nint; ++i)
        notordered += d[i-1] <= d[i]; 
    if(notordered){
        for(int i = 0; i < P.size(); ++i)
            P[i] = 0.0;
    } else {        
        const double nullzero = 0.0, nullone = 1.0;
        NumericMatrix Pk(N, nint + 2);
    
        for(int i = 0; i < N; ++i)
            Pk(i,0) = 1.0;
        for(int i = 0; i < nint; ++i){
            vector<double> tmp1(N), tmp2(N);
            itemTrace(tmp1, tmp2, a, &d[i], Theta, &nullzero, &nullone, ot);
            for(int j = 0; j < N; ++j)
                Pk(j,i+1) = tmp2[j];
        }
        if(itemexp){
            int which = N * (nint + 1) - 1;
            for(int i = (Pk.ncol()-2); i >= 0; --i){
                for(int j = (N-1); j >= 0; --j){
                    P[which] = Pk(j,i) - Pk(j,i+1);
                    if(P[which] < 1e-20) P[which] = 1e-20;
                    else if((1.0 - P[which]) < 1e-20) P[which] = 1.0 - 1e-20;
                    --which;
                }
            }
        } else {
            int which = 0;
            for(int i = 0; i < Pk.ncol(); ++i){
                for(int j = 0; j < Pk.nrow(); ++j){
                    P[which] = Pk(j,i);
                    ++which;
                }
            }
        }
    }
}
Exemplo n.º 12
0
void checkup::checkupfc(vector<vector<Point> > contours_in, std::vector<int> angulo, std::vector<int> *posiciones, vector<vector<Point> > *contours_out )
{

    int n;
    n=angulo.size();
    std::vector<int> tmp2(n,0);
    std::vector<int> tmp3(n,0);
    int tmp1=0;
    tmp1=angulo[0];

//    cout<<endl;
//    cout<<"Angulo original es: ";
//    for(int i=0; i<angulo.size(); i++){
//      // cout<<angulo[i]<<" ";
//    }

    for(int i=0;i<angulo.size();i++){
        if(abs(angulo[i]-tmp1)<=5)
            tmp2[i]=1;
        else
            tmp2[i]=angulo[i];
    }

   // cout<<endl;




 //   cout<<endl;
    for(int i=0;i<angulo.size();i++){
        if(tmp2[i]!=1){
            for(int k=0;k<angulo.size();k++){
                if(abs(angulo[k]-tmp2[i])<=5)
                    tmp3[k]=1;
                else
                    tmp3[k]=tmp2[i];
            }
        }
    }
//    cout<<endl;
//    for(int k=0;k<angulo.size();k++){
//        if(tmp2[k]==1)
//             cout<<"Igual en posicion tmp2: "<<k<<endl;
//    }
//    for(int k=0;k<angulo.size();k++){
//        if(tmp3[k]==1)
//          //   cout<<"Igual en posicion tmp3: "<<k<<endl;
//    }

    // Separar contornos
   // if(tmp)


}
Exemplo n.º 13
0
    virtual std::vector<Vector> placeObjects(const Vector & centre)
    {
      std::vector<Vector> localsites;
    
      Vector start{0,0,0}, tmp{0,0,0};
    
      for (int iStep = 0; iStep < chainlength; ++iStep)
	{      
	  bool test = true;
	
	  while(test)
	    {
	      test = false;
	    
	      {
		Vector tmp2(getRandVec());
		tmp2 /= tmp2.nrm();
	      
		tmp = start + tmp2 * walklength;
	      }
	    
	      for (const Vector & vec : localsites)
		if ((vec - tmp).nrm() <= diameter)
		  test = true;
	    }
		
	  localsites.push_back(start);
	
	  start = tmp;
	}
  
      //Centre the chain in the unit cell
      {
	Vector offset{0,0,0};
      
	for (const Vector & vec : localsites)
	  offset += vec;
      
	offset /= localsites.size();
      
	// move to the centre and offset
	for (Vector & vec : localsites)
	  vec -= offset + centre;
      }

      std::vector<Vector> retval;
      for (const Vector& vec : localsites)
	{
	  const std::vector<Vector>& newsites = uc->placeObjects(vec);
	  retval.insert(retval.end(), newsites.begin(), newsites.end());
	}

      return retval;    
    }
 int rob(vector<int>& nums) {
     if(nums.empty())
         return 0;
     if (nums.size() < 4)
         return *(max_element(nums.begin(), nums.end()));
     vector<int> tmp1(nums.begin() + 1, nums.end());
     int max1 = Sol(tmp1);
     vector<int> tmp2(nums.begin() + 2, nums.end() - 1);
     int max2 = nums[0] + Sol(tmp2);
     return max(max1, max2);
         
 }
Exemplo n.º 15
0
SEXP updateVertexNormals(SEXP vb_, SEXP it_,SEXP angweight_) {
  try {
    typedef unsigned int uint;
    bool angweight = Rcpp::as<bool>(angweight_);
    NumericMatrix vb(vb_);
    IntegerMatrix it(it_);
    mat vbA(vb.begin(),vb.nrow(),vb.ncol());
    mat normals = vbA*0;
    imat itA(it.begin(),it.nrow(),it.ncol());
    //setup vectors to store temporary data
    colvec tmp0(3), tmp1(3), tmp2(3), angtmp(3), ntmp(3);
    int nit = it.ncol();
    for (int i=0; i < nit; ++i) {
      tmp0 = vbA.col(itA(1,i))-vbA.col(itA(0,i));
      tmp1 = vbA.col(itA(2,i))-vbA.col(itA(0,i));
      if (angweight) {
	tmp2 = vbA.col(itA(1,i))-vbA.col(itA(2,i));
	angtmp(0) = angcalcArma(tmp0,tmp1);
	angtmp(1) = angcalcArma(tmp0, tmp2);
	angtmp(2) = angcalcArma(-tmp1, tmp2);
      }
      crosspArma(tmp0,tmp1,ntmp);
      for (int j=0; j < 3; ++j) {
	double co = dot(normals.col(itA(j,i)),ntmp);
      
	if (co < 0)  {
	  if (!angweight) {
	    normals.col(itA(j,i)) -= ntmp;
	  } else {
	    normals.col(itA(j,i)) -= ntmp*angtmp(j);
	  }
	} else {
	  if (! angweight) {
	    normals.col(itA(j,i)) += ntmp;
	  } else {
	    normals.col(itA(j,i)) += ntmp*angtmp(j);
	  }
	}
      }
    }
    for (uint i=0; i < normals.n_cols; ++i) {
      double nlen = norm(normals.col(i),2);
      if (nlen > 0)
	normals.col(i) /= nlen;
    }
		       
    return Rcpp::wrap(normals);
  } catch (std::exception& e) {
    ::Rf_error( e.what());
  } catch (...) {
    ::Rf_error("unknown exception");
  }
}
Exemplo n.º 16
0
void BorderFilter::pattern(DImg& src, DImg& dest, int borderWidth,
                           const DColor& firstColor, const DColor& secondColor,
                           int firstWidth, int secondWidth)
{
    // Original image with the first solid border around.
    DImg tmp;
    solid(src, tmp, firstColor, firstWidth);

    // Border tiled image using pattern with second solid border around.
    int width, height;

    if (d->settings.orgWidth > d->settings.orgHeight)
    {
        height = tmp.height() + borderWidth * 2;
        width  = (int)(height * d->orgRatio);
    }
    else
    {
        width  = tmp.width() + borderWidth * 2;
        height = (int)(width / d->orgRatio);
    }

    DImg tmp2(width, height, tmp.sixteenBit(), tmp.hasAlpha());
    qCDebug(DIGIKAM_DIMG_LOG) << "Border File:" << d->settings.borderPath;
    DImg border(d->settings.borderPath);

    if (border.isNull())
    {
        return;
    }

    border.convertToDepthOfImage(&tmp2);

    for (int x = 0 ; x < width ; x += border.width())
    {
        for (int y = 0 ; y < height ; y += border.height())
        {
            tmp2.bitBltImage(&border, x, y);
        }
    }

    solid(tmp2, dest, secondColor, secondWidth);

    // Merge both images to one.
    if (d->settings.orgWidth > d->settings.orgHeight)
    {
        dest.bitBltImage(&tmp, (dest.width() - tmp.width()) / 2, borderWidth);
    }
    else
    {
        dest.bitBltImage(&tmp, borderWidth, (dest.height() - tmp.height()) / 2);
    }
}
Exemplo n.º 17
0
    int ZmqEnd::startMsgLoop() {

        std::unique_ptr<std::thread> tmp1(new std::thread(std::mem_fn(&ZmqEnd::frontThreadFunc), this));
        mPtrMsgRThread = std::move(tmp1);

        std::unique_ptr<std::thread> tmp2(new std::thread(std::mem_fn(&ZmqEnd::backThreadFunc), this));
        mPtrMsgDThread = std::move(tmp2);
       
       mQuerySock.setsockopt(ZMQ_IDENTITY, mQuerySockID.c_str(), mQuerySockID.size()); 
       mQuerySock.connect(mExternUri);

        return 0;    
    }
double spec_template::sample_theta_conditional_revprop_logpdf()
{
    vector<double> Lbeta(L[0].size(),0);
    vector<double> meanvec(L[0].size(),0);

    MVprod(&L, &beta_draw, &Lbeta);
    double logprob=0;
    vector<double> var(psi_draw.size(),0);

    vector<double> meanbuf(pars.p);
    
    if(WAVELETS)
    { 
      for(int i = 0; i < pars.p; i++)
	  {
	    var[i]=(1/(1+psi_draw[i]));
	    meanbuf[i]=var[i]*(dataWy[i]-Lbeta[i]);
	  }
	  idwt(meanbuf, pars.levsize, pars.h_vec, meanvec);  
	  vector<double> y_draw(pars.n,0.0);
	
      idwt(theta_draw, pars.levsize, pars.h_vec, y_draw);  
	  for (int j = 0; j <pars.n; j++)
	  {  
	    logprob=logprob+truncated_normal_logpdf(y_draw[j], meanvec[j], sqrt(Temp/lambda_draw), tau_draw[j]);
	  } 
	
	  vector<double> addedpoints(pars.p-pars.n,0.0);
	  MVprod(&vex,&meanbuf,&addedpoints); 
	
	  vector<double> tmp2(pars.p-pars.n,0.0);
	  MVprod(&vex,&theta_draw,&tmp2);
	
	  VVdif(&tmp2,&addedpoints, &tmp2);
	  Vconstprod(&tmp2,sqrt(Temp/lambda_draw), &tmp2);
	
	  for(int j = 0; j <pars.p-pars.n; j++)
	    logprob+=normlogpdf(tmp2[j], 0, 1);
   }
   else
   {
      for(unsigned int i = 0; i<psi_draw.size(); i++)
  	  {
	    var[i] = (1/(1 + psi_draw[i]));
	    meanvec[i] = var[i]*(dataWy[i] - Lbeta[i]);
	  }      
  	  for (int j = 0; j < pars.p; j++) 
	    logprob=logprob+truncated_normal_logpdf(theta_draw[j], meanvec[j],sqrt(Temp*var[j]/lambda_draw), tau_draw[j]);
   }
   return logprob;
}
Exemplo n.º 19
0
int ExecutionTracker::SimulateCondBroadcast(thrID myself, void * ret_addr,
        pthread_cond_t * cond) {
    SignalPointInfo tmp(ret_addr, IS_BROADCAST, myself, cond, cond_map);
    wakeThreadWaitingOnCond(&tmp);
    glock();
    enableThread(myself);
    handleSimulateCondBroadcast(myself, ret_addr, cond);
    SchedPointInfo tmp2(ret_addr, "Simulate Broadcast", myself,
            enable_map, IS_NOT_YIELD, cond);
    schedule(&tmp2);
    gunlock();
    pauseThread(myself);
    return OPERATION_SUCCESSFUL;  
}
Exemplo n.º 20
0
bool checkEqual(Queue *queue, Buf *buf1, Buf *buf2, int size) {
  std::unique_ptr<int[]> tmp1(new int[size]);
  std::unique_ptr<int[]> tmp2(new int[size]);
  queue->readBlocking(buf1, 0, sizeof(int) * size, tmp1.get());
  queue->readBlocking(buf2, 0, sizeof(int) * size, tmp2.get());
  int err = 0;
  for (int i = 0; i < size; ++i) {
    if (tmp1[i] != tmp2[i]) {
      printf("%d %d %d\n", i, tmp1[i], tmp2[i]);
      if (++err >= 10) { return false; }
    }
  }
  return true;
}
Exemplo n.º 21
0
//复数类的四则运算
int main()
{
	Fushu a(10);
	Fushu b(20);
	Fushu tmp1(a+b);
	tmp1.Show();
	Fushu tmp2(a-b);
	tmp2.Show();
	Fushu tmp3(a*b);
	tmp3.Show();
	Fushu tmp4(a/b);
	tmp4.Show();
	return 0;
}
Exemplo n.º 22
0
Arquivo: Dip2.cpp Projeto: kziel1/dip
/*
fname:   path to input image
*/
void Dip2::generateNoisyImages(string fname){
 
   // load image, force gray-scale
   cout << "load original image" << endl;
   Mat img = imread(fname, 0);
   if (!img.data){
      cerr << "ERROR: file " << fname << " not found" << endl;
      cout << "Press enter to exit"  << endl;
      cin.get();
      exit(-3);
   }

   // convert to floating point precision
   img.convertTo(img,CV_32FC1);
   cout << "done" << endl;

   // save original
   imwrite("original.jpg", img);
	  
   // generate images with different types of noise
   cout << "generate noisy images" << endl;

   // some temporary images
   Mat tmp1(img.rows, img.cols, CV_32FC1);
   Mat tmp2(img.rows, img.cols, CV_32FC1);
   // first noise operation
   float noiseLevel = 0.15;
   randu(tmp1, 0, 1);
   threshold(tmp1, tmp2, noiseLevel, 1, CV_THRESH_BINARY);
   multiply(tmp2,img,tmp2);
   threshold(tmp1, tmp1, 1-noiseLevel, 1, CV_THRESH_BINARY);
   tmp1 *= 255;
   tmp1 = tmp2 + tmp1;
   threshold(tmp1, tmp1, 255, 255, CV_THRESH_TRUNC);
   // save image
   imwrite("noiseType_1.jpg", tmp1);
    
   // second noise operation
   noiseLevel = 50;
   randn(tmp1, 0, noiseLevel);
   tmp1 = img + tmp1;
   threshold(tmp1,tmp1,255,255,CV_THRESH_TRUNC);
   threshold(tmp1,tmp1,0,0,CV_THRESH_TOZERO);
   // save image
   imwrite("noiseType_2.jpg", tmp1);

	cout << "done" << endl;
	cout << "Please run now: dip2 restorate" << endl;

}
Exemplo n.º 23
0
// Compute features using Harris corner detection method
void ComputeHarrisFeatures(CFloatImage &image, FeatureSet &features)
{
	// Create grayscale image used for Harris detection
	CFloatImage grayImage = ConvertToGray(image);

	// Create image to store Harris values
	CFloatImage harrisImage(image.Shape().width,image.Shape().height,1);

	// Create image to store local maximum harris values as 1, other pixels 0
	CByteImage harrisMaxImage(image.Shape().width,image.Shape().height,1);

	// Create image to store orientation values
	CFloatImage orientationImage(image.Shape().width, image.Shape().height, 1);

	// Compute the harris score at each pixel position, storing the result in in harrisImage. 
	computeHarrisValues(grayImage, harrisImage, orientationImage);

	// Threshold the harris image and compute local maxima.
	computeLocalMaxima(harrisImage,harrisMaxImage);

	// Save images
	CByteImage tmp(harrisImage.Shape());
	CByteImage tmp2(harrisImage.Shape());
	convertToByteImage(harrisImage, tmp);
	convertToByteImage(grayImage, tmp2);
	WriteFile(tmp2, "grayImg.tga");
	WriteFile(tmp, "harris.tga");
	WriteFile(harrisMaxImage, "harrisMax.tga");

	// Loop through feature points in harrisMaxImage and fill in id, type, x, y, and angle 
	// information needed for descriptor computation for each feature point, then add them
	// to feature set
	int id = 0;
	for (int y=0; y < harrisMaxImage.Shape().height; y++) {
		for (int x=0; x < harrisMaxImage.Shape().width; x++) {
			if (harrisMaxImage.Pixel(x, y, 0) == 1) {
				Feature f;
				f.id = id;
				f.type = 2;
				f.x = x;
				f.y = y;
				f.angleRadians = orientationImage.Pixel(x,y,0);
				
				features.push_back(f);
				id++;
			}
		}
	}
}
Exemplo n.º 24
0
int test_rotate90()
{
#ifdef _MSC_VER
	cv::Mat matSrc = cv::imread("E:/GitCode/OpenCV_Test/test_images/1.jpg", 1);
#else	
	cv::Mat matSrc = cv::imread("test_images/1.jpg", 1);
#endif
	if (!matSrc.data) {
		std::cout << "read image fail" << std::endl;
		return -1;
	}

	int width = matSrc.cols;
	int height = matSrc.rows;

	fbc::Mat_<uchar, 3> mat1(height, width, matSrc.data);
	fbc::Mat_<uchar, 3> matTranspose(width, height);
	fbc::transpose(mat1, matTranspose);

	// clockwise rotation  90
	fbc::Mat_<uchar, 3> matRotate90(width, height);
	fbc::flip(matTranspose, matRotate90, 1);
	cv::Mat tmp2(width, height, CV_8UC3, matRotate90.data);
#ifdef _MSC_VER
	cv::imwrite("E:/GitCode/OpenCV_Test/test_images/rotate_90.jpg", tmp2);
#else	
	cv::imwrite("test_images/rotate_90.jpg", tmp2);
#endif

	// clockwise rotation 180
	fbc::Mat_<uchar, 3> matRotate180(height, width);
	fbc::flip(mat1, matRotate180, -1);
	cv::Mat tmp3(height, width, CV_8UC3, matRotate180.data);
#ifdef _MSC_VER
	cv::imwrite("E:/GitCode/OpenCV_Test/test_images/rotate_180.jpg", tmp3);
#else
	cv::imwrite("test_images/rotate_180.jpg", tmp3);
#endif
	// clockwise rotation 270
	fbc::Mat_<uchar, 3> matRotate270(width, height);
	fbc::flip(matTranspose, matRotate270, 0);
	cv::Mat tmp4(matTranspose.rows, matTranspose.cols, CV_8UC3, matRotate270.data);
#ifdef _MSC_VER
	cv::imwrite("E:/GitCode/OpenCV_Test/test_images/rotate_270.jpg", tmp4);
#else
	cv::imwrite("test_images/rotate_270.jpg", tmp4);
#endif
	return 0;
}
Exemplo n.º 25
0
  void NFFT2DGadget::extract_trajectory_and_dcw_from_queue
  ( ACE_Message_Queue<ACE_MT_SYNCH> *queue, cuNDArray<floatd2> *traj, cuNDArray<float> *dcw )
  {
    // Extract trajectory and (if present) density compensation weights.
    // They are stored as a float array of dimensions: {2,3} x #samples_per_readout x #readouts.
    // We need
    // - a floatd2 trajectory array 
    // - a float dcw array 
    //
        
    if( num_trajectory_dims_ == 2 ){
      boost::shared_ptr< hoNDArray<float> > host_traj = extract_trajectory_from_queue( queue );
      std::vector<size_t> dims_1d; dims_1d.push_back(host_traj->get_size(1)*host_traj->get_size(2));
      hoNDArray<floatd2> host_traj2(&dims_1d,(floatd2*)host_traj->get_data_ptr());
      *traj = cuNDArray<floatd2>(host_traj2);

    }
    else{

      boost::shared_ptr< hoNDArray<float> > host_traj_dcw = extract_trajectory_from_queue( queue );

      std::vector<size_t> order;
      order.push_back(1); order.push_back(2); order.push_back(0);
      
      boost::shared_ptr< hoNDArray<float> > host_traj_dcw_shifted = permute( host_traj_dcw.get(), &order );
      
      std::vector<size_t> dims_1d;
      dims_1d.push_back(host_traj_dcw_shifted->get_size(0)*host_traj_dcw_shifted->get_size(1));
      
      hoNDArray<float> tmp(&dims_1d, host_traj_dcw_shifted->get_data_ptr()+2*dims_1d[0]);
      *dcw = tmp;
      
      std::vector<size_t> dims_2d = dims_1d; dims_2d.push_back(2);
      order.clear(); order.push_back(1); order.push_back(0);
      
      tmp.create(&dims_2d, host_traj_dcw_shifted->get_data_ptr());
      auto _traj = permute( &tmp, &order );
      hoNDArray<floatd2> tmp2(&dims_1d,(floatd2*)_traj->get_data_ptr());
      
      *traj = cuNDArray<floatd2>(tmp2);
    }

    std::vector<size_t >dims_2d;
    dims_2d.push_back(traj->get_number_of_elements());
    dims_2d.push_back(1); // Number of frames

    traj->reshape(&dims_2d);
    if( num_trajectory_dims_ == 3 ) dcw->reshape(&dims_2d);
  }
Exemplo n.º 26
0
void SimpleXML::Tag::appendAttribString(string& tmp) {
	for(auto& i: attribs) {
		tmp.append(i.first);
		tmp.append("=\"", 2);
		if(needsEscape(i.second, true)) {
			string tmp2(i.second);
			escape(tmp2, true);
			tmp.append(tmp2);
		} else {
			tmp.append(i.second);
		}
		tmp.append("\" ", 2);
	}
	tmp.erase(tmp.size()-1);
}
Exemplo n.º 27
0
bool		Kitchen::checkError(std::string &str)
{
  std::string	tmp(str);
  std::string	tmp2("");
  int	      	n = 0;

  tmp2 = tmp.substr(0, 3);
  if (tmp2 != "c: " && tmp2 != "r: ")
    return (false);
  tmp.erase(0, 3);
  n = std::count(tmp.begin(), tmp.end(), ' ');
  if (n > 1)
    return (false);
  return (true);
}
Exemplo n.º 28
0
void SimpleXML::Tag::appendAttribString(string& tmp) {
    for(StringPairIter i = attribs.begin(); i!= attribs.end(); ++i) {
        tmp.append(i->first);
        tmp.append("=\"", 2);
        if(needsEscape(i->second, true)) {
            string tmp2(i->second);
            escape(tmp2, true);
            tmp.append(tmp2);
        } else {
            tmp.append(i->second);
        }
        tmp.append("\" ", 2);
    }
    tmp.erase(tmp.size()-1);
}
 string convertToTitle(int n) {
     
     if(n==0) return "";
     
     if(n <=26)
     {
         char tmp = n + 'A'-1;
         string tmp2(1,tmp);
         return tmp2;
     }
     if(n/26!=0 && n%26==0)
     {
         return convertToTitle(n/26-1) + convertToTitle(26);
     }
     return convertToTitle(n/26) + convertToTitle(n%26);
 }
double 
Stokhos::EpetraMultiVectorOperator::NormInf() const
{
  // ||A||_inf = || (|A_1| + ... + |A_n|) ||_inf where A_i is the i-th column
  // of the multi-vector A
  Epetra_Vector tmp1(multi_vec->Map());
  Epetra_Vector tmp2(multi_vec->Map());
  for (int j=0; j<multi_vec->NumVectors(); j++) {
    tmp1.Abs(*((*multi_vec)(j)));
    tmp2.Update(1.0, tmp1, 1.0);
  }
  double nrm;
  tmp2.NormInf(&nrm);

  return nrm;
}