问:
How to identify a PDF classification problem?
We are crawling and downloading lots of companies' PDFs and trying to pick out the ones that are Annual Reports. Such reports can be downloaded from most companies' investor-relations pages.

The PDFs are scanned and the database is populated with, among other things, the:

Title

Contents (full text)

Page count

Word count

Orientation

First line

Using this data we are checking for the obvious phrases such as:

Annual report

Financial statement

Quarterly report

Interim report

Then recording the frequency of these phrases and others. So far we have around 350,000 PDFs to scan and a training set of 4,000 documents that have been manually classified as either a report or not.

We are experimenting with a number of different approaches including Bayesian classifiers and weighting the different factors available. We are building the classifier in Ruby. My question is: if you were thinking about this problem, where would you start?

答:
I think you should match phrase in first few (say 500 words) as normally these report contains information whether they are quarterly or annual in first few pages only(like 1Q2012, FY2012 etc). Along with it you can have words which should not be there in annual report.

Much simpler would be to figure out if report is annual or not from the site from where you are downloading this report, so while downloading/crawling only look for this information on the site itself.


问:
initial Class design: access modifiers and no-arg constructors
Context:
Student working through Class design in personal/side project for Summer. I've never written anything implemented by others or had to maintain code. Trying to maximize encapsulation and imagining what would make code easy to maintain.

Concept:
Tight/Loose Class design where Tight and Loose refer to access modifiers and constructors.

Tight: initially, everything, including setters, is private and a no-arg constructor is not provided (only a full constructor).

Loose: not Tight

Exceptions: the obvious like toString

Reasoning:
If code, at the very beginning, is tight, then it should be guaranteed that changes, with respect to access/creation, should never damage existing implementations. The loosening of code happens incrementally and must be thought through, justified, and safe (validated).

Benefit:
Existing implementing code should not break if changes are made later.

Cost:
Takes more time to create.

Since this is my own thinking, I hope to get feedback as to whether I should push to work this way.  Good idea or bad idea?

答: Keep your public API a small as possible. Don't expose setters to class members unless you absolutely have to. Don't implement features you think may become useful in the future (this often leads to feature bloat).</p>

ContentLicense: CC BY-SA 3.0


问:
What's your strongest opinion against functional programming?
Functional programming is one of the oldest programming paradigms. However it isn't used much in the industry compared to more popular paradigms. But it have largely been emphasized in academia.

What's your strongest opinion against functional programming?

答:
The problem with functional programming isn't functional programming itself -- it's most of the people who do it and (worse) most of the people who design languages in which to do it.

The problem stems from the fact that despite being very smart (sometimes downright brilliant) far too many of the people are just a little too fanatical about purity, perfection, and enforcing their own (often rather narrow) view of the world and programing onto the language and everybody who uses it.

One of the results is a failure to compromise. This leads (among other things) to roughly 10,000 languages and dialects that are enough different to annoy but only rarely enough different for one to have a truly significant advantage over the others. Many also look at the real world, and decide that since it doesn't fit the functional model very well, it's basically just wrong and best ignored.

The inability to compromise has also led to quite a few languages that are absolutely beautiful for a specific type of problem (or a few specific types of problems) but really suck for a lot of others. Some of that is probably caused by the functional model itself, but a lot more seems (at least to me) to be caused by the basic personality type that's attracted to this area to start with.

That leads to a number of problems. First of all, learning "functional programming" is mostly of philosophical value. With most other types of languages, knowing one language of a particular genre is of significant help in learning another. If my project uses language X I can usually hire somebody who knows language Y (but not X) fairly safely. With functional languages, that's much less true. You might know Erlang quite well, but still find Haskell monads completely foreign and incomprehensible.

Couple the number of languages with the limited portability of talent between them, and you get an ugly situation: it's almost impossible for one language or dialect to form the "critical mass" necessary to make it into reasonably general use. That's slowly changing, but it's still a lot like Linux becoming the dominant desktop OS -- every year, people come up with convincing arguments that finally this is going to be the year -- and just like the people who've been predicting that every year for decades now, they'll be wrong yet again. That's not to say that it (either one) can't ever happen -- just that the people who look at the predictions and think "nope, not this year" have been the ones who were right so far.

ContentLicense: CC BY-SA 2.5


问:
Quality of Code in unit tests?
When writing unit tests, is it worth spending the extra time to make the code have good quality and readability?

When writing tests I often break the Law of Demeter, for faster writing and to avoid using so many variables. Technically, unit tests are not reused directly - they are strictly bound to the code so I do not see any reason for spending much time on them; they only need to be functional.

答:
if you cannot read a unittest and find out what it is testing the next time it fails you'll spend double the debugging time (once to find out what the test is about and once to fix the code it is testing)

honestly unittests should have a expected outcome; do procedure; get actual outcome; test expected against actual type of structure which is easy to write and understand

Title: Quality of Code in unit tests?


答:
It depends on whether these unit tests are "temporary" or not. If

Test will be frequently used;

Developers have to work with unit tests written by other developers;

Most of the testing is done by unit tests

then the tests should be written properly. In case there is a bug in the test itself, it will be difficult to find the bug and fix it, especially if some time has passed since the test was written.

On the other hand, if these tests are used only by the developers himself/herself only, than I think its ok. But still it is more preferable to write 'readable' code. As ratchet freak said, you'll have spend more time fixing your tests than you would spend on writing them properly.

Title: Quality of Code in unit tests?

Body:
When writing unit tests, is it worth spending the extra time to make the code have good quality and readability?

When writing tests I often break the Law of Demeter, for faster writing and to avoid using so many variables. Technically, unit tests are not reused directly - they are strictly bound to the code so I do not see any reason for spending much time on them; they only need to be functional.


答:
Yes, it matters. There are several reasons why unit tests should be held to a comparable standard as other code:

Each unit test also serves as documentation for the testee. When the tests are comprehensive and cover as many edge cases and error conditions as possible, they can often replace the comment-documentation of a class or function. They can also serve as a starting point for people new to the code base.

Unit tests can be buggy, too. And errors are more visible when the code is well written.

If, for some reason, you later need to split up a module, you'll probably need to split up its unit tests, too. This is easier if the tests are written such that they have easily discernible dependencies.

That said, there's always the question of practicality. Depending on the language and nature of your code, it can be hard to write "clean" unit tests without spending much more time on the tests than on the code they are supposed to test. In that case, I usually fall back on testing the easy, quick stuff and the most critical functionality, without worrying too much about complete coverage. Whenever a bug crops up at a later point, I write a test for it and check if I can refactor the new test and existing ones to make them nicer.

Title: Quality of Code in unit tests?


答:
It is absolutely worth spending time writing good-quality code for unit tests:

They will require maintenance like any other code.

Unit tests are one of the best sources of documentation for your system, and arguably the most reliable form. They should really show:

Intent: "what is the expected behaviour?".

Usage: "how am I supposed to use this API?".

They will require debugging like any other code.

The one factor in favour of a slightly more ad-hoc approach is that your unit tests are never going to be a public API so you don't need to worry about what interfaces/etc. you are exposing.

Title: Quality of Code in unit tests?


问:
Lead Programmer definition clarification
I have been working on PHP and MySQL based web application for more than 5 years now. I started my career as an Intern, and worked my way up through Jr Developer and Software Developer to Sr. Software Engineer (Team Lead), and that's what I am nowadays.

I was looking at the link at Wikipedia regarding who is a lead programmer. The link states the following:

A lead programmer is a software engineer in charge of one or more
  software projects. Alternative titles include Development Lead,
  Technical Lead, Senior Software Engineer, Software Design Engineer
  Lead (SDE Lead), Software Manager, or Senior Applications Developer.
  When primarily contributing in a high-level enterprise software design
  role, the title Software Architect (or similar) is often used. All of
  these titles can have different meanings depending on the context.

My current job responsibilities are more or less like a Development Lead and to some extent near Software Architect because I usually design the core structure of new products, and manage 2-3 project simultaneously while assisting other teams regarding the structural design of their projects. I am usually on call with clients along with project managers. I code most of the time when my team is stuck somewhere, has a heavy workload, is integrating some third party API, etc.

Does what I do qualify for a Development Lead title in accordance with my above mentioned job descriptions?

答:
Well, the job titles do not matter if you are not doing executive work.

What matters is how well you know your subject area and are you aware of the current trends. Are your skills in demand and how good you now the technology that you use everyday?

Another point is - most small to medium software development companies do not care about "job titles". What they look for is reliable and dependable person with ability to accomplish work, be able to learn quickly and have experience to handle complex situations, as well as a good team player for team development environment.


答: Summarizing your job into 2 words is usually not a good idea. If you are writing a CV, write what responsibilities you have, not only a job title.</p>

Title: Lead Programmer definition clarification

Body:
I have been working on PHP and MySQL based web application for more than 5 years now. I started my career as an Intern, and worked my way up through Jr Developer and Software Developer to Sr. Software Engineer (Team Lead), and that's what I am nowadays.

I was looking at the link at Wikipedia regarding who is a lead programmer. The link states the following:

A lead programmer is a software engineer in charge of one or more
  software projects. Alternative titles include Development Lead,
  Technical Lead, Senior Software Engineer, Software Design Engineer
  Lead (SDE Lead), Software Manager, or Senior Applications Developer.
  When primarily contributing in a high-level enterprise software design
  role, the title Software Architect (or similar) is often used. All of
  these titles can have different meanings depending on the context.

My current job responsibilities are more or less like a Development Lead and to some extent near Software Architect because I usually design the core structure of new products, and manage 2-3 project simultaneously while assisting other teams regarding the structural design of their projects. I am usually on call with clients along with project managers. I code most of the time when my team is stuck somewhere, has a heavy workload, is integrating some third party API, etc.

Does what I do qualify for a Development Lead title in accordance with my above mentioned job descriptions?


答:
I found myself in the same situation, as I got promoted rapidly from normal developer to development lead, because sometimes, bus factors may be very large. If the former lead leaves and you're the one who knows the application best, you become responsible for it.

This given as an entry statement, but to be clear: Titles are not much worth, as everbody may give himself a fancy title as senior chief development lead (in a one person project). Some companies even say "Make up the coolest name ever for your card as long as you're comfortable with it"...

It depends more on the jobs you do and how good you do them.

IMHO, there are two types of developers: Executioners and Designers. Both classes may overlap.

In a binary 1/0 world, executioners only do what they are told (by other developers), designers do (or delegate) what customers told them. But even executioners may delegate work to others.

The point in "lead developer" is, that there is someone you can lead. Know your team, know what they can do and delegate work to them (and jump in if somewhere the roof is on fire).

All other titles (Senior, Junior, Prehistoric) may be nice, but they don't say very much about what your abilities are. That's the 7*1 year vs. 1*7 year experience thing. A senior java developer who never did anything else than working in a single framework for seven years may not be as good as someone, who worked with different framesworks over a shorter period of time.


问:
C++ Iterator lifetime and detecting invalidation
Based on what's considered idiomatic in C++11:

should an iterator into a custom container survive the container itself being destroyed?

should it be possible to detect when an iterator becomes invalidated?

are the above conditional on "debug builds" in practice?

Details: I've recently been brushing up on my C++ and learning my way around C++11.  As part of that, I've been writing an idiomatic wrapper around the uriparser library.  Part of this is wrapping the linked list representation of parsed path components.  I'm looking for advice on what's idiomatic for containers.

One thing that worries me, coming most recently from garbage-collected languages, is ensuring that random objects don't just go disappearing on users if they make a mistake regarding lifetimes.  To account for this, both the PathList container and its iterators keep a shared_ptr to the actual internal state object.  This ensures that as long as anything pointing into that data exists, so does the data.

However, looking at the STL (and lots of searching), it doesn't look like C++ containers  guarantee this.  I have this horrible suspicion that the expectation is to just let containers be destroyed, invalidating any iterators along with it.  std::vector certainly seems to let iterators get invalidated and still (incorrectly) function.

What I want to know is: what is expected from "good"/idiomatic C++11 code?  Given the shiny new smart pointers, it seems kind of strange that STL allows you to easily blow your legs off by accidentally leaking an iterator.  Is using shared_ptr to the backing data an unnecessary inefficiency, a good idea for debugging or something expected that STL just doesn't do?

(I'm hoping that grounding this to "idiomatic C++11" avoids charges of subjectivity...)

答:
In C++, if you let the container get destroyed, then the iterators become invalid. At the very least this means that the iterator is useless, and if you try to dereference it, then lots of bad things can happen (exactly how bad depends on implementation, but it's usually pretty bad).

In a language like C++, it is the responsibility of the programmer to keep such things straight. That's one of the strengths of the language, because you can pretty much depend on when things happen (you deleted an object? That means that at the moment of deletion, the destructor will be called and the memory will be freed, and you can depend on that), but it also means that you can't go keeping iterators into containers all over the place, and then delete that container.

Now, could you write a container that keeps the data around until the iterators are all gone? Of course, you've clearly got that going. That's NOT the usual C++ way, but there's nothing wrong with it, as long as it's properly documented (and of course, debugged). It's just not how the STL containers work.


答:
Is using shared_ptr to the backing data an unnecessary inefficiency

Yes - it forces an extra indirection and an extra allocation per element, and in multithreaded programs each increment/decrement of the reference count is extra expensive even if a given container is used only inside a single thread.

All of these might be fine, and even desirable, in some situations, but the general rule is not to impose unnecessary overheads which the user cannot avoid, even when they're useless.

Since none of these overheads are necessary, but are rather debugging niceties (and remember, incorrect iterator lifetime is a static logic bug, not some weird runtime behaviour), no-one would thank you for slowing down their correct code to catch your bugs.

So, to the original question:

should an iterator into a custom container survive the container itself being destroyed?

the real question is, should the cost of tracking all live iterators into a container, and invalidating them when the container is destroyed, be foisted on people whose code is correct?

I think probably not, although if there is some case where it's genuinely hard to manage iterator lifetimes correctly and you're willing to take the hit, a dedicated container (or container adapter) that provides this service could be added as an option.

Alternatively, switching to a debug implementation based on a compiler flag might be reasonable, but it's a much bigger and more expensive change than most that are controlled by DEBUG/NDEBUG. It's certainly a bigger change than either removing assert statements or using a debugging allocator.

I forgot to mention, but your solution of using shared_ptr everywhere doesn't necessarily fix your bug anyway: it may merely exchange it for a different bug, namely a memory leak.

Title: C++ Iterator lifetime and detecting invalidation

Body:
Based on what's considered idiomatic in C++11:

should an iterator into a custom container survive the container itself being destroyed?

should it be possible to detect when an iterator becomes invalidated?

are the above conditional on "debug builds" in practice?

Details: I've recently been brushing up on my C++ and learning my way around C++11.  As part of that, I've been writing an idiomatic wrapper around the uriparser library.  Part of this is wrapping the linked list representation of parsed path components.  I'm looking for advice on what's idiomatic for containers.

One thing that worries me, coming most recently from garbage-collected languages, is ensuring that random objects don't just go disappearing on users if they make a mistake regarding lifetimes.  To account for this, both the PathList container and its iterators keep a shared_ptr to the actual internal state object.  This ensures that as long as anything pointing into that data exists, so does the data.

However, looking at the STL (and lots of searching), it doesn't look like C++ containers  guarantee this.  I have this horrible suspicion that the expectation is to just let containers be destroyed, invalidating any iterators along with it.  std::vector certainly seems to let iterators get invalidated and still (incorrectly) function.

What I want to know is: what is expected from "good"/idiomatic C++11 code?  Given the shiny new smart pointers, it seems kind of strange that STL allows you to easily blow your legs off by accidentally leaking an iterator.  Is using shared_ptr to the backing data an unnecessary inefficiency, a good idea for debugging or something expected that STL just doesn't do?

(I'm hoping that grounding this to "idiomatic C++11" avoids charges of subjectivity...)


答:
You should definitely take the same if not better care of your unit tests than your production code in terms of quality and readability. The unit tests are often the first thing you look at when trying to grasp what some piece of code does, and the reader should quickly understand what's at stake when looking at the test. Unit tests also tend to change a lot and will break a lot if their design is not robust, which kind of nullifies the benefits of having tests.

Violation of the Law of Demeter is definitely a problem in your unit tests for that reason as well as 2 others that come off my mind :

If your tests break the Law of Demeter in their Arrange or Act sections, it's probably a sign that your production code also does, since your unit tests are just another consumer of your code and will probably call and operate the class under test in the same way that any other production code would do.

If your tests break the Law of Demeter in their Assert sections (ie you verify the value of something that is deeply nested in the dependencies graph of the object under test), it might be that those are really integration tests rather than unit tests. In other words, if in TestA you assert that A.B.C.D equals something, it might be that you're actually trying to test D and A rather than just A.

By the way, when you say

I break very often the Law of Demeter, for faster writing and not
  using so many variables.

you should be aware that writing

```<code>var grab = myDependency.Grab;
var something = grab.Something;
var very = something.Very;

very.Deep();
</code>```

is actually no better Demeter wise than

```<code>myDependency.Grab.Something.Very.Deep();
</code>```

if that's what you meant.

Title: Quality of Code in unit tests?

Body:
You should definitely take the same if not better care of your unit tests than your production code in terms of quality and readability. The unit tests are often the first thing you look at when trying to grasp what some piece of code does, and the reader should quickly understand what's at stake when looking at the test. Unit tests also tend to change a lot and will break a lot if their design is not robust, which kind of nullifies the benefits of having tests.

Violation of the Law of Demeter is definitely a problem in your unit tests for that reason as well as 2 others that come off my mind :

If your tests break the Law of Demeter in their Arrange or Act sections, it's probably a sign that your production code also does, since your unit tests are just another consumer of your code and will probably call and operate the class under test in the same way that any other production code would do.

If your tests break the Law of Demeter in their Assert sections (ie you verify the value of something that is deeply nested in the dependencies graph of the object under test), it might be that those are really integration tests rather than unit tests. In other words, if in TestA you assert that A.B.C.D equals something, it might be that you're actually trying to test D and A rather than just A.

By the way, when you say

I break very often the Law of Demeter, for faster writing and not
  using so many variables.

you should be aware that writing

var grab = myDependency.Grab;
var something = grab.Something;
var very = something.Very;

very.Deep();

is actually no better Demeter wise than

myDependency.Grab.Something.Very.Deep();

if that's what you meant.


问:
Use my own GPL licensed code in a commercial product
I am developing a software project in Java/Swing licensed under GPL v3.
Later, I want to create a Android application which uses the algorithms of the Java/Swing application. This Android app will be a commercial product (sold on Google Play Store).

Is this a problem, when I use my OWN GPL code in a commercial SW developed by me?

答:
Is this a problem, when I use my OWN GPL code in a commercial SW developed by me?

No, why do you ask? Because you were so free to have released it once under
GNU GPL? You don't marry the GPL, so as long as you are the author and copyright owner, you can change the license for each release you do. You are in control.

From the GPL FAQ: I would like to release a program I wrote under the GNU GPL, but I would like to use the same code in non-free programs. :

To release a non-free program is always ethically tainted, but legally there is no obstacle to your doing this. If you are the copyright holder for the code, you can release it under various different non-exclusive licenses at various times.

However, if your code has other authors and copyright holder, too (e.g. being a derivative work), this depends. You have not said so, so this is just to give the counter-example.

OwnerDisplayName: Andreas Freitag


问:
Using default parameters for 404 error (PHP with mvc design)?
I have a custom made Framework (written in PHP). It all works very good, but i have some doubts about a certain thing.

Right now when a user call this url for example:

```<code>http://host.com/user/edit/12
</code>```

Which would resolve to:

user = userController

edit = editAction() in userController

12 = treated as a param

But suppose the controller 'userController' doesn't exist. Then i could throw a 404. But on the other hand, the url could also be used as params for the indexController (which is the default controller). So in that case:

controller = indexController

user = could be an action in indexController, otherwise treated as a param

edit = treated as a param

12 = treated as a param

That is actually how it works right now in my framework. So basically, i never throw a 404.

I could ofcourse say that only params can be given if the controller name is explicitly named in the URL. So if i want the above url:

```<code>http://host.com/user/edit/12
</code>```

To be invoked by the indexController, in the indexAction. Then i specifically have to tell what controller and action it uses in the URL.

So the URL should become:

```<code>http://host.com/index/index/user/edit/12
</code>```

index = indexController

index (2nd one) = the action method

user = treated as a param

edit = treated as a param

12 = treated as a param

That way, when a controller doesn't exist, i don't reroute everything as a param to the index controller and simply throw a 404 error.

Now my question is, which one is more preffered? Should i allow both options to be configurable in a config file? Or should i always use one of them. Simply because that's the only and best way to do it?

答:
If you are forcing the system to call the url http://host.com/user/edit/12 like http://host.com/index/index/user/edit/12 then you are rerouting for no reason for every controller that exists and you logic would only be good for a non-existing controller.

That way, when a controller doesn't exist, i don't reroute everything
  as a param to the index controller and simply throw a 404 error.

besides this if you have finally decided to throw 404 then why not do that in the main executing file? probably index.php?

Your system in index.php checks for a controller if exists execute it else pass it to default controller that checks if the said params contain any action for default controller and if it exists then fine else shows 404 error. Why involving default controller for this you are ultimately calling default controller for no reason.


问:
How do employers measure "strong or solid knowledge of programming language"?
Yesterday I had received a great job opportunity.

In requirements section I had seen the words:

solid knowledge of python;

solid knowledge of java;

good technical background;

Could you give me an answer, what does it mean?
How to test my current knowledge? What type of measure will be actually accepted by employer?

答:
Of course all these answers have been giving the benefit of the doubt to the person who posted the job requirements.  In a perfect world, the words "solid knowledge of..." would be easily quantifiable, and result in would-be employers and employees swiftly understanding each other's requirements.

In practice, these things are likely to mean different things to different people.  Sure, if you know little to nothing about Python or Java you definitely shouldn't be applying for this job.  But if you have some knowledge, there's not much point in fretting about whether that knowledge is "solid" enough.  Really like the look of the job?  Get in touch with the employer, and find out if your level of expertise is close enough to the level they were thinking about when they posted the opportunity.

There's no sense wasting time agonising about what a very vague description of requirements might mean. Acquire clarification.


问:
Scrum - how to carry over a partially complete User Story to the next Sprint without skewing the backlog
We're using Scrum and occasionally find that we can't quite finish a User Story in the sprint in which it was planned. In true Scrum style, we ship the software anyway and consider including the User Story in the next sprint during the next Sprint Planning session. Given that the User Story we are carrying over is partially complete, how do we estimate for it correctly in the next Sprint Planning session? We have considered:

a) Adjusting the number of Story Points down to reflect just the work which remains to complete the User Story. Unfortunately this will mess up reporting the Product Backlog.

b) Close the partially-completed User Story and raise a new one to implement the remainder of that feature, which will have fewer Story Points. This will affect our ability to retrospectively see what we didn't complete in that sprint and seems a bit time consuming.

c) Not bother with either a or b and continue to guess during Sprint Planning saying things like "Well that User Story may be X story points, but I know it's 95% finished so I'm sure we can fit it in."

答:
If your reporting tool cannot handle option A accurately then I would go with option B unless you have no hope of ever using your metrics.

In some cases you can do option B AND not skew what closed means by narrowing the scope of the old task you are about to close and only creating a new task for the scope that remains.  This makes the history make more sense semantically and usually indicates places where you should have considered breaking the task down further.  Sometimes this is not possible or logical and you simply have a task that is that large or runs into that level of issues.

edit:
This assumes (as I believe the OP was assuming) that nearly complete work has not been knocked down in priority and that getting to the payoff on the previous effort keeps it high enough in the list to continue working.  I know some shops do not do this, but most places I have worked consider finishing a near-complete leftover task to be valuable enough to simple continue unless something has changed dramatically.  The penalty of changing context is often not worth changing the order.


问:
Python and only Python for almost any programming tasks!
Am I wrong if I think that Python is all I need to master, in order to solve most of the common programming tasks?

EDIT
I'm not OK with learning new programming languages if they don't teach me new concepts of programming and problem solving; hence the idea behind mastering a modern, fast evolving, with a rich set of class libraries, widely used and documented, and of course has a "friendly" learning curve programming language.

I think that in the fast evolving tech industry, specialization is key to success.

答:
I don't think Python is going to be a very good fit for embedded microcontrollers which might have only 32K of flash and 4K of RAM, but need to handle 25,000 interrupts per second.

(p.s. I have nothing against Python, in fact I recently purchased Pycharm 1.0 from JetBrains.  I just don't see it as general-purpose as C, for example.  Can you write all of Python in itself?)


问:
Licensing a JavaScript library
I am developing a free, open-source (duh) JavaScript library, and wondering how to license it.

I was considering the GNU GPL, but I heard that I must distribute the license with the software, and I'm not sure anymore.

I would like the library to be available much like jQuery: In a free, downloadable script, preferably in either original or minified form. Am I mistaken about the GNU GPL license terms? jQuery is dual licensed under GNU GPL or MIT licenses.

How does the GPL apply to single script files like that? Can I license my library with nothing more than a few sentences in the script file? Is there another license that better suits my needs?

What would be nice is a license that allows you to put the URL in the source, for people to read if they want. I don't know that many do, unless I am mistaken.

I am generally looking to release the library as free software like the GPL specifies, but don't want to have to force licensees to download the full license unless they wish to read it.

答:
A BSD-like license is more business-friendly than a GPL license, a MIT license in this regard is more like a BSD license. Sometimes a MIT license can be considered an evolution or a slightly different approach to the licensing compared to a standard BSD license.

An apache license is probably not for you since it's more indicated for organization and large group of people, it's a GPL-like license but a little bit more complex, an apache license can also involve the use of patents and sometimes this can be a little tricky, the apache license is probably one of the longest license ever written for the free software world and this could be considered an hint.

You can also decide to release your software as "public domain" and with that you simple release your software without any sort of restriction or obligation for the user.
Sqlite is an example about public domain software http://www.sqlite.org/copyright.html

this are the most popular approaches, you can easily find all the details about this licenses online or in wikipedia.

Title: Licensing a JavaScript library


答:
Option A is a commonly recommended course of action. You do not award points for the completion of the story for the previous sprint and to move the story back into the product backlog, where it is reprioritized. You compute your velocity (and other metrics) based on the completed user stories and value-added. When you begin planning for the next sprint, you take the highest priority stories based on their value (which might or might not include the unfinished story, if business priorities have changed). When you estimate the story, include the work that has already been done when factoring in the new amount of points for the story.

Of course, an alternative option (and my preference) would be to use the original estimated number of story points, which is something that I've done in the past. This makes the assumption that your estimate was good and well-founded, but you pulled down too much work for the sprint (eg - the story was actually worth 3 points, but the problem lies in the fact that you pulled down 15 story points when you should have only pulled down 13). It's a potentially dangerous assumption if you aren't confident in your ability to perform the estimates, but it might work based on your team and process.

However, you mention that this will "mess up the reporting of the Product Backlog". The Product Backlog should be dynamic anyway, with the ordering and estimations of each story changing as more is understood about the technology, the system, the requirements, and the customer. Typically, what gets reported out of the Product Backlog is the number of user stories and the total number of story points. These should be expected to change as priorities change, new requirements are added, invalid requirements are removed, and more information is learned.

Title: Scrum - how to carry over a partially complete User Story to the next Sprint without skewing the backlog

Body:
We're using Scrum and occasionally find that we can't quite finish a User Story in the sprint in which it was planned. In true Scrum style, we ship the software anyway and consider including the User Story in the next sprint during the next Sprint Planning session. Given that the User Story we are carrying over is partially complete, how do we estimate for it correctly in the next Sprint Planning session? We have considered:

a) Adjusting the number of Story Points down to reflect just the work which remains to complete the User Story. Unfortunately this will mess up reporting the Product Backlog.

b) Close the partially-completed User Story and raise a new one to implement the remainder of that feature, which will have fewer Story Points. This will affect our ability to retrospectively see what we didn't complete in that sprint and seems a bit time consuming.

c) Not bother with either a or b and continue to guess during Sprint Planning saying things like "Well that User Story may be X story points, but I know it's 95% finished so I'm sure we can fit it in."


答:
In my current team we do c).

The velocity should account for things the team really finished in the sprint. Something that was not delivered has no value for the customer, so we don't count any points for it, it's all or nothing.

So we shift the whole unfinished story on to the next sprint and all its story points will be added to the next sprint's velocity. Velocities even out over time and we take an average of the few previous sprints as a reference to determine estimate future velocities.


答:
Job titles are often very specific to the politics of the company.  I have worked places that have as many as 11 tiers of titles with suffixes describing what the focus of your work is and I have worked other places that only have jr dev, dev, sr dev because they don't want more titles in IT than there are in other departments.  I have done more architect work with titles from the latter set than the former.

If you are choosing a title you can probably come up with something more descriptive or not if you don't care to, if your company has that position and you are wondering if you should go after it you may be close to doing that task as you describe your current work now.

The architect role usually has more internal politics/management interaction that you are describing in my experience.  That is the one thing that sounds different.


问:
Is it a security flaw to log the class and method name when an exception occurs?
I have the following :

```<code>public class doCheck(){

    public void performCheck(){
        try {
            perform all checks......
        }
        catch(Exception e){
            logger.error("Exception occured in class doCheck in method performCheck");
            thrown new MyNewException(e.getMessage());
        }
    }
}
</code>```

Is it safe to log the class and method name?

答:
@Konrad answered the direct question, however your exception handling has one minor and two serious problems. Since you originally posted to codereview.SE, here they are:

Logging an exception before throwing is pointless. Log it where you handle it, and don't bother catching it if you don't plan to handle ti.

If you're going to log an exception, log the exception; don't simply say "an exception happened" and expect people to guess what the exception is. All common logging frameworks provide a two-argument method: the first is the message, the second is the throwable.

Rethrowing an exception with just a message is the same problem but a worse instance. I can understand (barely) why you might not want an exception stack trace to show up in your logs. But once you throw the new exception, you have absolutely no way to tell what the real problem is. Especially if you keep up the habit of catching and rethrowing.

OK, I'm going to add a fourth issue: you log where the exception happened, but you don't say what you were doing when it happened, or give any contextual information. If you log the actual exception (point #1), you'll know where it happened. More important is saying something like "unable to open file foo.txt".


问:
Git: Fixing a bug affecting two branches
I'm basing my Git repo on A successful Git branching model and was wondering what happens if you have this situation:

Say I'm developing on two feature branches A and B, and B requires code from A. The X node introduces an error in feature A which affects branch B, but this is not detected at node Y where feature A and B were merged and testing was conducted before branching out again and working on the next iteration.

As a result, the bug is found at node Z by the people working on feature B. At this stage it's decided that a bugfix is needed. This fix should be applied to both features, since the people working on feature A also need the bug fixed, since its part of their feature.

Should a bugfix branch be created from the latest feature A node (the one branching from node Y) and then merged with feature A? After which both features are merged into develop again and tested before branching out?

The problem with this is that it requires both branches to merge to fix the issue. Since feature B doesn't touch code in feature A, is there a way to change the history at node Y by implementing the fix and still allowing the feature B branch to remain unmerged yet have the fixed code from feature A?

Mildly related: Git bug branching convention

答:
Although not a popular workflow in git, a workflow which is popular in Mercurial would be to update to revision X, fix the bug there (as X2) and then redo merge Y (which would have been a pair of merges in Mercurial).

In fact, this workflow is easier in git since after everyone has switched from Y to Y2 then the refs to the original Y will be lost and it will eventually be garbage collected. In hg you would have had to manually strip those commits to tidy up your repository.


问:
For nodejs what are best design practices for native modules which share dependencies?
Hypothetical situation, I have 3 node modules all native, A, B, and C.

A is a utilities module which exposes several functions to javascript through the node interface, in addition it declares/defines a rich set of native structures and functions

B is a module which is dependent on data structures and source in A, it exposes some functions to javascript, in addition it declares/defines native structures and functions

C is a module which is dependent on data structures and source in A & B, it exploses some functions to javascript, in addition it declares/defines native structures and functions

So far when setting up these modules I have a preinstall script to install other dependent includes, but in order to access all of another modules source what is the best way to link to it's share library object (*.node) ?

Is there an alternative best practice for native modules (such as installing all source from other modules before building that single module)?
Reply

答:
Prompted by rsms I'd like to share the architecture I'm going with now originally answered/shared here on stackoverflow.

What's the best way to create common native source code
  packages that other node modules can rely on?

...I do have an answer for constructing reusable libraries witlinh native node modules.

I'm using git submodules for all the independent native node modules, and added a conditional preprocessor definition for each of their wscript or binding.gyp files to specify whether or not to generate a shared object .node module.

In addition I'll be using this new package to aid in debugging or rewriting code sections (I can't spend too much time debugging utilization of several remote libraries).

in wscript or binding.gyp

```<code>  flags = ['-D_NAME_NODE_MODULE', '-O3', '-Wall', '-D_FILE_OFFSET_BITS=64', '-D_LARGEFILE_SOURCE', '-msse2']
</code>```

then in an initialization file

```<code>#ifdef _NAME_NODE_MODULE

extern "C" {
  static void init(Handle<Object> target) {
    HandleScope scope;
    NODE_SET_METHOD(target, "someFunction", someFunction);
  }

  NODE_MODULE(moduleName, init);
}

#endif
</code>```

This way a node native module is only added to when the flag is set. Otherwise it can be linked to normally (like in another node module).

Body:
Prompted by rsms I'd like to share the architecture I'm going with now originally answered/shared here on stackoverflow.

What's the best way to create common native source code
  packages that other node modules can rely on?

...I do have an answer for constructing reusable libraries witlinh native node modules.

I'm using git submodules for all the independent native node modules, and added a conditional preprocessor definition for each of their wscript or binding.gyp files to specify whether or not to generate a shared object .node module.

In addition I'll be using this new package to aid in debugging or rewriting code sections (I can't spend too much time debugging utilization of several remote libraries).

in wscript or binding.gyp

  flags = ['-D_NAME_NODE_MODULE', '-O3', '-Wall', '-D_FILE_OFFSET_BITS=64', '-D_LARGEFILE_SOURCE', '-msse2']

then in an initialization file

#ifdef _NAME_NODE_MODULE

extern "C" {
  static void init(Handle<Object> target) {
    HandleScope scope;
    NODE_SET_METHOD(target, "someFunction", someFunction);
  }

  NODE_MODULE(moduleName, init);
}

#endif

This way a node native module is only added to when the flag is set. Otherwise it can be linked to normally (like in another node module).


问:
Pronunciation in programming?
How do you correctly or erroneously pronounce programming terms?  Any that you find need strict correction or history into the early CS culture?

Programming

char = "tchar" not care?

! = bang not exclamation?

# = pound not hash? Exception #! = shebang

* = splat not star?

regex = "rej ex" not "regg ex"?

sql = "s q l" not "sequel" (already answered, just i.e.)

Unixen

| = pipe not vertical bar?

bin = bin as in pin , not as in binary?

lib = lib as in library , not as in liberate?

etc = "ett see" , not "e t c" (as in /etc and not "&c")

Annoyance

/ = slash not backslash

LaTeX = "laytek" not "lay teks"

答:
```#``` This can also be called the number sign or octothorpe for another couple of answers.

```<,>```

These are "angle brackets" usually now though growing up I knew them as less than and greater than respectively.

Title: Pronunciation in programming?

Body:
#
 This can also be called the number sign or octothorpe for another couple of answers.

<,>

These are "angle brackets" usually now though growing up I knew them as less than and greater than respectively.


问:
Business Analyst role in development process
I work as a business analyst and I currently oversee much of the development efforts of an internal project.  I'm responsible for the requirements, specs, and overall testing.  I work closely with the developers (onshore and offshore).

The offshore team produces all of the reports.  Version 1.0 had a 9 month development cycle and I had about 4-5 months to test all the reports.  There was the usual back and forth to get the implementation right.

Version 2.0 had a much shorter development cycle (3 months).  I received the first version of the reports about 3 weeks ago and noticed a lot of things wrong with it.  Many of the requirements were wrong and the performance of the queries was horrendous at 5x - 6x longer than it should have been.

The onshore lead developer was out and did not supervise the offshore development team in generating the reports.

Management knew about the performance issues and I also told them I was trying to find a way to improve performance; they did not explicitly approve of sending test queries, but they were also not concerned with the fact I was doing that.  I took a look at the SQL in the reports and was able to improve performance greatly (by a factor of 6x) which is acceptable for this version.

I sent the updated queries as guidelines to the offshore team and told them they should look at doing X instead of Y to improve performance and also to fix some specific logic issues.

I then spoke to my managers about this because it doesn't feel right that I was developing SQL queries, but given our time crunch I saw no other way.  We were able to fix the issue quite fast which I'm happy with.

Current situation: the onshore managers aren't too pleased that the offshore team did not code for performance.  I know there are some things I could have done better throughout this process and I do not in any way consider myself a programmer.

My question is, if an offshore team that works apart from the onshore project resources fails to deliver an acceptable release, is it appropriate to clean up their work to meet a deadline?  What kind of problems could this create in the future?

Update: So far management is upset with the offshore team, but have not "reprimanded" me in any way, so I'm not sure in their eyes if what I did was wrong, but I think their main source of frustration was the offshore team was not able to come up with a solution and I was, especially since this sort of performance issue had come up in the past.  I am not defending my actions, but I want to give context so that the picture is a little clearer.  I accepted the answer that most criticizes my actions I agree it's not something that should be done by someone in my position.

答:
No, it's not acceptable to clean up their work.

There are a number of reasons as to why.

1) v2.0 had a development cycle that was 1/3rd of the original cycle, and the report validation period was shrunk from 50% of the cycle to less than 30% of the cycle.

It's okay to contract a development cycle, but unless the quantity of reports was significantly smaller, the validation window should have remained proportionate.  Since the reports were significantly more complex, it would not be unreasonable to expect continuous validation of the reports throughout the entire dev cycle.

2) By taking things into your own hands, you broke the chain of command and you failed to notify management in a timely fashion of the significant problems with the report.  Those performance and requirements issues represented risks to meeting the schedule, and that's something the management team has a right to be aware of.  While you think you know what would have been done to resolve the matter, you don't know for certain since it wasn't your decision to make.  Management's role is to weigh the pros / cons of one path vs. the other and to accept responsibility for the consequences.  You short-circuited that process by presuming the answer and assuming that what the onshore team was working on was a higher priority.  For all you know, there may have been someone with capacity to fix the issue or a different solution could have been found.

3) You also broke out of your Area of Responsibility.  Normally, this is not an issue in my book as I'm in favor of everyone contributing where they can and growing their skills.  However, you most likely were not the most skilled person to resolve the matter.  By taking this on without notifying others, you denied the opportunity to get the issue resolved more quickly.  It's possible that the offshore team could have quickly fixed the issues once they had been notified of them.  What would the onshore team lead have said to you had he not been on vacation and knew what you were doing?

Complicating all of this is the invetiable tension between onshore and offshore teams.  You inadvertently walked straight into a hornet's nest of political issues.

The right thing would have been to notify your management immediately of the problem and then offer that you knew SQL and would be happy to tackle the challenge.  That puts another option on the plate for resolving the matter, but still allows management to pick the best approach for fixing the issue.


答:
One of the (often not said) difference between C++ and GC languages is that the mainstream C++ idiom assumes that all classes are value classes.

There are pointer and references, but they are mostly relegated in allowing polymorphic dispatch (via virtual function indirection) or managing object whose lifetime must survive the one of the block who created them.

In this last case, it is the programmer responsibility to define the policy and politics about who create and who and when must destroy.
Smart pointers (like shared_ptr or unique_ptr) are just tools to help in this task in the very particular (and frequent) cases an object is "shared" by different owners (and you want the last one to destroy it) or needs to be moved across contexts having always a single context owning it.

Interators, by design, makes sense only during ... an iteration, and hence they should not be "stored for later use" since what they refer to, is not granted to remain the same or to stay there (a container may relocate it's content when growing or shrinking ... invalidating everything). Link-based containers (like lists) are an exception to this general rule, not the rule themselves.

In the idiomatic C++ if A "needs" B, B must be owned in a place that lives longer than the place that owns A, hence no "life tracking" of B from A is required.

shared_ptr and weak_ptr help where this idiom is too restrictive, by allowing respectively the "don't go away until all of us allow you" or the "if you go away just leave a message for us" policies. But they have a cost, since -to do that- they have to allocate some auxiliary data.

The next step are gc_ptr-s (that the standard library doesn't offer, but that you can implement if you want, using -for example- mark & sweep algorithms) where the tracking structures will be even more complex and more processor intensive is their maintenance.


问:
Is this a good use for ThreadPool.QueueUserWorkItem?
I have an application that, among other things, imports documents, then emails necessary parties to let them know that a document has been imported.

It turns out that determining whom to email, then performing the emailing, is what's taking the longest.  I was thinking of doing something like this:

```<code>var document = ImportDocument();
ThreadPool.QueueUserWorkItem(s => SendEmail(document.Id));
return document;
</code>```

... similar to DelayedJob in Rails, if that helps. Does that make sense in this context?  What would you do?

答:
Yes, this sounds like a reasonable enough approach.

At a broader level, this is related to work management.

You have a main task (import the document) and some related sub-tasks triggered by the main task (email notification, archiving, etc...).

Generally, the sub-tasks should be asynchronous to the main task as they don't really affect declaring the main task complete.  IMO, if they do affect the main task being declared complete, then they would be part of the main task, not a sub-task.

You could also have a dedicated object that handles the email notifications.  It would have a queue (or equivalent) to receive notification of the document being imported, and would start-up upon a notification event.  If you end up with a notifications going out, consider this approach.  It will avoid the churn of spinning up (and down) all of those threads and it will avoid overloading the system with secondary, async type tasks.


问:
Why is it good to split a program into multiple classes?
I'm still a student in high school (entering 10th grade), and I have yet to take an actual computer course in school. Everything I've done so far is through books. Those books have taught me concepts such as inheritance, but how does splitting a program into multiple classes help? The books never told me.

I'm asking this mainly because of a recent project. It's an arcade video game, sort of like a Flash game as some people have said (although I have no idea what a Flash game is). The thing is, it's only one class. It works perfectly fine (a little occasional lag however) with just one class. So, I'm just asking how splitting it into multiple classes would help it.

This project was in Java and I am the only person working on it, for the record.

答:
This is a good question! Simple and well asked. Well... the answer is no so easy to understand for a student that is studying computer science and probably does not know in deep OO and probably does not have working on experience.

So, I can answer by describing a scenario and making you imagine how multi-classes software is better than monolithic software (made by one class only):

Readability: It is much harder to browse and write code inside a file with 10000 lines than several little and organized files.

Re-usability: If you write a single class, you can slip up in code duplication.  This means more lines of code and probably more bugs(!)

Testability: What about testing a single functionality? If you
isolate one logic functionality in one class, your life will be easier.

Code maintainability: You can fix a bug or enhance functionality with multiplie classes in one single place: The nice little classes.

Project structure: oooooh can you imagine how ugly a
project with only one source file will appear?


问:
What's the difference between stateful and stateless?
The books and documentation on the MVC just heap on using the Stateful and Stateless terms. To be honest, i am just unable to grab the idea of it, what the books are talking about. They don't give an example to understand any of the either state, rather than just telling that HTTP is stateless and with ASP.NET MVC microsoft is going along with it. Am I missing some fundamental knowledge, as i can't understand what is stateful and why is stateful and same goes for stateless.

A simple and short example that talks about a control like button or textbox can be simplify the understanding i suppose.

答:
A stateful operation modifies or requires some state of the system, and a stateless operation does not.

Example of a stateful textbox would be a previously edited comment on StackExchange - the textbox needs to display your previous comment and know the post-thread it was involved with to accept and process your input.

A generic email comment form with a mailto: tag would be a stateless textbox - it accepts your input and tosses it to your workstation's mail application without retaining any information.

OwnerDisplayName: Pankaj Upadhyay


问:
Can manager classes be a sign of bad architecture?
Lately I've begun to think that having lots of manager classes in your design is a bad thing. The idea hasn't matured enough for me to make a compelling argument, but here's a few general points:

I found it's a lot harder for me to understand systems that rely heavily on "managers". This is because, in addition to the actual program components, you also have to understand how and why the manager is used.

Managers, a lot of the time, seem to be used to alleviate a problem with the design, like when the programmer couldn't find a way to make the program Just WorkTM and had to rely on manager classes to make everything operate correctly.

Of course, mangers can be good. An obvious example is an EventManager, one of my all time favorite constructs. :P My point is that managers seem to be overused a lot of the time, and for no good reason other than mask a problem with the program architecture.

Are manager classes really a sign of bad architecture?

答:
Having lots of "manager" classes is often a sympton of an anemic domain model, where the domain logic is hoisted out of the domain model and instead placed in manager classes, which more or less equate to transaction scripts. The danger here is that you're basically reverting to procedural programming - that in itself may or may not be a good thing depending on your project - but the fact that it wasn't considered or intended is the real problem imo.

Following the principle of the "information expert", a logical operation should reside as close to the data it requires as possible. This would mean moving domain logic back into the domain model, so that it's these logical operations which have an observable effect on the state of the domain model, rather than 'managers' changing the state of the domain model from the outside.


答:
Thinking too much about this makes it seem more complicated than it is... It's actually pretty simple:

Option C

Incomplete stories go back into the product backlog, without the points being changed. When planning the next sprint and what can get done, the discussion should include the fact that much of the work is already accomplished. If the team decides they can fit it into the sprint, then it goes in, with its original number of points. If not, it stays in the backlog. Done. The points get awarded to the sprint in which the story was completed.

If it helps, you could track a separate "work remaining" metric per user story, so that if, by the end of the sprint, the story isn't complete, the estimated work remaining can be noted on the story and factored in when planning its inclusion in a subsequent sprint. But even then, don't alter the original story's point value.


问:
Custom graph comparison?
I'm trying to compare two graphs using hash value ( i.e, at the time of comparison, try to avoid traversing the graph )
Is there a way to make a function such that the hash values compared can also lead to determining at which height the graphs differ?
The comparisons between two graphs are to be made by comparing children at a certain level.
One way to compare the graphs is have a final hash value for the root node and compare them, but that wouldn't directly reflect at which level the graphs differ, since their immediate children might be the same ( or any other case ).</p>

答:
No there is no way to do what you are asking, the purpose of a hash value is to take something and make it something else with no apparent relation to what it was. This means hash values are only useful to tell you if to things are the same, not what is different between them.

It is theoretically possible to reverse engineer the source of a hash, and you could use the source to find differences, but this is both computationally expensive and entirely pointless when you have the source available with a much faster way to generate it.

Title: Custom graph comparison?


问:
Options for Application Registry
I work for a small software company (about 200 people building 8-10 applications) and I was hoping to get some advice on products that might be out there to manage the information of which clients are using which versions of our products?

The most fundamental relationship would be that a "product" has "versions" and a given "version" is used by a "client." Uses would be:

Determine which clients use which products

Determine which clients are on which versions of a product

Determine which clients are exposed to which vulnerabilities because of the version they use

Determine which clients cannot move to a new version because of a vulnerability in the new version that they may hit

Determine which clients should be approached for an upgrade

Any thoughts or product reviews would be greatly appreciated!

Thanks in advance.

答:
There are lots of products for keeping software inventories (google for "software inventory"), but those are mostly aimed at gathering the complete software stack inside a company`s network. Your case seems to be simple and small enough that someone could maintain that information more or less manually in an Excel sheet or an Access DB - nothing for which a full-blown product will pay off, I guess. That it is probably the reason why you have problems to find a ready-made solution for your case - it can be too easily solved with MS Office tools.

How to gather the information and transport it from your client to you is a completely different question. There are lots of real-world examples how online updaters could be designed to convince a user that he should allow a program to check for available updates and download those automatically (I don't think I have to list you any examples, I am sure you know them). Part of that update process may be transferring the version information together with the information who is downloading the update to you.

Title: Options for Application Registry


答:
Stateless - There's no memory (state) that's maintained by the program

Stateful - The program has a memory (state)

To illustrate the concept of state I'll define a function which is stateful and one which is stateless

Stateless

```<code>//The state is derived by what is passed into the function

function int addOne(int number)
{
    return number + 1;
}
</code>```

Stateful

```<code>//The state is maintained by the function

private int _number = 0; //initially zero

function int addOne()
{
    _number++;
    return _number;
}
</code>```

As others have said http is inherently stateless.  So state must be built into your applications.

Imagine a request over the web where you have a client browser communicating to a server process.  To maintain state over the stateless http protocol the browser will send typically send a session identifier to the server on each request.  For each request the server will be like "ah, its this guy".  State information can then be looked up in server side memory or in a database based on this session id.

In a purely stateless environment you wouldn't need this session id. Each request would contain all the information the server would need to process. But many applications need to maintain state to keep track of whether or not a session is authenticated to view certain content or to keep track of what a user is doing. You wouldn't want to send user credentials over the wire for each request.

Title: What's the difference between stateful and stateless?

Body:
The books and documentation on the MVC just heap on using the Stateful and Stateless terms. To be honest, i am just unable to grab the idea of it, what the books are talking about. They don't give an example to understand any of the either state, rather than just telling that HTTP is stateless and with ASP.NET MVC microsoft is going along with it. Am I missing some fundamental knowledge, as i can't understand what is stateful and why is stateful and same goes for stateless.

A simple and short example that talks about a control like button or textbox can be simplify the understanding i suppose.

Body:
Stateless - There's no memory (state) that's maintained by the program

Stateful - The program has a memory (state)

To illustrate the concept of state I'll define a function which is stateful and one which is stateless

Stateless

//The state is derived by what is passed into the function

function int addOne(int number)
{
    return number + 1;
}

Stateful

//The state is maintained by the function

private int _number = 0; //initially zero

function int addOne()
{
    _number++;
    return _number;
}

As others have said http is inherently stateless.  So state must be built into your applications.

Imagine a request over the web where you have a client browser communicating to a server process.  To maintain state over the stateless http protocol the browser will send typically send a session identifier to the server on each request.  For each request the server will be like "ah, its this guy".  State information can then be looked up in server side memory or in a database based on this session id.

In a purely stateless environment you wouldn't need this session id. Each request would contain all the information the server would need to process. But many applications need to maintain state to keep track of whether or not a session is authenticated to view certain content or to keep track of what a user is doing. You wouldn't want to send user credentials over the wire for each request.


问:
Is it necessary to memorize code?
I am a new developer, who just got hired at a big company.  I don't know how but I guess they are desperate.  However, I am well-versed with HTML5/CSS3 though things change and new things are released and I keep up with as much as I can.  But this job required me to hand-code Javascript, know Jquery and Ajax.  I have been exposed to this a bit but I am not sure if I can hand-code Javascript.

My question is, is it necessary to memorize all there is about Javascript or are there a few key things that I should know how to hand-code because looking at javascript code it seems there are lots of lines code!

Please point me in the right direction.

答:
I wouldn't make any specific effort to memorize everything you do.  It's best to just learn as you go.  If you find yourself looking something up 3+ times, it's time to memorize.

Exceptions to this rule:

Core items in your code

Framework shortcuts

Title: Is it necessary to memorize code?


答:
After working with something for some time you'll learn/know the important things automatically.

There is no need to know all APIs, function parameter lists, etc. There are docs for things like that. Generally spoken, you need to know things or where to find them.

For example, let's take the $.ajax() function of jQuery. I know what it does and the commonly used options such as url, type, data, etc. If I need something non-standard, I open the docs and check them.

When looking up stuff you need to be sure that your sources are trustworthy and up to date. For example, MDN is while w3schools isn't.

Title: Is it necessary to memorize code?

Body:
I am a new developer, who just got hired at a big company.  I don't know how but I guess they are desperate.  However, I am well-versed with HTML5/CSS3 though things change and new things are released and I keep up with as much as I can.  But this job required me to hand-code Javascript, know Jquery and Ajax.  I have been exposed to this a bit but I am not sure if I can hand-code Javascript.

My question is, is it necessary to memorize all there is about Javascript or are there a few key things that I should know how to hand-code because looking at javascript code it seems there are lots of lines code!

Please point me in the right direction.


问:
How is a switch statement better than a series of if statements?

Possible Duplicate:

  Should I use switch statements or long if…else chains?

I'm working on a small program that will conduct an Insertion Sort. A number will be inputted through the keyboard and stored in a variable I called "num." I've decided to use a switch statement in order to obtain the number inputted.

```<code>switch( e.getKeyCode() ) {

    case KeyEvent.VK_0: num = 0; break;
    case KeyEvent.VK_1: num = 1; break;
    case KeyEvent.VK_2: num = 2; break;
    case KeyEvent.VK_3: num = 3; break;
    case KeyEvent.VK_4: num = 4; break;
    case KeyEvent.VK_5: num = 5; break;
    case KeyEvent.VK_6: num = 6; break;
    case KeyEvent.VK_7: num = 7; break;
    case KeyEvent.VK_8: num = 8; break;
    case KeyEvent.VK_9: num = 9; break;
}
</code>```

I realized one other course of action could have been to use a set of if statements.

```<code>if( e.getKeyCode() == KeyEvent.VK_0 )
    num = 0;
else if( e.getKeyCode() == KeyEvent.VK_1 )
    num = 1;
etc. for every number up until 9.
</code>```

I then wondered what the essential difference is between a switch statement and a series of if statements. I know it saves space and time to write, but it's not that much. So, my question is, aside from the space, does a switch statement differ from a series of if statments in any way? Is it faster, less error-prone, etc.?

This question really doesn't affect my code that much. I was just wondering.
Also, this question pertains to the JAVA language, not any other programming language.

答:
You are correct that functionally they are identical. Practically speaking though, why would you type (or cut and paste) all that when a switch statement is so much more concise?

The difference is not one of functionality, but of intent. When you write a switch statement, you are in effect telling the reader that this section of code could branch multiple ways based on the state of one single variable. This statement is enforced by the compiler.

When you write an if block, however, you are not deliberately stating that only one variable is involved. When you write a series of ifs, as you suggest, it is much harder to see that the branching is only based on a single variable. This is a maintenance problem. Developers that have to modify your code in the future may not realize that you intended that decision to be so focused and will start adding conditions that are not using that variable. Someone will come along and say, "I want num to equal 10 if the last key sequence was 5-4-8," and tack an additional else if on the end of your block. Eventually that section will become a Gourdian knot of if...else if conditions that no one can understand. The future will hate you and bad karma will be added to your account.

Use a switch statement when possible. It clearly communicates that this section of code relies on a single variable and is much more future-proof.


答:
Some people feel switch reads more easily than if-else.  But I agree with the belief that worrying about performance is in the realm of micro-optimization.

SO Java version of this Q

SO Java version of this Q v2

SO C++ version of this Q

SO C++ version of this Q v2

SO C# version ...

Title: How is a switch statement better than a series of if statements?

Body:
Possible Duplicate:

  Should I use switch statements or long if…else chains?

I'm working on a small program that will conduct an Insertion Sort. A number will be inputted through the keyboard and stored in a variable I called "num." I've decided to use a switch statement in order to obtain the number inputted.

```<code>switch( e.getKeyCode() ) {

    case KeyEvent.VK_0: num = 0; break;
    case KeyEvent.VK_1: num = 1; break;
    case KeyEvent.VK_2: num = 2; break;
    case KeyEvent.VK_3: num = 3; break;
    case KeyEvent.VK_4: num = 4; break;
    case KeyEvent.VK_5: num = 5; break;
    case KeyEvent.VK_6: num = 6; break;
    case KeyEvent.VK_7: num = 7; break;
    case KeyEvent.VK_8: num = 8; break;
    case KeyEvent.VK_9: num = 9; break;
}
</code>```

I realized one other course of action could have been to use a set of if statements.

```<code>if( e.getKeyCode() == KeyEvent.VK_0 )
    num = 0;
else if( e.getKeyCode() == KeyEvent.VK_1 )
    num = 1;
etc. for every number up until 9.
</code>```

I then wondered what the essential difference is between a switch statement and a series of if statements. I know it saves space and time to write, but it's not that much. So, my question is, aside from the space, does a switch statement differ from a series of if statments in any way? Is it faster, less error-prone, etc.?

This question really doesn't affect my code that much. I was just wondering.
Also, this question pertains to the JAVA language, not any other programming language.


答:
A switch can be more efficient than a series of if/else if statements. See this article for an example in C. The big difference is that with if statements, the condition for each case can be anything. For example, you could write code that's the equivalent of:

```<code>If it's raining, put on a jacket, otherwise if it's a Sunday, call your mother.
</code>```

With a switch, though, each comparison is going to be a test for equivalence, and the only thing that changes is the value that you're comparing to. As the link explains, if the values for the cases are all close to each other, the compiler may implement the switch using a jump table. That is, the compiler can use the value that you're switching on to directly calculate the address of the code for that case. That avoids the need for a sequence of comparisons. Now, a really smart compiler could notice that you're using a series of if statements the same way and do the same thing; I don't know if that's a common optimization or not.

All that said, I wouldn't worry too much about the code that the compiler generates. Instead, choose between if and switch according to what seems natural for you and the other programmers. A switch represents a choice of one case out of some number of cases where each case has a corresponding value. It's a demultiplexer. If you find that you've got a sequence of if statements that all have the same condition except for the value that you're comparing, a switch can be a nicer, shorter, more obvious way to express that.

Body:
A switch can be more efficient than a series of if/else if statements. See this article for an example in C. The big difference is that with if statements, the condition for each case can be anything. For example, you could write code that's the equivalent of:

If it's raining, put on a jacket, otherwise if it's a Sunday, call your mother.

With a switch, though, each comparison is going to be a test for equivalence, and the only thing that changes is the value that you're comparing to. As the link explains, if the values for the cases are all close to each other, the compiler may implement the switch using a jump table. That is, the compiler can use the value that you're switching on to directly calculate the address of the code for that case. That avoids the need for a sequence of comparisons. Now, a really smart compiler could notice that you're using a series of if statements the same way and do the same thing; I don't know if that's a common optimization or not.

All that said, I wouldn't worry too much about the code that the compiler generates. Instead, choose between if and switch according to what seems natural for you and the other programmers. A switch represents a choice of one case out of some number of cases where each case has a corresponding value. It's a demultiplexer. If you find that you've got a sequence of if statements that all have the same condition except for the value that you're comparing, a switch can be a nicer, shorter, more obvious way to express that.


问:
flat files vs. RDBMS database, few read/writes, few changes
I have to handle data from long term (years, decades) climate monitoring stations. The data flow usually starts with raw data (voltages, etc.) plus quality check information (pressure, temperature, flow rate, etc.) generally recorded @ 1Hz. Then, the data are assigned a quality flag (human and/or program), processed (apply calibration curves) and flagged.

So, we basically end up with 2 datasets : raw and processed data. New data are typically added once a day (~500Ko/day/instrument). Simultaneous queries are not likely to ever happen.

I wanted to go for a RDBMS (we have a MySQL server) and have some experience in database design, but the IT guy keeps telling me that flat files will to the job just as well. I suspect him to try to make his life easier when it comes to backup/upgrade the MySQL.

There are not so many links between data, they don't change much, but the quality flags will change. A RDBMS is easier to compare data from different instruments on a "many days" scale, compared to daily text files.

Well, what would you advise ?

Thanks.

答:
RDBMS in my opinion, is definitely a good approach. Additionally, you can also backup those flat files as BLOB in MYSQL:http://dev.mysql.com/doc/refman/5.0/en/blob.html and correlate your data with the flatfiles saved in database...so that you can have best of both.
Hope this helps!</p>

OwnerDisplayName: Bob Lapique

OwnerDisplayName: Vikram


答:
I am facing a very similar debate in my own office: we have a large legacy system that uses flat files, and are attempting to persuade some of the long-time users to switch to a database. This is not a simple decision, and there are many, many issues that you will need to carefully consider. Here's a few:

BENEFITS of migrating to DB:

There are, of course, numerous advantages of a database system, but the ones that I think might be most relevant in your situation include:

Flexibile Analysis. Perhaps the raison d'être of databases -- they are capable of sophisticated, complex, relationally-oriented searches and queries. You can really slice & dice your data in far more intricate ways than with Excel.

Scalability. Once you move into the realm of gigabytes of data, text files really start to stretch at the seams. Databases can be much more efficient and resilient at this scale.

Availability & Consistency. If you have multiple users collaborating on the same data, a DB can ensure that everyone is looking at the same version and can help prevent people from overwriting each other's flags.

DRAWBACKS:

Of course, as useful as DBs are, there are a number of factors that might rule them out in your case:

Disruption. How many users are going to use this new system?  How invested are they in the current system (how many Excel macros and script files and workflows will have to be abandoned or re-configured?) How many other applications need to interact with the data?

Learning Curve. A DBMS can be a real bottlenect to those who aren't familiar with them. Who is going to train the users? Will their beloved data now be virtually "locked up" behind some DBA's desk? They will have to learn to read & write SQL, and how to interact with the MySQL interface, unless you plan to create a sophisticated front-end application for them (a daunting task!)

Tech Support. Who is going to manage the dbms software and servers (upgrades, patches, outtages, etc)? You've already indicated that IT is reluctant. Are you prepared to manage this yourself?

Cost. Even though MySQL is free, there are other conversion costs to consider, particularly migration time. Is management prepared to support a several-month gap in production time?

In the end, you will have to measure for yourself whether the disruption of workflow is worth the perceived advantages. In my opinion, I would suggest that unless and until the other system-users are significantly dissatisfied with the status quo, you really need to carefully consider whether you want to spend your chips on this battle.

Title: flat files vs. RDBMS database, few read/writes, few changes

Body:
I have to handle data from long term (years, decades) climate monitoring stations. The data flow usually starts with raw data (voltages, etc.) plus quality check information (pressure, temperature, flow rate, etc.) generally recorded @ 1Hz. Then, the data are assigned a quality flag (human and/or program), processed (apply calibration curves) and flagged.

So, we basically end up with 2 datasets : raw and processed data. New data are typically added once a day (~500Ko/day/instrument). Simultaneous queries are not likely to ever happen.

I wanted to go for a RDBMS (we have a MySQL server) and have some experience in database design, but the IT guy keeps telling me that flat files will to the job just as well. I suspect him to try to make his life easier when it comes to backup/upgrade the MySQL.

There are not so many links between data, they don't change much, but the quality flags will change. A RDBMS is easier to compare data from different instruments on a "many days" scale, compared to daily text files.

Well, what would you advise ?

Thanks.

OwnerDisplayName: kmote


答:
Correct answer to this question is:

It depends.

Every situation you'll encounter while writing the software is different. Maybe you're in a team where everyone knows how manager classes work internally? It would be completely crazy to not use that design. Or if you're trying to push manager-design to other people, in which case it might be bad idea. But it depends on exact details.

Title: Can manager classes be a sign of bad architecture?

Body:
Lately I've begun to think that having lots of manager classes in your design is a bad thing. The idea hasn't matured enough for me to make a compelling argument, but here's a few general points:

I found it's a lot harder for me to understand systems that rely heavily on "managers". This is because, in addition to the actual program components, you also have to understand how and why the manager is used.

Managers, a lot of the time, seem to be used to alleviate a problem with the design, like when the programmer couldn't find a way to make the program Just WorkTM and had to rely on manager classes to make everything operate correctly.

Of course, mangers can be good. An obvious example is an EventManager, one of my all time favorite constructs. :P My point is that managers seem to be overused a lot of the time, and for no good reason other than mask a problem with the program architecture.

Are manager classes really a sign of bad architecture?


问:
Efficient way to compare scene-graph trees
I'm designing a scene graph system, where it is required to compare two trees. The trees are populated with individual objects, each with varied number of children; and they have a root.

Eg: Parent: Scene, Children: Bullet1, Bullet 2, Player

What is a good way to compare two such tree? I'm using C++ for the code.

Also, this question is an off-shoot from this question

答:
Create a stack of node pairs for in-depth comparison.

Define an identifier you can use for quick comparison e.g. ID/name/model-path.

Shallow compare root nodes, if they match add them to stack.

For each pair in stack:

2.1. Sort children according to chosen identifier

2.2. Shallow compare children and add matches to stack.

Decide whether algorithm should be terminated on first mismatch or not (depending on required results).

If your nodes are themselves sub-trees (of smaller parts), you can apply the same algorithm to them.


答:
The power of switch is twofold:

It is more descriptive

It saves CPU cycles

Your post already comments on the descriptiveness of switch compared to a chain of ifs, so I will concentrate on part 2.

If the number of switch labels is N, a chain of ifs takes O(N) to dispatch, while a switch always dispatches in O(1). This is how it is done: compiler places addresses of switch labels into an array, computes an index based on the label values, and performs a jump directly, without comparing the switch expression to value one by one. In case of strings used as switch labels, the compiler produces a hash table, which looks up an address in O(1) as well.

When the number of switch becomes high (above 100), converting between switch and a chain of ifs could no longer be regarded as a micro-optimization: time savings may be very significant, especially in tight loops. If a profiler tells you that your chain of ifs is taking a significant time, rewriting as a switch may very well be a solution.


问:
Version control implementation advice on legacy websites?
Assuming no experience with version control systems, just local to live web development. I've been dropped in on a few legacy website projects, and want an easier and more robust way to be able to quickly push and revert changes en masse. I'm currently the only developer on these projects, but more may be added in the future and I think it would be beneficial to set up a system that others can use.</p>

答:
You have to start somewhere. Might as well just dive in.

```<code>$ git init
</code>```

or

```<code>$ hg init
</code>```

Git documentation

Mercurial documentation

Flip through the beginner pages and pick the one that looks the most sensible to you. Or flip a coin. It doesn't really matter, as either will be infinitely superior to what you're (not) using now.

(Note to others: Please don't turn the comments into a git vs. hg flame war. My point is simply to choose a modern source control system and learn it. Later on, learn the other. They are just tools, yet great tools at that.)

Body:
You have to start somewhere. Might as well just dive in.

$ git init

or

$ hg init

Git documentation

Mercurial documentation

Flip through the beginner pages and pick the one that looks the most sensible to you. Or flip a coin. It doesn't really matter, as either will be infinitely superior to what you're (not) using now.

(Note to others: Please don't turn the comments into a git vs. hg flame war. My point is simply to choose a modern source control system and learn it. Later on, learn the other. They are just tools, yet great tools at that.)


答:
Based on my understanding of your description:

You have no unique key in the data

All your changes occur sequentially in sequence and they affect 1 file at a time

There is no relationship between records/rows

No random inquiries required or random inserts/updates

No security risks on who can access the data

This data is not used by on-line system or shared by several systems

from the above, this is a typical case for batch file processing. If any of the points 2 through 6 are false, use a db.

One thing you can do to make your life easier is to properly structure your file names and directories so that you could, in the future, load sets of files into database automatically. Good naming conversion will help a lot.


答:
You will be using some system - whatever it is doesn't matter too much, as long as it isn't VSS.  Look at all of svn, git, mercurial, and I'd toss perforce in there too (the trial license is for 20 users, 20 workspaces, unlimited files).

svn and p4 have a central server model, while git and hg are a distributed system.  Each has its own advantages in disadvantages.

I'll describe more the idea of a central server system, I'm not as familiar with distributed.

Check in everything into the main line.  Make a tag from this initial check in.  Tags are a set of files at a certain set of revisions.  Make changes in the main line.  When you are ready for a release of a set of files, make a new tag for that release with the changes you want, and synchronize the dev, stage, or prod server to that tag.

The 'tag' idea differs between svn and p4 - p4 is as I described it, "a set of files at particular revisions" while svn is "a particular revision" of all files.

That's the basic workflow.

After you've got this workflow down, learn about branching and merging.  This would allow you to work on a redesign of the site in one branch while still doing small updates on the same files in the main line.

http://www.perforce.com/customers/white_papers/highlevel_scm_best_practices and http://www.vance.com/steve/perforce/Branching_Strategies.html are a good reads on the subject of branching (even though both perforce biased they have some applicability to any central server approach to version control).

Title: Version control implementation advice on legacy websites?

Body: Assuming no experience with version control systems, just local to live web development. I've been dropped in on a few legacy website projects, and want an easier and more robust way to be able to quickly push and revert changes en masse. I'm currently the only developer on these projects, but more may be added in the future and I think it would be beneficial to set up a system that others can use.</p>


答: Do the storage requirements of these files allow you to use both?  Import the flat files into a db for data analysis purposes, but maintain an archive of the flat files that you can fall back on.  Ultimately I think the RDBMS solution would be more flexible for them, and allow them to gather statistics that are otherwise more tedious to derive from flat files.  They may soon find that yes, there are in fact stats they are interested in now that they have the ability to query the data in a more flexible way.</p>


答:
stateless means there is no memory of the past.  Every transaction is performed as if it were being done for the very first time.

statefull means that there is memory of the past.  Previous transactions are remembered and may affect the current transaction.


问:
Technology/Techniques to prevent offensive images on a website
I am planing to build a website which one of its main features is the usage of pictures. I was wondering what existing techniques are used to prevent offensive pictures (i.e pornography) to get loaded by users. i.e What does Facebook or Pinterest use?

As well I would like to know what your recommendations would be to control offensive pictures to get uploaded to the site (OpenSource tools maybe..) Taking into consideration this is a personal project and will be developed with a very small budget.

Thank you

答:
There is no technological solution that will tell you that an image is "offensive".

You need to consider that "offensive" is culture dependent (as well as an individual thing) - that is, what you may find offensive and what I may are probably very different.

This is a social issue and can only be solved with social solutions - this may mean moderation (or community moderation).

So - either get moderators to approve/reject each image or put a system in place that allows your users to flag images as offensive and that will remove such images when a certain threshold has been reached. You may want to track users who upload such images in order to moderate/ban them as well.


问:
How to choose a server side language / framework
I am trying to come up with a list / ranking system on determining which server language to choose for a particular website.  Assume that familiarity  with a certain language is not important and the implementation can be done in any language.   Here are some things that might be important but I am not sure how to rank them :

Maintainability.

Libraries.

For example, Memcached and NoSql support right out the box would be really nice addition to a particular framework.

3rd party SDK's.

For example, if I need Paypal on my site they openly provide SDK's for all senarios in Java, PHP and .Net.  If I choose Django I would have to rely on 3rd party libraries that are don't support everything and are not officially maintained.   Would that be dealbreaker for Django?

Performance

This one is tricky to put on a generic list because it can be a deal breaker but for many websites performance will not be an issue that the language/framework is responsible for.

Cost (hosting, open source).

edit -
Any reason for the votes to close?  I didn't see any duplicates mentioned and the question should not drum up a flame war.

答:
I recently blogged a bit about this (non-English, unfortunately).

To me, you don't really need to be so detailed. Start with the TIOBE top 20, cross off languages which really don't have any sort of traction on the web (i.e. C, Logo, etc.) and you really get a short list. Cross out non-free languages if you want. You end up with less than 10 languages, from where you can discard a few more (i.e. I'd say node.js is not really mature yet, discard Javascript, etc.). You'll narrow it down to a few languages, which are really popular and have a strong ecosystem- they'll all have decent libraries for most about everything, with no significant differences between them (i.e. Java has tons of libraries, esp. for enterprise stuff, PHP has the Facebook SDK, etc.)... then it really comes down to personal choice.

Personally, I'd say (Python + Django)/(Java + Spring) are the top choices- depending on whether you want a dynamic language (and Django's admin) or a statically typed language. I'd be hard-pressed to find any other option which is "orders of magnitude better" than either.


问:
multitenancy with some data sharing
I'm in the planning stages of a new webapp, and I am leaning strongly toward a multitenancy model.  The app has a file storage function, where the user can upload (and operate on) files.

I would like the ability of the user to share these files, however.  How is this typically accomplished in a multi-tenant model?

The example would be something like google docs.  Each user has their own files; they can edit and tag and build collections with these files.  Then, they can share a doc or a collection with someone else for collaboration.

If every user has their own Database and tables, what strategy would one use to allow this kind of sharing while minimizing duplication of files and associated metadata?

答:
You want a single database, one single file store.

Multiple databases are only the way to go if you have an app which is not designed for multitenancy and it is not feasible to adapt it to use a single database.

If you have a logical entity scattered across more than one database, the database is not going to be able to enforce integrity and you will have to deal with problems caused by that- and that's just one of the many problems you will have.

Having a single database for a multi-tenant app is not a problem when you design the app from scratch- it definitely requires more work to really isolate different tennants [i.e. all your queries will need a customer=xxx condition, and you cannot forget about that], but it's certainly something less troublesome than having multiple databases.

Once you have a single database, it's just a question of schema design and n-m relationships (i.e. 1 document can belong to n users, 1 user can have m documents).

If you have a normalized schema, data duplication won't be there, by definition :)

Title: multitenancy with some data sharing


答: There are Image Content Filters out there which can prevent this type of thing. They turn the image contrast up and trace the edges and compare with "known" adult images.. There's a lot of research on the subject.. and i know that there is at least 1 service out there that does it, it escapes me for now.. but they're out there</p>

Title: Technology/Techniques to prevent offensive images on a website

Body:
I am planing to build a website which one of its main features is the usage of pictures. I was wondering what existing techniques are used to prevent offensive pictures (i.e pornography) to get loaded by users. i.e What does Facebook or Pinterest use?

As well I would like to know what your recommendations would be to control offensive pictures to get uploaded to the site (OpenSource tools maybe..) Taking into consideration this is a personal project and will be developed with a very small budget.

Thank you