mercredi 1 juillet 2015

How do I limit my output to 40 characters per line without truncating a word in the string?

I am working on an assignment and I have pretty much figured it all out but keep in mind I am not allowed to use arrays nor streams for this program. I must input string data from a file and display 40 characters per line of the data in the file without cutting off any of the words. This part of the problem has stumped me. I am also stumped on how to figure out how to capitalize the first letter of a word if it has symbols attached to the front. I was thinking that the 40 characters per line would work best in my void function for print_text and the capitalization should go in format_text. I have tried my best and was able to successfully capitalize the first letter and make the last letters of each word lower case, but I cannot figure out how to do it if the word has symbols in front (ex. **running)

What I have so far

#include <iostream>
#include <string>
#include <cctype>
#include <iomanip>
using namespace std;
void get_text(string&);
void format_text(string&);
void print_text(string);
int alphacount(string);
double charcount(string);
int consonantcount(string);
int sentencecount(string);
int main()

 {
  string filetext; // Text data input from file                                                                                                                                                                        
  int letters = 0; // amount of letters input from file                                                                                                                                                                
  int words = 0; // amount of words input from file                                                                                                                                                                    
  int sentences = 0; // amount of sentences input from file                                                                                                                                                            
  int consonants = 0;// amount of consonants input from file                                                                                                                                                           
  double amtchar  = 0.0;// amount of characters in file                                                                                                                                                                
  double average = 0.0; // average length of words in file                                                                                                                                                             
  cout << fixed << setprecision (3);
  get_text(filetext); // reads text in file                                                                                                                                                                            
  while (cin)
    {
      words++;
      sentences = sentencecount(filetext) + sentences;
      letters = alphacount(filetext) + letters;
      amtchar = charcount(filetext) + amtchar;
      consonants = ( consonants +   consonantcount(filetext));
      average = amtchar/ words;
      format_text(filetext);// formats text in file correctly                                                                                                                                                          
      print_text(filetext);// outputs data from file                                                                                                                                                                   
      get_text(filetext);
    }

  cout << "# of words: " << words << endl;
  cout << "# of sentences; " << sentences  << endl;
  cout << "# of letters: " << letters << endl;
  cout << "# of consonants: " << consonants << endl;
  cout << "Average word length: " << average << endl;
  return 0;
}

void get_text(string& ftext)
// Given a string of data from a file the function reads the strings and passes                                                                                                                                        
// them back to the calling function.                                                                                                                                                                                  
{
  cin >> ftext;
}

void print_text(string ftext)
// Given the string of text from the file the function displays the contents                                                                                                                                           
// of the file on screen.                                                                                                                                                                                              
{
  cout << setw(40) << ftext << endl;
}

void format_text(string& ftext)
  // Give the string of text from the file the function displays the contents                                                                                                                                          
  // so that the first letter of each word is capitalized and each follow word                                                                                                                                         
  // is lower case.                                                                                                                                                                                                    
{
  int wlength;// length of the word inputted from the file                                                                                                                                                             
  wlength = ftext.length();
  if (isalpha(ftext[0]))
  ftext[0] = toupper(ftext[0]);
  for ( int i=1; i < wlength; i++)
    ftext[i] = tolower(ftext[i]);

}

int alphacount(string filetext)
// will count the amount of alphabetical letters in the data file                                                                                                                                                      
{
  int lettertotal = 0; // total amount of letters in the datafile                                                                                                                                                      
  for (int i = 0; i < filetext.length(); i++)
      if ( isalpha(filetext[i]))
         lettertotal++;
         return lettertotal;
}


double charcount(string filetext)
// will calculate the amount of characters within the file and return to                                                                                                                                               
// main file                                                                                                                                                                                                           
{
  int numofchars = 0;// number of characters within file                                                                                                                                                               
  int sum = 0;// variable to determine exact amount of characters                                                                                                                                                      
  for (int i = 0; i < filetext.length(); i++)
    {
    if ( filetext != " ")
      numofchars++;

    }
  sum = sum + numofchars;
  return sum;
}

int consonantcount(string filetext)
// will determine amount of consonants  within the datafile and return to                                                                                                                                              
// main function                                                                                                                                                                                                       
{

char letter; // each alphabetical character in data file                                                                                                                                                             
  int vowelcounter=0;// number of vowels within data file                                                                                                                                                              
  int constotal = 0;// number of consonants within data file                                                                                                                                                           
  for (int i = 0; i < filetext.length(); i++)
    {
      letter = toupper(filetext[i]);
      switch(letter)
        {
          case 'a':
          case 'e':
          case 'i':
          case 'o':
          case 'u':
        case 'A':
        case 'E':
        case 'I':
        case 'O':
        case 'U':
            vowelcounter++;
          break;
        }
      if  ( isalpha(filetext[i]))
        constotal++;
    }
  constotal = constotal - vowelcounter;
  return constotal;
}


int sentencecount(string filetext)
// Will count the number of sentences within the data file and return to the                                                                                                                                           
// main function                                                                                                                                                                                                       
{
  int sentcount = 0; // amount of sentences within file                                                                                                                                                                
  for (int i = 0; i < filetext.length(); i++)
    {
      if (filetext[i] == '.' || filetext[i] == '?' || filetext[i] == '!')
        sentcount++;
    }
  return sentcount;
}

Halide hangs during Normalized Cross Correlation

I'm trying to implement normalized cross correlation in Halide.

The code below builds, and Halide JIT compilation doesn't throw any errors. However, Halide seems to hang after JIT compilation. No matter how many trace_* calls I put on different Funcs, only one trace ever prints (on Func output):

Begin realization normxcorr.0(0, 2028, 0, 2028)
Produce normxcorr.0(0, 2028, 0, 2028)

Any advice at all would be helpful.

This algorithm is meant to be equivalent to CV_TM_CCOEFF_NORMED in OpenCV, and normxcorr2 in MATLAB:

void normxcorr( Halide::ImageParam input,
                Halide::ImageParam kernel,
                Halide::Param<pixel_t> kernel_mean,
                Halide::Param<pixel_t> kernel_var,
                Halide::Func& output )
{
    Halide::Var x, y;
    Halide::RDom rk( kernel );

    // reduction domain for cumulative sums
    Halide::RDom ri( 1, input.width() - kernel.width() - 1, 
                     1, input.height() - kernel.height() - 1 );

    Halide::Func input_32( "input32" ),
             bounded_input( "bounded_input"),
             kernel_32( "kernel32" ),
             knorm( "knorm" ),
             conv( "conv" ),
             normxcorr( "normxcorr_internal" ),
             sq_sum_x( "sq_sum_x" ),
             sq_sum_x_local( "sq_sum_x_local" ),
             sq_sum_y( "sq_sum_y" ),
             sq_sum_y_local( "sq_sum_y_local" ),
             sum_x( "sum_x" ),
             sum_x_local( "sum_x_local" ),
             sum_y( "sum_y" ),
             sum_y_local( "sum_y_local" ),
             win_var( "win_var" ),
             win_mean( "win_mean" );

    Halide::Expr ksize = kernel.width() * kernel.height();

    // accessing outside the input image always returns 0
    bounded_input( x, y ) = Halide::BoundaryConditions::constant_exterior( input, 0 )( x, y );

    // cast to 32-bit to make room for multiplication
    input_32( x, y ) = Halide::cast<int32_t>( bounded_input( x, y ) );
    kernel_32( x, y ) = Halide::cast<int32_t>( kernel( x, y ) );

    // cumulative sum along each row
    sum_x( x, y ) = input_32( x, y );
    sum_x( ri.x, ri.y ) += sum_x( ri.x - 1, ri.y );

    // sum of 1 x W strips
    // (W is the width of the kernel)
    sum_x_local( x, y ) = sum_x( x + kernel.width() - 1, y );
    sum_x_local( x, y ) -= sum_x( x - 1, y );

    // cumulative sums of the 1 x W strips along each column
    sum_y( x, y ) = sum_x_local( x, y );
    sum_y( ri.x, ri.y ) += sum_y( ri.x, ri.y - 1);

    // sums up H strips (as above) to get the sum of an H x W rectangle
    // (H is the height of the kernel)
    sum_y_local( x, y ) = sum_y( x, y + kernel.height() - 1 );
    sum_y_local( x, y ) -= sum_y( x, y - 1 );

    // same as above, just with squared image values
    sq_sum_x( x, y ) = input_32( x, y ) * input_32( x, y );
    sq_sum_x( ri.x, ri.y ) += sq_sum_x( ri.x - 1, ri.y );

    sq_sum_x_local( x, y ) = sq_sum_x( x + kernel.width() - 1, y );
    sq_sum_x_local( x, y ) -= sq_sum_x( x - 1, y );

    sq_sum_y( x, y ) = sq_sum_x_local( x, y );
    sq_sum_y( ri.x, ri.y ) += sq_sum_y( ri.x, ri.y - 1);

    sq_sum_y_local( x, y ) = sq_sum_y( x, y + kernel.height() - 1 );
    sq_sum_y_local( x, y ) -= sq_sum_y( x, y - 1 );

    // the mean value of each window
    win_mean( x, y ) = sum_y_local( x, y ) / ksize;

    // the variance of each window
    win_var( x, y ) =  sq_sum_y_local( x, y ) / ksize;
    win_var( x, y) -= win_mean( x, y ) * win_mean( x, y );

    // partially normalize the kernel
    // (we'll divide by std. dev. at the end)
    knorm( x, y ) = kernel_32( x, y ) - kernel_mean;

    // convolve kernel and the input
    conv( x, y ) = Halide::sum( knorm( rk.x, rk.y ) * input_32( x + rk.x, y + rk.y ) );

    // calculate normxcorr, except scaled to 0 to 254 (for an 8-bit image)
    normxcorr( x, y ) = conv( x, y ) * 127 / Halide::sqrt( kernel_var * win_var( x, y ) ) + 127;

    // after scaling pixel values, it's safe to cast down to 8-bit
    output( x, y ) = Halide::cast<pixel_t>( normxcorr( x, y ) );
}

Any better ways to do calculations using each 2 elements in a vector

I have a very time consuming function, which needs to so some calculation using each 2 elements in a std::vector. The way I am doing now is,

std::vector<int> vec;
for (auto it = vec.begin(); it != vec.end(); ++ it)
  for (auto it2 = vec.begin(); it2 != vec.end(); ++ it2)
    if (it2 != it)
      f(*it, *it2) // the function

I am wondering if there are any other better ways to do this, because this process cost too much time.

Besides, I have tried to use OpenMP to parallelize the outer loop, it works fine when I use std::vector, but if I do similar things with std::map, it returns a segmentation fault.

Thanks.

C++ array to Halide Image (and back)

I'm getting started with Halide, and whilst I've grasped the basic tenets of its design, I'm struggling with the particulars (read: magic) required to efficiently schedule computations.

I've posted below a MWE of using Halide to copy an array from one location to another. I had assumed this would compile down to only a handful of instructions and take less than a microsecond to run. Instead, it produces 4000 lines of assembly and takes 40ms to run! Clearly, therefore, I have a significant hole in my understanding.

  1. What is the canonical way of wrapping an existing array in a Halide::Image?
  2. How should the function copy be scheduled to perform the copy efficiently?

Minimal working example

#include <Halide.h>

using namespace Halide;

void _copy(uint8_t* in_ptr, uint8_t* out_ptr, const int M, const int N) {

    Image<uint8_t> in(Buffer(UInt(8), N, M, 0, 0, in_ptr));
    Image<uint8_t> out(Buffer(UInt(8), N, M, 0, 0, out_ptr));

    Var x,y;
    Func copy;
    copy(x,y) = in(x,y);
    copy.realize(out);
}

int main(void) {
    uint8_t in[10000], out[10000];
    _copy(in, out, 100, 100);
}

Compilation Flags

clang++ -O3 -march=native -std=c++11 -Iinclude -Lbin -lHalide copy.cpp

QPixmap load segmentation fault

I am creating a Qt Console Application on windows 7. I am using Qt 5.3. And currently I have error that make me frustration because of it. Already check on the stackoverflow, but no answers help me.

My problem was when creating a Qpixmap I got error segmentation fault and I don't have any other error information about it.

Here my code :

QString filePath = (directory + xmlReader.attributes().value("relativepath").toString());
QFile _file(filePath);
if (!_file.exists())
{
    qWarning() << "Error : file " << filePath << " does not exist";
    return false;
}

QImageReader imageReader(filePath);
QImage mainImage = imageReader.read();
if(mainImage.isNull())
{
    qWarning() << "Error read image : " << filePath;
    qWarning() << imageReader.errorString();
    return false;
}
QPixmap mainPixmap(QPixmap::fromImage(mainImage));

On the last line of those code that generate the segmentation fault error on my machine. Is there anything i can do to debug this error?

Store pointer to map key

std::map<Key,Value> mymap;
(void)mymap[Key(...)]; // create value if not there
typename std::map<Key,Value>::iterator it = mymap.find(key);
it->second.pkey = &it->first; // store a pointer to the actual key

Is this safe? In other words, is map allowed to copy the key around during insert/erase operations, which would invalidate Value::pkey?

Any C++98 vs C++11 differences on this?

Protocol Buffer: How to print the contents of a field of type 'byte' as hex string?

Is there a way to specify that the Printer class prints fields of type byte as hex string instead of as a byte array (in C++)? (For reference, see the photo and program in this answer - notice the output is a byte array).