Friday, April 8, 2011

How do I fix my while Error?

I'm writing a program in Microsoft Visual Studio with C++ that will retrieve information from a .txt file. In that file there are negative numbers, but when I try to write a while loop that states what to do if there is a negative number, I get several errors.

Can someone please help me with this? Here is my code and I do realize there are errors but I can't figure out how to write the While loop statement to read these values which are hours worked and the hourly rate from the .txt file

Sample text file:

45.0    10.50
-35.0   7.75
50.0    12.00
45.0   -8.50
30.0    6.50
48.0    -10.25
-50.0   10.00
50.0    8.75
40.0    12.75
56.0    8.50

Code:

//*****************************
// This program is to help calculate an employee's weekly gross pay as well as
// the net pay while showing the taxes that were taken off.
// The data that will be shown will be calculated from a .txt file 
// that was created and called employee.txt.

// Input:  Will be the inFile known as employee.txt
// Output: Gross pay, taxable income, federal tax, state tax, and net pay

// Typed by:  
// Date:  
//******************************

#include <iomanip>
#include <fstream>
#include <iostream>

using namespace std;

float computeGross(float, float);
void computeTaxes(float, float&, float&, float&);
float computeNetPay (float&, float&, float&, float&);

const float hours = 40;     // Regular 40 hour work week
const float ovTime = 1.5;      // Overtime if hours go over 40
const float exemption = 200.0;    // Exemption  if pay goes over 200
const float fedTaxRate = 0.10;    // Federal Tax Rate
const float stTaxRate = 0.03;     // State Tax rate

ifstream inFile;
ofstream outFile;

int main()
{
    inFile.open("employee.txt");
    outFile.open("result.txt");

    float hours, rate, grossPay, taxableIncome, fedTax, stTax, NetPay;
    inFile >> hours >> rate;

    while(inFile)
    {
        if {
            (hours <= 0)&& (rate <= 0);
            outFile << "Invalid Data";
        }
        else{ 
            return 0;
        }
    }

    grossPay = computeGross(hours, rate);
    computeTaxes (grossPay, taxableIncome, fedTax, stTax);
    computeNetPay (grossPay, fedTax, stTax, NetPay);

    outFile << fixed << showpoint << setprecision(2);
    outFile << "Hours worked = " << hours << endl 
            << "Hourly rate = " << rate  << endl     
            << "Employee's gross pay = " << grossPay << endl
            << "Taxable Income = " << taxableIncome << endl
            << "Federal Taxes = " << fedTax << endl
            << "State Taxes = " << stTax << endl
            << "Net Pay = " << NetPay << endl;
    return 0;
}

float computeGross (float h, float r)     //Computes for the Gross Pay
{
    if (h > hours) 
     return hours * r + (h - hours) * r * ovTime;
    else 
     return h * r;
}
void computeTaxes(float g, float& taxable, float& fedTax, float& stTax) //Computes both Taxes
{
    taxable = g - exemption;

    if (taxable > 0.0)
    {
      fedTax = fedTaxRate * taxable;
      stTax = stTaxRate * taxable;
    }
    else
    {
     fedTax = 0.0;
     stTax = 0.0;
    }
}

float computeNetPay (float& grossPay, float& fedTax, float& stTax, float& NetPay)
{
    return NetPay = grossPay - fedTax - stTax;    
}
From stackoverflow
  • For a start, I think that this:

    if {
        (hours <= 0)&& (rate <= 0);
        outFile << "Invalid Data";
        }
    

    Should be this:

    if ((hours <= 0) && (rate <= 0)) {
        outFile << "Invalid Data";
    }
    

    Note that to get code to format properly on StackOverflow, you should only use spaces, not tabs. I think that's whats causing your format issues.

  • In your main function you have:

    while(inFile)
    {
        if ((hours <= 0) && (rate <= 0))
        {
            outFile << "Invalid Data";
        }
        else { 
            return 0;
        }
    }
    

    When the else is triggered the program finishes, the main function returns. You might want a continue break or nothing here instead, that return statement ends the main function not the While loop.

    To get all the data out of the file your read statement ( inFile >> hours >> rate); will need to be in this or another loop. Say after the IF test for validity, it could be in the Else.

        while(inFile)
        {
             if ((hours <= 0) && (rate <= 0)) {
    
                 outFile << "Invalid Data";
             }
             else { 
                 // call the data functions
                 // save the returned values     
             }
    
            //prime hours and rate for the next loop
            inFile >> hours >> rate;
        }
    
    Thomas : Then he'd end up with a never-ending while loop, because the reading of the data does not happen inside the loop. That's something else in need of fixing.
    Paxic : You don't need anything at this point, the continue is just a way to make a loop go to the next iteration. If you put nothing in the else you should be fine.
    Paxic : Good call on the continue, I'll strike that out!
    Paxic : @Thomas thanks for that heads up
  • Well.. my guess is this is what your looking for:

    Note that the:

    if ((hours <= 0) && (rate <= 0))
    

    is changed to:

    if ((hours <= 0) || (rate <= 0))
    

    otherwise it won't ever hit the "invalid data" with your supplied data

    //*****************************
    // This program is to help calculate an employee's weekly gross pay as well as
    // the net pay while showing the taxes that were taken off.
    // The data that will be shown will be calculated from a .txt file 
    // that was created and called employee.txt.
    
    // Input:  Will be the inFile known as employee.txt
    // Output: Gross pay, taxable income, federal tax, state tax, and net pay
    
    // Typed by:  
    // Date:  
    //******************************
    
    #include <iomanip>
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    float computeGross(float, float);
    void computeTaxes(float, float&, float&, float&);
    float computeNetPay (float&, float&, float&, float&);
    
    const float hours = 40;        // Regular 40 hour work week
    const float ovTime = 1.5;         // Overtime if hours go over 40
    const float exemption = 200.0;       // Exemption  if pay goes over 200
    const float fedTaxRate = 0.10;       // Federal Tax Rate
    const float stTaxRate = 0.03;        // State Tax rate
    
    int main()
    {
    
        ifstream inFile ("employee.txt");
        ofstream outFile ("result.txt");
    
        float hours, rate, grossPay, taxableIncome, fedTax, stTax, NetPay;
    
        if (inFile.is_open())
        {
            while (! inFile.eof() )
            {
    
                inFile >> hours;
                inFile >> rate;
    
                if ((hours <= 0) || (rate <= 0))
                {
                    outFile << "Invalid Data";
                }
                else
                { 
                    grossPay = computeGross(hours, rate);
                    computeTaxes (grossPay, taxableIncome, fedTax, stTax);
                    computeNetPay (grossPay, fedTax, stTax, NetPay);
    
                    outFile << fixed << showpoint << setprecision(2);
                    outFile << "Hours worked = " << hours << endl   
                            << "Hourly rate = " << rate  << endl        
                            << "Employee's gross pay = " << grossPay << endl
                            << "Taxable Income = " << taxableIncome << endl
                            << "Federal Taxes = " << fedTax << endl
                            << "State Taxes = " << stTax << endl
                            << "Net Pay = " << NetPay << endl;
                }
            }
        }
    
        return 0;
    }
    

    The rest is the same

    Paxic : Nice catch on the AND vs OR.
    Paxic : Do you mean "stdafx.h" ? It is a generated file http://en.wikipedia.org/wiki/Precompiled_header.
    Paxic : You should look for a Clean option in the build menu. Or try deleting the one file or or start a new project and add your hand coded classes to it...
    Paxic : try http://stackoverflow.com/questions/221803/visual-studio-2008-clean-solution-option
    Paxic : First do the Clean, then if that does not work remove the file that you say is there but it cannot find then Clean and Build
    Paxic : If the include is not generated by your VS then comment it out of the code and see what happens
    Paxic : Sometimes you have to start from scratch. Start a new project. Add code a little at a time, add the includes as you need them. You want to debug one bug at a time.
    Paxic : One last thing, I think there will be more io issues, you might need http://www.augustcouncil.com/~tgibson/tutorial/iotips.html - Good Luck
    uzbones : This site is good for a tutorial if you don't understand something with c++ http://www.cplusplus.com/doc/tutorial/files.html Anyway, sorry about the header above the comment, I missed cutting that out when I pasted it here...
    uzbones : I do have to admit though that I compiled it as is above with VS2008... not VS2005 so it may be slightly different syntax if MS did something funny between versions...

I need to generate bookmarks in word 2003 programaticaly based on locations denoted by section number.

I have an HTML page with links that when clicked open to a specific bookmark in a word document. I am working with an existing word 2003 document with no preexisting bookmarks. I want to add bookmarks to all section number header locations using a macro or a VBA script . Example

3.1.4.2 HERE
STUFF
3.1.4.2.1 Here again
MORE STUFF
3.1.4.2.1.1 Here again again
EVEN MORE STUFF
3.1.4.2.2 Here again again again
LOTS MORE STUFF

I want to bookmark all the lines that start with X.X.X... with a standard format for the name.

Example (using above as reference )

3.1.4.2 HERE line would have a book mark named M_3_1_4_2
3.1.4.2.1 Here again would have a book mark named M_3_1_4_2_1

ect.

My question is what approach with a VBA script or a macro would I need to take that would make this happen.

From stackoverflow
  • Adding a bookmark is easy enough if you have the range object already.

    ActiveDocument.Bookmarks.Add Name:=rngBookmark.Text, Range:=rngBookmark
    

    Getting the range is often the difficult task. Now you said these were section headers. Are they actual word section headers? Are they delimited with a certain style? Are they in the body of the document or in page headers?

    You can cycle through the sections of a document like this and set a range to the start of the section.

    Dim sectCurrent As Word.Section
    Dim rngCurrent As Word.Range
    For Each sectCurrent In ActiveDocument.Content.Sections
    
       ' get range that refers to the whole section
       Set rngCurrent = sectCurrent.Range.Duplicate
    
       ' collapse the range to the start of the section
       rngCurrent.Collapse wdCollapseStart
    
       ' expand the range to hold the first "word"
       ' you can also use other units here like wdLine
       rngCurrent.MoveEnd Unit:=wdWord, Count:=1
    
       ' now that you have the range you can add the bookmark
       ' you can process the range and create your own name with a custom function GenerateBookmarkName.  To get the string, just use rngCurrent.Text.
       ActiveDocument.Bookmarks.Add Name:=GenerateBookmarkName(rngCurrent), Range:=rngCurrent
    
    Next sectCurrent
    

    Now if they aren't actual sections, you'll often want to use the Find object to find something in the document and loop through all such items. The trick here is to know what to search for. An example loop is below.

       ' setup range object for search results
       Set rngFind = ActiveDocument.Content
    
       ' cycle through search results looking for whatever
       With rngFind.Find
    
          ' search text
          .Text = "FINDME"
          .Format = False
          .Wrap = wdFindStop
    
          ' loop while find is successfull
          Do While .Execute
    
             ' get range you can modify based on found item
             ' each time you call .Execute rngFind is changed to the found text
             Set rngModifyMe = rngFind.Duplicate    
    
    
          Loop
    
       End With
    

    For more word vba help, you can vist the word MVPs site here: http://word.mvps.org

  • Hi I tried to create a bookmark using hese code, i tried using wdLine instead wdWord since i want to select a particular range of lines for a bookmark. Can you just help me wat parameters to give for these

When is it appropriate to use C++ exceptions?

I'm trying to design a class that needs to dynamically allocate some memory..

I had planned to allocate the memory it needs during construction, but how do I handle failed memory allocations? Should I throw an exception? I read somewhere that exceptions should only be used for "exceptional" cases, and running out of memory doesn't seem like an exceptional case to me..

Should I allocate memory in a separate initialization routine instead and check for failures and then destroy the class instance gracefully?

Or should I use exceptions instead? The class won't have anything useful to do if these memory allocations should fail..


EDIT: The consensus seems to be that running out of memory IS an exceptional case.

Will see how to go about this.. Thanks.. :)

From stackoverflow
  • The usual behaviour in C++ when you are out of memory is to throw an exception. The built-in new operator does this by default.

  • I would argue that running out of memory (particularly heap memory) is an exceptional case, and if your class - and further, your application - cannot continue, I think exception throwing/handling is a very appropriate and graceful approach.

  • Assuming you are using new to allocate memory, and are not overriding the new operator, it will automatically throw the std::bad_alloc exception if it fails to allocate memory properly.

    I read somewhere that exceptions should only be used for "exceptional" cases, and running out of memory doesn't seem like an exceptional case to me..

    Running out of memory seems like a pretty exceptional case to me :)

    It is very difficult to handle this sort of situation. You may want to return a meaningful error to the user of your application, but if it's a problem caused by lack of memory, you may not even be able to afford the memory to allocate the error message. It's a bit of a catch-22 situation really.

    There is a defensive programming technique (sometimes called a memory parachute or rainy day fund) where you allocate a chunk of memory when your application starts. When you then handle the bad_alloc exception, you free this memory up, and use the available memory to close down the application gracefully, including displaying a meaningful error to the user. This is much better than crashing :)

    krebstar : YES! This is the approach I want to do.. thanks :)

What is the best way to print a table with delimiters in Python

I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done:

>>> tab = [['a', 1], ['b', 2]]
>>> for row in tab:
...     out = ""
...     for col in row:
...             out = out + str(col) + "\t"
...     print out.rstrip()
... 
a   1
b   2

But I have a feeling there is a better way to do it in Python, at least to print each row with specified delimiter, if not the whole table. Little googling (from here) and it is already shorter:

>>> for row in tab:
...     print "\t".join([str(col) for col in row])
... 
a   1
b   2

Is there still a better, or more Python-ish, way to do it?

From stackoverflow
  • I don't think it's going to get much better than your second code snippet... maybe, if you really want,

    print "\n".join("\t".join(str(col) for col in row) for row in tab)
    
  • Your shorter solution would work well as something quick and dirty. But if you need to handle large amounts of data, it'd be better to use csv module:

    import sys, csv
    writer = csv.writer(sys.stdout, delimiter="\t")
    writer.writerows(data)
    

    The benefit of this solution is that you may easily customize all aspects of output format: delimiter, quotation, column headers, escape sequences...

    Brian : As it stands though, that solution will probably do many things you wouldn't expect. It will double-up quotes in your input, for example. Embedded quotes are treated by "quoting" the whole string, which may or may not be what you want.
    Brian : (continued) If all that is desired is simple tab delmited data, with no danger of embedded tabs, the basic approach is probably easier to get right, rather than figuring the appropriate dialect to use with the csv module.
    ketorin : Excellent, cvs was exactly what I was looking for. I need to go through documentation, but I think the things I would not expect may very well be what I want anyway.
  • import sys
    import csv
    
    writer = csv.writer(sys.stdout, dialect=csv.excel_tab)
    tab = [['a', 1], ['b', 2]]
    writer.writerows(tab)
    
    J.F. Sebastian : `dialect` should be either `'excel-tab'` or `csv.excel_tab` but not `'csv.excel_tab'`
  • Please do not use concatanation because it creates a new string every time. cStringIO.StringIO will do this kind of job much more efficiently.

    recursive : str.join is efficient already.
  • It depends on why you want to output like that, but if you just want to visually reference the data you might want to try the pprint module.

    >>> import pprint
    >>> for item in tab:
    ...     pprint.pprint(item, indent=4, depth=2)
    ...
    ['a', 1]
    ['b', 2]
    >>>
    >>> pprint.pprint(tab, indent=4, width=1, depth=2)
    [   [   'a',
            1],
        [   'b',
            2]]
    >>>
    

WebForm_SaveScrollPositionSubmit is undefined - ASP.NET

I'm upgrading an ASP.NET 1.1 app and have things working but am seeing the Javascript error referenced in the title. From research it appears that ASP.NET is not spitting out the javascript that is used to maintain scroll position between postbacks.

I did some googling and have checked the various issues mentioned but can't seem to find what might be going on.

Environment details:

  • IIS 6 on Win Server 2003
  • The virtual directory is running ASP.NET 2.0.50727
  • I have set maintainScrollPositionOnPostBack="True" in the section of web.config

Any ideas?

From stackoverflow
  • Do you have any httphandlers or httpmodules that do any kind of request filtering or re-writing ? or anything special in global.asax that would prevent the javascript from coming down ? I would guess that something is blocking the built in axd request to get the javascript that deals with WebForm_SaveScrollPositionSubmit.

    To find out for sure fire up Fiddler and watch the HTTP requests and make sure they are all happening correctly.

    Also make sure there is at least 1 and only 1 form on the page.

Cannot render image to HttpContext.Response.OutputStream

Basically I am trying to render a simple image in an ASP.NET handler:

public void ProcessRequest (HttpContext context)
{
    Bitmap image = new Bitmap(16, 16);
    Graphics graph = Graphics.FromImage(image);

    graph.FillEllipse(Brushes.Green, 0, 0, 16, 16);

    context.Response.ContentType = "image/png";
    image.Save(context.Response.OutputStream, ImageFormat.Png);
}

But I get the following exception:

System.Runtime.InteropServices.ExternalException: A generic error
occurred in GDI+.
    at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder,
    EncoderParameters encoderParams)

The solution is to use this instead of having image write to OutputStream:

MemoryStream temp = new MemoryStream();
image.Save(temp, ImageFormat.Png);
byte[] buffer = temp.GetBuffer();
context.Response.OutputStream.Write(buffer, 0, buffer.Length);

So I'm just curious as to why the first variant is problematic?

Edit: The HRESULT is 80004005 which is just "generic".

From stackoverflow
  • I believe the problem is that the Response.OutputStream does not support seeking. In order to save a PNG (or JPEG), the image object needs to be able to write the output non-sequentially. If I remember correctly, it would have worked if you saved the image as a BMP since that image format can be written without seeking the stream.

    Serguei : I tried that actually but the result turned out the same.
  • From the look of it, it appears that you are trying to create a graph of some kind. Is this just to be rendered on a page within a div? If so, I would think you might be able to do something like this. Basically take the image object that is created and add that as a control to an existing div or placeholder in the code...

    Bitmap image = new Bitmap(16, 16);
    Graphics graph = Graphics.FromImage(image);
    graph.FillEllipse(Brushes.Green, 0, 0, 16, 16);
    this.myGraphPlaceholder.Controls.Add(graph);
    
    Serguei : Not really. This is an implementation of IHttpHandler and the consumer is a non-ASP.NET app.
  • Ok I used a wrapper for Stream (implements Stream and passes calls to an underlying stream) to determine that Image.Save() calls Position and Length properties without checking CanSeek which returns false. It also tries to set Position to 0.

    So it seems an intermediate buffer is required.

  • The writer indeed needs to seek to write in the stream properly.

    But in your last source code, make sure that you do use either MemoryStream.ToArray() to get the proper data or, if you do not want to copy the data, use MemoryStream.GetBuffer() with MemoryStream.Length and not the length of the returned array.

    GetBuffer will return the internal buffer used by the MemoryStream, and its length generally greater than the length of the data that has been written to the stream.

    This will avoid you to send garbage at the end of the stream, and not mess up some strict image decoder that would not tolerate trailing garbage. (And transfer less data...)

    Serguei : Good catch, thanks! MSDN says pretty much the same thing about GetBuffer(): http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx
  • Image.Save(MemoryStream stream) does require a MemoryStream object that can be seeked upon. The context.Response.OutputStream is forward-only and doesn't support seeking, so you need an intermediate stream. However, you don't need the byte array buffer. You can write directly from the temporary memory stream into the context.Response.OutputStream:

    /// <summary>
    /// Sends a given image to the client browser as a PNG encoded image.
    /// </summary>
    /// <param name="image">The image object to send.</param>
    private void SendImage(Image image)
    {
        // Get the PNG image codec
        ImageCodecInfo codec = GetCodec("image/png");
    
        // Configure to encode at high quality
        using (EncoderParameters ep = new EncoderParameters())
        {
            ep.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
    
            // Encode the image
            using (MemoryStream ms = new MemoryStream())
            {
                image.Save(ms, codec, ep);
    
                // Send the encoded image to the browser
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ContentType = "image/png";
                ms.WriteTo(HttpContext.Current.Response.OutputStream);
            }
        }
    }
    

    A fully functional code sample is available here:

    Auto-Generate Anti-Aliased Text Images with ASP.NET

Do you use UML diagrams to aid your development process?

So what are the UML diagrams (if any) Stackoverflow has been using for documentation and/or for communication with developers?

From what I see, Stackoverflow is something original that also provides rich user experience.

Just wondering what does it take (what helps) to realize a great thought into real life? I`m just a student graduating seeking for advice/experience/suggestions/examples from senieors.

How much these diagrams help in real life and in what volume (the diagrams), I wonder...

From stackoverflow
  • I really expect all my co-workers to be able to read a UML diagram properly; it's become a kind of universal language for speaking about OO designs.

    Back in the days of big design we made tons of models that we put in big binders. Especially sequence diagrams were really nice for detailed designs. These binders would look really impressive on some shelf, but it turned out most of the value in these models are in the process of making them

    So now we mostly just draw boxes with lines between them on whiteboards. But whenever we resort to explicit notations to be precise, it's always UML. Usually we photograph them with our phone if they seem like they're worth keeping. Sometimes we just leave them on the whiteboard because they kind-of burn into the whiteboard if they stay there for some days ;) [And you have to be especially daring to use the smelly strong cleaner]

    annakata : I'm of the opinion every project should be UML documented/designed but this has rather collided with my real world experience which has been general groans and negativity. Not unlike the subject of unit-testing now that I think of it...
    Marcin Gil : Yeah, UML "sucks" in terms that people don't want to do them, don't have time to do them, someone isn't allowing them to do them.. but this might also go to overall 'documentation' topic.. :)
  • My bet is that they didn't use any UML.

  • UML is a "standard" defined way to communicate something. Being well defined it removes ambiguities that may exist when using other methods.

    Having said that I don't use them with my team. I find that the overhead in doing proper UML is too high.

    Since I work in a small team (about 5 people) that works in the same location, we'll often sit down and sketch diagrams in discussions. If we need to reference these diagrams, we'll scan them and post them to a repository for later reference.

    UML is probably more beneficial in teams that don't communicate well, and may not be co-located.

  • I read an article in Inc Magazine about this site, which is how I found out about it. Apparently very little formal process was followed. Basically, the guys who did it were just really good. My money is also on no UML. I wonder if they use OO?