答:
It is the difference between having multiple statements which each has to commit and be saved to the transaction log, inserted into the corresponding indexes (if any) and having a single statement (though very long).

However, this is conjecture.

It is possible that during the first set of inserts, the database server was under high load, and during the second set, it wasn't.

You really need to benchmark both (several runs of each, resetting the DB each time, taking averages etc...).

Title: What's the difference between the insert methods and why one is faster

Body:
I have insert 14.485 lines on MySQL like this:

```<code>INSERT INTO `bairros` (`id`,`cidade_id`,`descricao`) VALUES (1,8891,'VILA PELICIARI');
INSERT INTO `bairros` (`id`,`cidade_id`,`descricao`) VALUES (2,8891,'VILA MARIANA');
...
</code>```

It took around 5 minutes.

I had to insert in another table 16.021 lines, same database, so for test I did this:

```<code>INSERT INTO `bairros` (`id`,`cidade_id`,`descricao`) VALUES (1,8891,'VILA PELICIARI'),(2,8891,'VILA MARIANA');
...
</code>```

It took just a few seconds.

What is the difference, for the database, between the scripts? And why one is faster than the other?


问:
Are There Realistic/Useful Solutions for Source Control for Ladder Logic Programs
Version control for ladder logic (LL) programs for programmable logic controllers (PLCs) seems to be virtually non-existent. It may be because LL is a visual language and tends to be stored in binary files, or it may be because source code control hasn't "caught on" in process control engineering circles - or perhaps my Google-Fu is weak tonight.

Do you know of any realistic and useful solutions for version control for such systems?

Definitions:

realistic = changes to the programs are tracked by user and subject to reversion and merges

useful = the system integrates with visual LL designers, is not limited to LL from a single PLC manufacturer, and does not cost a ridiculous amount of money?

Note: I have heard of people using SVN or Mercurial et al to track the binary files, but I don't think the diff/merge capabilities would display readable differences.

ADDENDUM:

At first we only had to support Allen-Bradley PLCs. Now we also have Siemens and MicroLogix PLCs. Still searching for a viable solution...

答:
If you can, look at B&R Automation.

Full Disclosure... I work for a sales partner of B&R Automation.

Modern B&R Automation projects work very well with versioning software.  I currently use GIT (which is not integrated), though there is supposed to be integration with SVN in the software.  All of the HMI source is saved as XML, and all of their PLC language sources (including ladder) is saved text based instead of binary (mostly XML as well).  If you have to do manual merges then you do have to "figure out" the XML to some extent, but I did not find it that difficult.  And the automatic merge usually makes that unnecessary anyways.

ContentLicense: CC BY-SA 3.0


问:
What makes C developers so curious if "i++ == ++i"?
Just a random observation, it seems that on StackOverflow.com, there are questions about if "++i == i++". That question gets asked all the time though, I think I saw it asked about 6 or 7 times in the past 2 months.

I just wonder why C developers are so interested in it? The same concept/question exists for C# and Java devs as well, but I think I saw only one C# related question.

Is it because so many examples use ++i? Is it because there is some popular book or tutorial? Is it because C developers just love to cram as much as possible into a single line for 'efficiency'/'performance' and therefore encounter 'weird' constructs using the ++ operator more often?

答:
Most likely because in C, it really matters if you write i++ or ++i when you're doing pointer arithmetic. There, increasing i before or after an operation could be crucial. I'd give you an example but the last time I wrote C was 10 years ago...

In C#, I've never come across a situation that would require me to think about i++ or ++i because AFAIK, for the for/while loops, it doesn't really matter.


问:
Should I take care of race conditions which almost certainly has no chance of occuring?
Let's consider something like a GUI application where main thread is updating the UI almost instantaneously, and some other thread is polling data over the network or something that is guaranteed to take 5-10 seconds to finish the job.

I've received many different answers for this, but some people say that if it is a race condition of a statistical impossibility, don't worry about it at all but others have said that if there's even a 10-53% (I kid you not on the numbers, this is what I've heard) of some voodoo magic happening due to race condition, always obtain/release locks on the thread that needs it.

What are your thoughts? Is it a good programming practice to handle race condition in such statistically-impossible situations? or would it be totally unnecessary or even counterproductive to add more lines of code to hinder readability?

答:
If you've recognised an unlikely race condition, at least document it in the code!

EDIT: I should add that I'd fix it if at all possible, but at the time of writing the above no other answer explicitly said at least document the problem in the code.


问:
What's the difference between the insert methods and why one is faster
I have insert 14.485 lines on MySQL like this:

```<code>INSERT INTO `bairros` (`id`,`cidade_id`,`descricao`) VALUES (1,8891,'VILA PELICIARI');
INSERT INTO `bairros` (`id`,`cidade_id`,`descricao`) VALUES (2,8891,'VILA MARIANA');
...
</code>```

It took around 5 minutes.

I had to insert in another table 16.021 lines, same database, so for test I did this:

```<code>INSERT INTO `bairros` (`id`,`cidade_id`,`descricao`) VALUES (1,8891,'VILA PELICIARI'),(2,8891,'VILA MARIANA');
...
</code>```

It took just a few seconds.

What is the difference, for the database, between the scripts? And why one is faster than the other?

答:
In first block : each insert operation acquires the lock and then after needs to be released, that takes time.

In second : one time hit to database that saves time.


问:
In what language should I name my business classes?
I'm requesting best practice with this question. This is only an issue if the customer company is strictly national has a native language other than English, I think.

If the customer has a lot of mainly very domain specific (say, German) expressions, mixed with some lesser domain specific namings. The language of our code comments, class/method/variable names is English. Would you translate all domain specific names?

答: My last project goal was to model business domain of collaterals and mortgages. All the developers and the company we worked for are from Poland. We built the software following Domain Driven Design principles. We used Polish names for all the business entities and I think it was a very good choice. I think that we were able to avoid communication problems thanks to this approach. Business domain consisted of many terms that I didn't even know in Polish, not to mention English translations. We used only latin letters and all technical classes were named in English.</p>


问:
Is it a must for every programmer to learn regular expressions?
I am new to programming, and at an interview I got a question on regular expressions; needless to say I couldn't answer. So I was wondering whether I should learn regular expression? Is it a must for every programmer of all fields? Or it is a must for programming for some particular fields?

Related questions:

Why are regular expressions so morbidly attractive?

When you should NOT use Regular Expressions?

答: Let me just say, Regular Expressions are often the right tool for the job and are quite handy, especially with applications that do a lot of text processing. However, memorizing them is madness. I have a cheat sheet pinned up on my wall that has all of the special characters, anchors, character classes, pattern modifiers, metacharacters... Just spend the 20 minutes it takes to learn how to use them and get a cheat sheet to keep track of everything else. All you need them for is to be able to write a regular expression when you need one, which is usually about every 6 months--about as often as you come across a problem where they are the best tool to use for the job. Unless you are on the Perl, Latex, Emacs or some other heavy text processing team.</p>


问:
C++ for C# Developers
I know C# pretty well (self-taught, sadly) and need to do some C++ programming for a Windows application.  I have been able to find a ton of information for C++ developers learning C# but haven't been able to find much on learning C++ when you already know C#.  Has anyone come across a good rundown of the basics?

MSDN has a comparison but it is not very in-depth.

I can piece together several sources but figured something was out there - I just can't find it.  Thanks for your help.

答:
I'm not sure if you're still looking for materials, I found this article a few months ago.  It isn't a book (only 53 pages).  The introduction says it all:

This is a somewhat short guide to the important things to know if you are a C# programmer and find yourself needing or wanting to work in C++

Link

And there is also an update post too:

Link

Above page now contains a dead link to a pdf version.
Here's the archived pdf.

Happy learning :)

Title: C++ for C# Developers

ContentLicense: CC BY-SA 4.0


问:
Javascript simple code to understand prototype-based OOP basics
I know Javascript for some time, although I am not a heavy user, I know it the first from the time when Netscape was my browser. I pretty much understand the main things, but since JavaScript approach to OOP is prototypical I have some problem grasping it.

One problem to add to this it seems that things can be done in more than one way, and here is where books don't help much because they put all the examples on the table making it hard to keep the pace.

What I need for start is only one way of doing it, if someone can help me with the simplest code possible an example where I can see how the prototypal OOP model works?

To be helpful the code should have an inherited object, to access a parent's property and its inherited properties and a parent's function, to overwrite a parent's function and and have an instance of a multiple inheritance where an object inherits two other objects.

答:
How can be inherited an object?

```<code>function inherit(o){ // inherit is called Object.create in modern implementations
    var F= function(){};
    F.prototype=o;
    return new F();
}

var parent = {
    name: "Josh",
    print: function(){
       console.log("Hello, "+this.name);
    }
};
parent.print(); // Hello, Josh
var child = inherit(parent);
child.name = "Jeremy";
parent.print(); //Hello, Josh
child.print();  //Hello, Jeremy
</code>```

How can I see a parent's property?

```<code>console.log(child.__proto__.name); //won't work in IE; also see getPrototypeOf
</code>```

How can I access a parent's function?

```<code>Object.getPrototyepeOf(child).print(); // or
child.print.apply(parent) //functions are just objects, and 'this' pointer can point to wherever you want
</code>```

How can I overwrite a parent's function?

```<code>child.print = function(){
    console.log("Hi ", this.name);
}

parent.print(); //Hello, Josh
child.print();  //Hi, Jeremy
</code>```

How an object can inherit two objects?

```<code>//in chain?

grandchild = inherit(child);

//otherwise, there's no way.
grandchild.name = "Eddie";
grandchild.print();
</code>```

Also see:

Mozilla Developers Network Inheritance guide

Object.getPrototypeOf on MDN

Douglas Crockford's second series of videos on JavaScript (the first one started the javascript revolution, the beginning is boring but full of surprises; the rest is full of surprises)

Crockford's Book (once I went into a team of 15 people who were working on one of the large JS apps out on the web made by a large, well-known company - I counted 5 of this on the desks)

Current specification drafts as they include built-in classes

Coffeescript, a JS-based language which is popular among JS-developers and supports classes

Body:
How can be inherited an object?

function inherit(o){ // inherit is called Object.create in modern implementations
    var F= function(){};
    F.prototype=o;
    return new F();
}

var parent = {
    name: "Josh",
    print: function(){
       console.log("Hello, "+this.name);
    }
};
parent.print(); // Hello, Josh
var child = inherit(parent);
child.name = "Jeremy";
parent.print(); //Hello, Josh
child.print();  //Hello, Jeremy

How can I see a parent's property?

console.log(child.__proto__.name); //won't work in IE; also see getPrototypeOf

How can I access a parent's function?

Object.getPrototyepeOf(child).print(); // or
child.print.apply(parent) //functions are just objects, and 'this' pointer can point to wherever you want

How can I overwrite a parent's function?

child.print = function(){
    console.log("Hi ", this.name);
}

parent.print(); //Hello, Josh
child.print();  //Hi, Jeremy

How an object can inherit two objects?

//in chain?

grandchild = inherit(child);

//otherwise, there's no way.
grandchild.name = "Eddie";
grandchild.print();

Also see:

Mozilla Developers Network Inheritance guide

Object.getPrototypeOf on MDN

Douglas Crockford's second series of videos on JavaScript (the first one started the javascript revolution, the beginning is boring but full of surprises; the rest is full of surprises)

Crockford's Book (once I went into a team of 15 people who were working on one of the large JS apps out on the web made by a large, well-known company - I counted 5 of this on the desks)

Current specification drafts as they include built-in classes

Coffeescript, a JS-based language which is popular among JS-developers and supports classes


问:
Using Bit Torrent for internal release management
We currently abuse our version control system and use it... pretty much as an FTP to store big release binaries (4+ GB).

We are seeking to move away from this horrendous practice which has and continues to devolve and take more and more of IT's resources while crippling the integration and release processes.

A solution for this would be using P2P file sharing to distribute these release images/binaries, mixing file servers and some key user machines as seeds.

So my question comes in two parts:

Have any of you resorted to setting up BitTorrent in your intranet to distribute release images/binaries?, if not, what do you think about this idea (which was not actually mine BTW, but I think it is great)

Is there open source web-based software for handling publishing of BitTorrent trackers?, so that when there is a new release it can be searchable and display its availability with regards to seeds and leeches? (...you know what I'm referring to)

Edit: The intranet is global (e.g. USA, China, Germany, Mexico). Regular FTP could work but it is not as cost-effective.

答:
I like the idea. BitTorrent is possibly the best solution for sharing large files among numerous users devised so far, it's a shame that the stigma it carries will probably continue hampering it's mainstream adoption. Still, many open source projects, including Linux distributions, use torrents as a secondary channel of distribution

You can find several open source trackers on sourceforge, among them TBSource and TBDev.net, current incarnations of popular torrentbits project. Another option is XBTT, although I suspect it might be an overkill for your needs. It has a spartan frontend, but there are third-party frontends available should you need them.

There's also a possibility to take advantage of torrents without having to setup and run a tracker, since torrent clients can operate in a trackerless mode, using a distributed hashtable to exchange peer information. You would still need to share torrent files somehow, but you can setup some simple website/ftp for that in no time, or store them on svn (not an issue since they weigh several kb per file).


答:
I suspect that at least part of it is a bit simpler: even now, we see a lot of questions like this starting around the beginning of the school year, and they gradually taper off throughout the year.

As such, I think it's fair to guess that quite a few of them are simply a result of classes in which the teacher talks at least a little about it, but doesn't explain his point(s) very well (as often as not because he doesn't really understand them himself). Especially based on the people who seem to ask these questions, few are based on actual coding.

Title: What makes C developers so curious if "i++ == ++i"?

Body:
Just a random observation, it seems that on StackOverflow.com, there are questions about if "++i == i++". That question gets asked all the time though, I think I saw it asked about 6 or 7 times in the past 2 months.

I just wonder why C developers are so interested in it? The same concept/question exists for C# and Java devs as well, but I think I saw only one C# related question.

Is it because so many examples use ++i? Is it because there is some popular book or tutorial? Is it because C developers just love to cram as much as possible into a single line for 'efficiency'/'performance' and therefore encounter 'weird' constructs using the ++ operator more often?

ContentLicense: CC BY-SA 2.5


问:
Freelance Web Developer tools
I'm thinking of freelancing and building web sites in my free time.

I have experience in C#/ASP.NET, JavaScript/jQuery as well as HTML/CSS and SQL.  Thus, I feel like I have sufficient web technologies knowledge to go down this path.

What I'm unsure of is if there are any tools which can be used to simplify the life of a freelance web dev.  As an example, I once designed an e-commerce website from scratch as a University project, which took around 3 months of hard work to accomplish.  The finished product was not even hosted, and I didn't delve into any security aspects.  I never even hosted a website or database before!

What concerns me is that there are millions of sites out there which can for example be used to create an e-commerce site in minutes.  Without having to bother with databases, security and other issues.  You don't even need to know how to code in server-side technologies to get these sites up and running.

Do professional web developers actually use these tools? If a client had to request an e-commerce site (for example), how would a pro go about developing it? I hear a lot about CMS systems like Joomla and Wordpress, but I think my main problem is that I don't know much about the available tools (other than Visual Studio) and I wouldn't know where to get started.

Can anyone guide me in the right direction?

答:
For web, Linux is the de-facto standard, Windows is a 15% market share (according to Netcraft) so you could start by getting a copy of Eclipse (an OSS IDE) and looking at PHP for starters. This will get you into a lot of web code that is written out there. Install xdebug on your Apache webserver instance to host PHP and you can debug through the code so simply I thought I'd done something wrong. (I even did it on Windows - install XAMPP to get a dev system running and then just configure xdebug and then run your website by putting the localhost url into your eclipse php project!)

Once you've got that out of the way, you can begin some real web development (not that PHP is particularly bad, its very very easy, which is why its popular)..

At this point you can make your web apps from javascript (node.js is the cool new kid, try looking at express), or C++ (Microsoft is big on native code this decade, check out Casablanca or try cppCMS), or the last big super-cool, fast-productivity tool Ruby on Rails or stuff based on Python (Django seems to the the standard) or Java (I hear struts is big).  Or you could do some boring old stuff in ASP.NET - just check the MS tutorials if you don't want to dabble in the myriad wonders of web development.

There's a lot of web frameworks out there.

As for dedicated tools, if you're creating websites for customers, you might be better advised to start with an existing tool such as Drupal or Joomla and build upon them. Drupal was used for the whitehouse.gov website, so you can see this is a very valid approach. 80% of the hard work will have been done for you like this, and as they're open source, you can either modify them yourself or look for modifications/addons others have created. Many of these CMSs already have ecommerce addons, or you could try looking at a dedicated ecommerce platform such as osCommerce, or ZenCart. If you're build full "corporate" websites you could look into things like Orange HRM, Horde, or Nuxeo.

However, 1 thing you must do is learn security. There are plenty of Linux hardening tutorials about, or you can hire people to harden your servers.  At least learn the basics so you know the pitfalls and the potential problems that you might get when you're called out to fix a hacked site.

There's a lot of really good stuff out there, when I started learning this, it was an eye-opener how much, and how good some of it was. I loved getting into Linux web platforms, it was refreshing change from Windows-only systems so its worth the time taken to learn something new.

Title: Freelance Web Developer tools


问:
How do you break out of the role of a code maintainer?
In my last three jobs, I was a code maintainer. In all three cases, I was hired after the majority of the code for the project was already written.

I'm a self taught programmer. Before I ever started my first professional job, I had maybe a dozen projects under my belt that I started and shipped successfully.

Writing new code and maintaining existing code are two completely different jobs. Its like comparing an aeronautical engineer with an aircraft mechanic.

It especially sucks when you're an aircraft mechanic working on an airplane that was designed by an engineer who made no attempt to engineer the plane to be in any way logical or easy to maintain.

I'm starting to feel like to be around when the project is first starting out, you have to be one of those special people who has somehow transcended the rest of the people in the computer science field. What does it take to be in that position?

I kind of feel like this question doesn't really have any easy answer, but could anyone give me some insights? Have you ever been on the ground floor of a new project? What did it take to get there?

答:
I have bad news for you: a lot of the applications humanity needs are already written, it's just that they should be fine-tuned to the constantly changing environment.

Some day, you'll be asked to write a new part of the system, like, a new module, and you can leverage your knowledge on green field development.

Until then, you can try to learn refactoring legacy applications to clean modules.

A good read is "Working with Legacy Applications" and "Refactoring to Patterns". If you didn't read the original Refactoring (Fowler), please do so. And learn Test-Driven Development (TDD), always helps.

In case you're working with PHP, I wrote a hands-on article this code still runs...

Have fun!


问:
Is there an specific way or algorithm to decode protocols?
I am designing a simple logic analyzer, I know that the best way to decode a protocol like I2C, SPI, UART is whit something like an FPGA but I want to do it by software by now :) I am running on an OMAP4460 ARM proccesor.

I would like to know if there is an special way of decoding protocols like I2C, SPI, UART or it is simply if() and flags as the normal way.

答:
A lot of people are doing what you are doing and making their own logic analyzer.  Some logic analyzers and scopes are able to do the decoding you are describing, including some that have open source software and hardware.

My suggestion is that you join with others to do some or most of what you are trying to do, or that you scope your effort as narrowly as possible to get something simple running, then build it up from there.

Reusing / Collaborating on existing projects:

If you are using Arduino, you can buy hardware for it and download software including the I2C, SPI, and UART support very reasonably.

http://www.arduinolab.us/

Another similar project is described here:

http://www.seeedstudio.com/depot/open-workbench-logic-sniffer-p-612.html?cPath=61_68

Other people are working on this kind of stuff at sump.org.  Sump seems to provide a hardware and two part software solution - one part on a PC used to display, the other on a target to capture.  The RS232 protocol between seems to be used by others, so potentially if you like what they did, you can skip the PC side and just implement the target side protocols.

Going it Alone, Starting Simple

I suggest that to make your implementation as easy as possible, you have the user configure as many options as possible instead of trying to figure them out.  Depending on protocol, some items the user might select include:

Interface speed (baud rate or expected clock rate).

Parity (none, mark, space, odd, even).

Master/slave address(es).

What input does what function (UART: RX, TX, maybe DSR, DTR, CTS, I2C: CLK, DATA, SPI: MISo, MOSI, CLK, SPID/SSEL0..N.

Polarity if inputs for any of the pins might be inverted from normal.

Address size.

Use the links from the earlier section, to see what Arduino and Sump guys are doing to get some ideas by looking at their sample code and documentation.

I suspect the UART will be the simplest to implement.  Both transmit and receive have identical structure, so you can make one state machine that implements both, and takes the an analyzer channel as its parameter.  You will need to sample this no less than twice the baud rate (8x or 16x might be better).  Typically, when idle, the line will be pulled up by a resistor, then the beginning of a byte (8 bits) will be signaled by a start bit (logic 0), followed by eight data bits, followed by an optional parity bit, and a mandatory stop bit (logic 1).  Timing diagrams for this bit pattern, with parity and without parity respectively, can be found at the following links:

http://www.romux.com/tutorials/embedded-system/peripherals

http://www.commfront.com/RS232_Protocol_Analyzer_Monitor/RS232_Analyzer_Monitor_Tester_TUTORIAL.HTM

The first reference also discusses DTC and DCE conventions and some other things you may want to monitor for UART serial if you wire it up beyond TX, RX, and GND.

You can use a timer to poll the input levels, and a state machine with states like UART_IDLE, UART_START_DETECTED, UART_D0, ...,  UART_D7, UART_PARITY, UART_STOP, and UART_RECOVER could be used.  UART_RECOVER might be a state that follows the detection of an exception where parity is not what it should be based on calculated parity, an expected stop bit that shows logic 0, or a start bit (or other bit) that changes within your over sampling, perhaps because of noise that is logic low like a start bit, but lasts much less than a bit time.  It may be beneficial to use more than one recovery state to count out a certain amount of time, or look for a stop/idle/start sequence.

I2C and SPI are synchronous serial protocols, so if you indicate which input is clock, you can sample or if desired over sample to determine whether data bits are zero or one when the clock transitions.  You will potentially be able to show addresses, data words, and either direction (I2C master or slave, read or write) or selected device (SPI).

Github and other open source repositories may have a lot of the code you need already written, and the wikipedia references include some bit-banging code that could be adapted (or at least studied) with high benefit.

http://en.wikipedia.org/wiki/I%C2%B2C

http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus

If you write these from scratch, start with a bunch of test cases for things like master read, master write, slave read, slave write, ideally taken from the spec or a known good implementation.  Being able to loop back your hardware or even to unit test your state machine with simulated inputs from a table, will accelerate your debug and let you retest quickly as you revise the code.

You will need more state machines.  I2C and SPI will be separate of course.  You may have nested state machines because there is a bit oriented recognition and a frame oriented recognition.  You may chose to divide things up so major use cases get their own decode functions in the code.

I2C and SPI may need to be more flexible about timing.  They will step through some state transitions based on changes on the clock and others based on changes in the data, but you will probably still use a timer to drive your sampling and your state machines.  Exception handling will be more complex, and use of nested state machines can help.  Grady Booch (et al) have great examples of state machines and nested state machines in section 5.11 of his book "Object Oriented Design and Analysis with Applications", 3rd Edition (c) 2007.


问:
Guided Questioning iOS App
I'm making an iPad app that will display a few choices and based on your choice will display a series of questions with each question triggering a different set of questions. I was wondering if there was a name for this or any open-source library that someone has made for this kind of app.

If not, would it be best to hard code all the questions and responses into the app, or to read them from a file?

答:
This is a tree.

Your nodes are the questions, and each question has as many children as there are answers to it. Your session context contains the current question, and it leaps forward by asking a new one.

We could also say that this tree is a directed bipartite graph with each question node connecting to multiple answers, and each answer node connecting to exactly one question node.

A good storage would be, for example, XML:

```<code><questions>
<question id='3'>
   How are you?
   <answers>
      <answer next_question_id='4'>Fine, thx</answer>
      <answer next_question_id='5'>Badly</answer>
   </answers>
</question>
<question id='4'>
   Boy or girl?
   <answers>
      <answer next_question_id='8'>Boy</answer>
      <answer next_question_id='9'>Girl</answer>
   </answers>
</question>
<!-- ...-->
</questions>
</code>```

Or, if you want to keep the tree visualized, you could try YAML:

```<code>root:
    title: How are you?
    answers: [
       {
          text: Fine, thx
          next_question:
               title: Boy or girl?
               answers: [
                   {
                   }
               ]
        }
        {
          text: Badly
        }
    ]
</code>```

A session might look the following:

So, how it is implemented MVC-wise is a different matter.

You have similar things in adventure games (infocom games) btw, but that's much more advanced.

Edit: this thing is called a Dialog Tree, and you can find answers on StackExchange as well.

Title: Guided Questioning iOS App

Body:
This is a tree.

Your nodes are the questions, and each question has as many children as there are answers to it. Your session context contains the current question, and it leaps forward by asking a new one.

We could also say that this tree is a directed bipartite graph with each question node connecting to multiple answers, and each answer node connecting to exactly one question node.

A good storage would be, for example, XML:

<questions>
<question id='3'>
   How are you?
   <answers>
      <answer next_question_id='4'>Fine, thx</answer>
      <answer next_question_id='5'>Badly</answer>
   </answers>
</question>
<question id='4'>
   Boy or girl?
   <answers>
      <answer next_question_id='8'>Boy</answer>
      <answer next_question_id='9'>Girl</answer>
   </answers>
</question>
<!-- ...-->
</questions>

Or, if you want to keep the tree visualized, you could try YAML:

root:
    title: How are you?
    answers: [
       {
          text: Fine, thx
          next_question:
               title: Boy or girl?
               answers: [
                   {
                   }
               ]
        }
        {
          text: Badly
        }
    ]

A session might look the following:

So, how it is implemented MVC-wise is a different matter.

You have similar things in adventure games (infocom games) btw, but that's much more advanced.

Edit: this thing is called a Dialog Tree, and you can find answers on StackExchange as well.


问:
Is STL implemented with OO?
There are several design patterns like Adaptor, Iterator implemented in STL.

Does that mean STL is implemented with OO concepts?

What is the relationship between OO and template parts of C++?

I learned that virtual member function which justifys the OO is contradict
with template, is this correct?

答:
To quote Alexander Stepanov from his STLPort interview:

STL is not object oriented. I think that object orientedness is almost as much of a hoax as Artificial Intelligence. I have yet to see an interesting piece of code that comes from these OO people. [...] I find OOP philosophically unsound. It claims that everything is an object. Even if it is true it is not very interesting - saying that everything is an object is saying nothing at all. I find OOP methodologically wrong.

That said, an individual implementation could be done using inheritance and polymorphism in places. Just for example, I've seen an implementation in which iterator was derived from const_iterator to support implicit conversion from iterator to const_iterator. Derivation is not however, characteristic of, or required by, the design.

Bottom line: while you can/could use object oriented code to implement some parts of the STL, the design of the STL itself is (emphatically) not object oriented.

Title: Is STL implemented with OO?


问:
Could implicit static methods cause problems?
This is a purely hypothetical question.

Say I create a class method that contains no references to instance variables or other resources.  For example (C#):

```<code>protected string FormatColumn(string value, int width)
{
    return value.Trim().PadLeft(width);
}
</code>```

As far as I can see, there is absolutely no reason why this method could not be declared static:

It only uses method-scope variables.

It doesn't override a base class method.

It's not virtual or abstract.

My questions are:

Is there any benefit to calling a static method over an instance method?

If so, why doesn't the compiler implicitly convert this to a static method?

I'm certain I've missed some key point here.  Any ideas?

答:
Static methods are usually utility operations shared among instances of a specific class, a.k.a utility methods. For example the String.Join() method which takes an array and join the elements by using a separator character or string.

So, my rule is that if the method is a utility shared functionality specific to instances of that class then it can be static.

It would be weird to have to create a new string in order to use the Join() method to join multiple strings into a new one.


答:
Maintenance means different things to different people, and comes about for different reasons.

Worst case, the initial system was thrown together in a hurry, the initial team took credit for the whole thing.  They followed the 80/20 rule, so while there might be a minimum viable product that can be sold, lots of customers need lots of fixes and small improvements.  Many problems, but not much glory remain.  You have the hardest job, and its thankless.  I hope this is not your situation.

Better case, you have shown that you are careful with your work and can be trusted to make changes to fielded product without breaking it.  What problems remain are too hard for the people who hammered the original system together.  Maybe they failed to build the system to last, and you are there, perhaps as their replacement, to set things right and rescue the customers, the project and the profits.

Very likely case, 60% of projects costs come during maintenance.  Perhaps it is timing, perhaps your organization segregates between new development and maintenance, but you are in the 3/5th majority because many of us do maintenance.

Here are a few things to try:

Do a great job, have a great attitude, be an idea leader.

As much as possible, work in teams, not alone.

Learn newer languages.

Learn newer platforms.

Request to work on smaller programs, maybe even apply with smaller companies.

Get skilled and get involved in documentation.  When projects start, even in the post waterfall era, they need a lot of written coordination to road-map, document, evaluate, and clarify requirements.

It is dangerous for projects to start in the hands of people who don't appreciate requirements management, estimation, and risk assessment, so learn and practice these skills as much as you can.

Get more formal training or certifications.  This may increase your status and make you a more attractive choice when teams for new development projects are formed.

Start a company or some consulting on the side.  This give you creative outlet to target your favorite kind of work, and gives you a better appreciation of what it is like to start with no code or documentation.

Get closer to your boss and to people who plan new projects.

Conversely, if you are super close to testers and QA, their output is often the input to maintenance, so guess who your boss thinks you work really well with?

Make as many friends, and win the respect of as many greenfield developers as you can.

New developers are the can do people, so be cautious about any hint of criticism or negativity.  Give them your ideas freely without blame or judgement.  Your ideas need no introduction, just say them.  Never say, we used to do it this way, or that doesn't work, try this.  Never say, I don't know, but this might work.  Just say the idea.  Or better, show it.

Find and take any opportunity to build a proof-of-concept that might turn into your new project.

Watch out who assigns you work.  Usually, it should be someone in your chain of command.  If it is your peers, push back some of the time.  If it is someone you supervise, there needs to be a good reason control is inverting.  If it is QA or test, make sure it matters to your chain of command and is not scheduled in a way that delays work you promised earlier.

Beware of perfection.  New development is often reserved for fast people, even if they cross the eyes and don't dot the t's.

Spend time learning and practicing early project skills appropriate to your line of development.  This could include: creating source repositories, defining the build environment, configuring the constant integration server, working closely with the hardware team to bring up new boards with board support packages or writing power on self tests.  It might even help to know how to work with purchasing to buy new development tools, training, and COTS hardware.

Make sure you move on before your maintenance project is closed, perhaps by shopping your skills internally to team leads and maybe managers, or externally.

Be fluent in every technology you know, and know a lot of technologies.

A maintenance role can be turned to your advantage in several ways.

You can potentially work on every project your group or even company
makes.

If new development and maintenance is separated, you can
potentially follow a less competitive leadership track.  Lead on new
projects is highly coveted, but maintenance lead might be available to you
for the asking.  If you have encouragement and mentoring to give, members of that team may appreciate it more.

If the project is in maintenance, you are more likely to interface with customers.  Handled wrong, this ends careers.  Handled right, it gets positive attention outside development that is hard to find without being a manager.

Having said all this, I am the counter-example not the role model.  Much of this perspective comes from experience and observation.

There are many new programs that still need to be written.

Be ready and you will be working on one surprisingly soon.

Title: How do you break out of the role of a code maintainer?

Body:
In my last three jobs, I was a code maintainer. In all three cases, I was hired after the majority of the code for the project was already written.

I'm a self taught programmer. Before I ever started my first professional job, I had maybe a dozen projects under my belt that I started and shipped successfully.

Writing new code and maintaining existing code are two completely different jobs. Its like comparing an aeronautical engineer with an aircraft mechanic.

It especially sucks when you're an aircraft mechanic working on an airplane that was designed by an engineer who made no attempt to engineer the plane to be in any way logical or easy to maintain.

I'm starting to feel like to be around when the project is first starting out, you have to be one of those special people who has somehow transcended the rest of the people in the computer science field. What does it take to be in that position?

I kind of feel like this question doesn't really have any easy answer, but could anyone give me some insights? Have you ever been on the ground floor of a new project? What did it take to get there?


问:
Application connecting to database server
I'm working on an application which requires user credentials and so on. So a database is required on the backend.

What is the best practice to connect to a database without hardcoding your password into it? The program could be reverse engineered and one might get the password which is something we obviously don't want.

答:
Put your credentials information in the <connectionString /> on the app.config file. Then, proceed to encrypt the <connectionStrings /> section.

See the following article for more information: Encrypting Passwords in a .NET app.config File


问:
What is better for coding - desktop or laptop?
Use of desktops are decreasing day by day in daily life but for coding purpose are there any reasons for using desktop over laptop? </p>

答: As long as you connect 2 monitors minimum and an external keyboard then the laptop takes it for me.  The automatic battery backup has saved me several times. Of course you could connect your desktop to a ups and get a similar affect.</p>


答:
Because C programmers HAVE to understand order of operations.  C# developers don't necessarily use the bitwise operators (&, |, ~) or prefix operators since we're normally more worried about other stuff.  However, what we C# devs don't realize is that we should know what the operators we use on a daily basis do and how to use them properly.  Most of us just avoid the places where this may be a problem.

Off the top of your head, what is the output of this snippet?

```<code>    double x = 5.5;
    Console.WriteLine(x++);
    x = 5.5;
    Console.WriteLine(++x);
</code>```

I would say a good number of seasoned C# devs have no idea what the output to the Console is.

Body:
Because C programmers HAVE to understand order of operations.  C# developers don't necessarily use the bitwise operators (&, |, ~) or prefix operators since we're normally more worried about other stuff.  However, what we C# devs don't realize is that we should know what the operators we use on a daily basis do and how to use them properly.  Most of us just avoid the places where this may be a problem.

Off the top of your head, what is the output of this snippet?

    double x = 5.5;
    Console.WriteLine(x++);
    x = 5.5;
    Console.WriteLine(++x);

I would say a good number of seasoned C# devs have no idea what the output to the Console is.


问:
Bump version number in commercial software development?
Who is responsible for bumping version number in commercial software development?
How to setup policies for that?

1) for small team

2) for medium team

It is important not to forget to change the version number that self-describes that output file.

Such as AssemblyInfo.cs / resource.rc / AndroidManifest.xml

答:
IMHO, the best versioning scheme is semantic versioning, and in this scheme, no role is specified, rather, rules are specified.

In other words, if Office introduces new features, and some of the oldest functionalities are gone, then the major version should be added another unit. Now who does that? Usually developers. Because they are the people to whom version matters most.


问:
Amortized Analysis? (Worst-case Performance Guarantees)
What is Amortized Analysis? And how can it help me achieve worst-case performance guarantees in my programs?

I was reading that the following techniques can help the programmer achieve Worst-case performance guarantees (i.e. in my own words: guarantee that the running time of a program would not exceed the running time in the worst cast):

Randomized algorithms (e.g. quicksort algorithm is quadratic in worst case, but randomly ordering the input gives a probabilistic guarantee that its running time is linearithmic
)

Sequences of operations (our analysis must take into account both data and the sequence of operations performed by the client)

Amortized Analysis (another way to provide a performance guarantee is to amortize the cost, by keeping track of the total cost of all operations, divided by the number of operations. In this setting, we can allow some expensive operations, while keeping the average cost of operations low. In other words, we spread the cost of the few expensive operations, by assigning a portion of it to each of a large number of inexpensive operations)

The author mentioned the use of resizing array data structure for Stack as one example of how to achieve amortized analysis but I still don't understand what amortized analysis is, and how it can actually be implemented (data structure? algorithm?) to achieve worst-cast performance guarantees

答:
First of all: It is a technique for analyzing program runtimes, not an implementation technique for algorithms.

The example mentioned in your list is a good one:
Appending a single item to array-backed data-structure. For every single append operation the worst-case is having to copy all existing items. That kind of analysis is way too pessimistic, as you don't have to do that if you are using a sane resizing strategy (multiplying the size by some x > 1.0). The analysis then says you have a O(n^2) bound - O(n) per item times n items - while the actual runtime is only O(n).

If you average the resizing cost over all items inserted (most of which don't need resizing) you are doing amortized analysis. The amortized analysis results in a O(n) bound which matches the actual behaviour of the algorithm.


问:
How to test a random-generating feature in application?

Possible Duplicate:

  How should I test randomness?

One of the features to be developed in our application was allowing user to click a button which will choose an element at random out of (normally 5-10) values registered in the database. The randomness doesn't need to be secure or scientifically uniform, but we do need it to be somehow unpredictable and not noticeably biased to one of the value.

Any suggestion how to write a good unit test and functional test for this feature?

答:
You can use the same seed on 2 parallell processes, and if they start in the same general (in GHz processor terms) timeframe they will have the same exact seed to the static seed.  Or most languages if seeded with the same static seed will have the same numerical generation (Java's a good RNG example of this API style).

To combat the inherent static predictability of this, RNG's are usually seeded with the internal system time down to micro or nano second range, giving high unpredictability in the long run and near impossible ability to predict based on time in the short, since it's internal crystal clock cycles that feed up to the API.

As an aside: all numbers generated by machines will be pseudo-random, but close enough for government work.

To get a numerical range you want just take the integer modulo (integer_range_max) of the RNG value [0-1).  So RNG * Modulo % Modulo will give you the range.


问:
How much should a floating license cost?
Floating licensing is a software licensing approach in which a limited number of licenses for a software application are shared among a larger number of users over time. Nice for the corporates to reduce the costs. It has also the developer aspect.

I saw lots of pricing examples for many software. As far I understood, there is no standard to set the prices.

As a software developer, it is also a goal to maximize the yield. Which criteria should I take in account by setting the floating license price?

答:
my opinion: This is a business decision. Pricing exists because markets can be segmented.

For instance, someone will pay $x for candles. Someone else might pay $x+3 for blue candles, or only pay $x-1 for pink candles. You get the picture.

Pricing is a function of value (and cost, and other things too). One presumably gets atleast $x worth of value for an item which costs $x. If you get more value, customers are happy (and you potentially could've made more).

Figure out how much value you are providing, and come up with a number. I don't know how companies arrive at pricing, perhaps, some courses can help, or someone with business background.

So, figure out who you want to sell floating licenses to. Big companies, small companies, academia, industry specific sectors? Is there a "norm" for similar service? If not, be bold and set it high. You can always reduce it. If you set it too low, raising it becomes difficult.

Hopefully, it helps. I read an excellent article a couple of years ago.
It is provided in the accepted answer for How do you decide how much your software will cost? It does a really good job of explaining software pricing.

Some other useful insights...

http://www.joelonsoftware.com/items/2004/10/26.html

http://onstartups.com/tabid/3339/bid/11097/How-To-Price-Software-Without-Just-Rolling-The-Dice.aspx

http://www.smashingmagazine.com/2011/09/28/youre-pricing-it-wrong-software-pricing-demystified/


问:
Does Clojure have continuations/coroutines/etc?
I started programming with Python, and I was really confused by concepts like coroutines and closures.

Now I think I know them on some superficial level, but I've never felt that "enlightement" moment, so I choose to learn Clojure. I bought the book by Stuart Halloway and it's good, but when I looked at the index there were no words like coroutine or continuation. I googled them, but there's nothing there either.

So, my question is:

Does Clojure have continuations or coroutines to do tasks like ping-ponging without a stack overflow?

Python example (though standard Python does not support a fully-featured version of this symmetric coroutine):

```<code>def ping():
  while 1:
   print "ping"
   function to switching to pong

def pong():
  while 1:
   function to switching to ping
   print "pong"
</code>```

答:
Clojure doesn't have call/cc, but you don't want undelimited continuations anyway.

We argue against call/cc as a core language feature, as the distinguished control operation to implement natively relegating all others to libraries. The primitive call/cc is a bad abstraction -- in various meanings of 'bad' shown below, -- and its capture of the continuation of the whole program is not practically useful. The only reward for the hard work to capture the whole continuation efficiently is more hard work to get around the capture of the whole continuation. Both the users and the implementors are better served with a set of well-chosen control primitives of various degrees of generality with well thought-out interactions...

...Offering call/cc as a core control feature in terms of which all other control facilities should be implemented turns out a bad idea. Performance, memory and resource leaks, ease of implementation, ease of use, ease of reasoning all argue against call/cc. If there is really one distinguished control feature to implement as a primitive, with others relegated into libraries, it is not call/cc.

David Nolen wrote a delimited continuations library for Clojure. Try it out!

delimc

A delimited continuations library for Clojure 1.4.0 (and 1.3.0). Portions based on cl-cont by Slava Akhmechet (http://defmacro.org)...


答:
You don't implement amortized analysis. It's a technique to get more accurate O bounds.

The essential observation you have to make is, that expensive operations cannot happen at any time.

In the case of an array-backed data structure, the array needs resizing every now and then – when it's full. This is the most expensive operation and takes O(n) time. All other inserts into the array are O(1).

To determine the runtime for inserting n items, you can multiply n with the most expensive operation O(n), which results in an overall runtime behavior of O(n^2).

However, this is inaccurate because resizing cannot happen very often.

When talking about money, you amortize cost, when you pay off your debt with multiple small payments over time.

We can use this model to think about algorithms as well. We simply substitute "time" with "money" to avoid mental mapping.

Once the array is fulled to it's length n, we can double it's size. We need to make the following operations:

Allocate 2n chunks of memory

copy n items

If we assume that both allocating memory and copying happen in linear time, this is going to be a very expensive operation. However, we can now use the idea of debt and amortizing it for our analysis. Only, we are going to amortize our debt before we actually make it.

Let's assume, that our balance (of money/time) is back to 0 (i.e. we don't have a debt nor do we have any leftovers) once we have resized the array.

This has the following implication:

Inserting the next n items will cover the cost of resizing and copying (we have n used slots, and n unused slots`)

We can now think about how much every insert operation needs to pay for:

The insert

The cost of allocating one chunk of memory

the cost of moving it to the newly allocated memory

We have now covered the costs to allocate memory, copy and insert the next n elements. However, we have yet neglected allocating space for the old n elements as well as copying them.

We simply distribute the costs of our old n elements to our new (yet to be inserted) n elements:

The cost of allocating one chunk of memory

the cost of moving it to the newly allocated memory

In total, every, every insert operation will cost 5 units. This pays for its own insertion, and the moving and allocating of space for itself and one of the old elements.

Every insert-operation still takes constant amount of time, but the resizing happens for free: We amortized it by spending "more" time on each insertion.

As a result, inserting n elements takes O(n) time.

Other techniques for amortized analysis are explained here.

Title: Amortized Analysis? (Worst-case Performance Guarantees)

Body:
What is Amortized Analysis? And how can it help me achieve worst-case performance guarantees in my programs?

I was reading that the following techniques can help the programmer achieve Worst-case performance guarantees (i.e. in my own words: guarantee that the running time of a program would not exceed the running time in the worst cast):

Randomized algorithms (e.g. quicksort algorithm is quadratic in worst case, but randomly ordering the input gives a probabilistic guarantee that its running time is linearithmic
)

Sequences of operations (our analysis must take into account both data and the sequence of operations performed by the client)

Amortized Analysis (another way to provide a performance guarantee is to amortize the cost, by keeping track of the total cost of all operations, divided by the number of operations. In this setting, we can allow some expensive operations, while keeping the average cost of operations low. In other words, we spread the cost of the few expensive operations, by assigning a portion of it to each of a large number of inexpensive operations)

The author mentioned the use of resizing array data structure for Stack as one example of how to achieve amortized analysis but I still don't understand what amortized analysis is, and how it can actually be implemented (data structure? algorithm?) to achieve worst-cast performance guarantees


问:
How to explain to my customer that the hosting provider is terrible, security-wise?
As a freelance developer, I sometimes have to access the administration panels of hosting providers of my customers. It is an astonishingly frightening experience. Below are some points I noticed when accessing recently a not-so-unpopular hosting provider based in UK which has the word "secure" mentioned in large on the home page:

The default administrative account is created with a terrible password: five lowercase and digits only characters, no uppercase, no symbols.

The password is displayed in several locations in the administration panel, which is a good sign that it's saved in plain text in the database.

This administrative account is used to access everything: FTP, MySQL and the administration panel itself (including personal information, invoices, etc.).

It is impossible to create additional accounts, which forces the customer to give the same administrative password to any freelancers who work on the project (giving them unlimited access to everything).

The MySQL database can be accessed from anywhere, not just locally. This behavior cannot be changed.

There is no audit.

Nothing helps or invites the customer to do regular backups.

The hosting uses PHP 5.2.4, a version released on August 30th, 2007 and cannot be upgraded to a more recent version. For those who are unfamiliar with PHP, the language has frequent updates due to lots of security issues discovered regularly, and running a website in 2012 even with the version released in 2011 is a very bad idea.

My experience with other well-known hosting companies in UK, USA and France is similar. Some are slightly better, security-wise, but too many are doing everything they can to enforce worst practices. Then, they claim being secure and easy to use, which gives the feeling that the customer can rely on the hosting provider for everything related to security.

What should be the professional response from a developer to the customer regarding such hosting companies?

As a developer who have a duty to inform the less technologically knowledgeable customers about the risks they encounter, what should I do?

Saying shortly that the hosting provider sucks because it's not secure is not a solution: if the hosting provider is not unpopular, the customer will trust the large hosting company, rather than some freelance developer.

Explaining in details every aspect of security and risk management wouldn't help neither, since it would be too long and boring for the customers to read. Spending hours reconfiguring stuff would be frightening for them too.

答:
I think you're answering your own question, sort of... You need to explain to the customer just what is wrong with the current provider, pretty much exactly like you explain in your question. If you also could give examples of better hosting providers, preferably ones that are not much more expensive there may even be a chance they will listen.

In the end it all comes down to the customer actually seeing that moving to another provider has benefits for them. Security alone may be difficult to use as an argument unless breaches will cause direct loss in revenue or cause extra expenses due to lawsuits or loss of business.


答: The easiest route to escape is to change your style of programming entirely and also add new skills in the same time. For example, you could try to be a Researcher. It might not be a prestige job for the first year, and certainly it is not as highly paid as normal programming jobs (in the first year if you are Researcher / Research Associate in the team of a University - of course as Senior Researcher is pretty much in line with the rest of the industry), but it will definitely put your skills to work on the hardest problems you can find today. After such a job you could easily jump into a better position, provided you have some interesting projects to show to your next boss.</p>


答:
If your customer is a business person, he/she is likely not understand what do you mean by most of the above. In a discussion about security with one customer, I received the question "and why would they go after my business anyway, I am no bank?".

I would suggest that you:

Make a list of threats (like the ones you mentioned above) and what effect could each have on your customer's business.

Make the alternative suggestion clear. Show cost comparison and other migration costs you see. Make simple final recommendation in plain English.

Deliver this advice as an official report to your customer and get the customer to acknowledge the advice.

If they don't listen, well, its their choice, you'd have done your part.

Title: How to explain to my customer that the hosting provider is terrible, security-wise?

Body:
As a freelance developer, I sometimes have to access the administration panels of hosting providers of my customers. It is an astonishingly frightening experience. Below are some points I noticed when accessing recently a not-so-unpopular hosting provider based in UK which has the word "secure" mentioned in large on the home page:

The default administrative account is created with a terrible password: five lowercase and digits only characters, no uppercase, no symbols.

The password is displayed in several locations in the administration panel, which is a good sign that it's saved in plain text in the database.

This administrative account is used to access everything: FTP, MySQL and the administration panel itself (including personal information, invoices, etc.).

It is impossible to create additional accounts, which forces the customer to give the same administrative password to any freelancers who work on the project (giving them unlimited access to everything).

The MySQL database can be accessed from anywhere, not just locally. This behavior cannot be changed.

There is no audit.

Nothing helps or invites the customer to do regular backups.

The hosting uses PHP 5.2.4, a version released on August 30th, 2007 and cannot be upgraded to a more recent version. For those who are unfamiliar with PHP, the language has frequent updates due to lots of security issues discovered regularly, and running a website in 2012 even with the version released in 2011 is a very bad idea.

My experience with other well-known hosting companies in UK, USA and France is similar. Some are slightly better, security-wise, but too many are doing everything they can to enforce worst practices. Then, they claim being secure and easy to use, which gives the feeling that the customer can rely on the hosting provider for everything related to security.

What should be the professional response from a developer to the customer regarding such hosting companies?

As a developer who have a duty to inform the less technologically knowledgeable customers about the risks they encounter, what should I do?

Saying shortly that the hosting provider sucks because it's not secure is not a solution: if the hosting provider is not unpopular, the customer will trust the large hosting company, rather than some freelance developer.

Explaining in details every aspect of security and risk management wouldn't help neither, since it would be too long and boring for the customers to read. Spending hours reconfiguring stuff would be frightening for them too.


问:
Limitations of Polymorphism in statically typed languages
I program mostly in statically typed languages, like C++ and Java.  A common strategy employed in languages like these to handle dealing with collections of objects which are related, but which need to employ specific behaviors, is to use polymorphism and inheritance hierarchies.  But Polymorphism only works when the Base class has a method (virtual function) which can then be overridden by every Derived class.  But there are often cases where a Derived class needs to have a method, and it doesn't make sense to place a method of the same name in the Base class, because it is very specific to the Derived class.

Let me give a concrete example that many of us can probably relate to: the HTML DOM.

Javascript programmers are quite used to doing things like iterating over collections of DOM nodes.  They take for granted the dynamically-typed nature of Javascript when they do something like:

```<code>node = document.getElementById("foo");
for (var i = 0; i < node.childNodes.length; ++i)
    doSomething(node.childNodes[i]);
</code>```

Something like this would be very messy to do in a statically typed language like Java, because inheritance-based polymorphism doesn't lend itself well to situations where Derived classes have methods which don't exist in the Base class.  For example, when iterating over the above HTML Nodes, we might find a DIV node, which has certain methods, and a Text node, which has certain different methods, and a TABLE node, which has its own unique methods - and it wouldn't make much sense for ALL of these various methods to exist in a common Base class "Node", because they are highly specific to each Derived type.  (e.g. a DIV node has no need of a "cells" method, but a TABLE node does.)

So, in a statically typed language, you'd be forced to fall back on something like Type Enums and a lot of messy down-casting to check what type of Node you have.  So basically you end up with messy code like:

```<code>Node node = document.getElementById("foo");
for (int i = 0; i < node.childNodes().length(); ++i)
{
   Node n = node.childNodes().elementAt(i);
   if (n.type() == Node.DIV_NODE) doSomethingWithDiv(((DivNode)(n)));
   else if (n.type() == Node.TABLE_NODE) doSomethingWithTable(((TableNode)(n)));
   /* etc... */
}
</code>```

This is similar to what C programmers do, and it's seemingly the sort of thing virtual functions were designed to avoid.  And yet, when you're faced with a situation where there are various different methods in a Derived class for which it doesn't make any sense to place in a common base class, you have no recourse but to resort to something like Type Enums.

So, how is this problem usually addressed in statically-typed languages?  Is there a better design pattern than Type Enums?

答:
Here's some rules of using inheritance:

Separate your code to two parts: interface and implementation

interface must publish all data via the interface

implementation can implement only the functions available in the interface. No other implementation is allowed.

constructor parameters of derived class are part of the "interface" of an object -- the interface is divided to two parts: common base class, and constructor parameters of derived class

All specific behaviour is handled via constructor parameters


答:
Wordpress

It is cheap, fast, and pretty good.
It has grown and taken a lot of pages on the web pretty quickly.

Wikipedia reports that according to Alexa, it is used for 14.7% of the top million websites, and 22% of new pages in 2011, and is the leading content management system.

http://en.wikipedia.org/wiki/WordPress

I have used it for simple stuff and found it pretty easy.
I have seen demos that looked fantastic (and some no so much), and I believe there are premium themes and a boat load of plug-ins that provide broad and unique capability.

I think you can use a lot of web technologies with it, but it may have trouble playing well with C# .NET, and ASP.

Another option, given that it sounds like you have some investment in Microsoft technologies like C# would be Windows 8 / Visual Studio 2012 / Metro.

I think it can be used to lay down apps or web pages from templates, do data binding with XAML, JS, etc. because they say they are adopting open source technologies into their tools.

I recently saw a presentation by a guy from Google on Angular JS.  It might have some learning curve, but what I saw certainly looked good in terms of exploiting HTML 5, separating view logic from business logic.  It seemed to pretty graciously handle data binding as well.

Good luck in your quest for simple and productive tools with the desired level of flexibility and power.

Title: Freelance Web Developer tools

Body:
I'm thinking of freelancing and building web sites in my free time.

I have experience in C#/ASP.NET, JavaScript/jQuery as well as HTML/CSS and SQL.  Thus, I feel like I have sufficient web technologies knowledge to go down this path.

What I'm unsure of is if there are any tools which can be used to simplify the life of a freelance web dev.  As an example, I once designed an e-commerce website from scratch as a University project, which took around 3 months of hard work to accomplish.  The finished product was not even hosted, and I didn't delve into any security aspects.  I never even hosted a website or database before!

What concerns me is that there are millions of sites out there which can for example be used to create an e-commerce site in minutes.  Without having to bother with databases, security and other issues.  You don't even need to know how to code in server-side technologies to get these sites up and running.

Do professional web developers actually use these tools? If a client had to request an e-commerce site (for example), how would a pro go about developing it? I hear a lot about CMS systems like Joomla and Wordpress, but I think my main problem is that I don't know much about the available tools (other than Visual Studio) and I wouldn't know where to get started.

Can anyone guide me in the right direction?


答:
I'd prefer contacting the service provider first, just in case some of the issues are easily solvable from their side. Their response could range from "no to everything" to "yes to everything, without additional charge", but it will probably be somewhere in the middle ("we can fix this and that, but we'll have to charge you a small fee").

If their response is unsatisfactory, you've at least shown initiative to solve the problem(s) before complaining to your customer. Explaining to the customer that there are multiple issues with the service is good, showing them that the service provider is unwitting, unable or simply not interested in doing their part to fix those issues is better.


问:
Use a partial in a partial?
I'm a Rails newbie, so bear with me.

I have a few places, some pages, some partials that use:

```<code><%= link_to "delete", post, method: :delete,
                                 data: { confirm: "You sure?" },
                                 title: post.content %>
</code>```

Would it make sense to make this a partial since it is used repeatedly, sometimes in other partials too?

Is it o.k. to put partials in partials?

答:
I would try and limit the use of partials within other partials, since it can negatively affect view rendering speed (i.e. rendering lots of partials is super slow), but that said, I have to say, yes it is okay to use partials within other partials.

A couple things you should probably realize about this:

It can get confusing as all hell, especially when:

you're passing around a lot of local variables.

you're rendering collections, i.e. looping over a partial with an array of some sort.

Inferring from the fact that you're asking this question, you probably don't know that you're already rendering partials within partials.

what I mean by this, is that the layout (presumably "application.html.erb") is really going to be your only non-partial in a view.

Whenever you have an action rendered by a view, i.e. 'show', 'new', 'edit' (assuming you're rest-ful), you should realize that the corresponding view (i.e. 'show.html.erb' for example) is a partial being rendered within the main layout file.

Therefore any use of a partial that you yourself make ('_users.html.erb' or what have you) is actually already a 'partial within another partial'.

Kinda feels like Inception, doesn't it? :)

As for your specific example, I agree with the other answerer that you should probably just use it as a helper. And you can use it across many models so long as you abstract enough of the stuff away in the helper, like so:

```<code>def delete_link_for(polymorphic_object, method_symbol)
   link_to "delete", polymorphic_object, method: :delete,
                             data: { confirm: "You sure?" },
                             title: post.send(method_symbol)
end
</code>```

That way you can invoke like this:

```<code> <%= delete_link_for(@post, :content) %>
 <%= delete_link_for(@user, :username) %>
</code>```

etc.

Title: Use a partial in a partial?

Body:
I would try and limit the use of partials within other partials, since it can negatively affect view rendering speed (i.e. rendering lots of partials is super slow), but that said, I have to say, yes it is okay to use partials within other partials.

A couple things you should probably realize about this:

It can get confusing as all hell, especially when:

you're passing around a lot of local variables.

you're rendering collections, i.e. looping over a partial with an array of some sort.

Inferring from the fact that you're asking this question, you probably don't know that you're already rendering partials within partials.

what I mean by this, is that the layout (presumably "application.html.erb") is really going to be your only non-partial in a view.

Whenever you have an action rendered by a view, i.e. 'show', 'new', 'edit' (assuming you're rest-ful), you should realize that the corresponding view (i.e. 'show.html.erb' for example) is a partial being rendered within the main layout file.

Therefore any use of a partial that you yourself make ('_users.html.erb' or what have you) is actually already a 'partial within another partial'.

Kinda feels like Inception, doesn't it? :)

As for your specific example, I agree with the other answerer that you should probably just use it as a helper. And you can use it across many models so long as you abstract enough of the stuff away in the helper, like so:

def delete_link_for(polymorphic_object, method_symbol)
   link_to "delete", polymorphic_object, method: :delete,
                             data: { confirm: "You sure?" },
                             title: post.send(method_symbol)
end

That way you can invoke like this:

 <%= delete_link_for(@post, :content) %>
 <%= delete_link_for(@user, :username) %>

etc.


问:
Analyzing Memory Usage: Java vs C++ Negligible?
How does the memory usage of an integer object written in Java compare\contrast with the memory usage of a integer object written in C++? Is the difference negligible? No difference? A big difference? I'm guessing it's the same because an int is an int regardless of the language (?)

The reason why I asked this is because I was reading about the importance of knowing when a program's memory requirements will prevent the programmer from solving a given problem.

What fascinated me is the amount of memory required for creating a single Java object. Take for example, an integer object. Correct me if I'm wrong but a Java integer object requires 24 bytes of memory:

4 bytes for its int instance variable

16 bytes of overhead (reference to the object's class, garbage collection info & synchronization info)

4 bytes of padding

As another example, a Java array (which is implemented as an object) requires 48+bytes:

24 bytes of header info

16 bytes of object overhead

4 bytes for length

4 bytes for padding

plus the memory needed to store the values

How do these memory usages compare with the same code written in C++?

I used to be oblivious about the memory usage of the C++ and Java programs I wrote, but now that I'm beginning to learn about algorithms, I'm having a greater appreciation for the computer's resources.

答:
It depends on the platform and implementation.

C++ guarantees that the size of char is exactly one byte and at least 8 bits wide. Then, size of a short int is at least 16 bits and not smaller than char. Size of an int is at least as big as size of short int. Size of long int is at least 32 bits and not smaller than int.

sizeof(char) == 1; sizeof(long int) >= sizeof(int) >= sizeof(short int) >= sizeof(bool) >= sizeof(char).

The actual memory model of C++ is very compact and predictable though. For example there is no metadata in objects, arrays or pointers. Structures and classes are contiguous just like arrays are, but padding may be placed where necessary and needed.

Frankly though, such comparison is silly at best as the Java memory usage depends more on the Java implementation than on the code it runs.


问:
Should I take care of race conditions which almost certainly has no chance of occuring?
Let's consider something like a GUI application where main thread is updating the UI almost instantaneously, and some other thread is polling data over the network or something that is guaranteed to take 5-10 seconds to finish the job.

I've received many different answers for this, but some people say that if it is a race condition of a statistical impossibility, don't worry about it at all but others have said that if there's even a 10-53% (I kid you not on the numbers, this is what I've heard) of some voodoo magic happening due to race condition, always obtain/release locks on the thread that needs it.

What are your thoughts? Is it a good programming practice to handle race condition in such statistically-impossible situations? or would it be totally unnecessary or even counterproductive to add more lines of code to hinder readability?

答:
Funnily enough, I encountered this problem recently.  I didn't even realise a race condition was possible in my circumstance.  The race condition only presented itself when multi-core processors became the norm.

The scenario was roughly like this.  A device driver raised events for the software to handle.  Control had to return to the device driver as soon as possible to prevent a timeout on the device.  To ensure this, the event was recorded and queued in a separate thread.

```<code>Receive event from device:
{
    Record event details.
    Enqueue event in the queuing thread.
    Acknowledge the event.
}

Queueing thread receives an event:
{
    Retrieve event details.
    Process event.
    Send next command to device.
}
</code>```

This worked fine for years.  Then suddenly it would fail in certain configurations.  It turns out that the queueing thread was now running truly in parallel to the event handling thread, rather than sharing a single processor's time.  It managed to send the next command to the device before the event had been acknowledged, causing an out-of-sequence error.

Given it only affected one customer in one configuration, I shamefully put a Thread.Sleep(1000) in where the problem was.  There's not been a problem since.

Body:
Funnily enough, I encountered this problem recently.  I didn't even realise a race condition was possible in my circumstance.  The race condition only presented itself when multi-core processors became the norm.

The scenario was roughly like this.  A device driver raised events for the software to handle.  Control had to return to the device driver as soon as possible to prevent a timeout on the device.  To ensure this, the event was recorded and queued in a separate thread.

Receive event from device:
{
    Record event details.
    Enqueue event in the queuing thread.
    Acknowledge the event.
}

Queueing thread receives an event:
{
    Retrieve event details.
    Process event.
    Send next command to device.
}

This worked fine for years.  Then suddenly it would fail in certain configurations.  It turns out that the queueing thread was now running truly in parallel to the event handling thread, rather than sharing a single processor's time.  It managed to send the next command to the device before the event had been acknowledged, causing an out-of-sequence error.

Given it only affected one customer in one configuration, I shamefully put a Thread.Sleep(1000) in where the problem was.  There's not been a problem since.


答:
I hope you realize that all of this is deeply implementation-defined, both for Java and C++. That being said, Java's object model requires quite a bit of space.

C++ objects do not (generally) need any storage except what the members need. Note that (unlike Java, where everything user-defined is a reference type), client code can use an objects both as value type or as reference types, i.e. an object could store a pointer/reference to another object, or store the object directly without indirection. One additional pointer per object is necessary if there are any virtual methods, but quite a few useful classes are designed to get along without polymorphism and don't need this. There is no GC metadata and no per-object lock. Thus class IntWrapper { int x; public: IntWrapper(int); ... }; objects need no more space than plain ints, and can be placed directly (i.e. without indirection) in collections and other objects.

Arrays are tricky simply because there is no pre-made, common equivalent to a Java Array in C++. You could simply allocate a bunch of objects with new[] (with absolutely no overhead/metadata) but there's no length field -- the implementation probably stores one but you can't access it. std::vector is a dynamic array and thus has additional overhead and a larger interface. std::array and C-style arrays (int arr[N];), need a compile-time constant. In theory, it should be just the object's storage plus a single integer for the length -- but since you can get dynamic resizing and a fully-featured interface with very little extra space, you just go for that in practice. Note that all these, as well as all other collections, default to storing the objects by value, thus saving you indirection and the space for references, and improving cache behavior. You must explicitly store pointers (smart ones, please) to get indirection.

The above comparisons is not entirely fair, because some of these savings are afforded by not including features Java includes, and their C++ equivalent is often less optimized than the Java equivalent (*). The common way to implement virtual in C++ imposes exactly as much overhead as the common way to implement virtual in Java. To get a lock, you need a fully-features mutex object, which is most likely larger than a few bits. To get reference counting (not equivalent to GC, and shouldn't be used as such, but sometimes useful), you need a smart pointer which adds a reference count field. Unless the object is constructed carefully, reference count, smart pointer object, and referenced object are in completely separate locations, and even when you construct it right, the shared pointer may (must?) still be two pointers instead of one. Then again, good C++ style does not use these features enough for it to matter -- in practice, a well-written C++ library's objects use less. That does not necessarily mean less memory usage overall, but it does mean C++ has a good head start in this regard.

(*) For instance, you can get virtual calls, identity hash codes and locking with only one word for some objects (and two words for many other objects) by merging the type information with various flags, and removing lock bits for objects that are unlikely to need locks. See Space- and Time-Efficient Implementation of the Java Object Model (PDF) by David F. Bacon, Stephen J. Fink, and David Grove for a detailed explanation of this and other optimizations.

Title: Analyzing Memory Usage: Java vs C++ Negligible?

Body:
How does the memory usage of an integer object written in Java compare\contrast with the memory usage of a integer object written in C++? Is the difference negligible? No difference? A big difference? I'm guessing it's the same because an int is an int regardless of the language (?)

The reason why I asked this is because I was reading about the importance of knowing when a program's memory requirements will prevent the programmer from solving a given problem.

What fascinated me is the amount of memory required for creating a single Java object. Take for example, an integer object. Correct me if I'm wrong but a Java integer object requires 24 bytes of memory:

4 bytes for its int instance variable

16 bytes of overhead (reference to the object's class, garbage collection info & synchronization info)

4 bytes of padding

As another example, a Java array (which is implemented as an object) requires 48+bytes:

24 bytes of header info

16 bytes of object overhead

4 bytes for length

4 bytes for padding

plus the memory needed to store the values

How do these memory usages compare with the same code written in C++?

I used to be oblivious about the memory usage of the C++ and Java programs I wrote, but now that I'm beginning to learn about algorithms, I'm having a greater appreciation for the computer's resources.


问:
C++ for C# Developers
I know C# pretty well (self-taught, sadly) and need to do some C++ programming for a Windows application.  I have been able to find a ton of information for C++ developers learning C# but haven't been able to find much on learning C++ when you already know C#.  Has anyone come across a good rundown of the basics?

MSDN has a comparison but it is not very in-depth.

I can piece together several sources but figured something was out there - I just can't find it.  Thanks for your help.

答:
So, about one year ago I was in the same boat as you: self taught c# dev who felt the need to learn C++. Granted, I stopped and started multiple times. On my third attempt, I finally stuck through it.

What is imperative to understand is that, in terms of C++ and C# methodologies, you will likely spend a lot of time understanding what data manipulation methods through pointers and references really means, as well as when and how to use them given the circumstances.

The nice thing about C++ is that object stack allocation is quite simple for the most part, and you should allocate objects this way if your program will meet the requirements specified under this method. Otherwise, you rely on pointers for speed, efficiency, and quick clean up. I recommend reading this: http://www.parashift.com/c++-faq-lite/ as it will give you a LOT of technical understanding of how C++ works under the hood.

Let me give you an example:

In C++ there exists this constructor implementation known as an "initialization list", which differs from initializing class members in the body of a constructor. Why? Because unless the type being initialized is primitive, the compiler will actually create multiple, and unnecessary copies of the object being created when allocated in the ctor's body. This can potentially reduce performance, depending on the compiler as well as the scaled requirements of the app.

Know what a delegate is? Well, in C++ it is known as a function pointer. This language is quite difficult to master at first, but if you want to be awesome... it's definitely required.

C# is easy...very easy.

Title: C++ for C# Developers


答:
The pricing algorithm will be complex.

Start with basic pricing:

How much does a single user license cost?

Do you have a volume discount?

Do you have a plan for an enterprise license?

Where does the software run?

PC only?

Server based?

Do you allow the use of Citrix?

The use of hardware dongles

Is the standard license fixed to a particular machine or is a hardware dongle used? The hardware dongle still requires it be attached to a PC/Laptop in order to be used.

Can the dongle be placed on a server?

Will the server only be used to hold the license dongle with the code existing on individual machines?

Will the dongle still be matched to a particular piece of hardware?

Usage Mode

What percentage of time is the software in use for a typical user?

How long does it take to install?

How often will multiple people clash when trying to use the software at the same time?

Will the user grab the license at boot up, or will they need to do something explicit to lock a license?

Flexibility

Do you plan on being to split licensees, with some users/machines have priority and the ability to kick others off the system?

Do you plan on having the licensing software calculate usage numbers to show how often they clash, so you can get them to add more licensing?

The price of floating licenses is set to maximize the revenue you can get in some of the variety of usage modes. Now you know why there is no standard.

Title: How much should a floating license cost?

Body:
Floating licensing is a software licensing approach in which a limited number of licenses for a software application are shared among a larger number of users over time. Nice for the corporates to reduce the costs. It has also the developer aspect.

I saw lots of pricing examples for many software. As far I understood, there is no standard to set the prices.

As a software developer, it is also a goal to maximize the yield. Which criteria should I take in account by setting the floating license price?


答:
A plain int, in java, takes exactly as much space as an int in C++, provided that both implementations use the same integer size and memory alignment.

An int 'object' (a boxed integer, that is, an instance of class Integer), carries all the overhead of a class instance in Java, so it is significantly larger than an int in C++. However, if you were to equip an object in C++ with the same features that Java objects come with out-of-the-box (polymorphism, boxing, garbage collection, RTTI), then you'd probably end up with an object of equal size.

And then there are optimization considerations; since the execution models and programming paradigms differ, it is unlikely that any non-trivial problem would be solved the same in both languages, so comparing storage size on this level doesn't make an incredible lot of sense.

Yes, Java objects carry more overhead by default than C++ classes, but they come with more features, and this leads to a different programming style - a good programmer can leverage the up- and downsides of either language.


问:
best way to do the compile and check cycle
I am trying to learn lua and am experimenting on my linux machine. I am not a programmer, so I am looking for your help to give me some suggestions.

What I want to accomplish is making my compile-rewrite-recompile cycle as efficient as possible.

Here is what I do.

I am using vim in one window to program. I have a shell open in another window. When I want to check my progress, I save the code in vim, switch to my shell, then execute the code.

However, this is still kind of tedious, I was there was a faster, more elegant way. Any ideas? How do you go about this problem?

答:
Switching back and forth works well enough for me, but that's partially due to my setup - I run a tiling window manager, and I have two xterms maximized on the same workspace; switching between them is a matter of <Super>-<Tab>.

Alternatively, <Ctrl-Z> to background vim does the same, but within the same xterm.

For larger projects, I probably have a makefile anyway; in a default vim configuration, the :make command runs make in a shell, and I have mapped <F6> to run this command. For running, I still use one of the above methods, but if you like, you can map another key to, say, :!./foobar, where 'foobar' is the name of your binary.


问:
Effective ways to make your OSS project popular?
After writing a few (relatively obscure) OSS frameworks, I've learned the hard way that writing a good framework isn't enough--there has to be some time spent marketing your framework as much as the time you spend coding it. So here's my question: What are some effective ways for making your OSS project become well-known? Aside from blogging, how do I gain the most market attention for my code with the least amount of effort as humanly possible?

(EDIT: I'm a lazy programmer and I hate documentation, but I'm biting the bullet. I want to be famous)

答:
Start making some friends with larger voices than yours.

Social networking is a great tool for this: influential people on Twitter, Facebook, Buzz, what-have-you love sharing new and interesting things their followers might enjoy. The novel link is like currency. So, think about people who are popular and have a large audience and would be interested in your work. Then, just let them know about it.

To facilitate this, you should be treating your project just like you would a startup: come up with an elevator pitch that succinctly describes what it is your project does, what problem it solves, and why someone should care. A blog or some sort of record of progress over time is also valuable, as people who are interested in following a project generally want to see how it evolves just as much, if not moreso, than the project itself.

9 out of 10 times if you're not spammy about it, realize you're talking to a person who is just trying to find something cool, and your project is interesting in its own right, they're going to talk about it to others, or at least link to it.


问:
In what language should I name my business classes?
I'm requesting best practice with this question. This is only an issue if the customer company is strictly national has a native language other than English, I think.

If the customer has a lot of mainly very domain specific (say, German) expressions, mixed with some lesser domain specific namings. The language of our code comments, class/method/variable names is English. Would you translate all domain specific names?

答:
It is generally easier to read source code written in a single language.  This for most programming languages implies you should write it in English.

That said, there is a major problem with domain concepts which do not easily translate into English.  A typical example is a unique identifier which the society gives the individual - in the USA the closest concept is the social security number, but it is not an accurate mapping.  Names and telephone numbers usually map quite well.

I believe that it is usually necessary to keep the domain terms whenever an accurate mapping is not readily available into English, but only those - keep the rest in English.  It will result in unusual identifiers like KommuneImpl but it should make immediate sense to those who know the domain.


问:
Choosing the right programmer among a class of undergrads
I am a CS undergrad but I landed a programming job last year and I like it a lot. We are currently 3 programmer in the development section of the company and we have to work with pretty much anything were asked to do. We deal with many different languages and learn them as needed for some quick jobs etc etc.

We want to hire a 4th programmer and I'm asked to suggest some students in my class, a year younger, since I failed a class. I don't really know any of these guys except my teammates which I wouldn't suggest. We don't really want to interview them all so I thought we could make a little challenge to help us choose who to interview. We're in need of someone who understand the business even though they're new to it, and likes to learn new stuff and code. Any idea on a programming challenge or a kind of letter saying why we should take them?

TL;DR: We need a new undergrad programmer, we want the best to come to us without interviewing them all. Any challenge or test you could suggest?

答:
three things matter when choosing teammates - or employees, for that matter:

do they really, really want to be there?

do you get along? can you work with them? under stress? and can they work with you?

are they willing and able to learn whatever the job requires?

don't skip the interview process. it's not as serious as getting married, but they are, to some degree, moving in with you