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?

How to use INNER JOIN in the scenario?

I have 2 tables:

'Users' Table

id      username  
----    -------- 
0001    user1          
0002    user2          
0003    user3          
0004    user4     

'Friends' Table

user_id  friend_id  friend
-------  ---------  ------
0001     0004       1
0002     0004       1
0005     0004       0

How do I display all user4 friends' name? if in friends table, friend column, 1 indicates they are friend, 0 indicate they are still not friend.

I use INNER JOIN, which looks like this:

SELECT users.username
FROM `users`
INNER JOIN `friends` ON users.id = friends.friend_id
WHERE friends.user_id = 0004
  AND friend = 1;

But what I get is:

user4 and user4 instead of user1 and user2

Can help me?

From stackoverflow
  • SELECT u.username
    FROM Friends f, Users u
    WHERE f.friend = 1 AND 
     ((f.friend_id = @userid AND f.user_id = u.id) OR
      (f.user_id = @userid AND f.friend_id = u.id))
    
  • select u.username
    from friends f, users u
    where f.friend_id='0004' and f.friend=1 and f.id=u.user_id;
    

    Edit: This is the same as:

    select u.username
    from friends f inner join users u on f.id=u.user_id
    where f.friend_id='0004' and f.friend=1;
    
    Simon Hughes : There is no u.user_id field.
    tehvan : thanks for pointing that out. fixed it (and some other things)
    roa3 : I tried all answer. Just change the u.user_id to u.id, its working... But the chris mehrdad and gordon answers not working..
    tehvan : you probably have the id columns set up as text (e.g. varchar). You might want to consider changing them into int(11). Internal IDs are usually stored as int.
  • SELECT users.username
    FROM `users`
    INNER JOIN `friends` ON users.id = friends.user_id
    WHERE friends.user_id = 0004
      AND friend = 1;
    
    roa3 : I tried few times, not working..
    Jarod Elliott : i think the "WHERE" needs to be "friends.friend_id = 0004" instead of user_id
    roa3 : Yup, after I change from friends.user_id to friends.friend_id, its working now.. Thanks a million
  • Are you sure you don't want to link the friends table to the users table on the user_id instead of the friend_id? Then change the where clause to use the friend_id instead of the user_id. There's different ways of formatting the join, but the way your doing it using an inner join looks fine.

    SELECT users.username
    FROM `users` 
    INNER JOIN `friends` ON users.id = friends.user_id 
    WHERE friends.friend_id = 0004   
    AND friend =1
    
  • SELECT u.username
    FROM   Friends f, Users u
    WHERE  f.user_id = u.id
           AND f.friend = 1
           AND f.friend_id = '0004'
    
    roa3 : no need to specify user id 0004??
    Simon Hughes : The @userID can be used as a parameterised query, so you can pass in the '0004' as the parameter. I've modified the select above so you can run it direct. However, you should really be using parameterised queryies to protect against SQL injection attacks. Never append '0004' to your query.
    Simon Hughes : What I mean is, what is someone entered ' OR 1=1 -- You would end up with AND f.friend_id = '' OR 1=1 --0004'
    roa3 : thanks.. I will take care of mysql injection
  • Do you mean like this?

    SELECT u.username
    FROM friends AS f
    INNER JOIN users AS u USING user_id
    WHERE f.friend_id = 0004 AND f.friend = 1
    
  • select U.Username
    from
        Users as U
        inner join Friends as F on U.Id = F.user_id and F.friend = 1
    where
        F.friend_id = '0004'
    

    If the friend table is just a mapping table then you not want to map both ways?

    select U.Username
    from
        Users as U
        left outer join
        (
         select 
          F.user_id as Id
         from
          Friends as F
         where
          F.friend_id = '0004'
         and
          F.friend = 1
    
        ) as Mapping1 on Mapping1.Id = U.id
        left outer join
        (
         select 
          F.friend_id as Id
         from
          Friends as F
         where
          F.user_id = '0004'
         and
          F.friend = 1
    
        ) as Mapping2 on Mapping2.Id = U.id
    
    where
        Mapping1.Id is not null or Mapping2.Id is not null
    
    roa3 : This is too advanced for me. Btw, does your method would be faster(faster in retrieving data) then the others?
    Damien McGivern : I assume you refer to the second query. It's a question of completness if you want the bidirectional lookup then this is so far the only query that does the job. As for speed that will depend on you table field indexes.
  • dmcgiv has an important point that you need to think about if the friend mapping is bidirectional (i.e., if A is friends with B then B is automatically friends with A). You need to check whether the user you're interested in is on either side of the Friends table mapping.

    You can either do it dmcgiv's way, or another way would be to just insert links in both directions into the Friends table when you add a friendship. For example, if user 0004 is friends with user 0006, you would insert into the Friends table:

    user_id | friend_id | friend
    0004    | 0006      |   1
    0006    | 0004      |   1
    

    I don't think you really need a friend column, by the way. Unless there's some reason to track "non-friends" you can just delete the mapping from the Friends table if the friendship ends.

  • select username from users us where us.id in ( select f.[user_id] from users u inner join friends f ON u.id = f.friend_id where f.friend=1)

Attach existing VS.NET 2008 instance that's already debugging as JIT debugger

Is it possible to configure the VS.NET 2008 "Just-In-Time" Debugger dialog to show an existing instance of Visual Studio that's already attached to another process?

The scenario I have is an NUnit unit test that runs another process. When I'm debugging the unit test I want to automatically launch the debugger for the child process it runs as well. I pass a special parameter to the child process and the child calls Debugger.Launch(), which is all fine, but when the JIT debug dialog comes up it doesn't list the existing VS.NET instance - I can only open a new instance, which is quite inconvenient.

From stackoverflow
  • A debugger that's attached to another process, cannot attach to a secondary process. I think it is possible to have a debugger attached to multiple programs (you can debug multiple websites that are part of the same solution for instance).
    Also, you cannot attach more than a single debugger to each process.

    Evgeny : Thanks, but VS.NET CAN debug multiple processes if you go through the Debug, Attach dialog. It just seems that it can't do that through the JIT debug dialog for some reason.

Do you know a GUI designer for YUI or for any other rich javascript library?

The question says it all... We are shopping for a a rich javascript library and are about to choose YUI. The issue of (non)existence of a GUI designer will strongly influence our choice.

From stackoverflow
  • Does the YUI CSS Grid Builder cover what you need?

    flybywire : nice, but too simple
  • Andy,

    Daniel's answer is a good one for YUI CSS Grids. There is no wysiswyg editor that supports YUI widgets afaik, but this article might be of interest if you're a Dreamweaver CS4 user:

    http://www.adobe.com/devnet/dreamweaver/articles/using_yui_widgets.html

    YUI's founder, Thomas Sha, did a lot of work to make YUI's widget's more accessible to Dreamweaver users.

    Aptana has also done a lot of work to make sure that all the big JS kits are well supported. They have a good YUI plugin for 2.6.0 and are working on the 2.7.0 update:

    http://yuiblog.com/blog/2008/10/28/aptana/

    -Eric

How to keep the windows install dialog from popping up in .NET?

When a user installs my application how do I keep User Account Control from producing this dialog? And no I don't want to tell them to disable UAC.

From stackoverflow
  • Your application would need to be certified by microsoft.

  • User Account Control, as it says at the bottom of the dialog, but you don't want to do. No other way. Either that or get it signed/certified? :)

  • You need a code signing digital certificate from a certificate authority like Comodo or VeriSign. It's debatable how useful it is, though, because it only replaces this scary-looking warning with a slightly less scary warning (yellow alert vs red alert) that says "Publisher: " instead of "Unidentified Publisher" and still tells the user only to run it if they trust you.

    I'm somewhat doubtful that the average user really notices the difference between the two warnings.

  • You'd need to design your installation such that it doesn't require administrative access to install, which essentially means that you'll need to install inside the user's home directory instead of ProgramFilesDir and write registry entries only to HKEY_CURRENT_USER. For more details on how do this with a .MSI package, see this article. Inno Setup also has some details on limited user installs.

    I don't think Visual Studio's setup project builder is capable of producing packages that don't require administrator rights to install. In any case, Vista seems to assume that anything that looks like a Setup.exe needs elevation (and results in the prompt).

    Code signing will not remove the prompt, it will only make it say "Program XYZ from Developer Name wants access to your computer" instead of "An unknown program wants access to your computer".

Using the QMDIArea with qt4.4

Hi I'm using the QMdiArea in qt4.4. What I'm doing: If a new project is created, I add a number of subwindows to a QMdiArea. And I'd like to disallow the user to close a subwindow during the runtime. The subwindows should be closed, if the hole application is closed or if a new project is created.

As I have seen in the qt-documentaion, there is no flag to apply this functionality.

How can I do this?

Thanx for your answers.

From stackoverflow
  • Could you sub-class QMdiArea and override the default closeActiveSubWindow/closeAllSubWindows methods to not close the window when user requests it?

  • You'd do this the same as for a top-level window: process and ignore the QCloseEvent it sent. QMdiArea::closeActiveSubWindow/QMdiArea::closeAllSubWindows just call QWidget::close, which sends a closeEvent and confirms that it was accepted before proceeding.

    You can process this event by subclassing QMdiSubWindow and reimplementing QWidget::closeEvent, or by using an event filter to intercept it..

What functional language techniques can be used in imperative languages?

Which techniques or paradigms normally associated with functional languages can productively be used in imperative languages as well?

e.g.:

  • Recursion can be problematic in languages without tail-call optimization, limiting its use to a narrow set of cases, so that's of limited usefulness
  • Map and filter have found their way into non-functional languages, even though they have a functional sort of feel to them

I happen to really like not having to worry about state in functional languages. If I were particularly stubborn I might write C programs without modifying variables, only encapsulating my state in variables passed to functions and in values returned from functions.

Even though functions aren't first class values, I can wrap one in an object in Java say, and pass that into another method. Like Functional programming, just less fun.

So, for veterans of functional programming, when you program in imperative languages, what ideas from FP have you applied successfully?

From stackoverflow
  • Pretty nearly all of them?

    If you understand functional languages, you can write imperative programs that are "informed" by a functional style. That will lead you away from side effects, and toward programs in which reading the program text at any particular point is sufficient to let you really know what the meaning of the program is at that point.

    Back at the Dawn of Time we used to worry about "coupling" and "cohesion". Learning an FP will lead you to write systems with optimal (minimal) coupling, and high cohesion.

  • Not having first-class functions really puts a damper on writing functional programs, but there are a few things that you can do that don't require them. The first is to eschew mutable state - try to have most or all of your classes return new objects that represent the modified state instead of making the change internally. As an example, if you were writing a linked list with an add operation, you would want to return the new linked list from add as opposed to modifying the object.

    While this may make your programs less efficient (due to the increased number of objects being created and destroyed) you will gain the ability to more easily debug the program because the state and operation of the objects becomes more predictable, not to mention the ability to nest function calls more deeply because they have state inputs and outputs.

  • Here are things that get in the way of doing FP in a non-FP language:

    • If the language doesn't support lambda/closures, and doesn't have any syntactic sugar to easily mostly hack it, you are dead in the water. You don't call map/filter without closures.
    • If the language is statically-typed and doesn't support generics, you are dead in the water. All the good FP stuff uses genericity.
    • If the language doesn't support tail-recursion, you are hindered. You can write implementations of e.g. 'map' iteratively; also often your data may not be too large and recursion will be ok.
    • If the language does not support algebraic data types and pattern-matching, you will be mildly hindered. It's just annoying not to have them once you've tasted them.
    • If the language cannot express type classes, well, oh well... you'll get by, but darn if that's not just the awesomest feature ever, but Haskell is the only remotely popular language with good support.
  • I've successfully used higher-order functions a lot, especially the kind that are passed in rather than the kind that are returned. The kind that are returned can be a bit tedious but can be simulated.

    All sorts of applicative data structures and recursive functions work well in imperative languages.

    The things I miss the most:

    • Almost no imperative languages guarantee to optimize every tail call.

    • I know of no imperative language that supports case analysis by pattern matching.

WinForms Accept Button Annoyance

I have a base panel class that has (among other things) three buttons. I use subclasses of this base class in two different config dialogues. Both dialogues have an OK button set as the accept button.

In one of the dialogues, if I click one of the buttons in the base class, focus immediately returns to the OK button, so pressing the enter key works as expected.

In the other dialogue, focus remains wth the button in the base class that was clicked if it is enabled, or moves to the next button if the clicked button is no longer enabled.

There is no code that handles the base class button click events in either of the derived classes.

Ideas anyone?

From stackoverflow
  • i don't know what language you are using, but the button class should have a focus method that will highlite it for enter pressing. in the click method, or when you open the dialog you can call this method to make the button you want get the form's focus

    c#
    myButton.Focus();
    
  • I'm not sure what's going on in your first dialog because it doesn't seem to be operating the way I would expect it to. The second dialog sounds more like the standard behavior.

    In Windows Forms, the AcceptButton property only comes into play when pressing Enter doesn't otherwise cause any actions. In both of your examples, clicking on a button should move the focus to that button, and subsequently pressing Enter would cause another click on that button.

    In any event, I think it's generally preferable to stick with the Windows user interface guidelines and not automatically change the input focus back to the OK button. If the user clicks on one of the other buttons, the focus should stay there until they move it.

c:import or c:url - specify a timeout value

Hi,

I would like to use c:import or c:url to grab the contents of a page (adserver). In addition, I need to specify a timeout, and if the call either times out or the page is not accessible I need some default text to be returned as my value.

Is there a jstl tag lib to do this? Or do I need to create my own?

From stackoverflow
  • Kind of.

    c:import opens a socket to the server and simply returns what the connection does (raw html in your case). If the server returns the page that is a 404 then that is what will be displayed, a 500 then you get the error page for that.

    Becasue it is a socket then it has access to all the socket errors. For a timeout:

     java.net.ConnectException: Operation timed out
    

    Unknown host:

     java.net.UnknownHostException: www.googasdasdasdassdle.com
    

    This means that you can wrap your import in a catch statement and handle right there on the page.

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    <c:catch var="socketExceptionVariable">
        <c:import url="www.googasdasdasdassdle.com"/>
    </c:catch>
    
    <c:if test="${socketExceptionVariable != null}">
        <p>There was an error here</p>
        <c:out value="${socketExceptionVariable}"/>
    </c:if>
    

    If the import happens then it works as intended, but if something (anything) goes wrong then your error page is displayed.

    You could write your own import tag but that encapsulates this but its a fair bit of work compared to this solution.

    Hyposaurus : PS you might want to fix your tag jstltimeout to be two actual words.

Different methods to use a class/struct - C++

struct Foo
{
    void SayHello()
    {
     std::cout << "Hi, I am Foo";
    }
};

I have the above given struct. I have seen a usage like this in one of our code base.

Foo foo;
{
     foo.SayHello();
}

IMO, It does same like

Foo foo;
foo.SayHello();

Or is there any advantage/difference for the first method?

Any thoughts?

From stackoverflow
  • Did you by any chance mean that your first option is

    {
      Foo foo;
      foo.SayHello();
    }
    

    That would make more sense because then the foo object is created, used, and destroyed within the smaller scope of the curly braces that wrap it. That is a common practice that aims to reduce the lifetime of transient things. Often, these sub-blocks can be refactored into separate functions.

  • In that particular case, it looks quite strange and like a candidate for review. Can be useful in other cases:

    Foo foo;
    {
        ReturnValue v = foo.SayHello();
        Send(v);
    }
    ...
    

    Where it would limit the scope of v. One common use is to make the objects in it destroy earlier. Classes that do special stuff in their constructor and destructor can then be used inside the braces:

    Foo foo;
    {
        MutexLocker locker(sendMutex);
        ReturnValue v = foo.SayHello();
        Send(v);
    }
    ...
    

    The lock for the send-queue would be held while sending v in that example, and be released when the locker is destroyed at the closing brace.

    Appu : That makes perfect sense. Thanks litb.
  • Identical as written (as far as I can tell).

    As other people have said, that construct is usually used to limit scope of something, but in your example, there's no difference.

  • There's no difference in the two examples. The following, however, would create and destroy the foo object within the scope of the braces:

    {
        Foo foo;
        foo.SayHello();
    }
    

    This is useful for objects that follow the RAII idiom.

How does zooming, panning and rotating work?

Using OpenGL I'm attempting to draw a primitive map of my campus.

Can anyone explain to me how panning, zooming and rotating is usually implemented?

For example, with panning and zooming, is that simply me adjusting my viewport? So I plot and draw all my lines that compose my map, and then as the user clicks and drags it adjusts my viewport?

For panning, does it shift the x/y values of my viewport and for zooming does it increase/decrease my viewport by some amount? What about for rotation?

For rotation, do I have to do affine transforms for each polyline that represents my campus map? Won't this be expensive to do on the fly on a decent sized map?

Or, is the viewport left the same and panning/zooming/rotation is done in some otherway?


For example, if you go to this link you'll see him describe panning and zooming exactly how I have above, by modifying the viewport.

Is this not correct?

From stackoverflow
  • Generally there are three steps that are applied whenever you reference any point in 3d space within opengl.

    Given a Local point

    • Local -> World Transform
    • World -> Camera Transform
    • Camera -> Screen Transform (usually a projection. depends on if you're using perspective or orthogonal)

    Each of these transforms is taking your 3d point, and multiplying by a matrix.

    When you are rotating the camera, it is generally changing the world -> camera transform by multiplying the transform matrix by your rotation/pan/zoom affine transformation. Since all of your points are re-rendered each frame, the new matrix gets applied to your points, and it gives the appearance of a rotation.

  • All of these "actions" can be achieved using model-view matrix transformation functions. You should read about glTranslatef (panning), glScalef (zoom), glRotatef (rotation). You also should need to read some basic tutorial about OpenGL, you might find this link useful.

  • They're achieved by applying a series of glTranslate, glRotate commands (that represent camera position and orientation) before drawing the scene. (technically, you're rotating the whole scene!)

    There are utility functions like gluLookAt which sorta abstract some details about this.

    To simplyify things, assume you have two vectors representing your camera: position and direction.

    gluLookAt takes the position, destination, and up vector.

    If you implement a vector class, destinaion = position + direction should give you a destination point.

    Again to make things simple, you can assume the up vector to always be (0,1,0)

    Then, before rendering anything in your scene, load the identity matrix and call gluLookAt

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt( source.x, source.y, source.z, destination.x, destination.y, destination.z, 0, 1, 0 );
    

    Then start drawing your objects

    You can let the user span by changing the position slightly to the right or to the left. Rotation is a bit more complicated as you have to rotate the direction vector. Assuming that what you're rotating is the camera, not some object in the scene.

    One problem is, if you only have a direction vector "forward" how do you move it? where is the right and left?

    My approach in this case is to just take the cross product of "direction" and (0,1,0).

    Now you can move the camera to the left and to the right using something like:

    position = position + right * amount; //amount < 0 moves to the left
    

    You can move forward using the "direction vector", but IMO it's better to restrict movement to a horizontal plane, so get the forward vector the same way we got the right vector:

    forward = cross( up, right )
    

    To be honest, this is somewhat of a hackish approach.

    The proper approach is to use a more "sophisticated" data structure to represent the "orientation" of the camera, not just the forward direction. However, since you're just starting out, it's good to take things one step at a time.

    Thomas : Let me add that at no point the "viewport" (as set through glViewport) comes into this process. The viewport determines into what region of your window you will render (this is not actually true, but think of it this way for now) and will usually span the entire window.

How do I call a C++ static library from Perl?

I'm writing a C++ static library that needs to be shared among several applications, one of them written in Perl. Unfortunately, I only barely know the core Perl language (I read the Llama book), and I'm not all that familiar with its libraries. How do you make calls to an external C++ binary from a Perl script?

By Google search, I found information on the Perl Inline module, but if I understand it correctly, that isn't what I need. I'm pretty sure that's for writing C and C++ code directly in your Perl scripts, not for calling external C++ libraries.

The C++ static library is being cross-compiled for an ARM processor, so there will be no C++ compiler on the target machine where the Perl script will be running. (If that makes a difference.)

From stackoverflow
  • Probably not what you're thinking, but how about writing a stand-alone C++ program that the perl program communicates through pipes with?

    Bill the Lizard : That's my backup plan.
  • You need to create a wrapper function that is callable from perl, and AFAIK, you'll need to have this wrapper function be in a dynamic library (unless you're going to rebuild the perl binary and link the static lib to it). I like to use a tool called SWIG (Simple Wrapper Interface Generator) to create the wrappers for me. It can create wrappers for 17 or so other languages too.

  • You want to look at using XS, which is how Perl normally interfaces with C/C++ libraries. It's not quite trivial. A couple of relevant portions of the Perl documentation:

  • You can call code from other libraries via Inline::C (and likely the same via Inline::CPP) - have a look at Inline::C::Cookbook. Most likely you want to start out with Inline and after you're done experimenting use the resulting .XS file to work further.

  • First, it does need to be in a dynamic library, not a static library (unless you'll be re-compiling perl itself and linking it against your static library).

    Second, since C++ will mangle the names (one of the most annoying "Features" of C++ if you ask me) you'll need an extern "C" block that contains hook functions. If you were using C++ you could probably get by with a single hook function that returns the C++ object that implements the interface you need to use. Since you're using perl, you may need to wrap an object in an interface like this:

    CPPObject object;
    
    extern "C"
    {
    
    int InitObject( void )
    {
      return object.init();
    }
    
    int DoCoolStuff( void )
    {
      return object.DoCoolStuff();
    }
    
    int DoOtherCoolStuff( int foo )
    {
      return object.DoOtherCoolStuff( foo );
    }
    
    int DestroyObject( void )
    {
      return object.Destroy();
    }
    
    }
    
  • I'm only starting to wrap my head around XS, so I can't offer much help. But here's what I do know...

    There is XSpp, which is XS for C++. It is distributed with WxPerl. WxPerl is under active and responsive development.

    Inline:CPP can be used to write your initial interface/wrapper code. Then you can analyze the generated XS. However, it doesn't look so well maintianed. If it works, it may provide you with a good head start.

    You might find this short note on XS and C++ by John Keiser helpful, if a bit dated.

What would cause ASP.NET validators not to trigger on a deployed site?

Locally it works, I know its the "it works on my machine" syndrome but i cant see why.

Simple web page, fields, required field validators, such as

<asp:textbox id="tbEmail" runat="server" CssClass="field"></asp:textbox>              <asp:requiredfieldvalidator id="Requiredfieldvalidator2" runat="server" Display="Dynamic" ControlToValidate="tbEmail" ErrorMessage="Email is required" CssClass="required"></asp:requiredfieldvalidator>

button with

<asp:button id="btnSendRequest" runat="server" Text="Submit" CausesValidation="True"></asp:button>

Locally it triggers and the code doesnt run, on the deployed version the validators dont fire and the code runs.

Should be simple but ive been staring at it for too long.

Thanks people - Tariq

From stackoverflow
  • I'm not sure if this is relevant for your version of .NET but you might have to run aspnet_regiis -i on the server to install the scripts for validation. Double-check this, please, before doing anything :)

    I hope this sends you in the right direction.

    http://msdn.microsoft.com/en-us/library/k6h9cz8h(VS.80).aspx

    cdonner : The scripts are only required for client-side validation, and I don't see that in his code. I had problems with aspnet_regiis -i not installing the scripts in the past, and had to install them manually, though.
    Henk Holterman : @cdonner: an asp:requiredfieldvalidator should validate both client-side and server-side.
  • I was thinking the same thing - the asp_regiis will create the aspnet_client folder in the root of your site. Also watch for javascript errors being reported, they will help in the diagnosis.

  • In a situation like this, I find it helpful to compare the raw HTML output you get locally with the output on the deployed server. You are probably missing the validation javascript on the deployed version, as Eric pointed out... but this will tell you for sure.

  • The difference might be that on your local test you are getting the client side validators triggered and on the server only the server side. Make sure you add an IsValid if to your method, like:

    void MyClickHandler(object sender, EventArgs e)
    {
       if( IsValid)
       {
          //rest of the code
       }
    }
    
  • Install Fiddler: Fiddler and watch the traffic. Is it getting any 404 or 500 HTTP errors while loading your page? It's probably trying to load the necessary client-side validation files but running into problems.