Tuesday, April 5, 2011

Login to windows xp programatically

Anyone heard that its possible to login to windows xp programatically, I want to modify the way the Domain Controller authenticates the user and if the user authenticated in my special way it returns the user name and password to the service working on the client machine so it should login the user using its passed credentials from the DC without waiting for user to insert his original credentials.

From stackoverflow
  • Have a look at this: Gina.dll MSDN

    Gina is the system that fingerprint readers etc. use to customise the login screen. You may be able to use this to achieve your purpose?

    To future proof your app (Vista and Windows 7) you may wish to look into these: MSDN Mag Vista Credential Providers

    Spence : Cheers, I had always wondered how the hell windows allowed a fingerprint to substitute for a 3 finger salute so I looked it up one day... ;)
    netseng : Thanks Man, I exactly want to login using fingerprint.

Returning Rows from a .NET Web Service

I am using a .NET web service as an interface to a database. What is the best way to return rows from this web service?

I vaguely remember that .NET 2.0 had issues with returning DataTable objects. Do those issues still exist?

Update: Some of the issues in .NET 1.1. Also, I believe that in 2.0 the DataTable is deserialized as a DataSet object on the client side. Am I correct?

From stackoverflow
  • You're effectively trying to do the job of ADO.net? You much better off returning POCO (plain old c# objects) which you can serialize efficiently to send down soap then pull them back out at the other side. Perhaps you could give us some more information in your question as to what your trying to do.

    DataRows and DataTables haven't changed in .net 3.0. If you want to use the entity framework to pass things around though you will run into different trouble. If they are rows, have a look at using Linq, and serializing then passing row entities as a collection. There are ways to reconstruct the entities into a data context on the client side so that the references link back up etc.

    Vulcan Eager : My web service fetches records from a database. I merely want to return the rows to the client. Returning a DataSet/DataTable should work but I've heard bad things about them back in .NET 2.0. Do any similar issues exist in .NET 3.0?
    Gerrie Schenck : What are those "bad things" actually? Performance?
    Vulcan Eager : No. Here are some links I found: http://support.microsoft.com/kb/306134 and http://bytes.com/groups/net-web-services/376326-possible-return-datatable-webservice-method These apply to .NET 2.0. How are in 3.0?
    Gerrie Schenck : That KB article applies to .Net 1.0 and 1.1. I use datatables with webservices a lot, and never had any problems.
  • I would agree with Spence. With a web service you create a contract with the client. This contract should not be broken just because you want to change the shape of your database. I would create a class that matches the table structure and return a "list of" objects of this structure. Then, when the datamodel changes you can maintain this interface and create a second service method that matches the new structure.

What does the EXE do in the Visual Studio setup project output

We are working on a winforms app in Visual Studio 2005 and the setup project we created output both an MSI and an EXE. We aren't sure what the EXE file is used for because we are able to install without the EXE.

From stackoverflow
  • It's a bootstrapper that checks to make sure that the .NET Framework is installed, before launching the MSI. It's pretty handy.

    I suggest using something like SFX Compiler to package the two together into one self-extracting .exe and then launch the extracted setup.exe. This way you retain the benefits of the bootstrapper, but your users only download a single thing.

    Edit: also see

    Ruben Bartelink : link is broken, any replacement available (simple google didnt yield anythign, but then I didnt know what to look for :P)
    Ruben Bartelink : Anyone know of an SFX compiler that'll work without a GUI?
    Ruben Bartelink : can you also point out that the setup.exe automates the download and install of the prereqs
    loraderon : I'm using Make SFX http://74.cz/en/makesfx/ instead since it supports command line (for automatic builds)
  • I think the EXE is just a wrapper/bootstrapper for the MSI in case you don't have Window Installer. If you have the requisite Windows Installer version installed then the MSI should work fine on its own.

    Ruben Bartelink : it also does auto download of WI and other packages like .NET
  • The EXE checks if Windows Installer 3.0 is present and downloads and installs it if it's not. It's needed only for Windows 2000 or older. Windows XP and newer all have Windows Installer 3.0 out of the box.

    Other prerequisites, like .NET, are checked for by the MSI itself.

    Marek : not true, the bootstrapper checks for all specified prerequisites, including .NET

jQuery - Edit a table row inline

Hi,

I have a table with arbitrary columns and rows. This fact is irrelevant though really, all I want to do is develop a function that will turn a row (or multiple rows) into a series of text inputs containing the data in the table (or empty if no data in cell).

I can't find any examples of people explicitly doing this, so I wondered what people here think is the best way to find a solution.

Thanks :)

From stackoverflow
  • Iterate over the table cells in the rows, and replace the contents with text inputs:

    function editRow(row) {
        $('td',row).each(function() {
             $(this).html('<input type="text" value="' + $(this).html() + '" />');
        });
    }
    

    You need to pass the relevant row/rows into the function obviously.

    Héctor Vergara R. : What happens if cell content has html entities?
    Eran Galperin : I answered it in the simplistic way you described it. I usually use a hidden input with the data in raw form, and load up the text input with that.

How do I automate unit tests for a console application in TeamCity?

I've written a console application that has a number of unit tests and I'm wanting to include it in my nant build script so that it will be run on our TeamCity CIS.

Unfortunately I'm not quite sure how to do that. The nant script has examples of current projects that have been added...they they all have to supply the assemblies that need to be tested. ie MyProject.dll But my console app doesn't have anything like that since it compiles into MyProject.exe

There must be a way to automate these tests since I'm able to run the unit tests from within Visual Studio without issue.

Does anyone know if and how this is possible?

From stackoverflow
  • What Test framework do you use for those tests? You've mentioned Visual Studio, I may guess it is mstest. TeamCity added support for MSTest starting from 4.0 for sln2008 build runner.

    Could you please have a look to a full list of supported .NET unit test frameworks at http://www.jetbrains.net/confluence/display/TCD4/.NET+Testing+Frameworks+Support

    Any way, have a look to custom unit tests integration manual pages at http://www.jetbrains.net/confluence/display/TCD4/Build+Script+Interaction+with+TeamCity

    mezoid : Well technically this question has been answered by Gishu (http://stackoverflow.com/users/1695/gishu) in the first comment to the question. I'm just waiting for him to write his comment up as an answer before I accept someone's answer...
  • I've just noticed xUnit tag. xUnit supports TeamCity. Please refer to http://www.codeplex.com/xunit/WorkItem/View.aspx?WorkItemId=4278 for more details.

    mezoid : I must admit I've only heard about xUnit.net recently. Typically I use the tag xUnit to mean one of the members of a family of unit testing frameworks ie MBUnit, JUnit, NUnit etc...I guess that'll have to change now... but to what? *Unit? LOL
  • The answer to this question is that you add the name of the executable in the same place you add the list of DLL assemblies. The set of unit tests is compiled into the executable instead of into a separate dll file.

    Gishu is the one who should take credit for this answer...since he answered me via a comment...however, I'm wanting to mark this question as answered so I'm writing up the answer so others can benefit from the solution.

    Gishu, if you ever come back to this question, please feel free to write up your comment as an answer and I'll change the accepted answer to yours.

    Gishu : The answer is here... that's all that matters. Your intent is appreciated. Thanks.
    mezoid : No worries! :) Thanks for helping me out on this problem!

Did you get any good out of collaborative editors usage?

Hello, today I was looking for a free collaborative code editor for Mac OS X, I don't really need it but I find the idea pretty charming. So I want to know you opinion about that: is there someone in real world who is using a collaborative code editor and gets some benefits out of it?

From stackoverflow
  • We use it over the Internet when discussing code via Chat/VoIP. Something along:

    A: "If we change this to be an Integer the function gets much simpler" (Edit)

    B: "Niftiy, but then we have to change it here, too" (Edit)

    A: ...

  • If you're pairs programming it is very useful. The approach can be discussed and everyone can drive when they have ideas. I can't say I've had the privilege of using this at work.

    mdorseif : I would say if you are using two computers for pair-programming you aren't pair-programming.
  • I've found it fairly useful when putting together packing/todo/etc lists with my wife while at work. We use google docs, which isn't quite realtime, but it is definitely better than emailing back and forth throughout the day.

  • Anyone else who used collaborative text editors like SubEthaEdit or Gobby?

delphi 7 SOAP application stop compiling

Hello there,

I don't know why, but a SOAP Server application and a pair of clients of this services stop compiling without any know causes for me. I have installed delphi 2007 and delphi 2009 and I don't know if the cause can come from this.

Now when I compile a soap application I get an error like: 'Unit XMLSchema was compiled with a different version of XMLDOM.SHttp'

Someone known the cause?

From stackoverflow
  • Remove all the dcus and try a build all. In case your compile with both d2007 and D2009, be sure to have different folders for the compiled code...
    Make sure also that you don't have a "mixmatch" of D2007 and d2009 path to reference the used units.

  • I think this will not be suficient because this error is raised with new projects too.

    Lars Truijens : You are mixing the same unit of different Delphi versions. Francois is right. Find out why you are mixing them. And please do not use multiple accounts. And please use comments for these type of...well..comments
    Argalatyr : @Lars: he needs 50 rep to leave a comment (of course, it will be hard for him to get there with multiple accounts!)
    Argalatyr : @FrancisR: I know you can't leave a comment, but answers should strictly be used to answer the question. In this case, it would be better to Edit your original question (starting the new text with "EDIT:") and address an answerer, e.g. "@Francois: I think this will not..."
    Lars Truijens : @Argalatyr: You can always comment your own posts according to http://stackoverflow.com/questions/132017/how-do-comments-work-in-stackoverflow of course that won't work if you use multiple accounts
  • At end I found where was the problem. This come from a free library from codebot.org which contains another version of xmldom.pas

    Thank you and regards

    P.D. I will try to refund my accounts.

Assign function result to a table variable

The SQL Server (2000/2005) function gets 'table name' and 'field name' as a parameter and returns results from a dynamic query within the function. The results should be assigned to a Table variable which will be used further in a Stored procedure. How to achieve this?

I am getting error: "Only functions and extended stored procedures can be executed from within a function."

Code:

Declare @Data as table (FieldValue varchar(100)) insert into @Data select * from MyFunction ('Person.Address','AddressID')

-- Function

Alter function MyFunction ( @TableName varchar(100), @FieldName varchar(100) ) returns @GetData table ( FieldValue varchar(100)

) as begin Declare @SQL varchar(250) Set @SQL = 'Select '+@FieldName+ ' from '+ @TableName Exec sp_executesql @SQL return end

From stackoverflow
  • I'm not sure how this works with functions, but if you have a Stored Procedure that returns a resultset, you can insert that into a table variable using INSERT EXEC statements.

    INSERT @TableVariable
    EXEC spYourProcedure
    

    As long as the fields match that will work. Otherwise you can use:

    INSERT @TableVariable (FieldInSp1, FieldInSp2)
    EXEC spYourProcedure
    

    This way you can pass data between stored procedures. See this page on INSERT EXEC Statements for some extra information.

  • You can't use "exec" in a user defined function. UDFs must be side effect free.

Assigning a list of atoms in Scheme

I'm trying to learn Scheme from the book "The Little Schemer" using DrScheme on a Macintosh. It starts with things like "What is the car of l where l is the argument (a b c)?"

I understand that the answer to this question is a, but I'm not able to actually figure out what to type into Dr Scheme to "follow along". A simple idea on how to assign to l such as > (def l ('a 'b 'c))

gives me the error: "function call: expected a defined name or a primitive operation name after an open parenthesis, but found something else"

From stackoverflow
  • Try this:

    (define l '(a b c))
    

    Here, the quote applies to the whole list (a b c).

    Leonard : Error message: def: name is not defined, not a parameter, and not a primitive name
    Kyle Cronin : It's supposed to be "define" not "def", see my answer for more info: http://stackoverflow.com/questions/464057/assigning-a-list-of-atoms-in-scheme#464072
    Greg Hewgill : er, I was just following your example. Changed to 'define'.
  • Or, just use

    (car '(a b c))
    

    What the error is telling you is this: when the reader sees a list, it wants to treat the first element of the list as a function. That's how (+ 1 2 3) works: it invokes hthe function +. (Strictly, it looks at the symbol '+ and finds that there is a function bound to that, then invokes that function.)

    So, when you type

    (define l ('a 'b 'c))
    

    it looks at the inner list and then wants to find a function. Instead it find s the symbol named a. Since there isn't a function there, you get the error. If, instead, you type

    (define l '(a b c))
    

    you've told the reader via the quote that it's to treat that as a list without trying to interpret it.

    Here's an example from MIT Scheme on a Mac:

    1 ]=> (define li '(a b c))
    
    ;Value: li
    
    1 ]=> (car li)
    
    ;Value: a
    
    1 ]=> (car '(a b c ))
    
    ;Value: a
    
    Kyle Cronin : > then wants to find a function named a [...] Strictly speaking, that's not true. Even if you had a function named a it would still be an error because it's not looking for the value a, but attempting to use the symbol a. It's always an error to try to use a symbol as an operator.
    Charlie Martin : True enough. it was late.
  • To define something:

    (define <name> <value>)
    

    So to define l:

    (define l '(a b c))
    

    This defines l as the list (a b c). The single quote mark quotes whatever is after it, whether it's a symbol or a list, which means it's not evaluated but read as-is. You don't, however, quote the name that you're setting it to. Thankfully, this is one of the very small number of operations in Scheme where you have this inconsistency.

    Leonard : This works after I change the language selected from "Beginning Student" to "Beginning Student with list abbreviations". Thanks.
    Kyle Cronin : I use DrScheme quite a bit, but the student limitations are just stupid. Instead of telling you you're using a more advanced feature, it just throws an error. My suggestion would be to avoid the student stuff and just use the unabridged Scheme. Use Module and preface all your files with #lang scheme
    Leonard : Um, sounds good but I can't get this to work. I get the error message: standard-module-name-resolver: collection not found: "scheme" in any of: (# #)
    Kyle Cronin : Sorry, I thought you were using a newer copy of DrScheme! With version 4 they standardized on the Module language; for earlier versions I would suggest using Pretty Big (or upgrading).
    Kyle Cronin : The largest compatibility issue with version 4+ is the removal of set-car! and set-cdr!. They were "replaced" with set-mcar! and set-mcdr!, and can only operate on a "mutable" pair, created with mcons (as opposed to cons). As long as you're mindful of this change you should be all set.
    soegaard : > I use DrScheme quite a bit, but the student limitations > are just stupid. The student limitations are a god sent gift, when teaching from HtDP. If you are not following HtDP, then don't use the teaching languages - use the module language instead and start your file with #scheme
  • Non-abbraveted form of

    (define l '(a b c))
    

    is

    (define l (quote (a b c)))
    

    or in this case even this:

    (define l (list 'a 'b 'c))
    

    without a "list" part it tries to execute 'a, obviously

Complex databinding to DataGridView header text

Is there a way to complex databind to a column's header text? Or is the only way to manually set the values and listen for change events from the source?

For the record, I've tried both

MyDataGrid.DataBindings.Add("Columns[<columnIndex>].HeaderText",MySource,"MyProperty");

and

MyDataGrid.DataBindings.Add("Columns[\"ColumnName\"].HeaderText",MySource,"MyProperty");

to no avail, and neither DataGridViewColumn and DataGridViewColumnHeaderCell have a DataBindings property.

From stackoverflow
  • No, the column headers don't support data binding, since it is understood that this metadata will be (largely) static.

    In this case, I would simply do it manually, as you propose (read from a property and subscribe to an event to update the column header).

    For more complex requirements (for completeness only), you can take more control if you write your own PropertyDescriptor implementation, exposed by either TypeDescriptionProvider or ITypedList - or even better, an IBindingList implementation where you raise ListChanged events of type ListChangedType.PropertyDescriptorChanged; however any of these is a significant amount of work, and it simply isn't worth it just for what you are suggesting.

Using java (desktop) codebase in a webapp

I have a rather large (80k loc) java desktop app that talks to a database. We're now looking at exposing some parts of the database via a web application, using the existing codebase and preferably not having to modify it.

I have good separation between the data access, business logic and presentation layers, but we haven't used enterprise java beans or anything like that (if that's important).

What's the best way forward? Which of the java web frameworks will be best suited to the problem? Learning curve isn't terribly important, since I haven't done any java development on the web...

From stackoverflow
  • To be true, it depends what you already have, and how well is the design of your current desktop application. You might not be able to use any or may be minimal of your existing code without modifying it, if its designed badly, and everything is tightly coupled.

    Assuming that you are having a system with a good design, everything is de-coupled well enough. You can look into Stripes to make your presentation for the web, and use your existing data access and business code. I wish you all the luck.

    Few other goodies to look into are, Groovy on Grail, Wicket.

    I don't recommend anything like Seam and Spring they are more of a container and sophisticated large frameworks, which give you almost everything, solution for almost all of your problems. As you mentioned that you already have a complete system, and you just need to make a web interface to publish it for the web, these are not recommended, IMO.

    JSF, is a good framework, but it might drive you nuts and has a big learning curve, according to few folks.

    SCdF : "I don't recommend anything like Seam and Spring they are more of a container and sophisticated large frameworks" JSF is in that boat as well imo
    Adeel Ansari : Hmm... may be. But IMO, JSF doesn't try to answer all your questions, and rather stick to the presentation layer. Moreover, it doesn't really work like a container, like Seam and Spring IoC. As far as, the term sophisticated goes, I tend to agree.
    rjohnston : Thanks for the pointer to Stripes - looks like the most straight-forward option at the moment. As I said, the code is very well separated, I expect to be able to reuse all of the access code, and the majority of the logic code (all of it with a little refactoring)...
  • The two frameworks I would recommend would be Grails and Struts 2.

    Grails comes with a whole bunch of stuff that it configures under the covers including Hibernate and Spring. It makes generating dynamic pages to send to the browser ridiculously easy. What you are probably going to need to do is set up controllers that call Grails services which reference your existing code as you probably don't want Grails managing your database interactions. The disadvantage with Grails is not so much that it is written in Groovy, which is easy to learn for Java programmers, but that the IDE support for Groovy is still maturing. Still if you want quick productivity this is the route to go down.

    Struts 2 offers a clean command pattern framework implementation that talks to JSPs (or velocity or FreeMarker templates) on the front end. To use this you would configure actions to call your existing code. You may want to investigate adding Spring to the mix depending on what you need to do.

    There are other choices but these are two that I have had some success with.

Inserting HTML as a last child of a selected tag using JQuery

I am new to JQuery. I'm reading JQuery in action, but only up to page 39 and need some quick help!

Please note: I'm simplifying my actual requirement, so what I'm asking for may sound odd but I'm just tryin to get to the crux of the JQuery expression and not my situation (related to an animation plugin).

I have my HTML code (which is generated and I dont want to change) :

<div class="favorite">
   <div>
          <a href='http://www.stackoverflow.com'>Stackoverflow</a>
   </div>
</div>

Now that I want to do is insert the text '(favorite)' INSIDE the A tag after the current contents. Or in other words as the last child of the <a>.

<div class="favorite">
   <div>
          <a href='http://www.stackoverflow.com'>Stackoverflow (favorite)</a>
   </div>
</div>

The best I have so far is this :

$('<span> (favorite)</span>').insertAfter('.favorite div a');

Of course this ends up putting the (favorite) text OUTSIDE the A link and it wont be underlined (which I want).

I need to somehow say .parent().lastChild() but I'm not quite sure how to do that.

Note: I had to put <span> in because otherwise it didnt see it as 'insertable' text. I'm sure there a way around that too but thats a secondary concern.

From stackoverflow
  • The append method inserts nodes at the end of match elements. Prepend inserts nodes at the beginning.

    Example:

    $('div.favorite div a').append('<span> (favorite)</span>');
    

    The span element isn't necessary - you can just do this:

    $('div.favorite div a').append(' (favorite)');
    
    Simon_Weaver : oops! I had actually tried append and it appeared to do NOTHING. turns out this is because my animation was relying on a css selector for '.favorite div a' which contains 'display:none'. So it was workin but instantly vanishing itself. thanks
    Simon_Weaver : plus in addition i had got the two clauses the wrong way round - which was key. so i had only almost got it working
  • You can also do:

    $("div.favorite div a").text($("div.favorite div a").text() + " (favorite)");
    
    Simon_Weaver : thats making my head spin :)
    Birk : haha, yeah, but it *is* an option :)

Quickie - replace all occurences of ' (apostrophe) with '' (two apostrophes) in an AnsiString (C++)

I think you can guess the problem I'm having. I'm inserting filenames in to an sql database in C++ Builder. Some files have an apostrophe in their name. This breaks the sql insert query. the usual way to fix this is to double up and apostrophes you want to be part of the field value.

For example if I want to add 'george's' to field 'owner' the sql query would be "insert into table (owner) values ('george''s')"

I'm ok with that bit. I just need to get the single apostrophes replaced with double ones. AnsiString doesn't seem to have a built in function for this. Is there a simple way to do it without having to include a whole new header file?

From stackoverflow
  • I haven't used AnsiString, but basically I'd do the following:

    • Reverse find single quotes in your string
    • Look to the left and right of the current single quote index
    • If there's not a single quote there already, insert a single quote after your current index
    • Continue looping until you hit index 0.
    MrVimes : I was posting my own answer before I saw yours. but thanks anyway.
    Rob Kennedy : That's OK if you just want to make sure no apostrophe is bare, but it's no good if you actually want to preserve the data. A double-apostrophe will become a single apostrophe upon insertion in the database, and it won't be re-doubled upon selection, so you won't know what was originally inserted.
  • Actually I got the answer by myself...

    item = StringReplace( item, "'", "''", TReplaceFlags() );

    (so there is a built in replace function in AnsiString afterall)

    Ray : Am I missing something, but wouldn't that make double apostrophes triple apostrophes as well?
    MrVimes : Don't know. One way to find out. I'll put a double quote in a filename and see what happens... It seems to work fine. It turns double quotes into quadrouple quotes, which would preserve the double quotes in the database.
    MrVimes : So I guess it will always give an even number of quotes (every quote is turned into two), which would always 'work' in the database.
    MrVimes : p.s. the correct syntax for what I'm doing is... item = StringReplace( item, "'", "''", TReplaceFlags()<
  • The usual way to do this is to use prepared statements as opposed to generating your own sql. Look up SQL Injection for one reason why this is bad. Basically, if anywhere in your app, you forget to double up the quotes in any sql statement, and an attacker can somehow submit a value into that sql statement, your database is hacked. (See this xkcd comic for a humourous example of what can happen.)

    MrVimes : Can you explain that? My filenames are being generated in real time so I need to insert them one at a time after the name has been aquired. how do I do prepared statements?
    MrVimes : SQL Injection. What I'm doing is for my own use so nobody else will be able to see it. But I'll read up on SQL Injection anyway as I may one day be doing lots of sql for a website.
    Eclipse : The actual details will depend on your database API that you are using. Look through it for something like prepared statements or parameterized queries.
  • In C++ Builder, you're looking for the AnsiQuotedStr function, in SysUtils. Its inverse is AnsiExtractQuotedStr. They aren't methods of the AnsiString type itself because they don't need intimate knowledge of the type's internals.

    More importantly, though, you should be using parameterized queries. If the components you're using for database access don't support those, then get a different database library. There is no shortage of database choices, so you can afford to be picky about features, and parameterized queries should be near the top of the list.

    Note that despite their names, the AnsiX functions accept UnicodeString parameters, not AnsiString, in Delphi and C++ Builder 2009.

  • What happens if you substitute it like that

    item = StringReplace( item, "'", "\'", TReplaceFlags() );
    
    MrVimes : I get an SQL error.
    Riho : OK. Also it should be possible to use ", like that : values("O'Malley's")

return statement vs exit() in main()

Should I use exit() or just return statements in main()? Personally I favor the 'return' statements 'cause I feel it's like reading any other function and the flow control when I'm reading the code is smooth (in my opinion). And even if I want to refactor the main() function, having 'return' seems like a better choice than exit().

Does exit() do anything special that 'return' doesn't?

Thanks for your time!

From stackoverflow
  • In C, return in main will return to the _start function in libc which will call main and after that invokes exit system call, so there's no special difference. I prefer return as it's more stylish.

    FreeMemory : This isn't entirely correct when dealing with C++. Or rather, your comment is correct, but incomplete.
    Mehrdad Afshari : @FreeMemory True, I edited my comment to specify "In C," explicitly.
    brone : Nit-pick alert, but this is target-specific -- there is no requirement that there be anything, let alone with a particular name, that calls main. The compiler seems free to treat returns from main as special (according to my reading of the standard anyway).
    Mehrdad Afshari : Yes, it was just an example, but it's nevertheless the same, whatever the name of _start be, and even if the main would be a special function, somehow the compiler should inject the exit after it. It doesn't make much difference here though.
  • I always use return because the standard prototype for main() says that it does return an int.

    That said, some versions of the standards give main special treatment and assume that it returns 0 if there's no explicit return statement. Given the following code:

    int foo() {}
    int main(int argc, char *argv[]) {}
    

    G++ only generates a warning for foo() and ignores the missing return from main:

    % g++ -Wall -c foo.cc
    foo.cc: In function ‘int foo()’:
    foo.cc:1: warning: control reaches end of non-void function
    
    Jason Baker : I don't know about C, but the C++ standard specifies that if you don't return a value in main, it's assumed to return 0.
    Jason Baker : It seems as though C99 is the same: http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?id=1043284376&answer=1044841143
    d0k : C99 and C++ return 0 if there is no return statement, C90 doesn't.
  • Even though there is not much of a difference, i strongly prefer return to keep the natural flow of an application.

  • Actually, there is a difference, but it's subtle. It has more implications for C++, but the differences are important.

    When I call return in main(), destructors will be called for my locally scoped objects. If I call exit(), no destructor will be called for my locally scoped objects! Re-read that. exit() does not return. That means that once I call it, there are "no backsies." Any objects that you've created in that function will not be destroyed. Often this has no implications, but sometimes it does, like closing files (surely you want all your data flushed to disk?).

    Note that static objects will be cleaned up even if you call exit(). Finally note, that if you use abort(), no objects will be destroyed. That is, no global objects, no static objects and no local objects will have their destructors called.

    Proceed with caution when favoring exit over return.

    http://groups.google.com/group/gnu.gcc.help/msg/8348c50030cfd15a

    Arkadiy : abort() exits with error condition (non-zero exit code) and may be even a core. If you need to exit w/o calling static destructors, use _exit .
    FreeMemory : @Arkadiy **Absolutely.** abort signals some error condition. And, stylistically, I usually also use exit() to signal an error condition, and return 0 from main to indicate normal termination.
    Mike Koval : From the exit() manpage: 2. Flush all open output streams. It sounds like any open output streams would be flushes regardless of whether the appropriate destructor is called.
  • Another difference: exit is a Standard Library function so you need to include headers and link with the standard library. To illustrate (in C++), this is a valid program:

    int main() { return 0; }
    

    but to use exit you'll need an include:

    #include <cstdlib>
    int main() { exit( EXIT_SUCCESS ); }
    

    Plus this adds an additional assumption: that calling exit from main has the same side effects as returning zero. As others have pointed out, this depends on what kind of executable you're building (i.e., who's calling main). Are you coding an app that uses the C-runtime? A Maya plugin? A Windows service? A driver? Each case will require research to see if exit is equivalent to return. IMHO using exit when you really mean return just makes the code more confusing. OTOH, if you really do mean exit, then by all means use it.

Is there a good browser based sandbox to practice regex?

I am looking for recommendations for a browser based regex sandbox to practice some proof of concept expressions.

From stackoverflow
  • I've used http://www.rubular.com/ a few times, seems to do the job.

  • I like RegExPal.com. Good luck.

  • Try NRegEx.

  • This one's pretty good too: RegExr

    John Sheehan : Also has a downloadable AIR app which is nice
  • http://demo.1060research.com/ep+name@app_regular_expression_cookbook

  • For online sandboxes for several different languages, platforms, and open source applications, see this similar SO question.

  • Which flavor? Regex support is included in most of the major programming languages in use today, in editors and IDE's, in command-line tools like grep and findstr, and lots of other places. Every one of these tools/languages/applications has its own regex flavor, and no two flavors are completely alike.

    For the regex flavor of a specific programming language, I just Google for "<language> regex tester"; there always seems to be at least one online tester available.

  • I'm biased of course because I wrote it. But there's a good one for .NET regular expressions called Regex Hero.

  • I wrote my own Regular Expression (REGEX) Online Test Sandbox with a Match and Replace feature since I could not find one with a Replace feature. It's running under a DOT NET (.NET) Engine. Great for testing Regex patterns, but also good for quick and dirty reformatting of text files and strings.

    http://regex.cyberpine.com

  • This is fairly handy for .net based stuff:

    http://regexlib.com/

Python - Doing absolute imports from a subfolder

Hi,

Basically I'm asking the same question as this guy: http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python

But no one gave him a correct answer. Given that you are inside a subfolder and you want to go up a directory and then into ANOTHER subfolder, doing what they suggested does not work (as the OP pointed out in his comments to their answers).

I know that you can do this by using sys.path, but I would prefer a cleaner method.

Example:

App
__init__.py
Package_A
--__init__.py
--Module_A.py
Package_B
--__init__.py
--Module_B.py

How would I import Module_A into Module_B?

From stackoverflow
  • If I'm reading correctly, in Python 2.5 or higher:

    from ..Module_B import Module_B
    

    I thought I was well-versed in Python but I had no idea that was possible in version 2.5.

    bobince : That's correct. It's a bit ugly though, and absolute imports are generally the best thing except in special circumstances.
    ryeguy : THis doesn't work I get "attempted relative import in non-package"
    bobince : The statement is assumed to be inside Module_A.py (and, post-edit, should be from ..Package_B.) relative imports are based on the package path of the module you are inside, not directories; you can't use them from a top-level script or simple module.
  • If you are then importing Module_B in to App, you would

    Module_B.py: import ModuleA

    App.py (which also imports ModuleA which is now by default in your Pythonpath)

    import Module_B.Module_B
    

    Another alternative, is to update __init__.py (the one in Module_A/App folder) to:

    import os
    import sys
    sys.path.extend('%s../' % os.getcwd())
    import ModuleA
    

    Another alternative, is to add your folder to the PYTHONPATH environment var.

    Aaron Gallagher : Modifying `sys.path` at runtime is nearly always wrong. It's fragile and indicates a badly-structured package.
    Nick Stinemates : I definitely agree.
  • main.py
    setup.py
    app/ ->
        __init__.py
        package_a/ ->
           __init__.py
           module_a.py
        package_b/ ->
           __init__.py
           module_b.py
    
    1. You run python main.py.
    2. main.py does: import app.package_a.module_a
    3. module_a.py does import app.package_b.module_b

    Alternatively 2 or 3 could use: from app.package_a import module_a

    That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then.

    So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.

Does Microsoft.ServiceModel.Web only work in GAC?

Hi guys,

I created my first WCF RESTful service with just one GetData so I can try, and it works perfectly in localhost, but when I add it to a hosting environment, I get:

Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0234: The type or namespace name 'ServiceModel' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)

Does this means that I need to place the dll in the GAC to this work? Shouldn't work in the BIN forlder of my Service?

Here is how my service folder looks like:

Service.svc
Service.svc.cs
web.config
BIN
  Microsoft.ServiceModel.Web.dll
  Microsoft.ServiceModel.Web.pdb
  MyService.dll
  MyService.pdb
PROPERTIES
  AssemblyInfo.cs

What can I do in order to make this working?

From stackoverflow
  • EDIT: Removed erroneous answer

    blowdart : No. ServiceModel.Web is part of the REST starter kit/Dynamic Data. It's *not* a System namespace.
  • I had the same problem when I first tried to create a virtual directory directly in IIS 7.5, prior to publishing my RESTful web service to this folder.

    The solution for me was to use Visual Studio 2008 (Project Properties / Web tab / "Use IIS Server") to choose the folder, and then the "Create Virtual Directory" button on the same tab to create the virtual directory. Everything then worked OK.

UnicodeEncodeError with BeautifulSoup 3.1.0.1 and Python 2.5.2

With BeautifulSoup 3.1.0.1 and Python 2.5.2, and trying to parse a web page in French. However, as soon as I call findAll, I get the following error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1146: ordinal not in range(128)

Below is the code I am currently running:

import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen("http://fr.encarta.msn.com/encyclopedia_761561798/Paris.html")
soup = BeautifulSoup(page, fromEncoding="latin1")
r = soup.findAll("table")
print r

Does anybody have an idea why?

Thanks!

UPDATE: As resquested, below is the full Traceback

Traceback (most recent call last):
  File "[...]\test.py", line 6, in <module>
    print r
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1146-1147: ordinal not in range(128)
From stackoverflow
  • Here is another idea. Your terminal is not capable of displaying an unicode string from Python. The interpreter tries to convert it to ASCII first. You should encode it explicitly before printing. I don't know the exact semantics of soup.findAll(). But it is probably something like:

    for t in  soup.findAll("table"):
        print t.encode('latin1')
    

    If t really is a string. Maybe its just another object from which you have to build the data that you want to display.

    Martin : It works! :D But what do you mean by "Your terminal is not capable of displaying an unicode string from Python.". I am running my script inside IDLE (Python Shell). This should work, isn't it?
    unbeknown : A terminal has to tell the Python interpreter what characterset it uses. Usually this is done through an environment variable. I don't know how this is handled by IDLE.
    bobince : print repr(t) is also useful. It's generally a good idea to repr() stuff you're outputting for debugging purposes so you can see exactly the type and any top-bit-set or control characters lurking in there, as well as not making your debug code throw more spurious exceptions.

A PHP API for retrieving Mail From Yahoo, GMail, Hotmail

Hello all,

There are a few APIs for grabbing the address book/contact list from the major providers of email.

I was wondering do APIs like this exist for grabbing emails/messages received?

Thanks all

EDIT

I am sure I can do this myself. However, I don't want to "re-invent" the wheel if someone has done it already. Probably better than I can since I am just a noob :P

From stackoverflow
  • I think all of this services provide POP/IMAP protocol which you can acces with PHP's functions: http://si.php.net/manual/en/book.imap.php

    Till : You might also want to check out the email related classes in PEAR, ezComponents and ZendFramework.

weird IE 7 javascript problem

I have this javascript code working in firefox, chrome, and safari

for (idx in all_auction_ids){
    alert(all_auction_ids[idx]);
};

for the above, instead of getting the values in all_auction_ids, the first value I get is text of type function that looks like a for loop!

But if I run the code below, it works fine.

for (idx=0;idx<all_auction_ids.length;idx=idx+1){
    alert(all_auction_ids[idx]);
};

edit: updates

I did some debugging and found out that, adding Orbited and stomp.js is probably doing something with the array!

for now i am using Tracker1's suggestion jquery's $.each.

more info: http://groups.google.com/group/orbited-users/browse_thread/thread/7fd658cfb166e9fa

array with the problem http://bayimg.com/fAnhaAaBb

array without the problem http://bayimg.com/FaNhEAabb

From stackoverflow
  • JavaScript's for/in construct is traditionally for iterating over object member names, not array indices. The more forward-thinking browsers have added features like hidden properties to help cases like Array enumerate in the way you would expect, but IE stilll does it the old-school way and gives you Object members like the 'toString' method when you use for/in over an Array.

    The indexed-for is still the canonical JavaScript array loop. (Although you probably mean 'for (var idx=...', and 'idx++' is more common.)

    Prestaul : I agree that the "for(var i = 0..." method is preferable for an indexed array, but IE has always supported the "for(var i in..." iterator because an Array object is just an object with an auto-increment feature after all.
    mark : yeah!, IE should support for in , this is weird right?
    Prestaul : @kevin: Not "should", DOES! There is something else going on here and I don't think we've been given enough detail yet...
    Prestaul : @bobince, when was the last time you saw IE return 'toString' using for/in on an Array? I don't think I've ever seen this, going back to IE5...
    bobince : Hmm, you're right, seems toString has been gone for a while. However there is also the chance something could have added to Array.prototype... actually if you're running one of those JavaScript frameworks that just loves spraying methods into prototypes it's a certainty.
    Prestaul : @bobince, that is certainly true. @mark (@kevin?), are you using any javascript libraries (e.g. jQuery, Prototype.js, Mootools, something homegrown)?
  • I agree with @bibince that you probably should be using the "for(var i = 0..." syntax, but there is no reason that the syntax you chose should not work unless you have done something strange in your creation of all_auction_ids. How are you initializing your array?

    Arrays in JavaScript are just objects with a special auto-incrementing feature, but in reality they are not much different that an anonymous object. Try this in Firebug:

    var a = ['a','b','c'];
    a.d = 'd';
    for(var i in a) console.log(i, a[i]);
    

    or paste this into your address bar in IE and hit enter:

    javascript:var a = ['a']; a.d = 'd'; for(var i in a) alert(a[i]); alert(a.length);
    

    EDIT:

    I doubt this is your problem, but do you have the same problem if you use:

    var all_auction_ids = [];
    

    rather than

    var all_auction_ids = new Array();
    

    If that doesn't help then could you post a little more of your code to give us a better idea of how you are populating all_auction_ids?

    mark : Prestaul: I have this problem only in IE (both 7 and 8) not in firefox. all_auction_ids = new Array(); and i add data to it this way. all_auction_ids.push(id); it works well in safari/ffox
    Prestaul : @kevin: I've updated my post. I think that I would start by changing the declaration to var all_auction_ids = []; and removing the semi-colon after the for block. That probably isn't your problem but we might need more detail to figure it out.
    Prestaul : Also, you might add a "var"... i.e. "for(var idx in..."
  • It's worth noting that some libraries such as prototype.js extend Array, so that they have additional properties beyond the internal indexes. This breaks for x in y notation beyond, as other mentioned, that IE will iterate properties. for i=0...i++ is preferred.

    Also worth noting is jQuery, prototype and others offer a .each(fn) notation that I actually prefer.

  • This topic on the YUI blog is germane to your problem.

  • I've been having similar problems lately creating "select all / clear all" buttons for lists of checkboxes. In Firefox and Chrome they work fine, but in IE7/8 they don't. I'm not using any frameworks or external libraries, all the JavaScript is my own, it's fairly straightforward stuff, and there isn't much of it. I build the array of input elements using getElementsByTagName, then loop through:

    var allClearInputs = document.getElementsByTagName("input");
    for(ac=0;ac<allClearInputs.length;ac=ac+1){
        if(allClearInputs[ac].id){
            var thisNameArr = allClearInputs[ac].id.split("-");
            var thisName = thisNameArr[0];
            if(thisName == checkName){
                if((actionType == 'all' && allClearInputs[ac].checked == false) || (actionType == 'clear' && allClearInputs[ac].checked == true)){
                    allClearInputs[ac].click();
                }
            }
        }
    }
    

    Works perfectly with: for(ac=0;ac<allClearInputs.length;ac=ac+1){
    Fails miserably with: for(var ac in allClearInputs)