答:
Most "higher-ranked" universities don't focus on particular technologies or languages, because they are teaching concepts of Computer Science. Their primary goal is not to prepare graduates to do enterprise software development.

So while their introductory courses might all use the same language for consistency's sake, it's not like they chose it based on how popular it is in the software industry.

As for courses later in their programs, my experience has been that teachers just use whatever they're familiar with. They don't care as much that you learn Python, for example, as much as they care that you learn the theoretical concepts they're teaching. Programming languages are generally just a vehicle professors use to hammer home what they're really interested in teaching.


问:
Why it is not recommended to post several defects in the same issue / ticket?
I am not sure if this is the place to ask the following conceptual question (Stackoverflow is definitely not).

I saw this question in a multiple choice exam (single answer), similar to the ISTQB exams:

Why it is not recommended to report several defects in the same issue
  / ticket ?

a. In order to keep the report concise and clear.

b. Because the developers might fix only one bug.

c. Because the testing group testers are rated by the amount of bugs
  they find.

d. Bugs management systems does not support this feature of multiple
  bugs.

My sole opinion is that a is the correct answer.

b - can't be it as the fix-feedback-resolved-closed should avoid that case.
c - Obviously wrong.

d - Redmine / Trac plugins supports multiple fields.

The answer according to the answer sheet is b.

Can someone explain why ? Comments with opinion about answers are welcome.

答:
Scope:

This answer (and the question) seems only applicable to the tracking of code defects, where the source code does not perform according to the specification or the programmers' intentions.

On the contrary, it is common for GUI defect tickets to contain multiple specifications, because each GUI ticket is effectively a "redesign" (design defect), a "revised specification" or a "feature request" (missing functionality).

One important purpose of defect tracking is to communicate and coordinate between multiple roles (programmers, testers, customers and managers).

In projects where code quality has high significance (compared to user-friendliness for example), defect tracking may consist of multiple facets, one of which would focus on the tracking of code defects, separately from the tracking of enhancements and customer support requests.

The purpose of code defect tracking system is:

To enable the independent and unambiguous tracking of independently reproducible defects, and

To provide the best approximation (one-to-one correspondence) to the root-cause of each defect.

While doing so, it should maximize the following desirable qualities:

Scale efficiently as the number of defects increase over time.

Prevent the moving-target syndrome.

Disclaimer: this rephrase is from my personal experience. It may be insufficient or incorrect for certification exam purpose.

Independent and unambiguous tracking means that:

Each valid defect can be either resolved or not resolved, without ambiguity.

Reason 1: to simplify management,

Example: it enables the use of "number of unresolved tickets" as a metric.

Reason 2: to translate into actionable item

Example: if it's not resolved, responsibility lies on the assigned programmer. If it is resolved but not closed, responsibility lies on the assigned tester (verifier).

Consequence: In this methodology, a partially resolved defect deserves to be broken down into several dependent defects.

Independently reproducible defects should be tracked independently.

"Independently reproducible" means they can have different states. One can appear to be fixed while the other remains broken.

Reason: to minimize the mismatch between defect tracking and root-cause analysis.

Each root-cause that can be traced to a code defect is believed to require at least one code change.

If two defects are independently reproducible, then multiple code changes will be needed.

If two defects are independently reproducible, they must both be tested (verified), because the passing of one test does not imply that the other test will pass.

Example 2: if two symptoms were initially believed to have the same root-cause and thus classified into the same ticket, and they were later shown to be independently reproducible, then they should be split into two tickets.

ContentLicense: CC BY-SA 3.0


问:
Scrum: How much can the Product Owner shake up the Product Backlog?
For the last 3 sprints or so, I've observed our Product Owner suddenly shoving new stories -- stories not previously in the Product Backlog -- at the top of the Product Backlog.

Because of this, the existing items in the backlog never get worked on.  New stories continuously take over the helm and make into our Sprint Backlog.

My question is - how much can the Product Owner really shake up the Product Backlog?  Is it really fair game to ignore what's already in the backlog and keep on shoving new stories at the top?

I've tried to argue that this is hogwash, but I often hear counter-arguments such as "adapting to frequently changing business needs," "we're moving so fast - we're super agile" and I don't know what to say to those arguments, although I feel it is not how Scrum was meant to be.

EDIT:
I understand that the product owner owns the product backlog.  What I am observing at my team though, is that the PO constantly puts new items at the top of the backlog, ignoring the existing backlog items completely.

For instance, say we're building a car and PO creates 10 stories to make it happen.  We decide to take on 3 stories in our sprint backlog - thus 7 stories still remain in the product backlog.  Everything is good so far.

At the next sprint planning, however, the PO now claims that we need to build a baseball bat and creates 5 stories around that - which are then placed at the top of our backlog (i.e. highest priority); nevermind those car stories we already had in the backlog.

答:
In traditional Scrum, the Product Owner is the person who owns the Product Backlog. This person is responsible for adding or removing stories as appropriate and ensuring that the list is prioritized based on the needs of the stakeholders. However, the Development Team is responsible for ensuring that the Product Backlog Items that are added are understood and good enough (complete, clear, testable, feasible, etc) to be estimated and delivered when they come up in a future sprint.

From your perspective on the development team, you shouldn't be relying on the product backlog. All of your actions - your requirements elaboration, architecture and design, implementation, and testing should be fully based on the Sprint Backlog. This is what gets fixed for a particular Sprint and changes to the Sprint Backlog should be minimized.

Remember that the Product Owner is the voice of the stakeholder for the development team. They are the ones who understand what the business need for the system is and what capabilities or features would have the most impact.

Warning signs to look out for would be the Product Owner attempting to change the Sprint Backlog or having a Product Owner that is out of touch with the needs of the business or user base.


问:
Should I ask/tell my boss before freelancing?
I am currently working as an intern at a consulting firm. I am soon to move to a full time employee once I graduate next semester, and I love working there. However, as a student, I lack money and I have met a business owner outside of work who has offered to hire me for some freelance web development.

Because I met this individual outside of work, I feel it would not be a conflict of interest to freelance for him. However, the work his is wanting me to do is very similar to what I already do for my current boss.

Should I speak with my boss before considering the offer?

Edit: I understand that I cannot take IP from work, and I am not in a contract, I'm employed at will.

答:
Be aware of local laws.  In the UK, there are standard terms in the software industry that grant your employer ownership of all software code you write.  As these are standard terms in the industry your employer can argue successfully that these terms apply even if they are not written in your contract.

In the UK, you should get explicit permission in writing from your employer, as otherwise you are potentially putting your employer and your freelance customer into a copyright fight over ownership of that source code.

ContentLicense: CC BY-SA 2.5


答:
Just to comment on your statement:

can't be it as the fix-feedback-resolved-closed should avoid that case

This assumes that all bugs raised will be fixed at the same time. Imagine a scenario where a ticket is raised against v1 of the product with two issues:

A form reset button actually submits the form, rather than clearing
the values

The font-size on the button is 110% when it should be 115%.

Both are correct for a tester to raise, as they are both faults with the implementation. But let's say that the product owner decides that the first subtask is a blocker to release (i.e. it has to be fixed before the product can go live), but the second task is a minor issue (i.e. it can be fixed in a v1.1 release).

In that case, we've no choice but to split out #2 into it's own ticket (or risk forgetting about it). If we can do this, it means they can be implemented, tested and deployed independently of each other, in which case it makes sense to have individual issues from the start.

Title: Why it is not recommended to post several defects in the same issue / ticket?

Body:
I am not sure if this is the place to ask the following conceptual question (Stackoverflow is definitely not).

I saw this question in a multiple choice exam (single answer), similar to the ISTQB exams:

Why it is not recommended to report several defects in the same issue
  / ticket ?

a. In order to keep the report concise and clear.

b. Because the developers might fix only one bug.

c. Because the testing group testers are rated by the amount of bugs
  they find.

d. Bugs management systems does not support this feature of multiple
  bugs.

My sole opinion is that a is the correct answer.

b - can't be it as the fix-feedback-resolved-closed should avoid that case.
c - Obviously wrong.

d - Redmine / Trac plugins supports multiple fields.

The answer according to the answer sheet is b.

Can someone explain why ? Comments with opinion about answers are welcome.


问:
Sum of divisors of numbers of the range ~ 10^6
I was trying to find the sum of divisors of numbers upto 106. The test cases are like of the order of 105. I have done some pre processing like

```<code>int divisors(int num)
{
    int sum=0;
    for(int i=1; i*i<=num; i++)
        sum += (num%i)? 0 : ((i*i==num)? i : i+num/i);
    return sum;
}
</code>```

Is there any better method to do the same. Should I also make an array of prime numbers or something like that?

答:
Hint.  It is easier to figure out how many numbers in a range that, say, 12 will divide than it is to bother figuring out which ones it divides.

This gives you a O(n) algorithm that allow you to calculate your answer in likely acceptable time for 106.

If you want it faster, hint 2 is that you only have to do this up to n/2 - after that you just need the sum of the numbers, because each is a factor only once.  There is a well-known formula for the sum of all of the integers up to 'n', that provides a short circuit.  Still O(n), but a better factor.

For faster still, hint 3 is that you only have to do this up to n/3 - you have 2x the sum of the range from n/3 to n/2 and then all of the range from n/2 to n.  Same performance comment as before.

Hint 4 is that as you repeat this there is a more general pattern you can figure out.  Get it right and performance becomes O(sqrt(n)) which is definitely fast enough.


问:
Should I fork in case the upstream deletes
I'm creating an open source PHP project that reuses other open source code instead of reinventing the wheel. I'm using composer to pull these projects into my vendor folder. What happens if these vendors delete their repository & all traces of their code from the internet? Now composer can't download the project. Should I fork every project I'm depending on, and depend on the fork? Seems like a pain, but the only 'safe' way to ensure the vendor can't delete things my project needs to run.</p>

答:
OK, I'll play the devil's advocate here: forking in today's DVCS world is so cheap, and so low impact that yes, I would definitely fork. Aside from the possibility of the project owner executing a Mark Pilgrim and actively seeking to delete their online presence this has the added benefits of being able to work out things that appear to you to be bugs in the original project while still relying on an online repo (and all of the associated benefits thereunto) without issuing a pull request for your changes and also without having to update your vendor-relying code to point to your new fork when you decide that you need to fork to try to address an issue you've found.

In fact, I wouldn't rely on another project without forking it first - it protects you against all manner of possible chaos, and costs very little to maintain.

In addition, and this is somewhat github-specific, but one measure of the adoption of an open-source project is how many forks it has, so in one sense you're adding credence to the library you're consuming by saying "I think this library is important enough that I want my own fork."


答: Tell him and if you dont do well all the blame will come to Freelancing work. However it is still important to do what your contract says.</p>

Title: Should I ask/tell my boss before freelancing?

Body:
I am currently working as an intern at a consulting firm. I am soon to move to a full time employee once I graduate next semester, and I love working there. However, as a student, I lack money and I have met a business owner outside of work who has offered to hire me for some freelance web development.

Because I met this individual outside of work, I feel it would not be a conflict of interest to freelance for him. However, the work his is wanting me to do is very similar to what I already do for my current boss.

Should I speak with my boss before considering the offer?

Edit: I understand that I cannot take IP from work, and I am not in a contract, I'm employed at will.


问:
Must I think about compiled machine code when I write my code?
For example I've got following code:

```<code>auto z = [](int x) -> int {
    if (x > 0) {
        switch (x) {
            case 2: return 5;
            case 3: return 6;
            default: return 1;
            }
        }
    return 0;
    };
</code>```

And later I call this several times. In asm code I see external calls with lambda....something... It's becoming not easy to read and I think it also can cause performance. So maybe I win in meta-programming but do I lose in asm debugging and performance? Should I avoid modern language features, macros and other meta programming aspects to be sure in performance and debugging simplicity?

答:
The choice between lambda and functor-class is a tradeoff.

The gain from lambda is mostly syntactic, by minimizing the amount of boilerplate and allowing conceptually-related code to be written inline, inside the function that is going to utilize it (immediately or later).

Performance-wise, this is no worse than a functor class, which is a C++ struct or class that contains a single "method". In fact, compilers treat lambda no differently than a compiler-generated functor class behind the scene.

```<code>// define the functor method somewhere
struct some_computer_generated_gibberish_0123456789
{
    int operator() (int x) const
    {
        if (x == 2) return 5;
        if (x == 3) return 6;
        return 0;
    }
};

// make a call
some_computer_generated_gibberish_0123456789 an_instance_of_0123456789;
int outputValue = an_instance_of_0123456789(inputValue);
</code>```

In your code example, performance-wise it is no different from a function call, because that functor class happen to have no state (because it has an empty capture clause), thus requiring no allocation, constructor nor destruction.

```<code>int some_computer_generated_gibberish_0123456789_method_more_gibberish(int x)
{
    if (...) return ...;
    return ...;
}
</code>```

Debugging any non-trivial C++ code using a disassembler has always been a difficult task. This is true with or without using lambda. This is caused by the sophisticated code optimization by C++ compiler that resulted in reordering, interleaving and dead code elimination.

The name-mangling aspect is somewhat unpalatable, and debugger support for lambda is still in its infancy. It can only be hoped that debugger support will improve over time.

Currently, the best way to debug lambda code is to use a debugger that supports setting breakpoints at the source code level, i.e. by specifying the source file name and the line number.

Body:
The choice between lambda and functor-class is a tradeoff.

The gain from lambda is mostly syntactic, by minimizing the amount of boilerplate and allowing conceptually-related code to be written inline, inside the function that is going to utilize it (immediately or later).

Performance-wise, this is no worse than a functor class, which is a C++ struct or class that contains a single "method". In fact, compilers treat lambda no differently than a compiler-generated functor class behind the scene.

// define the functor method somewhere
struct some_computer_generated_gibberish_0123456789
{
    int operator() (int x) const
    {
        if (x == 2) return 5;
        if (x == 3) return 6;
        return 0;
    }
};

// make a call
some_computer_generated_gibberish_0123456789 an_instance_of_0123456789;
int outputValue = an_instance_of_0123456789(inputValue);

In your code example, performance-wise it is no different from a function call, because that functor class happen to have no state (because it has an empty capture clause), thus requiring no allocation, constructor nor destruction.

int some_computer_generated_gibberish_0123456789_method_more_gibberish(int x)
{
    if (...) return ...;
    return ...;
}

Debugging any non-trivial C++ code using a disassembler has always been a difficult task. This is true with or without using lambda. This is caused by the sophisticated code optimization by C++ compiler that resulted in reordering, interleaving and dead code elimination.

The name-mangling aspect is somewhat unpalatable, and debugger support for lambda is still in its infancy. It can only be hoped that debugger support will improve over time.

Currently, the best way to debug lambda code is to use a debugger that supports setting breakpoints at the source code level, i.e. by specifying the source file name and the line number.


问:
Migrating from python 2 to 3
It is easy to find questions asking if one should start with python 2 or python 3, and it is a consensus that python 2 is the way to go as it is has more libraries and thus better supported.

Python 3 was launched back on 2008 and this question already addressed a migration. As it was too soon, the solution was to wait.

5 years have passed now and a good bunch of libraries already support python 3. At the time I write this question, according to this page 244 packages on pypi support python 3 while 156 does not. On the top 30 most downloaded packages, 24 support python 3

Following this I feel safe enough to start migrating from python 2 to 3 and also avoiding telling people to start on python 2

My reasons explained, the question is:

What concerns should I have when migrating from python 2 to 3?

Not just code syntax and replacements, as its easy to find a conversion tool to do the 80% of the job, but general concerns, like:

Do virtual environments mechanism changes?

Building, packaging and distribution differences

Will I have only cPython? (Looks like Jython has a long way to go to reach python 3)

Multi threading/processing programming. Always a delicate subject

Testing. Any changes?

What common things that I can still do like in python 2 but I should stop and start doing in an other way? I feel that a code replacement tool will change the code to make it just "runnable", but it will not use the correct or better option if the option itself involves big changes

ps: This question was asked on stack overflow, but was closed as too broad. Anyway, I felt that the correct place is here

答:
Largely depends on the project.

Choose the version with which the libraries you need will work.

Almost everything will work on Python 2.x, but if you find that your dependencies are also available for Python 3.x, then use 3.x.

As for migration, this page covers all the differences (there doesn't seem to be any change on the multithreading/processing front compared to 2.x, but I could be wrong).

Virtualenv works with Python 3 since 1.6, with fixes for each new Python version in subsequent releases.

As for alternative Python implementations, that depends on the implementation itself, but most of them are still 2.x only for the time being.

Title: Migrating from python 2 to 3


答:
Must I think about compiled machine code when I write my code?

No, not when you write your code the first time and don't suffer from any real, measurable performance problems. For most tasks, this is the standard case. Thinking too early about optimization is called "premature optimization", and there are good reasons why D. Knuth called that "the root of all evil".

Yes, when you measure a real, provable performance bottleneck, and you identify that specific lambda construct as the root cause. In this case, it may a good idea to remember Joel Spolsky's "law of leaky abstractions" and think about what might happen at the asm level. But beware, you may be astonished how small the performance increasement will be when you replace a lambda construct by a "not so modern" language construct (at least, when using a decent C++ compiler).

Body:
For example I've got following code:

```<code>auto z = [](int x) -> int {
    if (x > 0) {
        switch (x) {
            case 2: return 5;
            case 3: return 6;
            default: return 1;
            }
        }
    return 0;
    };
</code>```

And later I call this several times. In asm code I see external calls with lambda....something... It's becoming not easy to read and I think it also can cause performance. So maybe I win in meta-programming but do I lose in asm debugging and performance? Should I avoid modern language features, macros and other meta programming aspects to be sure in performance and debugging simplicity?


问:
Best approach for near real time message passing from server to client across router?
I am developing an application which must run on up to thousands of client systems that I control (Linux) which are connected behind common NAT devices to public Internet.  Each of these client devices must receive infrequent messages from a cloud service (1 or 2 per day) and on average, must receive these messages in less than a 500ms.

I have full control of both server and client systems to install any operating system, programming languages or applications.  However I will not have control of the router and network in between.  Otherwise, I could just call a web service running on the "client" devices in order to send the messages.

I have considered running Node.js on the cloud service, with javascript sockets on the client kept open 24x7.  From what I am told Node can handle tens of thousands of open connections, making it an ideal server for this.

NAT devices will time out open connections, so dummy keep alive data could be sent. And if the connection is dropped, the client just renews the socket.

Other options include Erlang or even a simple c socket with long polling.

However I am having a difficult time researching this problem for other approaches.

What would be the best approach?  Given no restrictions on language or programming.

答:
One way of handling this is to use PubNub.  It is a paid service, but well worth it since it basically handles the entire messaging portion of what you describe, and wouldn't have any scale issues.

Its very easy to implement.  The clients would connect to the service using long polling (if you roll your own) or one of their client libraries.  Messages are passed as JSON.

I have used PubNub for a commercial software project, and it works very well.


问:
Paradigm Diagram
Does anyone have a diagram showing all significant programming paradigms. Something like this but with paradigms as titles would be ideal:

答:
As thorsten müller already gave the link to the diagram, and there are no close votes yet, let me take a shot at a proper answer.

First off, the diagram by Peter von Roy. Note that he is famous for his book Concepts, Techniques and Models of Computer Programming (together with Seif Haridi).

While that original book already covers a lot about programming paradigms, Peter von Roy has another book in work, which is title "Programming Paradigms for Dummies". The overview chapter is freely available at his site and is the source of the above diagram - in other words, you will find an excellent 39-page long explanation of the diagram in there.

Title: Paradigm Diagram


问:
When to start thinking about scalability?
I'm having a funny but also terrible problem. I'm about to launch a new (iPhone) app. It's a turn-based multiplayer game running on my own custom backend. But I'm afraid to launch.

For some reason, I think it might become something big and that its popularity will kill my poor lonely single server + MySQL database.

On one hand I'm thinking that if it's growing, I'd better be prepared and have a scalable infrastructure already in place.

On the other hand I just feel like getting it out into the world and see what happens.

I often read stuff like "premature optimization is the root of all evil" or people saying that you should just build your killer game now, with the tools at hand, and worry about other stuff like scalability later.

I'd love to hear some opinions on this from experts or people with experience with this. Thanks!

答:
So, there are two times you should think about scalability.

First, it should be gently pondered before you write a single line of code. This is to ensure you don't write yourself into a scalability hole and to make sure your code is instrumented to give you the measurements you need for the second time.

The second time to consider scalability is in enough of an advance of things becoming unacceptably slow. That means you need to know what "too slow" means and how your thing reacts under load. If you have a service whose driver (probably qps) increases by N% per month, you have rather different times from "95% of machine resources consumed" if your resource usage is load-squared or linear in load.

With a turn-based game, you ought to have a decent margin of safety (you are probably not having a single game world, and if you do, there is probably an internal geometry, meaning you do not have "everyone interacts with everyone each turn" problems).

Without knowing specifics, I would take one or two days to think about where you have scaling issues and what possible strategies you have for resolving them. But, this is important, Think About. Not do, just think (and document). Unless you have scalability problems that start manifesting at a few hundred users, you should then have time to check load and spin up more back-end resources.


问:
When did the first "REST"-model and friendly URL web technology come to be?
Everyone knows that the "current" way to do things is to have user-readable URLs. Like:

http://example.com/blog/edit/1234

Rather than:

http://example.com/blog.php?action=edit&id=1234

When exactly did people start making web technologies handling this though? I remember in the dark ages of the early 2000s, I don't remember ever seeing a friendly URL. In fact, I think Stackoverflow (in 2008/9) may have been the first time I noticed them.

When exactly did this become so popular, and what were the first servers/frameworks built with friendly URLs in mind?

I'm interested as well in when rewriting to friendly URLs became common, and when serving friendly URLs natively became common

答:
I’d say the first publicly available website of the Web had/has a friendly URL:

http://info.cern.ch/hypertext/WWW/TheProject.html

The same is true for many of the early websites, e.g. the WWWVL (see the history, which contains some of the original URLs).

It’s a subject for debate if the file extension (.html) is "friendly" or not. I’d say especially in the first years it was important for users. But even today it can be good for usability, e.g. if you provide the resource in several different file formats.

But to be fair, those sites don’t use many GET forms, if any at all (at least in 1995 the form element was defined, which can be considered "HTML 2"). You can get friendly URLs by using static HTML files "for free", but if you provide GET forms, you’d have to rewrite the URLs.


答: Since you care about this issue, and are considering working for them full time, I think now is a great time to find out how they handle it. They may say "sure, go ahead, we like to see people improving themselves!" They may put some restrictions on you about using their tools. They may forbid you to do it, or even threaten to fire you. They may say "oh gosh, you need more money, we can pay you more (possibly for more hours)". Anything could happen. Even the ones that don't feel good (like forbidding you) actually are, because they tell you what this job is like before you're committed to it. If they will lock you in and control you, do you want to work there when you graduate?</p>


问:
Why is Scheme my first language in university?
I hear about C, C++, Java every day whenever people starting talking about computer science, but in my first computer science class we are asked to write in Scheme (DrRacket).

Why is that?

What differences will this make to my future understanding of programming?

UPDATE: I have finished my first term, but not completely done with Scheme. In my second term (which is now) we got in to C programming. It was frustrated to learn pointers at first, but now I feel much better.

There's not much more to say than that. I'm trying to teach myself Java (or C++?) for the OOP part which I'm missing. So far, I still like functional programming best. Lambda is just fascinating. :)

答:
We completed Scheme in the first and first-half of the second semester. It was not until we actually got down to working with C that I began to realize the power of Scheme.

As to your question, why Scheme is chosen: the answer is that it is one of the simplest languages out there and it allows you to do alot (especially when we start playing with lazy lists later on). Moreover :

For people who have no programming experience, it is easier to learn. There aren't many technical details and just a few special forms.

It allows for higher level abstraction. A good course can focus on teaching programmers how to think instead of focusing on the technical details which allows students to become better programmers.

The lists are amazing. There is so much that you can do with them. Car and cdr prove to be powerful tools and it is only when you start working with pointers that you realize that Scheme was amazing at handling lists.


问:
How to identify (business) processes for automation?
I recently started at a company and am working on statistical data analysis and data handling (market research). A lot of my tasks were previously done entirely by hand, so I created a few tools to automate much of my work.

My boss asked if I could go ahead and look for other automation-possibilities. I certainly have the time and skill, but I don't know how to find processes which would be good candidates to be automated.

I could ask co-workers, but most of them don't understand what is easy to automate and what isn't. I believe that there are  processes for this sort of thing - but I don't know enough to start Googling.

What comes before requirements discovery and analysis?

How do I identify business processes that will be more efficient as automated tasks?

答:
If you are looking for projects with the greatest impact create a value stream map of some of your key processes (Google Lean manufacturing and value stream). You will quickly be able to identify bottlenecks in many of your processes. You may even notice that most or all of your processes have a common constraint (ie data has to be manually manipulated before it can be passed on to the next step of the process). This is where you can apply your VBA/.Net/Database skills.

If you are looking for small projects, just look at any task that takes a long time, is done repetitively and does not add a lot of value to the final product (ie people in the office will commonly say "It's not that it's difficult, it's just very manual." about these tasks).

If you are looking for more formalized approaches to identifying projects for process improvement, research Lean, Six Sigma and/or Theory of Constraints. All provide useful approaches and tools for process improvement.


问:
Levels of user permissions in a RESTful API
Let's say I have a company that ranks the cutest cats on the internet.

I offer a resource at /cats/ which provides users with the latest, cutest adorable cats.

Users can either get just the top 3 cats if they haven't paid at all or registered. The top 10 cats if they paid 337 dollars and are logged in, and the top 100 cats if they paid 1337 dollars and are logged in. I have a 'user identifier' when making the request.

In short, consumers of /cats/ get a different number of cats based on their 'user
ranking'. I do have a user identifier on the consuming end, but I have no explicit representation of the user level on the consuming end. I'd like to inform users they can upgrade their subscription when making the request. That is, I need to distinguish between 3 cats since I only offer 3 cats and 3 cats  because that's what the user level allowed.

What is the best practice for distinguishing limiting the resource because the consumer does not have sufficient priviledges and limiting it because that's what the consumer has?

How does the client know if  they can upgrade their ranking? That is, they only got a limited resource because they don't have permissions. What is the best practice here?

Note, this is a gross simplification of the actual case. Also, just to clarify - reading is appreciated.

Update:

Here are options we've considered:

Storing the user permissions objects once on the client, querying for it only when account login or upgrade is performed.

Passing null values in JSON indicating it exists, but an actual nothing was transfered. So 10 cats for a user with 3 cats could be ["Garfield","Sylvester","Puss in Boots",null*7]

Passing a resource permission pair {cats:["Whiskers","Fluffy","Socks"],authCount:3}

I'd like to do this right the first time to deliver the cutest cats in the best way possible and we'd and we'd like

答:
How does the client know if they can upgrade their ranking?

That depends on the client. Normally you can put such information in form of a hyptertext message (aka HTML) into the response body of the REST method. However that only makes sense if the REST API is used with a HTML client.

Similar for XML and JSON.

Edit: You might confuse using an API (expand this acronym) with the marketing of your account-types / user-plans. I would not mix this, as it always gets fishy (business decisions might requires faster changes than the changes in the software to communicate different responses due to these changes are able to get on the platter in time).

Instead tell your users through a different channel, e.g. with the newsletter what their benefits are.

This works particularly well when the person signing up to the service isn't the one who is programming against the API. For example:

George (who is a proudly gay guy at the age of 36 loving kittens) buys access to cute-cats-4-me.com and tells his 16 year old spouse (who is well with scripting computer systems incl. linux) to create a digital signage application displaying nice little cutie kitties on the wall in the apartment.

So the guy who is having fun programming this actually is not that much the most straight-forward addressee of the information.

Alternatively in response to login and a user-info method, provide all the gory details.

But when a user requests cats programmatically, she should be already aware why she only gets three cats back or more. But you don't solve this communication problem with code.

Otherwise, allow them to query more and then give back a failure notice if their rights are not sufficient. But again, that's not a user-friendly software.


答:
I'd say it depends on your audience.

No-dev

If your audience is not a developer's one, I'd go with the following way:

Let's say you return JSON for the sake of the example.

```<code>GET /cats HTTP/1.1

{
    "cats": [
        "Can I haz cheeseburger",
        "If it fits, I sits",
        "It's caturday!"
    ],
    "permissions": {
        "level": "free",
        "information": "You have access to 3 cats. Upgrade to ... to get 10 cats!"
    }
}
</code>```

Or something similar.

It is informative for the user to know what the status of his account is, and it allows you to put whatever information you want, such as a marketing message. The most important point of this way is to give some easy visibility to your users of their current account.

Dev

However, if your audience is purely developers, then I'd say: go with the full HTTP compliant way. To store the metadata, you use HTTP headers.

Here is an example:

```<code>GET /cats HTTP/1.1

X-Account: anonymous
X-Account-Possible-Upgrades: 2
X-Account-Limit: 3
</code>```

Then, provide a clear documentation of what these headers mean. Most developers will go straight for the documentation when they'll see these custom headers, especially if they're seeing a limit. You can go even further and show the link in the headers. Or you can show a link to the pricing page.

```<code>X-Account-Doc: http://your/doc
</code>```

But then again, many developers don't know how HTTP works.

So it's your call

One is more correct, the other is more accessible.

Misc

Some other miscellaneous stuff related to your question:

Don't forget about 429 Too many requests.

Don't forget about the WWW-Authenticate response header.

Title: Levels of user permissions in a RESTful API

Body:
Let's say I have a company that ranks the cutest cats on the internet.

I offer a resource at /cats/ which provides users with the latest, cutest adorable cats.

Users can either get just the top 3 cats if they haven't paid at all or registered. The top 10 cats if they paid 337 dollars and are logged in, and the top 100 cats if they paid 1337 dollars and are logged in. I have a 'user identifier' when making the request.

In short, consumers of /cats/ get a different number of cats based on their 'user
ranking'. I do have a user identifier on the consuming end, but I have no explicit representation of the user level on the consuming end. I'd like to inform users they can upgrade their subscription when making the request. That is, I need to distinguish between 3 cats since I only offer 3 cats and 3 cats  because that's what the user level allowed.

What is the best practice for distinguishing limiting the resource because the consumer does not have sufficient priviledges and limiting it because that's what the consumer has?

How does the client know if  they can upgrade their ranking? That is, they only got a limited resource because they don't have permissions. What is the best practice here?

Note, this is a gross simplification of the actual case. Also, just to clarify - reading is appreciated.

Update:

Here are options we've considered:

Storing the user permissions objects once on the client, querying for it only when account login or upgrade is performed.

Passing null values in JSON indicating it exists, but an actual nothing was transfered. So 10 cats for a user with 3 cats could be ["Garfield","Sylvester","Puss in Boots",null*7]

Passing a resource permission pair {cats:["Whiskers","Fluffy","Socks"],authCount:3}

I'd like to do this right the first time to deliver the cutest cats in the best way possible and we'd and we'd like

Body:
I'd say it depends on your audience.

No-dev

If your audience is not a developer's one, I'd go with the following way:

Let's say you return JSON for the sake of the example.

GET /cats HTTP/1.1

{
    "cats": [
        "Can I haz cheeseburger",
        "If it fits, I sits",
        "It's caturday!"
    ],
    "permissions": {
        "level": "free",
        "information": "You have access to 3 cats. Upgrade to ... to get 10 cats!"
    }
}

Or something similar.

It is informative for the user to know what the status of his account is, and it allows you to put whatever information you want, such as a marketing message. The most important point of this way is to give some easy visibility to your users of their current account.

Dev

However, if your audience is purely developers, then I'd say: go with the full HTTP compliant way. To store the metadata, you use HTTP headers.

Here is an example:

GET /cats HTTP/1.1

X-Account: anonymous
X-Account-Possible-Upgrades: 2
X-Account-Limit: 3

Then, provide a clear documentation of what these headers mean. Most developers will go straight for the documentation when they'll see these custom headers, especially if they're seeing a limit. You can go even further and show the link in the headers. Or you can show a link to the pricing page.

X-Account-Doc: http://your/doc

But then again, many developers don't know how HTTP works.

So it's your call

One is more correct, the other is more accessible.

Misc

Some other miscellaneous stuff related to your question:

Don't forget about 429 Too many requests.

Don't forget about the WWW-Authenticate response header.


答:
To add to the answer by @DocBrown, remember that these days CPU's are cheap but labour is expensive.

In the overall cost of a program, hardware is usually trivial in comparison to the cost of maintenance, which is by far the most expensive part of a typical project (even more than its development).

Therefore, your code needs to optimise maintenance above everything else, except when performance is critical (and even then maintenance needs to be considered).

Title: Must I think about compiled machine code when I write my code?


问:
When to use primitive vs class in Java?
I see that Java has Boolean (class) vs boolean (primitive).  Likewise, there's an Integer (class) vs int (primitive).  What's the best practice on when to use the primitive version vs the class?  Should I basically always be using the class version unless I have a specific (performance?) reason not to?  What's the most common, accepted way to use each?</p>

答:
In layman's words:

You use the wrappers when you need to add things to collections.

Collections can't hold primitives.

Title: When to use primitive vs class in Java?


答:
Java features autoboxing as m3th0dman pointed out.  Think about in the lowest level possible and you'ĺl see that autoboxing (in or out) a primitive value will imply clock cycles spent in some tasks you don't need if you're working with native data types around your application.

As a general rule, you should try to use native data types whenever possible.

Title: When to use primitive vs class in Java?

Body: I see that Java has Boolean (class) vs boolean (primitive).  Likewise, there's an Integer (class) vs int (primitive).  What's the best practice on when to use the primitive version vs the class?  Should I basically always be using the class version unless I have a specific (performance?) reason not to?  What's the most common, accepted way to use each?</p>


问:
Java - using single class or multiple class for each type?
I currently have a Java class called "node" which has a number of fields. Which fields in the class are used depends on a field called "type". There are close to 10 (this can grow) different types of "nodes". I was wondering if it is good to have a single class to handle all types or have different class for each type. What is the best programming practice in these cases? I would like to know (or a link to similar question/tutorials) how the performance will be affected (like memory etc.) if I use a single class?</p>

答:
I'd say that you can use a design pattern, subclassing or even a single class.  It depends on the sparsity of the fields.

Are most of the fields or only a few ones in a single class null?

Are there a lot of different "types" involved?

Those are questions to be answered before a decision can be made.


问:
Hardware that accelerates pointer dereferencing?
Most modern languages make a heavy use of pointers / references: a typical OOP language uses VMT lookups, a typical functional language builds key data structures out of pointers, etc. Even typical C code often sports things like foo->bar->baz.

It is well-known that dereferencing a pointer is cache-unfriendly, unless the pointer happens to point very near some just-accessed location and hits the same cache line.

Is there, or has there been, hardware that tries to address this problem? It's not currently widely deployed; why?

Hitting L1 or even L2 cache is so much faster than hitting RAM on current hardware that the goal of making pointer dereferencing reap some of the caching benefits seems worthy.

答:
there are cache pre-filling strategies.  Those I'm aware of are trying to detect (some subset of) linear patterns of memory accesses and when they are successful, they are quite effective (for instance I remember having measured a difference between forward and backward sequential accesses on a processor, difference which was no more present on later generations).  I'm not aware of tentative to use the memory or register content to do that pre-filling, but I'm not following that closely enough to be sure that nothing has been done in that area, it could have been proved useless in practice or less useful than some other things.

there is the whole set of efforts done around the principle of "if you have to wait, try to do something else and hope it will be useful".  OoO execution is the application for single thread (finding some instructions in the thread which don't have to wait for memory or for the result of not-finished-yet instructions, branch prediction being there to help to find more candidates).  And there is a bunch of variants in ways to make the processor thread aware and try to use the processor resources to advance the other threads while one is stuck on a slow memory access, hyperthreading being just one of them.


答:
The standard practice is to go with the primitives, unless you're dealing with generics (make sure you are aware of autoboxing & unboxing!).

There are a number of good reasons to follow the convention:

1. You avoid simple mistakes:

There are some subtle, non-intuitive cases which often catch out beginners. Even experienced coders slip up and make these mistakes sometimes (hopefully this will be followed by swearing when they debug the code and find the error!).

The most commmon mistake is using a == b instead of a.equals(b). People are used to doing a == b with primitives so it's easily done when you're using the Object wrappers.

```<code>Integer a = new Integer(2);
Integer b = new Integer(2);
if (a == b) { // Should be a.equals(b)
    // This never gets executed.
}
Integer c = Integer.valueOf(2);
Integer d = Integer.valueOf(2);
if (c == d) { // Should be a.equals(b), but happens to work with these particular values!
    // This will get executed
}
Integer e = 1000;
Integer f = 1000;
if (e == f) { // Should be a.equals(b)
    // Whether this gets executed depends on which compiler you use!
}
</code>```

2. Readability:

Consider the following two examples. Most people would say the second is more readable.

```<code>Integer a = 2;
Integer b = 2;
if (!a.equals(b)) {
    // ...
}
int c = 2;
int d = 2;
if (c != d) {
    // ...
}
</code>```

3. Performance:

The fact is it is slower to use the Object wrappers for primitives than just using the primitives. You're adding the cost of object instantiation, method calls, etc. to things that you use all over the place.

Knuth's "...say about 97% of the time: premature optimization is the root of all evil" quote doesn't really apply here. He was talking about optimisations which make the code (or system) more complicated - if you agree with point #2, this is an optimization which makes the code less complicated!

4. It's the convention:

If you make different stylistic choices to 99% of the other Java programmers out there, there are 2 downsides:

You will find other people's code harder to read. 99% of the examples/tutorials/etc out there will use primitives. Whenever you read one you'll have the extra cognitive overhead of thinking about how it would look in the style that you're used to.

Other people will find your code harder to read. Whenever you ask questions on Stack Overflow you'll have to sift through answers/comments asking "why aren't you using primitives?". If you don't believe me, just look at the battles people have over things like bracket placement, which doesn't even affect the generated code!

Normally I'd list some counter-points, but I honestly can't think of any good reasons to not go with the convention here!

Title: When to use primitive vs class in Java?

Body:
The standard practice is to go with the primitives, unless you're dealing with generics (make sure you are aware of autoboxing & unboxing!).

There are a number of good reasons to follow the convention:

1. You avoid simple mistakes:

There are some subtle, non-intuitive cases which often catch out beginners. Even experienced coders slip up and make these mistakes sometimes (hopefully this will be followed by swearing when they debug the code and find the error!).

The most commmon mistake is using a == b instead of a.equals(b). People are used to doing a == b with primitives so it's easily done when you're using the Object wrappers.

Integer a = new Integer(2);
Integer b = new Integer(2);
if (a == b) { // Should be a.equals(b)
    // This never gets executed.
}
Integer c = Integer.valueOf(2);
Integer d = Integer.valueOf(2);
if (c == d) { // Should be a.equals(b), but happens to work with these particular values!
    // This will get executed
}
Integer e = 1000;
Integer f = 1000;
if (e == f) { // Should be a.equals(b)
    // Whether this gets executed depends on which compiler you use!
}

2. Readability:

Consider the following two examples. Most people would say the second is more readable.

Integer a = 2;
Integer b = 2;
if (!a.equals(b)) {
    // ...
}
int c = 2;
int d = 2;
if (c != d) {
    // ...
}

3. Performance:

The fact is it is slower to use the Object wrappers for primitives than just using the primitives. You're adding the cost of object instantiation, method calls, etc. to things that you use all over the place.

Knuth's "...say about 97% of the time: premature optimization is the root of all evil" quote doesn't really apply here. He was talking about optimisations which make the code (or system) more complicated - if you agree with point #2, this is an optimization which makes the code less complicated!

4. It's the convention:

If you make different stylistic choices to 99% of the other Java programmers out there, there are 2 downsides:

You will find other people's code harder to read. 99% of the examples/tutorials/etc out there will use primitives. Whenever you read one you'll have the extra cognitive overhead of thinking about how it would look in the style that you're used to.

Other people will find your code harder to read. Whenever you ask questions on Stack Overflow you'll have to sift through answers/comments asking "why aren't you using primitives?". If you don't believe me, just look at the battles people have over things like bracket placement, which doesn't even affect the generated code!

Normally I'd list some counter-points, but I honestly can't think of any good reasons to not go with the convention here!


问:
Can compilers and interpreters have bugs, and what can we (as users) do to deal with them?
If a compiler's work is essentially translating source code into machine level code, can there be any glitch in a compiler, i.e. a faulty "translation?"

The same goes for an interpreter: can it fail to output the required content sometimes?

I have not heard of any bugs in compilers/interpreters, but do they exist?

答:
In layman's words:

All programs can have bugs.

Compilers are programs.

Ergo, compilers can have bugs.


答:
Yes

You tend to find them more in languages that are actively being developed than in those that are relatively mature (and thus don't see a lot of change on a frequent basis). This is probably why most languages are released at various 'stages' of stability. A nightly build is far less likely to be stable than a release candidate, which itself is less likely to be stable than a fully released and actively used version.

Luckily most of these languages (especially those that are open source) will have a public bug tracking system that you can submit reports to.

In my own experience, I ran into a fairly obscure but severe bug in Scala on Windows. I submitted my findings to the bug tracker and the issue was fixed fairly quickly. In that case, the language developers were smart enough to include a helpful note in the error log output, suggesting that what I'd run into was in fact a compiler error, and said where to submit the report.

Title: Can compilers and interpreters have bugs, and what can we (as users) do to deal with them?

Body:
If a compiler's work is essentially translating source code into machine level code, can there be any glitch in a compiler, i.e. a faulty "translation?"

The same goes for an interpreter: can it fail to output the required content sometimes?

I have not heard of any bugs in compilers/interpreters, but do they exist?


答: Yes of course like any software compilers have bugs, for example the gcc bug list is here </p>


答:
Compilers and interpreters are software too, and thus they aren't free from any of the problems of other software.

This is an example from a compiler as recent as MSVC 11 (2012), and here's an article on how they test the backend.

ContentLicense: CC BY-SA 4.0


问:
Career advice: stay with PHP or start a new career in something else ( .Net?)
I'm planning on moving to NY in 6-12 months tops, so I'm forced to find a new job. When I'm planing to start my life in another city it's also probably a good time to think about career changes.

I've found a lot of different opinions about PHP vs .Net vs Java and this is not the topic here. I don't want to start a new fight about which language is better. Knowing a programming language is not the most important thing for being a software developer. To be a really good developer you need to know OOP, design patterns, testing... and a language is just a tool to make things happen.

So back to my question. I have mixed experience in IT - 1 year as an IT support guy (Windows administration and support), around 2 years of experience in embedded programming (VB.Net 2005) and for the last 2 years I'm working with PHP/MySQL. I have worked with Magento web shop, assisted in some projects in Symfony, modified few Drupal sites.

My main concerns are the following:

Do I continue to improve my skills in PHP e.g. to start learning some major PHP framework like Zend, Symfony maybe get some PHP certification.

Or do I start learning .NET or Java. I'm more familiar to .NET so I'll probably choose it if choice falls between .NET and Java ( or you could convince me to choose Java :).

Career-wise, I don't know what is the best choice. Learning a new framework and language is more time consuming then improving my existing skills in PHP. But with .NET you have a lot of possibilities (Windows 7 Phone development, Silverlight, WPF) and possibly bigger chances to find better jobs.

PHP jobs are less well payed then .NET, at least, according to my research (correct me if I'm wrong). But if I start now with .NET I'm just a beginner and my salary will be low. I need at least 2+ years of experience in some language to even try to find some job that is paying higher than $50-60k in NY. My main goal in the next 2-3 years is to try to find a job in the $60-80k category. Don't get me wrong, I'm not just chasing money, but money is an important factor when you're trying to start a family.

I'm 27 years old and I feel that there isn't a lot of room for wrong decisions regarding my career, so any advice will be very welcome.

Update

Thank you all for spending time to help me with my problem. All of the answers and comments have been very helpful. I have decided to stick with PHP but also to learn C# and Silverlight 4. We'll see where the life will take me.

答:
The long term answer to this question is basically what our esteemed host (Joel Spolsky) and Steve Streeting said. Programming at it's core is not about languages it is about using the computer to solve problems, and is a craft that must be learned and worked and thought about over time. Knowing how to code does not make one a programmer.

But you asked a pragmatic and time-sensitive topic .. what should you do NOW?

I suggest that you dig into PHP until the move. Dig into it, hard, really hard, 20 hours a week outside of work hard. With PHP it is pretty easy .. get a hosting account and a domain and start building apps. With focused effort, 6 months is an eternity. Over that time, get to be really good at it. This will help you find a good job once in New York, and will very likely make you a better programmer to boot.

BTW .. if you didn't know already, there is an IT employment site in the StackExchange family.

THEN, when the life transition has settled down a bit, begin following Mr. Streeting's playbook and educating yourself about the craft of programming rather than the trade of coding. Use some time outside of work to read and do things on other platforms and with other tools.


问:
How to organize MVVM files in solution
I'm fairly new to the MVVM concept but like a lot of the flexibility it gives me so far.  However, I'm struggling to find a good way to manage my code.  I have several classes that are just sitting in a folder in my solution such as xxxView.cs, xxxViewModel.cs, yyyView.cs, yyyViewModel.cs, zzzView.cs, zzzViewModel.cs you get the idea.  It has started to crowd my solution, making it harder to find the files I'm looking for.  Is there some standard way to organize these files?  Do I create a View and ViewModel folder to separate and clean up the solution or have people found a better way?

答:
In one project we had more or less 60 "screens" with a lot of nesting and similar names.

Organizing it in Views, ViewModels and Controllers folders was quite difficult to work with, since the whole folder nested structure was replicated on all of the 3 main folders and going from the view model to its view and back was a pain.

I keep thinking that it would be a more comfortable-to-work organization by keeping together the files that belong to the same screen or functional area, like:

Section A

Section A 1

ISectionA1ViewModel.cs

SectionA1ViewModel.cs

SectionA1View.xaml

SectionA1View.xaml.cs

SectionA1Controller.cs

Section A 2

ISectionA1ViewModel.cs

SectionA2ViewModel.cs

SectionA2View.xaml

SectionA2View.xaml.cs

SectionA2Controller.cs

Section B

ISectionBViewModel.cs

SectionBViewModel.cs

SectionBView.xaml

SectionBView.xaml.cs

SectionBController.cs

Mainly because, at that project (and some others I worked with), those things are quite static. You will only perform small changes. And in the case of a huge refactor, it is easier to move from one file to the other, you can see them together in the Solution Explorer, which makes it very intuitive.

Also, If you have the Track items option activated in Visual Studio, it won't drive you crazy navigating up and down a lot all the time.

Title: How to organize MVVM files in solution


答:
There can bugs even in hardware; a famous example is the Pentium FDIV bug.
Without doubt there is the possibility that the compilers contain bugs.</p>


问:
Revokable BSD - What are the implications?
While examining alternatives to Exim/Dovecot for a dedicated mail server, I came across the lamson project, a python-based MTA.  I also found the following fork of the project:

https://github.com/moggers87/salmon

Quoting from the docs at the fork:

Salmon is a fork of Lamson. In the summer of 2012 (2012-07-13 to be
  exact), Lamson was relicenced under a BSD variant that was revokable.
  The two clauses that were of most concern:

Contributors agree that any contributions are owned by the copyright holder and that contributors have absolutely no rights to
  their contributions.

The copyright holder reserves the right to revoke this license on anyone who uses this copyrighted work at any time for any reason.

I read that to mean that I could make a contribution but then have said
  work denied to me because Mr. Shaw didn't like the colour of my socks.
  So I went and found the latest version that was available under the
  GNU GPL version 3.

Salmon is an anagram of Lamson, if you hadn't worked it out already.

I am familiar with the BSD license but have never seen it modified in this way.  I am curious what the implications of this kind of license would be for other developers using the code, especially in paid commercial projects (thinking something like subscription-based webapps here).

Assuming the license were revoked, could the user be liable for monetary damages, or would a scenario like this be equivalent to a cease-and-desist, in which case whatever functionality the library was providing would have to be reimplemented?

To Clarify:

Usual caveats with regard to answers are assumed.  I ask out of curiosity only and have no intentions on acting or assuming legal risk via the advice posted.

答:
I'm not a lawyer; this answer comes out of my (US-centric) understanding of basic licensing and copyright fundamentals. I'll address some basic US copyright law and case law in an attempt to shed some light on the topic, but don't take anything below as definitive (except the last two sentences -- if you want a tl;dr, read those).

Lamson's license is very bad, for a large number of reasons, and the author of Salmon was wise to move as far away from it as possible.

Some US-centric copyright and licensing review:

In the US, copyright offers monopoly rights over six particular actions:

(1) to reproduce the copyrighted work in copies or phonorecords;

(2) to prepare derivative works based upon the copyrighted work;

(5) in the case of literary, musical, dramatic, and choreographic works, pantomimes, and pictorial, graphic, or sculptural works, including the individual images of a motion picture or other audiovisual work, to display the copyrighted work publicly; and

[(3), (4), and (6) omitted, as they relate only to audio and/or performance works]

As you can see, "in the case of software, run the program code" is not included. This suggests that if you have received a copy of the software already, you can do whatever you like with it. Imagine an analogous case with a book: when you receive a book in a sale, copyright disallows you from copying it, but it has no say in how often you can open it and read it.

This point is heavily muddied, however, by software licensing. If you only use software under a license (i.e., it is "licensed, not sold"), you have not actually participated in a bona fide sale-transfer of a copy of copyrighted material -- you have been granted some limited, license-dependent rights over that copyrighted material. The ruling in Vernor v. Autodesk devises a test to determine if a particular transfer is a sale or a license:

First, we consider whether the copyright owner specifies that a user is granted a license. Second, we consider whether the copyright owner significantly restricts the user’s ability to transfer the software. Finally, we consider whether the copyright owner imposes notable use restrictions.

In the narrow case of Lamson's BSD-like license, it certainly passes the first test, but probably fails the other two tests. However, it's difficult to guess exactly how a court might rule here, as it is painfully obvious that the license was not composed with the intent of being legally rigorous. Let's assume (rightly or wrongly) that this BSD-like license is actually a "sale with restrictions" rather than an actual license. From there, we'll infer from that fact that right-to-use is granted naturally, unfettered. (This means that for other licenses with more rules, like copyleft or proprietary licenses, this may be a significantly less safe assumption.)

To review our assumptions thus far:

Lamson's license is actually a sale with restrictions

The sale with restrictions implies an unfettered right to use the software (this is perhaps a more dubious assumption, and I consider it first as true and then again as false, below)

Actual answer:

Thus, if we assume that the preceding analysis is true: if you have a copy of the software, and your license is revoked, your only obvious responsibility is to immediately stop distributing the code. If you aren't distributing the code in the first place (e.g., you use it as part of a network service), you can continue using the software, as is your natural right as the recipient of a sale-transfer.

If we assume that the Lamson's license does impose enforceable restrictions on use (either because it passes the Vernor license test after all, or the sale-transfer does come with enforceable use restrictions), then a user would indeed need to stop using the software as well, or else be legally liable for violating the sale restrictions.

The user would need to comply immediately, but it seems extremely unlikely that the copyright holder could impose a retroactive revocation of the license. If the copyright holder informs a user that his license is revoked, the user might be held accountable for violations from that point onward. (To what degree a user might be held accountable for automated violations -- e.g., the license was revoked on Sunday, but the file server kept serving files to downloaders until it was shut down on Tuesday -- is left as an exercise for the courts.)

This license is also quite troubling because it requires private modifications to have their copyright assigned to the original Lamson copyright holder. It is totally unclear if those private modifications must be sent to the author, however. Again, this license was obviously not written by someone who gave (or was trained to give) significant legal consideration to the license.

The moral:

Please don't write your own license.

If you must, consult a lawyer.


答:
Once forked from Lamson, Salmon became it's own codebase and all other bets are off.

The terms of BSD remain with Salmon since that's how that code was licenced at the point of forking.  Changes to Lamson's licencing or codebase are irrelevant and cannot be applied retroactively (although changes/diffs from the Lamson codebase would be under the terms of the new licence.)

That licencing protection works both ways and Salmon cannot legally move to GPL v3 without violating the BSD licence.  So if someone has attempted to re-licence Salmon as GPL v3 without permission from the Lamson authors (who presumably wrote most of the codebase) then that will be a big problem and I'd walk away at that point.

The terms which have been added to Lamson are probably not enforceable since there are no details on what constitutes a revocation even if the authors were to attempt one.

Usual caveats apply - I am not a lawyer so you should neither act (nor refrain from acting) based on anything I say.  If you're in doubt, speak to a real lawyer.

Title: Revokable BSD - What are the implications?

Body:
While examining alternatives to Exim/Dovecot for a dedicated mail server, I came across the lamson project, a python-based MTA.  I also found the following fork of the project:

https://github.com/moggers87/salmon

Quoting from the docs at the fork:

Salmon is a fork of Lamson. In the summer of 2012 (2012-07-13 to be
  exact), Lamson was relicenced under a BSD variant that was revokable.
  The two clauses that were of most concern:

Contributors agree that any contributions are owned by the copyright holder and that contributors have absolutely no rights to
  their contributions.

The copyright holder reserves the right to revoke this license on anyone who uses this copyrighted work at any time for any reason.

I read that to mean that I could make a contribution but then have said
  work denied to me because Mr. Shaw didn't like the colour of my socks.
  So I went and found the latest version that was available under the
  GNU GPL version 3.

Salmon is an anagram of Lamson, if you hadn't worked it out already.

I am familiar with the BSD license but have never seen it modified in this way.  I am curious what the implications of this kind of license would be for other developers using the code, especially in paid commercial projects (thinking something like subscription-based webapps here).

Assuming the license were revoked, could the user be liable for monetary damages, or would a scenario like this be equivalent to a cease-and-desist, in which case whatever functionality the library was providing would have to be reimplemented?

To Clarify:

Usual caveats with regard to answers are assumed.  I ask out of curiosity only and have no intentions on acting or assuming legal risk via the advice posted.


问:
Text search - big data problem
I have a problem I was hoping I could get some advice on!

I have a LOT of text as input (about 20GB worth, not MASSIVE but big enough).  This is just free text, unstructured.

I have a 'category list'.  I want to process the text, and cross-reference the items in the category list, and output the categories for each match, e.g.

Input text

The quick brown fox ran over the lazy dog.

Category lookup

Colour

Red | Brown | Green

Speed

Slow | Quick | Lazy | Fast

Expected Output

Colour - Brown

Speed - Quick, Lazy

To add to the complexity of the problem, the source text probably doesn't match the categories exactly, e.g. there will have to be a fuzzy match algorithm of sorts applied here.

I want to use 'Big data' tech to solve this (whether or not it TRULY NEEDS big data isn't the question - it's a secondary objective).

My thoughts are to utilize Hadoop Map/Reduce with Lucene to do the fuzzy-matching.

What do you think?  Am I way off base?

Thanks a lot - ANY advice appreciated!!

Duncan

答:
I would recommend starting with Solr, then do your machine learning with Mahout and Hadoop. Solr will give you basic text analysis through word stemming, normalization (lower-casing), and tokenization. If you enable term vectors in the schema you can feed those directly into Mahout and experiment with the different algorithms there. A lot (maybe most) of Mahout's algorithms will work in a distributed manor on Hadoop, as well as in a pseudo-distributed manor locally while you're working.

Once you've got Mahout picking out the right features of your text you can then add them to the docs already in Solr and then do facet queries over them.

Title: Text search - big data problem


问:
Best way to convert existing project to be open source in GitHub
I've been working on a personal closed source project for some time and would like to make it open source. I've never created my own open source project before so it will be a good learning experience. I have been using GitHub as source control, so once I've written some decent docs on how to use and develop for it etc, it should be as simple as switching the repo to be public right?

I guess my main question is around licencing. I was thinking of going with Apache 2.0 licence just because it seems to be widely used. It requires the licence header to be attached to all the source files, but if I do that now then all the other commits in the past will have it missing. Does that mean some one could pull an earlier version and it wouldn't have a licence? Is it best to start a new repo with the initial commit containing all the code with licence headers? Or maybe is there some advanced Git functionality that allows me to apply the licence header to all existing commits some how?

Cheers.

答:
Well you seem to want to use the Apache licence because it's the most common one.

I was thinking of going with Apache 2.0 licence just because it seems to be widely used

This Coding Horror Post explains in a clear and concise fashion the different licences available.

If you create a new branch and commit to it, it's cleaner. unless you want the older version(s) available to your users.


问:
Best practices for sharing tiny snippets of code across projects
I always try to follow the DRY principle strictly at work; every time I've repeated code out of laziness it bites back later when I need to maintain that code in two places.

But often I write small methods (maybe 10 - 15 lines of code) that need to be reused across two projects that can't reference each other. The method might be something to do with networking / strings / MVVM etc. and is a generally useful method not specific to the project it originally sits in.

The standard way to reuse this code would be to create an independent project for the reusable code and reference that project when you need it. The problem with this is we end up in one of two less-than-ideal scenarios:

We end up with tens/hundreds of tiny projects - each to house the little classes/methods which we needed to reuse. Is it worth creating a whole new .DLL just for a tiny bit of code?

We end up with a single project holding a growing collection of unrelated methods and classes. This approach is what a company I used to work for did; they had a project named base.common which had folders for things like I mentioned above: networking, string manipulation, MVVM etc. It was incredibly handy, but referencing it needlessly dragged with it all the irrelevant code you didn't need.

So my question is:

How does a software team best go about reusing small bits of code between projects?

I'm interested particularly if anyone has worked at a company that has policies in this area, or that has come across this dilemma personally as I have.

note: My use of the words "Project", "Solution" and "Reference" come from a background in .NET development in Visual Studio. But I'm sure this issue is language and platform independent.

答:
I recently came up with this service: Snip2Code (http://www.snip2code.com).

It's an interesting way to share just your snippets (not entirely libraries) with your team. It breaks the usual point to create common libraries that should be referenced in other projects, and in my opinion this is a valuable vision.

Moreover, there are a lot of scenarios were the use of a common library simply doesn't apply: let's consider for example some Design Patterns like Singleton, Strategy or Observer. You can create libraries to support such patterns but still there's no 100% coverage.

The real need is to have a tool to share common practices among the team. I tried to use Github's gists but I'm stuck with the search of them (really poor) and with the fact that I cannot share them just among my team and not with other...

(Disclaimer: I'm one of the founder of Snip2Code, and I was - together with my co-founders - in your very same mindset some time ago: this is why we decided to start this project!!)


问:
Should I ask/tell my boss before freelancing?
I am currently working as an intern at a consulting firm. I am soon to move to a full time employee once I graduate next semester, and I love working there. However, as a student, I lack money and I have met a business owner outside of work who has offered to hire me for some freelance web development.

Because I met this individual outside of work, I feel it would not be a conflict of interest to freelance for him. However, the work his is wanting me to do is very similar to what I already do for my current boss.

Should I speak with my boss before considering the offer?

Edit: I understand that I cannot take IP from work, and I am not in a contract, I'm employed at will.

答:
No

Unless your contract specifically forbids freelancing, what you do on your own time is none of his business.


问:
substitute for static inheritance
I currently have a number of classes (~20) that all do the same thing (abstractly), namely, generate an instance of a particular class from an xml file.

The way that they use the content of the xml file varies quite a bit, and the data gets stored into different substructures (fields, groups, etc) that are shared across the classes, so I took all of the parsing and field information out of the files, and created a helper class (as is the final constructed type)

All of the above classes and methods are static, as they have no need to contain any state.

I then wanted to have all the classes derive from one common class so that I am not referencing a seemingly unrelated class constantly, only to discover that inheritance and static do not work together well.

What is the appropriate way of setting this up? Its bascially a large set of factory methods for a type that require no state.

Update: The control flow is currently as follows:

Pick one of ~20 factory methods

Read in an XML file (all tags, attributes are the same across the files, but the files are distict across the methods).

Convert the content in the XML files to a class that has some data structures as members (List<Field>, List<Group>, Dictionary<string,string> etc). These data structures use types that are nested in the helper.

Add these collections to the uninitialized object.

Return the object to caller.

Right now, the 20 factory methods are thier own static classes, and all return objects of the same type, as even though there might be some semantic difference between the "types" all of the memebers and functions are the same. The code that parses the XML file is in a helper, as this logic is common to all of the factory methods. Step 3 has to be different for all the methods, so that part is found in the static classes.

答:
I then wanted to have all the classes derive from one common class so that I am not referencing a seemingly unrelated class constantly, only to discover that inheritance and static do not work together well.

I was with you up to this point, but this bit sounds like a misuse of inheritance.

If you feel like your classes are too tightly bound to the helper class, concentrate on improving the public interface of the helper class.

Title: substitute for static inheritance


答:
Yes.

Also, not only with compilers, but also with Interpretors/debuggers, and any 3rd party software tool.

We are currently using some 3rd party software, and have been having some of the issue.
Sometimes they thank us, for finding and reporting a bug. :)

Some of them have some memory leaks too, which leads to crash. The important question here could be, how to determine if the 3rd party tool, or the compiler has bugs for your application to work correctly?


答:
Pick one of ~20 factory methods

This part is interesting and may hold the key to solving this problem. How do you 'pick' the appropriate factory method? Is there a Factory class? Without an example it's quite difficult to provide a concrete answer but the way I would envisage solving this problem is as follows:

```<code>public abstract class BaseClass
{
    //common code and maybe some abstract methods

    //This could (should?) go into it's own class.
    public static BaseClass Factory(File file)
    {
        if (something)
        {
            return Class1.Create(file) //or just call the constructor
        }
        if (somethingElse)
        {
            return Class2.Create(file)...
        }
    }
}

public class Class1 : BaseClass
{
    //private constructor so that you have to go through the Create() method
    private Class1()
    {}

    //variables/code for handling the file and populating the variables

    private void ParseFile(File file)
    {
    }

    public static Class1 Create(File file)
    {
        Class1 class1 = new Class1();
        class1.ParseFile(file);
        return class1;
    }
}
</code>```

Obviously this is all pseudo-code!

I note that you say that the classes don't need to hold any state which is why they are static but something about that along with the need for inheritance doesn't quite add up. With my code you would call the Factory method on the base class (or in it's own class if you so desire) passing in each file and what you end up with is a list of BaseClasses which you pass back to the caller who presumably does something with them.

Perhaps if you could provide more detail of what you start with, what you want to end up with, and what you do in the middle we could offer some more concrete advice.

Title: substitute for static inheritance

Body:
I currently have a number of classes (~20) that all do the same thing (abstractly), namely, generate an instance of a particular class from an xml file.

The way that they use the content of the xml file varies quite a bit, and the data gets stored into different substructures (fields, groups, etc) that are shared across the classes, so I took all of the parsing and field information out of the files, and created a helper class (as is the final constructed type)

All of the above classes and methods are static, as they have no need to contain any state.

I then wanted to have all the classes derive from one common class so that I am not referencing a seemingly unrelated class constantly, only to discover that inheritance and static do not work together well.

What is the appropriate way of setting this up? Its bascially a large set of factory methods for a type that require no state.

Update: The control flow is currently as follows:

Pick one of ~20 factory methods

Read in an XML file (all tags, attributes are the same across the files, but the files are distict across the methods).

Convert the content in the XML files to a class that has some data structures as members (List<Field>, List<Group>, Dictionary<string,string> etc). These data structures use types that are nested in the helper.

Add these collections to the uninitialized object.

Return the object to caller.

Right now, the 20 factory methods are thier own static classes, and all return objects of the same type, as even though there might be some semantic difference between the "types" all of the memebers and functions are the same. The code that parses the XML file is in a helper, as this logic is common to all of the factory methods. Step 3 has to be different for all the methods, so that part is found in the static classes.

Body:
Pick one of ~20 factory methods

This part is interesting and may hold the key to solving this problem. How do you 'pick' the appropriate factory method? Is there a Factory class? Without an example it's quite difficult to provide a concrete answer but the way I would envisage solving this problem is as follows:

public abstract class BaseClass
{
    //common code and maybe some abstract methods

    //This could (should?) go into it's own class.
    public static BaseClass Factory(File file)
    {
        if (something)
        {
            return Class1.Create(file) //or just call the constructor
        }
        if (somethingElse)
        {
            return Class2.Create(file)...
        }
    }
}

public class Class1 : BaseClass
{
    //private constructor so that you have to go through the Create() method
    private Class1()
    {}

    //variables/code for handling the file and populating the variables

    private void ParseFile(File file)
    {
    }

    public static Class1 Create(File file)
    {
        Class1 class1 = new Class1();
        class1.ParseFile(file);
        return class1;
    }
}

Obviously this is all pseudo-code!

I note that you say that the classes don't need to hold any state which is why they are static but something about that along with the need for inheritance doesn't quite add up. With my code you would call the Factory method on the base class (or in it's own class if you so desire) passing in each file and what you end up with is a list of BaseClasses which you pass back to the caller who presumably does something with them.

Perhaps if you could provide more detail of what you start with, what you want to end up with, and what you do in the middle we could offer some more concrete advice.


问:
Check-list to avoid vendor lock-in?
Is there a set of industry-approved rules to avoid vendor lock-in?

I mean, something one can show to a manager, or other decision maker, that is easy to understand and easily verifiable.

Are there any universally accepted set of rules, a checklist or set of conditions that helps detect and prevent vendor lock-in in an objective, measurable way?

Have any of you warned a manager about the risk of vendor lock-in during the initial stages of a project?

答:
In my work as a consultant I frequently warn clients about the risk of vendor lock-in. This is from bitter experience of being called in to turn around failing projects: if you don't think about this at the beginning, then it will probably cost you in the long term.

There is no "standard checklist" but here is a good checklist of the main things that I look for:

Open API: is the API that we will be using (i.e. building a dependency on) open in the sense that it can be freely implemented by competing vendors?

Standards compliance - does the product conform with relevant industry standards?

Presence of compatible alternatives - Is there actually another compatible product (either commercial or open source) that we could switch in with minimal changes?

Open source - is the vendor's code open source (i.e. under an OSI approved license)?

Platform independence - is the technology stack portable across different platforms?

Contractual flexibility - can we terminate or scale back the contract early without significant penalties?

Independent service provision - are there credible options to buy services from different vendors (i.e. not just the original vendor)

Capabilities and skills - if we were to part company with the original vendor, do we have the required capabilities and skills to continue working effectively either in-house or with another vendor?

Record of good behaviour - does the vendor have a good track record that suggests you can trust them not to exploit any lock-in they may obtain?

Stability of requirements - are our requirements well defined and likely to stay the same? (if so, you can contract for these requirements up front and vendor lock-in doesn't matter so much...)

If the answer is yes to most or all of these questions, you can be reasonably certain of avoiding vendor lock-in. If not, you should be careful.

Title: Check-list to avoid vendor lock-in?


问:
Dynamic form builder forms and database design?
Say your users can create their own web-based forms (textboxes, selects, etc) and publish them on the web for their users to fill out.

Does anyone have a resource or any advice on how to architect the database to tie into the dynamic forms?

For example, would you create a child table for each form, or different versions of a given form?

答:
Creating new tables dynamically based on user input is usually not a good idea. If the basic structure of forms changes, all the dynamically created tables will need to be updated to include new columns or have old ones removed, and this can cause maintenance headaches. Then there's problem of knowing which table to query (which will probably lead to dynamic SQL which opens up all new problems). And there's probably performance problems too, but I'm not certain how bad that would be. Also, a table is usually used to represent a type of entity (such as "web form") rather than having copies of the same table for each new instance of the same entity.

I'd suggest a single table for the forms. You'll need an identifier on each form to identify whose form it is:

```
forms
-----
  id (PK)
  name
  owner_id (FK to users.id)
  (other fields)

form_elements
-------------
  id (PK)
  form_id (FK to forms.id)
  element_type_id (FK to element_types.id)
  caption
  (other fields)

element_types
-------------
  id (PK)
  name

element_list_values
-------------------
  id (PK)
  element_id (FK to form_elements.id)
  name
  value
  (other fields??)
```

Your web application can let users create forms which will be saved in the forms tables, with a reference to the user that created (assuming that you are tracking users as proper entities). The form is populated with form_elements that reference the forms table so they know which form they belong to, and the element_types so they know which type they are. element_types will store a static (mostly) list of different elements a form can have. Types could be: "text_field", "drop_down_list", "radio_buttons", "checkbox". For types such as "drop_down_list" and "radio_buttons", you'll need an extra table, maybe called element_list_values to store the possible options for the lists that these elements normally have.

Body:
Creating new tables dynamically based on user input is usually not a good idea. If the basic structure of forms changes, all the dynamically created tables will need to be updated to include new columns or have old ones removed, and this can cause maintenance headaches. Then there's problem of knowing which table to query (which will probably lead to dynamic SQL which opens up all new problems). And there's probably performance problems too, but I'm not certain how bad that would be. Also, a table is usually used to represent a type of entity (such as "web form") rather than having copies of the same table for each new instance of the same entity.

I'd suggest a single table for the forms. You'll need an identifier on each form to identify whose form it is:

forms
-----
  id (PK)
  name
  owner_id (FK to users.id)
  (other fields)

form_elements
-------------
  id (PK)
  form_id (FK to forms.id)
  element_type_id (FK to element_types.id)
  caption
  (other fields)

element_types
-------------
  id (PK)
  name

element_list_values
-------------------
  id (PK)
  element_id (FK to form_elements.id)
  name
  value
  (other fields??)

Your web application can let users create forms which will be saved in the forms tables, with a reference to the user that created (assuming that you are tracking users as proper entities). The form is populated with form_elements that reference the forms table so they know which form they belong to, and the element_types so they know which type they are. element_types will store a static (mostly) list of different elements a form can have. Types could be: "text_field", "drop_down_list", "radio_buttons", "checkbox". For types such as "drop_down_list" and "radio_buttons", you'll need an extra table, maybe called element_list_values to store the possible options for the lists that these elements normally have.


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
My favorite is the "No magic numbers" rule applied cluelessly.  For example, I once saw a comment in a code review stating then the "No magic numbers" rule had been violated by this line of code:

```<code>if (fscanf(file, "%s %hd",name, nbrObject ) != 2 )
</code>```

I guess the reviewer wanted a constant instead of 2, such as
    #define TWO 2

Body:
My favorite is the "No magic numbers" rule applied cluelessly.  For example, I once saw a comment in a code review stating then the "No magic numbers" rule had been violated by this line of code:

if (fscanf(file, "%s %hd",name, nbrObject ) != 2 )

I guess the reviewer wanted a constant instead of 2, such as
    #define TWO 2

OwnerDisplayName: Chalie Wax


问:
starting off with non trivial programs -- publish or not?
I've just started making some simple but non trivial(i think) programs in Ubuntu -- as of now have made a small xkcd scraper, which i plan to develop into a multi webcomic downloader+viewer

At this point, would it be a good idea to start publishing the code on a site like Github or launchpad? (currently I'm not really worried about people copying my code/licensing)

Or is it better to publish the code only after the program is completed?

Also, can you suggest some such sites where I can post such codes and get suggestions for improvements/discuss the code with others?

答:
It's a good idea to push it to a public repository for multiple reasons -

Motivates you to keep it up, maintain it

You might get unexpected feedback from others

Looks good on your resume/profile/blog

So even if it's not complete yet, put it up somewhere. Don't be worried about incompleteness, because people who visit will know it's a work in progress.

Update : As Skilldrick mentions, www.github.com is a great repos.


问:
Encryption Cannot Be Reversed?
I am under the impression that an encrypted string cannot be decrypted so the original value is lost forever.

However, if the following string always equals "dominic" (my name), then can't there be some logical way to reverse it; being as it's not random nor is it based on the date/time, but there is a logical method to it?

```<code>0WrtCkg6IdaV/l4hDaYq3seMIWMbW+X/g36fvt8uYkE=
</code>```

No matter what or how many times I encrypt "dominic" (string), it always equals as above.  So, shouldn't there be some way to decrypt a string like that?

Example of what I'm talking about:

```<code>public string EncryptPassword(string password)
{
    return Convert.ToBase64String(
        System.Security.Cryptography.SHA256.Create()
        .ComputeHash(Encoding.UTF8.GetBytes(password)));
}
</code>```

答:
Encryption can always be reversed.  The point of encryption is to take a message and encode it with a secret key so that only another person who has the key can reverse the encryption and read the message.

What you're looking at here is hashing, which is not the same as encryption, though cryptographic techniques are often used in implementing hashes.  The idea of a hash is that it uses complicated mathematical techniques to build a new value that maps to an old value, which is repeatable.  There's no key, and it's not meant to be reversed.  A cryptographically strong hash is created with the mathematical property that, if you have value A whose hash is value B, it's very, very difficult to intentionally create another value C that also hashes to B.

Hashes don't need to be reversible, because they're used for authentication.  If you give me a username and a password, you really don't want me storing that password in my database, because if someone hacks in and gains access to my database, they could get ahold of your password!  So instead, I'd store the hash of your password in the database.  Then when you log in, I check to see if there's a username that matches yours, with a password entry that matches the hash of the password you sent, and if so you're authenticated, because it's very difficult to create a hash collision (two values that hash to the same value) with a good hash, so I'm almost perfectly certain that the password you used is the right one.

The other property of a strong cryptographic hash is that it's very difficult to reverse.  You know that the value 0WrtCkg6IdaV/l4hDaYq3seMIWMbW+X/g36fvt8uYkE= is the hash for "dominic" because you just worked it out, but if you didn't know that, and didn't know where to start looking, and all you had was 0WrtCkg6IdaV/l4hDaYq3seMIWMbW+X/g36fvt8uYkE=, it could literally take you billions of years to figure out that the original was "dominic", if the hash is a good one.  Again, this is useful to prevent collateral damage in case a password list gets stolen.

Title: Encryption Cannot Be Reversed?