问:
"A good programmer can be as 10X times more productive than a mediocre one"
I had read an interview with a great programmer (it is not in English) and in it he said that "a great programmer can be as 10 times as good as a mediocre one" giving reason for why good programmers are very well paid and why programming companies give many facilities for their employees. The idea was that there is a very large demand for good programmers, because of the above reason and that's why companies pay very much to bring them.

Do you agree with this statement? Do you know any objective facts that could support it?

Edit: The question has nothing to do with experience; if you talk about one great programmer with 1 year experience then s/he should be 10 times more productive than a mediocre programmer with 1 year experience. I agree that from certain experience years onwards, things start to dissipate but that's not the purpose of the question.

答:
"The productive programmer in that environment is the one who is best at understanding and implementing the users' needs, not the one who can write the cleverest code." (From Carson63000 answer)

That key point coupled with bethlakshmi's points makes a huge point.  A great developer can be great in his/her one slice of reality but break apart soon as the world changes.  Being able to keep up with the business' needs is far more important than anything else.  At the end of the day, unless your business is technology, the business doesn't care about technology; they need solutions.  So being great with design patterns doesn't mean diddly squat to end-users who just need a data dump to show on a webpage.  I've seen mediocre developers secure themselves a job by catering to the business that supports them while great developers get bored and walk away in search of a never-ending challenge.  Depending on your organization and project(s), it's possible to feed these challenge-starved developers but likely, there will be a point in time when you just don't need that amount of processing power.  These developers don't like to just sit idle like a processor.  They'll shutdown and reboot elsewhere.

Lastly, I'll say it's OK to know who your "key" performers are, but a development "team" is still a team.  To reiterate bethlakshmi, "what are you going to do with this metric?"  If you need a team that behaves like a team, I wouldn't focus on metrics as these.  I would realize that even the smallest player is still an important part of the team.  Even at 60% less of the productivity of your key player, that one player may be giving your team something it needs.  Find out what it is and try to multiply it.  Don't burn out your key player by assuming he should lead the team, find ways to multiply his output as well, by contaminating the other players with that greatness.  This requires a bit of creativity, not just numbers.  In the end, you may learn that what makes a good programmer is not even that programmer, it could be his peers, his opportunities in the workplace or it could even be you.


问:
Object locking over Internet
I am building a tutoring application that can be used to draw objects and then one is able to drag them around. I would like to know what is the best thing to do when someone clicks on an object and starts to drag it.

I was told I should "lock" it - prevent it from being grabbed by someone else at the same time and being able to drag it. But that would require sending a request to the server (and then to all other users connected to the tutoring session) to lock it which might take a bit of time (what if a teacher is in USA and student is in Africa on dialup)? I was also told I should loop until I see that the object was locked by me. This way, the user might not be able to grab and drag and object for several seconds (UX design problem).

I proposed perhaps to only enable one to drag object you drew, but that seems short sided. Any suggestions? Thank you!

答:
The way a lot of online real time games deal with latency is to go ahead and perform an action locally, then correct it later when the authoritative result is given by the central server.  In your case, you start dragging the object locally, sending a lock request to the server as soon as your drag starts, but acting as though you already own the lock.  If the lock request succeeds, you carry on as normal.  If someone else beat you to it, the local client ends the drag and gives control of the drag to the winning user until the lock is released.  None of the other users will see your aborted drag attempt.

You'll have to decide for yourself if having someone "steal" your drag on rare occasions is more annoying or less than having to wait for a lock every single time.  In my opinion, removing the delay in the most common case is the preferred solution.

ContentLicense: CC BY-SA 3.0

Title: Object locking over Internet


问:
Randomly Generate Points in a Spiral Motion using Javascript
So I have a javascript program that currently gets random points, it generates a random x,y,z value around the center point, within the radius r

```<code>  var maxArms = 3;
  var i = 0;
    var color = [];
  for(var arm = 0; arm <= maxArms; arm++) {
    var perArm = (numStars/maxArms);
    var perPoint = Math.ceil((r/10)/5);
    var actualPoints = ((r/10)/5);
    perPoint = (perArm/(actualPoints+(actualPoints/4)));
    var angle = 8;

    for (var ra = 0; ra < 412; ra += 2) {
        for (var p = 0; p < (580-ra); p++) {
        var an = Math.random() * Math.PI * 2;
        var pX = x(ra,angle) + ((Math.cos(an) * (Math.random()*512)) * (Math.random() > .5 ? 1 : -1)),
                pY = y(ra,angle) + ((Math.cos(an) * (Math.random()*512)) * (Math.random() > .5 ? 1 : -1)),
            pZ = Math.random() * ((r/2)-p) * (1 / ra) * (Math.random() > .5 ? 1 : -1),
                particle = new THREE.Vertex(
                    new THREE.Vector3(pX, pZ, pY)
                );
            innerRing.vertices.push(particle);

            var h = Math.random() * (291 - 185) + 185,
                s = Math.random() * (66 - 34) + 34,
                v = Math.random() * (100 - 72) + 72;
            color[i] = new THREE.Color(0xffffff);
            color[i].setHSV(h / 360, s / 100, v / 100);

        i++;
        }
    }
  }
</code>```

Now I am trying to find a way rather than just randomly placing things anywhere within the radius, to spiral out the points, into a defined number of "Spiral Arms", I am sure this is going to require something with Sine and Cosine, but I have spent hours now looking to understand how to use these functions to do what I need and I am not sure how to do it.

What I am looking for is I want a variable for the number of arms numArms and I want to have the function above take the number of arms, and create an equal number of points in each arm, and each arm  arc out from the center point 0,0 in a spiral motion.

Does that make sense?

I have found other questions, and different answers with google about how to make a spiral, as well as how to find random points (as shown above) but nothing that can help me find random points around spiral arms, but once I have the points for the spiral I am not sure how to get the random x,y,z coordinates around the spiral.

Also, if it is possible, to make it so towards the beginning of each arm there are more points than at the end of the arm.

Yes I know my script is not properly optimized, but I am looking more for function at the moment.

I have attached an image of what the currently generated with the code below, as well as a sample of a spiral galaxy, althought I do not want the center as huge as the second image.

Edit

I have made some changes to the generation script, although rather sloppy, it starts out making stars come from the middle like a spiral, but it inevitably gets larger and no longer looks like a spiral, I have tried playing with all of the variables (ra and angle) but it does not make the spiral look any better, what can I do?

Current Generation:

Sample Generation:

答:
I believe you just need to follow the formula for a spiral, given as,

```<code> x(t) = a * t * cos(t), y(t) = a * t * sin(t)
</code>```

where a is constant you can use to express how fast your spiral expands. For the 3D case just add the extra argument z. To define a number of arms, you could just place this inside another for statement. However, if don't want to create a growing 3D spiral, you could fix the z parameter within a certain range. To create the illusion of a galaxy, I believe you could add an offset to x and y and run it multiple times,

```<code>var a = 5;
var offset = 2; // You have to choose a good offset for your project.

var numArms = 3;
for (var arm; arm < numArms; arm++) {
    for (var p = 0; p < num; p++) {
        var pX = a * p * cos(p + (Math.PI * arm)) + (Math.random() * offset);
        var pY = a * p * sin(p + (Math.PI * arm)) + (Math.random() * offset);
        var pZ = Math.random() * a;

        // do something with pX, pY, and pZ
    }
}
</code>```

Look in here for the original spiral formulas, and to this question, which does something similar using PHP.

Body:
I believe you just need to follow the formula for a spiral, given as,

 x(t) = a * t * cos(t), y(t) = a * t * sin(t)

where a is constant you can use to express how fast your spiral expands. For the 3D case just add the extra argument z. To define a number of arms, you could just place this inside another for statement. However, if don't want to create a growing 3D spiral, you could fix the z parameter within a certain range. To create the illusion of a galaxy, I believe you could add an offset to x and y and run it multiple times,

var a = 5;
var offset = 2; // You have to choose a good offset for your project.

var numArms = 3;
for (var arm; arm < numArms; arm++) {
    for (var p = 0; p < num; p++) {
        var pX = a * p * cos(p + (Math.PI * arm)) + (Math.random() * offset);
        var pY = a * p * sin(p + (Math.PI * arm)) + (Math.random() * offset);
        var pZ = Math.random() * a;

        // do something with pX, pY, and pZ
    }
}

Look in here for the original spiral formulas, and to this question, which does something similar using PHP.


问:
Verifying a debit card online - What information is checked?
I am eager to know what information is checked by the online companies to confirm that the card is yours?

If a programmer has to implement this functionality, how can he access information like address of the client which is not written on the debit card? Thanks

答:
If a programmer has to implement this functionality, how can he access information like address of the client which is not written on the debit card? Thanks

He doesn't, He simply collects data from the user and submits that data to the CC via some API. The API returns a Status (Authorized, Captured, ect).

The API will NOT give the merchant any data about the customer hes\he\it does not already have.


问:
Alternatives to the repository pattern for encapsulating ORM logic?
I've just had to switch out an ORM and it was a relatively daunting task, because the query logic was leaking everywhere. If i'd ever had to develop a new application, my personal preference would be to encapsulate all query logic (using an ORM) to futureproof it for change. Repository pattern is quite troublesome to code and maintain so i was wondering if there are any other patterns to solve the problem ?

I can foresee posts about not adding extra complexity before it's actually needed, being agile etc. but i'm only interested about the existing patterns solving a similar problem in a simpler way.

My first thought was to have a generic type repository, to which i add methods as needed to specific type repository classes via extension methods, but unit testing static methods is awfully painful. IE:

```<code>public static class PersonExtensions
{
    public static IEnumerable<Person> GetRetiredPeople(this IRepository<Person> personRep)
    {
        // logic
    }
}
</code>```

答:
First think I say is that ORM is already big enough abstraction over your database. Some ORMs provide binding to all common relational databases (NHibernate has bindings to MSSQL, Oracle, MySQL, Postgress, etc..) So building new abstraction on top of it doesn't seem profitable to me. Also, argummenting, that you need to "abstract away" this ORM is meaningless.

If you still want to build this abstraction, I would go against Repository pattern. It was great in age of pure SQL, but it is quite troublesome in face of modern ORM. Mainly because you end up re-implementing most of the ORM features, like CRUD operations and querying.

If I was to build such abstractions, I would use these rules/patterns

CQRS

Use as much as possible of existing ORM features

Encapsulate only complex logic and queries

Try to have "plumbing" of the ORM hidden inside an architecture

In concrete implementation, I would use CRUD operations of ORM directly, without any wrapping. I would also do simple queries directly in code. But complex queries would be encapsulated in their own objects. To "hide" the ORM, I would try to inject the data context transparently into an service/UI objects and have same done to query objects.

Last thing I would like to say, is that many people use ORM without knowing how to use it and how to make best "profit" out of it. People recommending repositories are usually of this kind.

As a recommended reading, I would say Ayende's blog, especially this article.


答:
A pretty thorough overview and analysis of research about productivity differences is provided in two articles written by Steve McConnell:

Productivity Variations Among Software Developers and Teams: The Origin of "10x"

Origins of 10X – How Valid is the Underlying Research?

First article (Productivity variations...) states:

...The original study that found huge variations in individual programming productivity was conducted in the late 1960s by Sackman, Erikson, and Grant (1968). They studied professional programmers with an average of 7 years’ experience and found that the ratio of initial coding time between the best and worst programmers was about 20 to 1; the ratio of debugging times over 25 to 1; of program size 5 to 1; and of program execution speed about 10 to 1. They found no relationship between a programmer’s amount of experience and code quality or productivity.

Detailed examination of Sackman, Erickson, and Grant's findings shows some  flaws in their methodology... However, even after accounting for the flaws, their data still shows more than a 10-fold difference between the best programmers and the worst.

In years since the original study, the general finding that "There are order-of-magnitude differences among programmers" has been confirmed by many other studies of professional programmers (Curtis 1981, Mills 1983, DeMarco and Lister 1985, Curtis et al. 1986, Card 1987, Boehm and Papaccio 1988, Valett and McGarry 1989, Boehm et al 2000)...

This article also has an interesting side note:

This degree of variation isn't unique to software. A study by Norm Augustine found that in a variety of professions--writing, football, invention, police work, and other occupations--the top 20 percent of the people produced about 50 percent of the output, whether the output is touchdowns, patents, solved cases, or software (Augustine 1979).

Second article (...How Valid is the Underlying Research?) has been written mainly to address critical review of the first one by Laurent Bossavit:

original critique in French: Folklore ou fait scientifique, comment les différencier

English translation: Fact and folklore in software engineering.

In second article, in section A Deeper Dive Into the Research Supporting “10x” McConnell re-checks in more details the references used in the first article and concludes:

...As I reviewed these citations once again in writing this article, I concluded again that they support the general finding that there are 10x productivity differences among programmers. The studies have collectively involved hundreds of professional programmers across a spectrum of programming activities.

...the body of research that supports the 10x claim is as solid as any research that’s been done in software engineering. Studies that support the 10x claim are singularly not subject to the methodological limitation described in Figure 1, because they are studying individual variability itself (i.e., only the left side of the figure). Bossavit does not cite even one study — flawed or otherwise — that counters the 10x claim, and I haven’t seen any such studies either. The fact that no studies have produced findings that contradict the 10x claim provides even more confidence in the 10x claim. When I consider the number of studies that have been done, in aggregate I find the research to be not only suggestive, but conclusive—which is rare in software engineering research.

For the sake of completeness, list of references used in the Productivity variations... is also quoted below:

References

Augustine, N. R. 1979. "Augustine’s Laws and Major System Development Programs." Defense Systems Management Review: 50-76.

Boehm, Barry W., and Philip N. Papaccio. 1988. "Understanding and Controlling Software Costs." IEEE Transactions on Software Engineering SE-14, no. 10 (October): 1462-77.

Boehm, Barry, et al, 2000. Software Cost Estimation with Cocomo II, Boston, Mass.: Addison Wesley, 2000.

Boehm, Barry W., T. E. Gray, and T. Seewaldt. 1984. "Prototyping Versus Specifying: A Multiproject Experiment." IEEE Transactions on Software Engineering SE-10, no. 3 (May): 290-303. Also in Jones 1986b.

Card, David N. 1987. "A Software Technology Evaluation Program." Information and Software Technology 29, no. 6 (July/August): 291-300.

Curtis, Bill. 1981. "Substantiating Programmer Variability." Proceedings of the IEEE 69, no. 7: 846.

Curtis, Bill, et al. 1986. "Software Psychology: The Need for an Interdisciplinary Program." Proceedings of the IEEE 74, no. 8: 1092-1106.

DeMarco, Tom, and Timothy Lister. 1985. "Programmer Performance and the Effects of the Workplace." Proceedings of the 8th International Conference on Software Engineering. Washington, D.C.: IEEE Computer Society Press, 268-72.

DeMarco, Tom and Timothy Lister, 1999. Peopleware: Productive Projects and Teams, 2d Ed. New York: Dorset House, 1999.

Mills, Harlan D. 1983. Software Productivity. Boston, Mass.: Little, Brown.

Sackman, H., W.J. Erikson, and E. E. Grant. 1968. "Exploratory Experimental Studies Comparing Online and Offline Programming Performance." Communications of the ACM 11, no. 1 (January): 3-11.

Valett, J., and F. E. McGarry. 1989. "A Summary of Software Measurement Experiences in the Software Engineering Laboratory." Journal of Systems and Software 9, no. 2 (February): 137-48.

Weinberg, Gerald M., and Edward L. Schulman. 1974. "Goals and Performance in Computer Programming." Human Factors 16, no. 1 (February): 70-77.

Title: "A good programmer can be as 10X times more productive than a mediocre one"

Body:
I had read an interview with a great programmer (it is not in English) and in it he said that "a great programmer can be as 10 times as good as a mediocre one" giving reason for why good programmers are very well paid and why programming companies give many facilities for their employees. The idea was that there is a very large demand for good programmers, because of the above reason and that's why companies pay very much to bring them.

Do you agree with this statement? Do you know any objective facts that could support it?

Edit: The question has nothing to do with experience; if you talk about one great programmer with 1 year experience then s/he should be 10 times more productive than a mediocre programmer with 1 year experience. I agree that from certain experience years onwards, things start to dissipate but that's not the purpose of the question.


问:
Testing UI for azure web app on iPad
I am working on debugging my mobile application.  There is a specific requirement/issue that I am having related to a drag and drop touch interface on an iPad.  I am at the trial and error phase of trying to figure out how to fix this (meaning I have no idea how to fix the issue I'm seeing).

The only way I have been able to figure out how to test my app on a mobile device is to deploy it to my azure test instance because the azure compute emulator always runs sites under 127.0.0.1.  This is really annoying since each deploy to azure takes 10+ minutes.

So my question is, how the heck to people do mobile development on this platform?    I've have found some people suggesting I could set up a reverse proxy using fiddler to allow remote connections but so far I haven't been able to get this to work.  Is there some sweet ios simulator that I haven't been able to find?  Am I missing something?

答:
I ended up copying/tweaking the offending code into JSfiddle from my laptop.  Then I navigated to the JSfiddle on my iPad.  Still a pain, but much faster than azure deploy.  Helped alot!

Also this question has some helpful tips for how to debug javascript from iPad.

Title: Testing UI for azure web app on iPad


问:
How flexible can hardware get?
This subject is long time in the making for me and it particularly took off when I was researching bootloaders for computers and consumer electronics, which, I will note, differ drastically. I've learned how ancient and inflexible x86 hardware is and just how much the structure of software is constrained by it. Examples of what I am talking about:

Bootloaders cannot have an arbitrary size.

Specialized functions like memory-mapped hardware.

An Intel processor's ties to a particular type of firmware.

So I've wondered about systems that might be designed like this:

Writing text to the screen handled pixel-by-pixel by an operating system instead of an intermediary microcontroller.

Sectorless hard drives wherein a computer simply begins executing at the first address and the bootloader can be any size.

Functionality of microcontrollers moved into the software.

I understand that this would take away a lot of simplicity, but do systems like this exist? I am guessing this would be more prevalent in embedded systems. To better understand this question, imagine a device where there are no controllers or independent systems and everything is controlled by the CPU.

答:
Beyond the now traditional x86 architecture, there are many other forms of computing hardware - all the way to analog processors and back.

I don't think I can address all of your points (or provide broader ones) but you bring up microcontrollers and embedded systems. The flexibility in embedded is not one of software, but one of modularity. If you have a clearly defined communications protocol; a collection of modular, single-purpose controllers and sensors; and a configuration tool to link inputs and outputs from each module, then you have a highly flexible hardware setup.

The problem is, flexibility brings the expense of complexity - so most modular embedded systems are typically limited and require some central controller to achieve anything beyond simple input/output. In fact, at least in building control systems, things that were once hardware driven in modules (like the control feedback loop relating valve controls to temperature input) have been moved into embedded software in a central controller - creating less flexible hardware, but more flexible systems.

Title: How flexible can hardware get?


问:
I've been told HTML is a markup language, C++ is a programming language, what could make that difference?
My programming friends are always telling me that HTML is a markup language and C++ is a programming language. When I ask them what's the difference, they never give me a reasonable answer.

What could make one call C++ a programming language, and HTML not?

答:
Markup languages mainly deal with how the information is displayed and they generally lack in the programming infrastructure of variables, math, comparison, decision making (if ... then), loops (for, while), etc.

HTML by itself is static; that is, much like a word-processor, it is meant to present the information as it is. Only with the addition of some sort of programming languages (usually scripting languages like JavaScript, PHP, etc) can the HTML web pages can have a "changing" content. The scripting languages provide the "programming" possibilities with variables, math, comparisons, decision making, loops, etc.


问:
Design Patterns - Service Layer
I currently reading a lot about Design Patterns and I have been watching various Pluralsight videos from their library. Now so far I have learnt the following:

Repository Pattern

Unit of Work Pattern

Abstract Factory Pattern

Reading the awesome "DI in .NET" book

Now I read lot about Services and Service Layers and wanted some advice about the best place to read up and learn about these. I presume this fits into Domain Driven Design and I should start there? The term "Service" just seem to be used widely within IT and it can be confusing the exact meaning.

So my questions is:

What is the Service Layer

Where is the best place to learn about them. I know there are probably tonnes of interweb/books/blogs on the subject, but some good areas to start from would be nice.

If I'm being too vague, let me know.

答:
How accurate this advice is may vary, over on StackOverflow someone stated: "Be wary of Design Patterns; learning a Pattern may inhibit your ability to correctly implement the proper design. This can cause bad developer habits and practices."

Which does make sense; as your bending your application to a pattern rather the pattern to your application.  Which is essentially like a cookie-cutter approach.

However...

Codeplex has some great tutorials on Dependency Injection, Repository, Unit Of Work.  Plus Amazon has some great books out there as well. Microsoft has a free architecture handbook which is very solid also. The Stack Overflow post has a link to that manual, but here is a direct link.

A pattern you may want to look into is SOA(Service Oriented Architecture).  It is looked at as an Anti-Pattern, but with the culmination of Windows Communication Service and abstraction.  It can provide a very agile lightweight flexible solution. Assuming your application benefits from this approach.

Service Oriented Architecture

ORM

Dependency Injection

Repository Pattern

N-Tier Applications

Those are few sites with good details; hopefully that is helpful.  There is a lot to learn; but the simplest solution is usually the right solution.

I had a bunch of links; but my rep is too low on this site to post em.  Just Google those terms and you should get some nice articles.

Title: Design Patterns - Service Layer


答:
Addressing your items specifically:

Writing text to the screen handled pixel-by-pixel by an operating system instead of an intermediary microcontroller. Early personal computers did this, more or less. Most of the early machines that I can think of had some sort of video chip to generate the video signal that actually drove the display, writing pixels into the display buffer (often a region of main memory) was usually left up to the CPU. Updating the display consumed a fair portion of the CPU's time (and also tied up the memory bus). Offloading all that work to a graphics processor was a step forward in making machines faster.

Sectorless hard drives wherein a computer simply begins executing at the first address. Where is the "first address" on a hard drive? Without some sort of formatting information, there's no way to find any location on a disk. That said, there's quite a lot of variety in disk formats. One interesting one was Spiradisc, in which there was essentially just one spiral track. Many optical disc formats (e.g. CD-ROM) are also laid out with spiral tracks. More to the point, though, microprocessors generally are set up to "simply begin executing at the first address" in memory, which is how bootloaders themselves get executed.

Functionality of microcontrollers moved into the software. What functionality are you talking about? You might be interested in Reduced Instruction Set Computing, a chip architecture which calls for simplified instructions that can be executed quickly. For example, RISC processors often won't have instructions for multiplication or division; instead, those operations are built up from simpler instructions like shift and add. This is a clear example of functionality being moved into software.

Title: How flexible can hardware get?

Body:
This subject is long time in the making for me and it particularly took off when I was researching bootloaders for computers and consumer electronics, which, I will note, differ drastically. I've learned how ancient and inflexible x86 hardware is and just how much the structure of software is constrained by it. Examples of what I am talking about:

Bootloaders cannot have an arbitrary size.

Specialized functions like memory-mapped hardware.

An Intel processor's ties to a particular type of firmware.

So I've wondered about systems that might be designed like this:

Writing text to the screen handled pixel-by-pixel by an operating system instead of an intermediary microcontroller.

Sectorless hard drives wherein a computer simply begins executing at the first address and the bootloader can be any size.

Functionality of microcontrollers moved into the software.

I understand that this would take away a lot of simplicity, but do systems like this exist? I am guessing this would be more prevalent in embedded systems. To better understand this question, imagine a device where there are no controllers or independent systems and everything is controlled by the CPU.


问:
How are OSS licenses upheld on unbacked projects?
If an OSS project is not backed (for example, by the Apache Foundation), how is the OSS license upheld?

My specific scenario is this: if I create an GPLd mobile application with a non-commercial transformations clause, what's to actually stop someone from re-releasing it as "Pro" and charging for it?

I assume the owner of the store (Apple/Google/MS) aren't going to uphold licenses on my behalf. Would it come down to me personally having to pay for a lawyer (which seems like a lot of effort to protect a good will gesture)?

答: Only the person whose rights were violated can sue, or they can authorize someone else to sue. You can't just go around and randomly sue people on other people's behalf.</p>


答:
The way these things usually works is roughly like so:

Customer proceeds through checkout on your shopping site.

Your site redirects to payment processor, sending the required data along with the request (your site's ID, amount, remarks, etc.).

Payment processor processes payment.

Payment processor redirects back to your site.

Your site verifies that the payment was successful, and if so, completes the order.

Step 3 is entirely between the customer and the payment processor; your site is completely out of the loop at this point.

For step 5, I have seen three approaches.

The most solid one is that the payment processor simply passes you a transaction ID (in step 4), which you can then use to call a web service provided by the payment processor, and this call will tell you that the transaction ID does indeed match your request and was indeed successful. Because the web service is not publicly accessible, and the response contains some sort of token that uniquely identifies your order, a customer cannot replay the redirect back to your site to reuse the successful payment.

The second approach does the same, but instead of you polling the payment provider, the payment provider pushes a message to you. The problem with this approach is that you have to check payment statuses asynchronously, which in turn means the customer's order can't be completed directly after the redirect.

The third approach uses cryptography to pass the entire verification through the client. This is usually done by sending complete payment information, digitally signed by the payment processor, along with the request. The upside of this is that the extra web service call between your server and the payment processor's isn't needed, but as a downside, all the sensitive information passes through the client, which means the attack surface is larger - a malicious shopper could store the payment response, try to crack the key used to sign the message, and then produce their own fake responses on future orders without involving the real payment processor at all. This is bad, because your server will think the payment has been made, while the payment processor has absolutely no clue that anything is going on at all.

This procedure is mostly the same whether it's a debit or credit card; the difference lies in what the payment processor does, and what exactly that is depends on the card, the card issuer, the country, and a few other things.

Title: Verifying a debit card online - What information is checked?

Body:
I am eager to know what information is checked by the online companies to confirm that the card is yours?

If a programmer has to implement this functionality, how can he access information like address of the client which is not written on the debit card? Thanks


问:
Is there a synonym for "Blittable" that is more common?
Is there a more common name for a "Blittable" data type?  In my software there is a distinction between a variable sized structure and a fixed size structure that has a similar behavior to "blittable" but I have only seen the name used in Microsoft software.</p>

答: The generic term would be Block Transferable. It originates with the PDP-10 as the "Block Transfer Instruction and was abbreviated as "BLT", hence "Blit or Blittable". It had to do with passing something through from Memory to Memory without going through the Accumulator like the Move Instruction would.</p>


问:
Developing with confidence without a real development environment
I've recently been hired for a project that involves working with and around several third-party "enterprise" systems. Due to what I imagine would be the astronomical cost and effort required to build a sufficiently faithful replica of the production environment, the prospect of having a real development environment seems vanishingly slim.

This is of course not ideal. On the bright side, I imagine there must be people out there safely testing and deploying software into unreplicable environments like this, and I can probably follow in their footsteps.

How those who effectively deal with these kinds of situations do it?

答: This happens all the time in the real world.  I know a guy who writes apps that control gigantic agricultural greenhouses - ventilation, heating, moisture control, you name it.  He doesn't have a "test greenhouse", but he has a simulator program provided by the company that builds the actual hardware systems.  If the code works correctly with the simulator, it is presumed to work correctly with the real equipment.  On rare occasions the simulator turns out to be wrong, but that's the greenhouse-hardware company's issue to deal with, because it isn't simulating correctly.


答:
According to Wikipedia the Blittable types  are originated from:

A memory copy operation is sometimes referred to as a 'block transfer'. This term is sometimes abbreviated as BLT (there's actually a BLT instruction on the PDP-10) and pronounced 'blit'. The term 'blittable' expresses whether it is legal to copy an object using a block transfer.

In the Microsoft .NET framework, data is often represented in memory differently in managed and unmanaged code However, blittable types are defined as having an identical presentation in memory for both environments, and can be directly shared. So, this concept of blittable and non-blittable data types applies to specifically to the problem of data conversion between managed and unmanaged memory.

Title: Is there a synonym for "Blittable" that is more common?

Body: Is there a more common name for a "Blittable" data type?  In my software there is a distinction between a variable sized structure and a fixed size structure that has a similar behavior to "blittable" but I have only seen the name used in Microsoft software.</p>


答:
I Am Not A Lawyer, ask a real lawyer, yada, yada, etc.

Basically what's stopping them is the GPL itself + Econ 101: they'd have to admit that it's just your code sold for an infinitely higher amount. Otherwise, you can (legally) force them to provide the source code to you (if you buy their app) and then incorporate it in your version.

This freedom is a foundation of the GPL and it is not considered stealing or otherwise bad/unethical within the GPL community.

Everybody gets to use what you wrote, and what someone wrote over it (modified). The source code is an integral part of a product in GPL and so is the right to redistribute it freely.

The only thing you would lose if someone forks your app is the ability to license to yourself their codebase under a different license (than GPL).

To explain this further, if you write something from A to Z, you have full copyright and you can do with it whatever you want, including licensing it to some people under the GPL, while you can license it to yourself under another license. However, when someone else has created a derivative work, you no longer have copyright over their edits of your software and you need their permission to use their edits under a non-GPL license (Your GPL rights are guaranteed by the GPL itself, since it is "viral" and it automatically spreads to the modified source, a.k.a. the derivative work).

Also, if you write the app yourself, you can release it under another license that forbids other parties to sell derivative works from your app. This way you would be legally protected from such problems.

In reality, things are actually quite different. In many cases, the owner of the store is either not cooperative, not a legal entity at all, operating in the 'shadowy' zone of law, in another country, where your copyright does not allow you to force them to take down the app, etc.

However, most big stores would actually go out of their way to oblige to the party that claims its rights are infringed. This is because copyright infringement laws are getting more and more (too much, IMO) stringent and the potential loss for a service provider that does not comply with a DMCA takedown far outweigh the losses of a legit app taken down by a mis-targeted takedown notice.

Of course, you should refrain from posting fake DMCA takedowns, since I believe this is a crime at least in the US, and even if it's not, you are less likely to be taken seriously, if your account spams takedown notices 24/7.

Title: How are OSS licenses upheld on unbacked projects?

Body:
If an OSS project is not backed (for example, by the Apache Foundation), how is the OSS license upheld?

My specific scenario is this: if I create an GPLd mobile application with a non-commercial transformations clause, what's to actually stop someone from re-releasing it as "Pro" and charging for it?

I assume the owner of the store (Apple/Google/MS) aren't going to uphold licenses on my behalf. Would it come down to me personally having to pay for a lawyer (which seems like a lot of effort to protect a good will gesture)?


问:
Constants in C#
Why does the compiler store constant values in the assembly metadata?
Are they directly embedded to Intermediate Language code from the assembly metadata?</p>

答:
Constants are known at compile time and then they are stored in assembly's metadata. This means that you can only define constants for primitive types.

Yes they are directly loaded from metadata. There would be no memory allocation at runtime.

Title: Constants in C#


答:
These are situations were API documentation, interface control documents, and emulators are paramount.  In a company I worked for previously, this actually happened this would happen frequently within a project during certain integration phases where one segment was ready, but others were behind, has another feature being worked on, or for some other reason they couldn't deploy the latest version of their segment to our test system.  So, yes we did actually have a faithful replica of our production environment that we tested on; however, in practice all segments were never ready on schedule, but interfaces had been agreed upon and locked down prior to development starting, and emulators had been created that could for the most part mimic the other segments behavior.

As another answer stated the emulator is what will enable the testing to take place before deployment.  A good emulator; however, depends on well defined interfaces and documentation.

Title: Developing with confidence without a real development environment

Body:
I've recently been hired for a project that involves working with and around several third-party "enterprise" systems. Due to what I imagine would be the astronomical cost and effort required to build a sufficiently faithful replica of the production environment, the prospect of having a real development environment seems vanishingly slim.

This is of course not ideal. On the bright side, I imagine there must be people out there safely testing and deploying software into unreplicable environments like this, and I can probably follow in their footsteps.

How those who effectively deal with these kinds of situations do it?


问:
Divisional/Sectional comments, good or bad?
I know the general trend against comments explaining how something works, and how it's a good idea to use them only to explain why you're doing what you're doing, but what about using comments as a means of dividing up the code?

Assume you have a script that does a preamble, searches through a bunch of records, prints the records, then closes everything:

```<code>// Preamble
... preamble code, say about 10-15 lines ...

// Find records
... sql query ...
... put records into array ...
... some other stuff ...

// Print records
... printing records, 20-30 lines a record ...

// Close everything
...
</code>```

More of a way to visually divide the code, make it easier to find a certain section. Like if in a month you need to fix the printing code, rather than reading through a couple hundred lines to try and find the right spot, just look at the comments to see where it is.

What actually happens in each section being fairly straightforward and easy to tell what's going on, would this approach to comments be considered good or bad?

Edit:
I'm working mostly with PHP scripts, where you either can't put code into functions, or it's impractical to do so. However, the same sort of thing would apply to large class files, with several methods that do related things, like getters/setters, database updates, etc.

答: Personally it would be redundant. The reason being is if you were to create a function or class to handle the task then it should be straight foreword to go back and make changes in the future.</p>

ContentLicense: CC BY-SA 2.5


问:
How to create view models - Constructor, Factory Method, ...?
I'm trying to lead a charge for re factoring our rather bloated controllers.
We currently have a BaseModel from which all our other models inherit. The BaseModel contains things common to all pages, such as the page title, css files needed, current user.

Each constructor has a private method to construct a particular ViewModel (essentially a factory method)

BaseModel.cs

```<code>Class BaseModel {
    public string title {get; set;}
    public List<String> cssFiles {get;set;}
    // More Properties
}
</code>```

HomeModel.cs

```<code>Class HomeModel : BaseModel {
    public List<News> LatestNews {get;set;}
}
</code>```

ExtendedHomeModel.cs

```<code>Class ExtendedHomeModel : HomeModel {
    public List<RSSItem> Twitter {get;set;}
}
</code>```

HomeController.cs

```<code>public ActionResult Index(int userid) {
    return View(MakeExtendedHomeModel(userid));
}

private ExtendedHomeModel MakeExtendedHomeModel(int userid) {
    var model = new ExtendedHomeModel();

    InitialiseBaseModel(model, userid);
    InitialiseExtendedBaseModel(model);

    model.Twitter = DomainModel.Twitter.GetLatestItems();
}

private HomeModel MakeHomeModel() {
    var model = new HomeModel();
    InitialiseBaseModel(model);
    InitialiseHomeModel(model);
}

private void InitialiseHomeModel(HomeModel model) {
    model.LatestItems = DomainModel.GetLatestItems;
}

private void InitialiseBaseModel(BaseModel model, int userid) {
    model.PageTitle = "Home"
    model.UserId = userid
}
</code>```

So, my question is: what is the best way of initialising these kind of base models? As far as I can tell what the constructor essentially does is the factory method, and at the very least it should be moved out of the constructor.

However, I'm convinced there is a more elegant way of doing this. The main problem that I see is that the code is thoroughly depended on you calling the initialise methods in the correct order.
One idea I've had is to use constructors, passing necessary parameters down the chain as necessary. Are there any pitfalls to this approach I havent seen? (Bearing in mind I've only started asp mvc six months ago). Are there any better ways?

Thanks for reading

答:
The pattern I have settled on for creating my view models is SomeViewModel is created by a static method (or instance method if appropriate) on SomeViewModelFactory. I don't inherit from base models for members that are duplicated. I use interfaces and external setter methods that operate on those interfaces to set the properties. This abstracts away the creation of the view model to a single function call for a single view model and one setter function called internally for each interface the view model implements. As you can tell, I prefer composition over inheritance in this case. To me, it is less complex and more reusable than inheritance.

You might be interested in Automapper if you are doing any mapping between your domain model for your database and your view models. Hope this helps spur on any ideas that may be laying dormant in your mind.

Edit: I forgot to mention that you can define extension methods on those interfaces to take inputs and do the setting on the object its self. This technique is called a "mixin". That way you don't need to create classes for your setter methods, they appear to you as instance methods on the viewmodel object.

Edit 2: To answer your first comment, that is up to you and your preferences. Personally, I like to stay consistent and I would just copy/paste the model into a new class and add the property. Then use the setter for the old class and just set that one property normally. Remember that there should be no logic in your view models; they should only know that they are holding data, not how that data is created.

Automapper is still being actively developed as far as I can tell. It's really more of a utility library rather than a full blown framework. It seems to be pretty mature to me, I've been using it at work with much success. You may have to write the code that goes from ViewModel to DomainModel for stuff like updating data in a database, but at least you won't have to do the DomainModel > ViewModel part. Automapper takes care of that very well.

Edit 3: Your concern about staying DRY is valid; however, I interpret that principle as don't repeat your logic (not data structure). Your view model is a support structure for your data that provides you the benefit of static typing in your view. Each view model is specific to a single view. Using inheritance for property reuse needlessly ties the view model of 2 separate views that just happen to be similar. If you use inheritance, changing the base view model has a ripple effect across all your views with view models that inherit from it. Maybe that is what you want, but you can get the same benefit by defining an interface for all view models that need it. If there is a change, this allows you to decide for each model if it should still implement that interface or if a new interface is needed.


答:
I am in such situations all the time.

You surely does not need to interact with the entire application, but probably a few interfaces of some sort. Make sure you have confirmed and detailed documentation of the interfaces, then setup mocks of these interfaces only to verify that your added/changed code works the way you intended it to work.

You can also do a hybrid. Try to replicate the parts that you can rather easy do, then "connect" to the real systems (if this is possible in your situation). I have done so with some success - in some cases where my logic and the server software was run locally, but I still had a connections to the real ERP system to verify invocies etc. Not ideal, but things rarely are.

Given you have only a production system to work with - note that you cannot count only any development time saved on setting up a replica, but you have to take into account the business risk of using largely untested code with live business data. Your code WILL be less reliable than code tested against a replica. Can the systems be down for some time? Can they be restored in case of data corruption? How much does that cost?

A best practice in enterprises is to put up a replica (or maybe more than one) of the production at the moment the production environment is setup. At that moment, the additional cost won't be that huge.


问:
JQuery / JSON + .Net Service Layer - to WCF or Not to WCF?
I Recently had a discussion with a colleague of mine about the pros / cons of WCF. He mentioned about how much code is generated to support WCF, and also the overhead required. It was mentioned that a simple jQuery /Ajax post to a .aspx page (or a handler for that matter) that returns JSON would work more efficiently and takes much less code to implement. I am also aware of the new WCF Web API and feel that technology may solve the "bloated"-ness required in attaining a proxy etc... by just outputting JSON.

So when developing a relational DB (MSSQL) storage model, with a fairly complex Business Layer (C#) and Data Access Layer (EntityFW)..  what's a good technology for creating a "service layer" which will spit out View Models represented in JSON, with a CQRS(Command Query..) approach in mind.. The app would use the service layer to support it's required UI, as well as provide an available subset of services (outputting JSON data) for service subscribers..

In other words an admin panel to support the admin UI, and service endpoints that return JSON to access the configurations made from the administration UI.

What are some potential technologies to use as the transport / communication layer. I'd like to use a pure RESTful approach, but am not against doing some URL rewriting with IIS.

Obviously some of the available technologies are:
WCF

WCF Web API (should this even be separate?)

Straight request / response (query string to .aspx / handler)

Would using MVC .Net solve this entire problem? maybe their single page app approach?

any suggestions / feedback from developing this type of application?

Thanks,

答:
If you are on frontline .Net (4.5), I see two options really:

Web API (the mvc controller REST thing)

Wcf via SOAP

Both of these could act as a service layer in a .Net system.

You could also use Wcf over JSON (REST), but this is not a simple thing to implement and maintain.

Wcf have a high learning curve, but once you pass it, Wcf really becomes simple for most usages, especially if you are containing your client proxy creation meaningfully.


答:
In a procedural scripting environment, where all code is contained in one file as subroutines, comments describing sections of code would be a must after a certain point, and there's nothing wrong with that.

I'm currently staring at an Applescript that is almost 700 lines long that is about to double in size here pretty soon (other Applescripts I have top over 2000 lines) with dozens of subroutines. Moving code to external files is more trouble than it's worth right now, so section commenting is the better way of managing it all until I find time to improve the situation.

I'm basing my answer on the fact that you specifically used the word "script" in your question, which belies a procedural script as opposed to object-oriented code.

Title: Divisional/Sectional comments, good or bad?

Body:
I know the general trend against comments explaining how something works, and how it's a good idea to use them only to explain why you're doing what you're doing, but what about using comments as a means of dividing up the code?

Assume you have a script that does a preamble, searches through a bunch of records, prints the records, then closes everything:

```<code>// Preamble
... preamble code, say about 10-15 lines ...

// Find records
... sql query ...
... put records into array ...
... some other stuff ...

// Print records
... printing records, 20-30 lines a record ...

// Close everything
...
</code>```

More of a way to visually divide the code, make it easier to find a certain section. Like if in a month you need to fix the printing code, rather than reading through a couple hundred lines to try and find the right spot, just look at the comments to see where it is.

What actually happens in each section being fairly straightforward and easy to tell what's going on, would this approach to comments be considered good or bad?

Edit:
I'm working mostly with PHP scripts, where you either can't put code into functions, or it's impractical to do so. However, the same sort of thing would apply to large class files, with several methods that do related things, like getters/setters, database updates, etc.


答:
When the credit card number is entered, you can check the checksum --LUHN Formula (Mod 10)--, length, and character set.  Since you probably are only going to accept 2 or 3 different types of credit card, it is also common to seperately check the issuer number (the first 6 digits).

That's it. You can't do any more online - you have to send the credit card number to your merchant account supplier for verification.


答:
Hardware can get as flexible as you may dream, e.g., by implementing CPUs with RAM-based FPGAs. Imagine: one process on Intel, another one on ARM...

But do you really need this flexibility? Sometimes, even in software, the simplicity of hardwired or hardcoded configurations is a huge advantage.

Title: How flexible can hardware get?


答: Rarely, you may use the term memory mapped. That sometimes refers to structures that have been mapped to a specific memory address (either because it has been bitblted there, using DMA, or so that it can be bitblted out) but it has also been used to refer to data that has been mapped to a fixed structure so that internal structures can be shared.


答:
The website gpl-violations.org offers support to small GPL-based open source projects when they need to defend their copyrights (although their main tool is raising public awareness).

There is also the Software Freedom Law Center which which offers legal support for developers of all kinds of free software.


问:
R vs Python for data analysis
I have been programming for about a year and I am really interested in data analysis and machine learning. I am taking part in a couple of online courses and am reading a couple of books.

Everything I am doing uses either R or Python and I am looking for suggestions on whether or not I should concentrate on one language (and if so which) or carry on with both; do they complement each other?

-- I should mention that I use C# in school but am familiar with Python through self-study.

答:
I use both Python (for data analysis ofcourse including numpy and scipy) and R next to each other. However, I use R exclusively to perform data analysis, and Python for more generic programming tasks (e.g. workflow control of a computer model).

In terms of basic operations, say operations on arrays and the sort, R and Python + numpy are very comparable. It is in the very large library of statistical functions that R has an advantage. In addition, matplotlib does not seem to be as good as ggplot2, but I have not used matplotlib that much. In addition, I would focus first on one language and become good at the specifics of that. You seem to be primairily interested in data analysis, not software engineering. I would pick R and stick to that. That said, I think choosing for Python + numpy + scipy + scikit is defintely and excellent choice, it is just that I feel that R is just a bit more excellent.

I would also take a look around you what your colleagues and other people in your field are using. If they all use, say, Python, it would make sense to stick to that in order to more easily learn from them and exchange code.

Disclaimer: Note that I am a heavy R user, so my opinion might be biased, although I have tried to keep my answer as objective as possible. In addition, I have not used Python + numpy extensively, altough I know collegaues who do all their data analysis in it.

ps: This link might be interesting: http://seanjtaylor.com/post/39573264781/the-statistics-software-signal

pps: or this quote from this post:

I use R and Python for all my research (with Rcpp or Cython as
  needed), but I would rather avoid writing in C or C++ if I can avoid
  it. R is a wonderful language, in large part because of the incredible
  community of users. It was created by statisticians, which means that
  data analysis lies at the very heart of the language; I consider this
  to be a major feature of the language and a big reason why it won't
  get replaced any time soon. Python is generally a better overall
  language, especially when you consider its blend of functional
  programming with object orientation. Combined with Scipy/Numpy,
  Pandas, and statsmodels, this provides a powerful combination. But
  Python is still lacking a serious community of
  statisticians/mathematicians.

Title: R vs Python for data analysis


问:
Multi-platform Mobile Development?
So my question is this:

Is there any easy way for a single developer to release an app on iOS and Android?

I am a web developer that primarily plays in PHP, Node, Ruby, AS, and JS. I have dabbled a tiny, tiny bit in Objective-C and Java. Basically I am looking for a good way to release a fairly simple app on both Android and iOS and have a uniform UI that is fairly easy to maintain. The app's main purpose is a well designed visual interface (with animation to help convey actions) to a simple backend API.

Currently I was looking at using Flex, but want to find out other options if they exist. Thank you!

答:
When choosing a technology for multi-platform development there are some main issues to consider.

The first issue is the quality of the application. PhoneGap, for example, is probably the most popular option for writing an application that works both for Android and iOS. But, of course, it has it's disadvantages (native languages wouldn't be used otherwise :))).

The second issue is the speed of development. It is much faster to use one single technology instead of two quite different ones. Though Android and iOS have a lot of common (the MVC pattern for example), the technologies are very different _ the languages, the way views are constructed, etc. So it would take some time to learn both.

Here are some useful links where native and multi-platform development are compared:

PhoneGap or Native Language

appcelerator vs phonegap vs native XCode speed-to-market

iOS XCode native vs PhoneGap for speed of development

P.S. If you have sufficient time, I'd suggest you learn both Android and iOS development separately. Both technologies differ form what you previously did. It would be a great experience, and lot's of fun!

Title: Multi-platform Mobile Development?


答:
They're not out and out bad but I would ask if your routine is so long that it has sections that are significant in their own right and need a comment wouldn't you be better breaking it down into smaller routines?

You'd then have a top level routine which was totally readable without comments:

Thing.Initialise

Thing.PopulateFromDatabase

Thing.PrintResults

Thing.ShutDown

Plus it's all reusable now.

I'd also add that generally things like "close everything down" should be obvious from the code and the structure and therefore unnecessary.  If the code is This.Close(), That.CleanUp(), TheOther.Disconnect() then you really don't need a comment explaining.

Where I think these sorts of comments are good is in roughing out your design and structure before you start.  I find it's good to write the thing out in pseudo code in comments and then remove them as I actually code it.  You can then add and amend the design quickly as you are coding without the risk of forgetting what it was you'd decided.


问:
How to auto-format and auto-capitalize SQL in Vim
I'd like to use vim to write SQL queries, but haven't figured out how to get two key features that I use all the time in programs like SQL Yog.

I usually start an instance of Yog in the background, cut-and-paste my SQL into it, hit F12 which auto-formats the whole thing. All the SQL keywords are automatically capitalized as soon as the text is pasted. I then copy it back into whatever other tool I'm using (often SQL Query Browser at work) and go from there.  The benefits of these two features are worth the extra effort.

Does anyone know how I can set up vim to do this? I still may need to cut and paste back into Query Browser, which is acceptable to me, but I'd like to stick with vim for all my editing.

答:
I just put this map in my .vimrc:

```<code>" prettify sql:
vnoremap <Leader>rp :s/\<update\>\\|\<select\>\\|\<from\>\\|\<where>\\|\<left join\>\\|\<inner join\>\\|\<group by\>\\|\<order by\>/\r\U&/ge<cr><esc>
</code>```

I've mapped it rp - but choose what you want. (rp = run prettify)

The way to use it is visually select your query (eg*emphasized text* with

```<code>vip
</code>```

or whatever, then press J to join your query into one line, then run this map.

Body:
I just put this map in my .vimrc:

" prettify sql:
vnoremap <Leader>rp :s/\<update\>\\|\<select\>\\|\<from\>\\|\<where>\\|\<left join\>\\|\<inner join\>\\|\<group by\>\\|\<order by\>/\r\U&/ge<cr><esc>

I've mapped it rp - but choose what you want. (rp = run prettify)

The way to use it is visually select your query (eg*emphasized text* with

vip

or whatever, then press J to join your query into one line, then run this map.


问:
"A good programmer can be as 10X times more productive than a mediocre one"
I had read an interview with a great programmer (it is not in English) and in it he said that "a great programmer can be as 10 times as good as a mediocre one" giving reason for why good programmers are very well paid and why programming companies give many facilities for their employees. The idea was that there is a very large demand for good programmers, because of the above reason and that's why companies pay very much to bring them.

Do you agree with this statement? Do you know any objective facts that could support it?

Edit: The question has nothing to do with experience; if you talk about one great programmer with 1 year experience then s/he should be 10 times more productive than a mediocre programmer with 1 year experience. I agree that from certain experience years onwards, things start to dissipate but that's not the purpose of the question.

答:
In his book The Leprechauns of Software Engineering, Laurent Bossavit describes researching the 10x productivity claim. He discovered that there aren't sound numbers behind it - the claim has gone from speculation to "established fact" by a telephone game of successively more concrete claims in citation. The blog post that comprises the chapter on the 10x claim, and includes the relevant citations and misquotes, is fact and folklore in software engineering.

What he found is something like this: someone in 1968 did a study comparing people solving a particular debugging problem, and found that some of them did it 10x faster than others. From this we could conclude that some people are 10x better at solving that problem, or we could conclude that some people got lucky, or a wide variety of different things. Some people chose to quote this as (these are all paraphrases) "a study (Sackman et al, 1968) found some programmers work 10x faster than others". Then it became "studies have shown that good programmers are 10x better than average" then finally "it is common knowledge that programmer productivity varies by 10x between individuals". Then someone collects all these citations, misquoting one original source to say "many researchers believe…".

Of course, it wouldn't be a telephone game if only the veracity of the assertion changed: the multiplier goes to 11 and beyond too.


问:
Finding Bugs in Tasks
A colleague and I have run a Kanban board at 2 places of work now, introducing a kind of scrum-ban agile/lean process into the team. Helping us move towards more flow orientated work and continuous releases.

I just wanted to ask your advice, that when a task is peer tested or tested by the test team further down the board, what should happen to the tickets where a fault is found? We've tried 2 methods:

Create a new ticket for the problem and chase this through the board until it catches up with the original faulted ticket. Then progress them both together through the board.

Move the original ticket back to 'development to-do' or 'development work in progress'.

Does anyone have any suggestions on best practices in this situation?

答: Move it back.  Agile development environments need to function based on their "definition of done", and until the task is "done", it doesn't flow off the right edge of the board.  In a good agile environment, "done" includes tested-for-unexpected-behavior and verified-against-requirements.  Even better than the motherhood-and-apple-pie aspect of not polluting your board, it also motivates your developers to finish the task: "Darn it, the WidgetFrobulator is back in TO-DO again - I need to get it off the board!"

Title: Finding Bugs in Tasks


答:
The answer to your question is simple. Do the version that fits your process and system best. Agile, and especially Lean is all about adapting the ideas to your team and to your process.

As for the 2 ways you mentioned, we did it both ways and we sometimes still do it both ways. For example if I have a Story in "Testing" on the board and one of my colleagues finds something wrong with it he will tell me immediately. In most of the cases these problems are trivial or relatively easy to fix and they will be fixed. Sometimes even the tester can fix the problem. Also, we have to consider that the story is in the last stage before being "Done" and it is usually best to make it so. Fix the bug so that the story can be finished and considered Done. One Done story is much better than 2 unfinished ones.

On the other hand, sometimes, but very rarely, a fundamental problem is discovered in the last stages of that story. When this happens more work and time may be required and you may be already half-done with the second story you started meanwhile. In this case you can again choose to finish the story that can be done faster and add another task to "catch up" with the bogus story or bring it back on the board, as you wish.

Title: Finding Bugs in Tasks

Body:
A colleague and I have run a Kanban board at 2 places of work now, introducing a kind of scrum-ban agile/lean process into the team. Helping us move towards more flow orientated work and continuous releases.

I just wanted to ask your advice, that when a task is peer tested or tested by the test team further down the board, what should happen to the tickets where a fault is found? We've tried 2 methods:

Create a new ticket for the problem and chase this through the board until it catches up with the original faulted ticket. Then progress them both together through the board.

Move the original ticket back to 'development to-do' or 'development work in progress'.

Does anyone have any suggestions on best practices in this situation?


问:
What is Developer Anarchy?
I've been reading about Developer (or Programmer) Anarchy, which seems to be billed as a post-Agile development methodology. I found a few resources on it (1, 2) but it doesn't seem to be a lot out there.

I was wondering if anyone had any good resources where I could find out more about it _ how to implement it, pros and cons, comparison with other methodologies etc.

答:
I can point you to Alistair Cockburn's thoughts on this aspect of 'true' Agile projects:

One member in the Crystal family of methodologies is Crystal Clear.
  Crystal Clear can be described to a Level 3 listener in the following
  words:

“Put 4-6 people in a room with workstations and whiteboards and access to the users. Have them deliver running, tested software to the
  users every one or two months, and otherwise leave them alone.”

I did, in fact, describe Crystal Clear in those words to a savvy
  project sponsor. He followed those instructions and reported five
  months later, “We did what you said, and it worked!”

I interviewed the team leader some months later and his report was
  about as short as my instructions:

“Following your suggestion, the four of us took over this conference
  room, which has network connections. We kept it for all four months,
  drawing on the whiteboards over there, delivering software as we went.
  It worked great.”

that's what agile was about, and it seems this is the approach taken by the Anarchy methodology - the point is that, if you have experienced guys, then you can tell them to "sod off and make it work" and they will do just that. (this doesn't work with less experienced people, you wouldn't let a team of juniors do it without at least some supervision).

All the guff about agile that's built up over the years, like daily standups and scrum boards, product backlog grooming sessions, pre-meeting meetings about the product backlog scrum board grooming session planning meetings.. are all heavyweight project stuff that should be seen as overheads to successful product delivery.

Too much today though, these things are seen as mandatory and the 'agile' methodology descends into a system that has more process than the old methods!

Title: What is Developer Anarchy?


答:
Personally, I'm against this type of commenting but only because most modern code editors allow you to collapse methods making it easier to read.  Adding comments therefore tends to at clutter since it no longer contributes to clarifying anything but simply declaring grouping.

C# has a grouping using #region and #endregion which is useful.
Eclipse makes decent use of an outline.

However, there's no wrong way to comment code and generally speaking it's not 'worse' to have more comments (not going to pretend you can code faster without it).


答:
Here's a quick list of the options I'm aware of:

Flex - Develop apps in Flash, deploy to various mobile platforms. Paid.

Phonegap - Deploy HTML5/javascript apps to various mobile platforms. Freeware.

appcelerator/Titanium - Deploy HTML5/javascript apps to various mobile platforms. Paid.

RhoMobile Suite - Similar to Titanium. Paid.

MonoTouch - Similar to Titanium, but for C#/.NET. Paid.

Codename One - Develop the app in Java, which is then converted to native code/UI components. Free, with a paid 'pro' option.

J2ObjC - Not a complete solution (there's no UI!) but can be used to port business logic written in Java to ObjectiveC. Free.

Title: Multi-platform Mobile Development?

Body:
So my question is this:

Is there any easy way for a single developer to release an app on iOS and Android?

I am a web developer that primarily plays in PHP, Node, Ruby, AS, and JS. I have dabbled a tiny, tiny bit in Objective-C and Java. Basically I am looking for a good way to release a fairly simple app on both Android and iOS and have a uniform UI that is fairly easy to maintain. The app's main purpose is a well designed visual interface (with animation to help convey actions) to a simple backend API.

Currently I was looking at using Flex, but want to find out other options if they exist. Thank you!


问:
Unit Testing and Asserting
Assume we have a method that validates an object before saving it to a DB. It returns back KVP something like:

```<code>public KeyValuePair<bool, List<FooErrorReason>> ValidateABar(Bar b)
{
    var reasons = new List<FooErrorReason>();
    if (string.IsNullOrEmpty(bar.Name))
    {
        reasons.Add(new FooErrorReason { PropName = "Name", Message = "The name was missing" };
    }
    if (string.IsNullOrEmpty(bar.OtherName))
    {
        reasons.Add(new FooErrorReason { PropName = "OtherName", Message = "The other name was missing" };
    }
    return new KeyValuePair<bool, List<FooErrorReason>(reasons.Count == 0, reasons);
}
</code>```

So now I want to test that, for a missing bar.Name, the error is returned. My question is on the make up of the test, concerning what to Assert.

```<code>public void ValidateABar_Fails_For_Missing_Name()
{
    //arrange
    var b = new Bar { OtherName = "Other" };

    //act
    var result = ValidateABar(b);

    //assert
    Assert.IsFalse(result.Key);
    Assert.AreEqual(1, result.Value.Count);
    Assert.IsTrue(result.Value.Any(x => x.PropName.Equals("Name")));
}
</code>```

I have 3 Assert calls and it has a whiff of code smell about it, but I can't quite convince myself either way.

I'm asking myself 'What do you want to test?' and I do kind of feel that I should test that this failed, but failed specifically for the property of the test.

Is it enough to just use

```<code>Assert.IsTrue(result.Value.Any(x => x.PropName.Equals("Name")));
</code>```

Or should I also check that there are no other errors I have picked up along the way?

Say for example someone added another validation rule without my knowing about it, I would think I would want my tests to tell me about this the next time I ran them. As an example, let's say someone changed the method as below:

```<code>public KeyValuePair<bool, List<FooErrorReason>> ValidateABar(Bar b)
{
    var reasons = new List<FooErrorReason>();
    if (string.IsNullOrEmpty(bar.Name))
    {
        reasons.Add(new FooErrorReason { PropName = "Name", Message = "The name was missing" };
    }
    if (string.IsNullOrEmpty(bar.OtherName))
    {
        reasons.Add(new FooErrorReason { PropName = "OtherName", Message = "The other name was missing" };
    }

    //added this!
    if (string.IsNullOrEmpty(bar.ThirdName))
    {
        reasons.Add(new FooErrorReason { PropName = "ThirdName", Message = "The third name was missing" };
    }
    return new KeyValuePair<bool, List<FooErrorReason>(reasons.Count == 0, reasons);
}
</code>```

The test would now fail and I would see that this rule had been added, and amend my test accordingly (and presumably write another test to cover the new rule).

Am I taking the 'one Assert per test rule' too literally?

答:
honestly the "one assert per test" rule is overrated, a better rule would be "on act per test" and have a smell when you have more than a few asserts which means that the act does too much

you have a method with a compound output so it makes sense to test all parts of the output. Doing this in a single test means that when a new field is required you only need to change 1 test instead of 3

I believe that you can add a string to the assert to be displayed when it fails, or you should at least see the line where it fails in the stacktrace. this way you can narrow it down what went wrong

besides the first relfex you should have should be to add a breakpoint before the first assert and run the test again and see what output you got

Title: Unit Testing and Asserting


问:
How to obtain GPS Coordinates for local businesses?
Is anybody aware of a database that consists of businesses, addresses and GPS location information, preferably searchable by city at a minimum?  I have an application in mind that I'd like to develop and would like to know if someone is doing this for free or cheap in possibly a web service or similar open format.  </p>

答:
A good source of information that has not yet been mentioned is SatNav Point of Interest (POI) files.

You can find an array of different categories, from public entities to local pubs.

I did some personal work on these files last summer for a project, they are (in the majority) just CSV files with a different file extension that you import into your SatNav. However, it is a task to find reputable sources of these and you may need to confirm the licenses that come with them.

Should be perfectly fine for any personal projects though.


答:
You are taking one assertion per test too literally, but not too seriously. It's a good rule to follow.

However, there are cases, like this one, where you cannot fully assert your one assertion with literally one Assert method. What you are trying to assert is that the response is showing an error message. Assert.AreEqual doesn't really allow you to do that, unless you write an equality comparer for your response object.

Another option is to use the Assert.That syntax and create your own IResolveConstraint object as a comparer. With a little effort, you could have something as simple as

```<code>Assert.That(response, Fails.With.Message("Blah"));
</code>```

But really, is it worth the effort? What you have is just fine and it is asserting your response is correct. That is one assertion.

In other cases, you won't actually have any calls to Assert methods, because the thing you're asserting is that a mocked method was called correctly. That's still an assertion, even if it isn't an Assert, per se.

For example, say you have a Save method, which sends data to a repository (not caring if it's SQL, file system, mock object, etc.) and then returns nothing.

```<code>public void Save()
{
     // How do I test this method with an Assert call???
     FooRepository.Save(this.Name, this.OtherName.Trim());
}
</code>```

What you don't want to do is set an expectation on a mock method and then assert the response from the method under test. That would be two assertions in one test (although only one Assert call) and, if one thing goes wrong, it will be more difficult to figure out exactly what.

In a case like that, write two tests:

one to test that the method is called correctly

one to assert the contents of any response

In the latter, simply stub the method, so that it passes regardless of whether the method is called, as long as the response is correct.

TL;DR: Do not confuse asserting one thing with having one call to an Assert method. They're not the same thing.

Title: Unit Testing and Asserting

Body:
Assume we have a method that validates an object before saving it to a DB. It returns back KVP something like:

```<code>public KeyValuePair<bool, List<FooErrorReason>> ValidateABar(Bar b)
{
    var reasons = new List<FooErrorReason>();
    if (string.IsNullOrEmpty(bar.Name))
    {
        reasons.Add(new FooErrorReason { PropName = "Name", Message = "The name was missing" };
    }
    if (string.IsNullOrEmpty(bar.OtherName))
    {
        reasons.Add(new FooErrorReason { PropName = "OtherName", Message = "The other name was missing" };
    }
    return new KeyValuePair<bool, List<FooErrorReason>(reasons.Count == 0, reasons);
}
</code>```

So now I want to test that, for a missing bar.Name, the error is returned. My question is on the make up of the test, concerning what to Assert.

```<code>public void ValidateABar_Fails_For_Missing_Name()
{
    //arrange
    var b = new Bar { OtherName = "Other" };

    //act
    var result = ValidateABar(b);

    //assert
    Assert.IsFalse(result.Key);
    Assert.AreEqual(1, result.Value.Count);
    Assert.IsTrue(result.Value.Any(x => x.PropName.Equals("Name")));
}
</code>```

I have 3 Assert calls and it has a whiff of code smell about it, but I can't quite convince myself either way.

I'm asking myself 'What do you want to test?' and I do kind of feel that I should test that this failed, but failed specifically for the property of the test.

Is it enough to just use

```<code>Assert.IsTrue(result.Value.Any(x => x.PropName.Equals("Name")));
</code>```

Or should I also check that there are no other errors I have picked up along the way?

Say for example someone added another validation rule without my knowing about it, I would think I would want my tests to tell me about this the next time I ran them. As an example, let's say someone changed the method as below:

```<code>public KeyValuePair<bool, List<FooErrorReason>> ValidateABar(Bar b)
{
    var reasons = new List<FooErrorReason>();
    if (string.IsNullOrEmpty(bar.Name))
    {
        reasons.Add(new FooErrorReason { PropName = "Name", Message = "The name was missing" };
    }
    if (string.IsNullOrEmpty(bar.OtherName))
    {
        reasons.Add(new FooErrorReason { PropName = "OtherName", Message = "The other name was missing" };
    }

    //added this!
    if (string.IsNullOrEmpty(bar.ThirdName))
    {
        reasons.Add(new FooErrorReason { PropName = "ThirdName", Message = "The third name was missing" };
    }
    return new KeyValuePair<bool, List<FooErrorReason>(reasons.Count == 0, reasons);
}
</code>```

The test would now fail and I would see that this rule had been added, and amend my test accordingly (and presumably write another test to cover the new rule).

Am I taking the 'one Assert per test rule' too literally?

Body:
You are taking one assertion per test too literally, but not too seriously. It's a good rule to follow.

However, there are cases, like this one, where you cannot fully assert your one assertion with literally one Assert method. What you are trying to assert is that the response is showing an error message. Assert.AreEqual doesn't really allow you to do that, unless you write an equality comparer for your response object.

Another option is to use the Assert.That syntax and create your own IResolveConstraint object as a comparer. With a little effort, you could have something as simple as

Assert.That(response, Fails.With.Message("Blah"));

But really, is it worth the effort? What you have is just fine and it is asserting your response is correct. That is one assertion.

In other cases, you won't actually have any calls to Assert methods, because the thing you're asserting is that a mocked method was called correctly. That's still an assertion, even if it isn't an Assert, per se.

For example, say you have a Save method, which sends data to a repository (not caring if it's SQL, file system, mock object, etc.) and then returns nothing.

public void Save()
{
     // How do I test this method with an Assert call???
     FooRepository.Save(this.Name, this.OtherName.Trim());
}

What you don't want to do is set an expectation on a mock method and then assert the response from the method under test. That would be two assertions in one test (although only one Assert call) and, if one thing goes wrong, it will be more difficult to figure out exactly what.

In a case like that, write two tests:

one to test that the method is called correctly

one to assert the contents of any response

In the latter, simply stub the method, so that it passes regardless of whether the method is called, as long as the response is correct.

TL;DR: Do not confuse asserting one thing with having one call to an Assert method. They're not the same thing.


问:
Scale an image with unscalable parts
Brief description of problem: imagine having some vector picture(s) and text annotations on the sides outside of the picture(s).

Now the task is to scale the whole composition while preserving the aspect ratio in order to fit some view-port.  The tricky part is that the text is not scalable only the picture(s).  The distance between text and the image is still relative to the whole image, but the text size is always a constant.

Example: let's assume that our total composition is two times larger than a view-port. Then we can just scale it by 1/2. But because the text parts are a fixed font size, they will become larger than we expect and won't fit in the view-port.

One option I can think of is an iterative process where we repeatedly scale our composition until the delta between it and the view-port satisfies some precision. But this algorithm is quite costly as it involves working with the graphics and the image may be composed of a lot of components which will lead to a lot of matrix computations. What's more, this solution seems to be hard to debug, extend, etc.

Are there any other approaches to solving this scaling problem?

答:
 Please note, part of this solution was introduced by Oleksandr Voietsa

Ok, so I have some sort of answer that may be not ideal, but it works quite well.

Let's look at the next picture. A blue shape is scalable while the red one is not. Also note that vertex x scales with the rest of the image, only dimensions of the red shape are unscalable. For now on we'll look only at the X axis.

Now in this situation are two possible outcomes.

1: Scalable component scales over the end of unscalable one and so we have a standard situation where we scale a whole scalable composition:

2: If the bounds are small in size of even x vertex is located after the edge of the scalable component then problem with the scalable spears. But on the other hand we already know the size of the unscalable part, and we know that it will be positioned next to the bounds. This way we can just reduce size between the bounds by unscalable component's width and then scale the part of the whole composition without unscalable part.

This way we can compute both ratios for scaling and choose the one that results in a smaller final image.

Also in my implementation I have a current min/max X/Y values for each component. This values represent a current bounding box of the scalable part. Also components with unscalable parts have upwards, downwards, rightwards and leftwards unscalable offset. This way a true maximum x coordinate of this component will be maxX * scale + rightwardsOffset.

The algorithm is next one:

(for one axis)

Form two collections: one for positive offsets and one for negative.

Elements of collections should be pairs consisting of the value of unscalable offset and a coordinate of scalable boundary _(in the above examples it will be an x as everything after it is considered to be unscalable)_.

Current bounds of the scalable part of the whole composition should be also added to this collections with 0 offsets (with is done to find a correct solution if no unscalable components are present or they are smaller and in the middle of the scalable once etc...)

For each pair of the elements from the negative and positive collections find a scale ratio that satisfies the given offsets. I calculate ratios as sizeToScale/sizeToFit.

Find the minimal ratio (or if you're calculating ratio the other way than me you should aim to get the smallest resulting image)

That's it. Remember, for other axis you calculate ratio the same way and take min.

Please note, part of this solution was introduced by Oleksandr Voietsa

Title: Scale an image with unscalable parts


问:
Constructing a Finite State Automaton
I have an exam question that I am unsure of the answer. The question is:

In organisation X valid user names have the following structure. The
  user name can be either the employee’s name followed by a colon and
  then the department name or a string of one or more alphanumeric
  letters consisting of lower case, upper case letters and digits from 0
  to 9. All user names end with a period ("."). The employee’s name is
  expressed as ﬁrst name followed by an underscore and then the surname.
  The ﬁrst name and the surname must begin with an uppercase letter and
  is followed by an arbitrary number of lower case letters. All
  department names are an arbitrary number of lower case letters.
  Express the language for valid user names as a regular expression.

The answer I have is,

[A-Z][a-z]+"_"[A-Z][a-z]+":"[a-z]+"." | [A-Za-z0-9]+"."

The next question is:

Construct a deterministic ﬁnite state automaton for recognising the
  user names as described in Question 1.

For which I have this:

I am under the impression this is wrong because [A-Z] is a subgroup of [A-Za-z0-9] and a DFA cannot have the same symbol going from one state. Does anybody have an idea how to solve this / is it correct?

Thanks !

答: from 1 to 9 remove the [A-Z] transition and add transitions form 2 and 3  to 9 with [A-Z0-9]</p>

Title: Constructing a Finite State Automaton


问:
How does Django turn field name strings to field name variables?
I'm very new to python and (coming from Java) am trying to think in a "pythonic" way. I'm having trouble understanding how Django turns a function (or variable) name given in string to the actual function.

Example from Django tutorial: If we give:

```<code>list_display = ('question', 'pub_date', 'was_published_recently')
</code>```

Django reads the function and some related properties from the code:

```<code>def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'
</code>```

So, my question: How does the string get turned into the actual function name?

答:
Python has numerous ways to turn strings into objects. The most important are:

Attribute access with getattr(), allowing you to translate foo.bar into getattr(foo, 'bar').

Dictionary access, mapping[key]. Almost anything in Python can be reduced to dictionaries; by default class instances store information in a mapping called __dict__ for example, so instance.__dict__[key] works in many cases. Module namespaces use a mapping like that too.

The built-in functions vars(), locals() and globals() all return a namespace mapping.

If you are interested in Python introspection, you may want to study the Python datamodel, and take a look at the inspect library as well.


答:
As pointed out in the comments arbitrary can include 0, so you should have * instead of + in your regular expression at the corresponding places.

From your original regular expression you correctly derived a nondeterministic finite state automaton (NFA). To adapt it to the * mentioned above, you only need to eliminate the states 2 and 5 in order to have a corresponding NFA again.

The interesting part of the exam question though is to derive a deterministic finite state machine from your NFA. This is mechanically possible via an algorithm referred to as the powerset construction. This link should give you enough information (and you should have learned it in your lessons anways, given the exam question!) to learn how to get from NFA to DFA.

The resulting DFA is usually too large due to the powerset of states, which is the reason, why one normally performs a DFA minimization afterwards. Though to be honest, I would skip that given that the question only asks for a DFA, not a minimal DFA.

Title: Constructing a Finite State Automaton

Body:
I have an exam question that I am unsure of the answer. The question is:

In organisation X valid user names have the following structure. The
  user name can be either the employee’s name followed by a colon and
  then the department name or a string of one or more alphanumeric
  letters consisting of lower case, upper case letters and digits from 0
  to 9. All user names end with a period ("."). The employee’s name is
  expressed as ﬁrst name followed by an underscore and then the surname.
  The ﬁrst name and the surname must begin with an uppercase letter and
  is followed by an arbitrary number of lower case letters. All
  department names are an arbitrary number of lower case letters.
  Express the language for valid user names as a regular expression.

The answer I have is,

[A-Z][a-z]+"_"[A-Z][a-z]+":"[a-z]+"." | [A-Za-z0-9]+"."

The next question is:

Construct a deterministic ﬁnite state automaton for recognising the
  user names as described in Question 1.

For which I have this:

I am under the impression this is wrong because [A-Z] is a subgroup of [A-Za-z0-9] and a DFA cannot have the same symbol going from one state. Does anybody have an idea how to solve this / is it correct?

Thanks !


问:
(Dis)advantages of datetime vs. long in globally used applications
I am currently designing a web/mobile application the bulk of whose users will be distributed across the different U.S. time zones with a potential of scaling up to other countries and time zones as well

I have worked with several other globally used apps and noticed they all used datetime to record timestamps with the default time zone being that in which the application is typically hosted.  In displaying the times, they would typically do not care about the user preference (locale) and simply display the timestamp with the TZ and leave it up to the user to convert if (s)he wishes.

I am entertaining the idea of shifting away from that paradigm and recording timestamps as one global time (GMT) in long milis regardless of the user location and collecting the user locale by their IP or letting them change their TZ as a preference in their profile, which would later be used for display formatting of all their GMT long milis.  This seems like a simpler solution than confusing the app design with TZs.

I am curious to hear feedback of pros and cons to this approach.  I am also curious to hear some explanations why the, IMO overcomplicated time zoned datetime data type has ever been used across databases and not a uniform single time zone with conversions just for display.

答:
This depends greatly on the purpose of your datetime information.

For a calendaring app, the ability to track time zones is essential. For a logging daemon, having all records in the same TZ is quite convenient. What kind is your app?

OTOH I don't see what will be your gain from using a long int to store the timestamp. This looks like a premature optimization to me; you can store datetimes as GMT as well, and have your servers' clocks always set to GMT (as many of us do). If this is the point of your question, then yes, having everything internally stored in the same TZ may be a good idea.


答:
Is that GMT going to always be the same without any adjustments for Daylight Savings Time scenarios?  I could imagine if suddenly a bunch of date data has been shifted because of DST that could be an issue and so you may have to contemplate what business rules would you have for this.

Jon Skeet's "Epic Fail" has a section about Time Zones that I find interesting and quite funny at the same time.

Title: (Dis)advantages of datetime vs. long in globally used applications

Body:
I am currently designing a web/mobile application the bulk of whose users will be distributed across the different U.S. time zones with a potential of scaling up to other countries and time zones as well

I have worked with several other globally used apps and noticed they all used datetime to record timestamps with the default time zone being that in which the application is typically hosted.  In displaying the times, they would typically do not care about the user preference (locale) and simply display the timestamp with the TZ and leave it up to the user to convert if (s)he wishes.

I am entertaining the idea of shifting away from that paradigm and recording timestamps as one global time (GMT) in long milis regardless of the user location and collecting the user locale by their IP or letting them change their TZ as a preference in their profile, which would later be used for display formatting of all their GMT long milis.  This seems like a simpler solution than confusing the app design with TZs.

I am curious to hear feedback of pros and cons to this approach.  I am also curious to hear some explanations why the, IMO overcomplicated time zoned datetime data type has ever been used across databases and not a uniform single time zone with conversions just for display.


答:
I'm no expert but I think this assumption is correct.

I am under the impression this is wrong because [A-Z] is a subgroup of [A-Za-z0-9] and a DFA cannot have the same symbol going from one state.

It sounds like you have a pretty good grasp but I'll spell it out just to be thorough.

Following are the steps to convert the current NFA to a DFA. The first step is assessing where the non-determinism exist so the problem can be broken down further.

The initial split needs to happen based one of these two conditions:

The user name can be either the employee’s name followed by a colon and then the department name

Ie. an 'employee_name' name is encountered

a string of one or more alphanumeric letters consisting of lower case, upper case letters and digits from 0 to 9

Ie. a 'string' is encountered

It looks like you have identified the issue already. In that, there's no way to determine a split on state 1 because both paths share the common subset [A-Z][a-z]*. To create a valid NFA you first need to identify the constraints.

To start I'd look at separating out cases where the initial input is not an 'employee_name'.

Such cases include:

the first char is a lower-case alpha char

a numeric char is encountered

In addition, both an 'employee_name' and a 'string' can be made up of the identical subset [A-Z][a-z]*. To cover that condition there should be a two way split where either [] or [.] is encountered. Where [] is encountered you would transition what is currently state 4. Where [.] is encountered you'd transition to what is currently state 10.

Now that all of the constraints are identified, it's just a matter of re-mapping your state diagram to represent the flow. There should be one more state containing a * repeater for processing the rest of the 'string' value and 3 more transitions. It's just a matter of placing them correctly.

Following what @Frank said, you should also eliminate two of the states using * instead of + for repetition because the 1-or-more constraint is technically incorrect. For instance a valid user name could contain only one character of [A-Z] and no additional chars before the [_]. The same pattern applies to the 'surname'

Title: Constructing a Finite State Automaton


答:
I don't think you're going to gain much by storing all of your datetimes as longs.  Every language I can think of has ways to convert dates to other formats (string, long) use the preferred format for your database.

Store the dates in UTC.  I think this makes sense for nearly every application, since many languages and APIs have a way to get Now() in UTC.  Also, for most devices and browsers it's trivial to figure out the timezone offset.  Then it's simple addition for displaying a user's local time.  You will save yourself much headache down the road.