问:
OpenGL Image Load-Store Atomics Applications
I originally asked this on plain old stack but it was closed for being too open-ended. (Which was a good call as this is a better place for such questions.)

Original Link: https://stackoverflow.com/questions/15132135/opengl-image-load-store-atomics-applications

So, I've been spending the last couple months or so getting familiarized with the latest OpenGL 4 features when I find myself with free time. (Things like transform feedback, tessellation, compute shaders, etc..) I've finally taken time to mess around with using Image Load-Store textures, and while the idea of being able to atomically read/write to any texture from any GPU core regardless of shader stage seems incredibly powerful, I could not think of interesting applications utilizing the unique facilities these textures provide. Even after consulting "the google" for interesting applications, I was left empty handed. So, are there any WOW-THATS-COOL or even DAMN-THATS-HANDY applications you can think of?

Application 1 (Suggested By Nicol Bolas): "Search for order-independent transparency. That requires atomic image operations."

答:
As far as I can tell, you got it somewhat wrong. You're looking in the wrong direction, cool and handy stuff here is in code, not in applications.

This is explained in OpenGL wiki, although one needs to apply certain effort to to get what's so cool about it:

Consider a shader that reads from a location, adds 1 to it, and then writes to it. It is theoretically possible for two such shaders to read from and and write to the same location in the same image at the same time. Because of the way memory accesses are handled, it is entirely possible that this sequence of events works like this:

Shader A reads the image value, say 0.

Shader B reads the image value, also 0.

Shader B adds 1 to its local value of 0, becoming 1.

Shader B writes its local value to the image. The image now has 1.

Shader A adds 1 to its local value of 0, becoming 1.

Shader A writes its local value to the image. The image now has 1.

Do you see what's wrong with above? Look, image value is intended to go 0 then 1 then 2 but it goes only 1: this means you'd get light-gray where you intended to be dark-gray or maybe you'll get green if you're really unlucky - this is indeterministic behavior.

Well, you won't see bad stuff like that in real applications even before atomics were introduced, but what did that cost to programmer? Just think about it, to avoid side effects, programmer would have to manually synchronize shaders, so that their code was looking like that:

enter synchronized section

Shader A reads the image value, say 0.

Shader A adds 1 to its local value of 0, becoming 1.

Shader A writes its local value to the image. The image now has 1.

quit synchronized section

enter synchronized section

Shader B reads the image value, it is guaranteed to be 1 now, how nice

(if we forget that coder had to write 3 extra statements to get it right).

Shader B adds 1 to its local value of 1, becoming 2.

Shader B writes its local value to the image. The image now has 2.

quit synchronized section

Now, as wiki state,

Atomic operations prevent this possibility entirely. Each shader's independent atomic operation will fully complete before the next one starts.

What would that mean to coder? Let's see, we still want our two shaders to add that 1 twice so that 0 becomes 2. Okie dokie, here we go...

Shader A reads-modifies-writes the image value in one step, 0 is guaranteed to become 1.

Shader B reads-modifies-writes the image value in one step, 1 is guaranteed to become 2.

...and that's all. That's it. That's it!!! We've got to two statements (that are quite easy to read btw) from 10 that mixed rendering and synchronization in not particularly apparent way.

Have you ever been through code changes like this? I've been and, well, this is one of the coolest, handiest, sexiest experiences one can ever imagine.

Oh applications... you asked about these, right? Well, applications will look and behave the same. There will only be 5 times less code there, if that matters to you.


问:
Is JSF really ready to deliver high performance web applications?
I have heard a lot of good about JSF but as far as I know people also had lots of serious complains with this technology in the past, not aware of how much the situation has improved. We are considering JSF as a probable technology for a social network project. But we are not aware of the performance scores of JSF neither we could really come across any existing high performance website that had been using JSF. People complain about its performance scalability issues.

We are still not very sure if we are doing the right thing by choosing jsf, and thus would like to hear from you all about this and take your inputs into consideration.

Is it possible to configure JSF to satisfy the high performance needs of social networking service ? Also till what extent is it possible to survive with the current problems in JSF. What exactly are its problems ?

I am not  worried about the development complexities with JSF what others usually complain about because as per my personal experience I believe that's not at all true, but I am more concerned about what performance and scalability issues. And please don't just abuse it on its old issues linked to previous versions. I just care about the present state whatever had been its past.

答:
Disclaimer: I like JSF. Anyway, even with the latest RI (Mojarra 2.2.x) or MyFaces, even with the long awaited stateless implementation
performance is very poor. This is because of the JSF lifecycle and the fact that each View is  (expensively) built for every request.

To get a clue, this is a simple benchmark against a plain java servlet
vs a JSF page, both just printing "hello world"

Servlet

```<code>glassfish-3.1.2.2$ ab -n 10000 -c 100 http://localhost:8080/mavenproject-web/NewServlet

Server Software:        GlassFish
Server Hostname:        localhost
Server Port:            8080

Document Path:          /mavenproject-web/NewServlet
Document Length:        128 bytes

Concurrency Level:      100
Time taken for tests:   0.970 seconds
Complete requests:      10000
Failed requests:        0
Write errors:           0
Total transferred:      4300000 bytes
HTML transferred:       1280000 bytes
Requests per second:    10307.02 [#/sec] (mean)
Time per request:       9.702 [ms] (mean)
Time per request:       0.097 [ms] (mean, across all concurrent requests)
Transfer rate:          4328.14 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   1.0      1       5
Processing:     1    9   4.6      8      51
Waiting:        1    8   4.4      7      40
Total:          4   10   4.1      8      51

Percentage of the requests served within a certain time (ms)
  50%      8
  66%     10
  75%     11
  80%     11
  90%     12
  95%     14
  98%     29
  99%     33
 100%     51 (longest request)
</code>```

JSF

```<code>glassfish-3.1.2.2$ ab -n 10000 -c 100 http://localhost:8080/mavenproject-web/xhtml/test/jsf.xhtml

Server Software:        GlassFish
Server Hostname:        localhost
Server Port:            8080

Document Path:          /mavenproject-web/xhtml/test/jsfxhtml
Document Length:        100 bytes

Concurrency Level:      100
Time taken for tests:   4.676 seconds
Complete requests:      10000
Failed requests:        0
Write errors:           0
Total transferred:      4250000 bytes
HTML transferred:       1000000 bytes
Requests per second:    2138.60 [#/sec] (mean)
Time per request:       46.759 [ms] (mean)
Time per request:       0.468 [ms] (mean, across all concurrent requests)
Transfer rate:          887.60 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.5      0       6
Processing:     5   46   6.0     46      73
Waiting:        2   45   5.5     45      72
Total:          8   47   5.8     46      73

Percentage of the requests served within a certain time (ms)
  50%     46
  66%     48
  75%     50
  80%     51
  90%     54
  95%     56
  98%     60
  99%     62
 100%     73 (longest request)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Disclaimer: I like JSF. Anyway, even with the latest RI (Mojarra 2.2.x) or MyFaces, even with the long awaited stateless implementation
performance is very poor. This is because of the JSF lifecycle and the fact that each View is  (expensively) built for every request.

To get a clue, this is a simple benchmark against a plain java servlet
vs a JSF page, both just printing "hello world"

Servlet

glassfish-3.1.2.2$ ab -n 10000 -c 100 http://localhost:8080/mavenproject-web/NewServlet

Server Software:        GlassFish
Server Hostname:        localhost
Server Port:            8080

Document Path:          /mavenproject-web/NewServlet
Document Length:        128 bytes

Concurrency Level:      100
Time taken for tests:   0.970 seconds
Complete requests:      10000
Failed requests:        0
Write errors:           0
Total transferred:      4300000 bytes
HTML transferred:       1280000 bytes
Requests per second:    10307.02 [#/sec] (mean)
Time per request:       9.702 [ms] (mean)
Time per request:       0.097 [ms] (mean, across all concurrent requests)
Transfer rate:          4328.14 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   1.0      1       5
Processing:     1    9   4.6      8      51
Waiting:        1    8   4.4      7      40
Total:          4   10   4.1      8      51

Percentage of the requests served within a certain time (ms)
  50%      8
  66%     10
  75%     11
  80%     11
  90%     12
  95%     14
  98%     29
  99%     33
 100%     51 (longest request)

JSF

glassfish-3.1.2.2$ ab -n 10000 -c 100 http://localhost:8080/mavenproject-web/xhtml/test/jsf.xhtml

Server Software:        GlassFish
Server Hostname:        localhost
Server Port:            8080

Document Path:          /mavenproject-web/xhtml/test/jsfxhtml
Document Length:        100 bytes

Concurrency Level:      100
Time taken for tests:   4.676 seconds
Complete requests:      10000
Failed requests:        0
Write errors:           0
Total transferred:      4250000 bytes
HTML transferred:       1000000 bytes
Requests per second:    2138.60 [#/sec] (mean)
Time per request:       46.759 [ms] (mean)
Time per request:       0.468 [ms] (mean, across all concurrent requests)
Transfer rate:          887.60 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.5      0       6
Processing:     5   46   6.0     46      73
Waiting:        2   45   5.5     45      72
Total:          8   47   5.8     46      73

Percentage of the requests served within a certain time (ms)
  50%     46
  66%     48
  75%     50
  80%     51
  90%     54
  95%     56
  98%     60
  99%     62
 100%     73 (longest request)


问:
How to negotiate with software vendors who do not follow HL7 standards
Take, for instance the "", I'd hope that anyone who has spent any time in dealing with HL7 messages knows that the "" signifies that something should be deleted.  "" is not an empty string, it's not a filler etc... But occasionally, one may meet a vendor who persists in sending "" instead of just sending nothing at all.

Since, I work for a small business and have an extremely flexible HL7 interface, I can ignore ""'s in received messages.  But these things are adding up.

Some vendors like to send custom formatted fields with psuedo-components that they leave others to interpret themselves.

Some vendors send all their information in note segments and assume you're going to only show users the information they send in a monospace font.

Some vendors even have the audacity to send Carriage Return Line Feeds at the end of each line of a file interface.

Some vendors absolutely refuse to send decimal numbers and in-so-doing refuse to send any numbers.

So, with all this crippling humanity against the simple plastic software man, how does one bend without breaking*?  Or better yet, how does one fight back and still make money?

*my answer is usually to create an interface for the interface and keep the HL7 processing pure, but I don't think this is the best solution

答:
The answer depends on who you are dealing with and what your goals are.

You can negotiate with other developers of small/custom emrs.  Sometimes you can even dictate what you'll accept.  But other times you'll be the one forced bend. How much depends on your goal.

We've taken the position that it's easy for us to customize the HL7 communication to fit the needs of the vendor because ultimately we want our clients to receive our data.  A little upfront pain goes a long way.

Additionally some vendor will bend...but that process takes a long time.  Days turns into weeks which turn into months.  In order for us to complete an interface on time we need the momentum to continue....once we have to wait a couple of days for a vendor to change something, that momentum has been lost and our focus is diverted to other interfaces and projects.  Stop/go/stop/go is a killer for, where as if the onus is all on us we can proceed much more quickly.

We manage the process like this.  First we use Mirth which is extremely flexible.  Second our architecture creates a "base" HL7 message.  Each EMR (or client) channel is customized to the specifics of the vendor/client - but it's built off of the base channel which is standardized in the sense that if you follow the HL7 spec, there should be no transformation and the only thing that is custom is the delivery mechanism.

This leaves the heavy lifting to a channel that is tried and true, and that channel never changes.

Our custom channels typically have 0-3 transformations.  Usually stuff like moving/copying Pid 3 instead of Pid 2 for patient ID or altering the client id in the MSH.  Those types of changes are very manageable.


问:
Setting up a development environment in the cloud?
I'm interested in transitioning my development environment onto the cloud.

I currently use VirtualBox with Vagrant to manage separate virtual machines for each individual project.

What would be the optimal setup for hosting these virtual machines in the cloud?

Given than I have nearly a dozen VMs, setting up separate EC2 instance for each one is not economical.

A cheaper option might be to snag a low-end VPS from one of the many cheap VPS providers out there. The downside, aside from reliability, is that I don't need all my VMs available to me at all times. For example, VMs that I use as my staging environments only need to be on a few times a week at best.

As an alternative, I've thought about running VirtualBox and Vagrant on a powerful box with enough memory to support multiple machines running simultaneously. Is this a smart setup, or are there caveats I have not considered?

As a side note to the aforementioned option, is there an alternative to VirtualBox that would be a wiser choice?

答:
EC2 only charges storage for non-running VMs.  Import VMs to EC2, just be sure to turn them off when you are done.  Use EBS backed AMIs for permanent storage, cost about $9/mo for 12 10GB volumes.  If you use the VM 40-50 hours/week your costs will be minimal.  Cheap VPS servers are generally overprovisioned and you will have performance issues, I would recommend EC2.  Another note, adding a VM on top of a VM (VPS) will also tend to kill performance and is not recommended.  The only viable other option is dedicated servers like from StormOnDemand.  I believe they are one of the few to sell full bare-metal servers by the hour, but I haven't used that product of theirs so I can't say for sure.

Multiple VMS
Just launch the AMIs as needed on different instances, the cost of multiple instances vs a larger instance is negligible.  Running multiple VMs on top of a VM will cause problems.  Paying the extra per-hour for a large enough bare-metal server to host multiple VMS will increase the cost quite a lot also.  The only reason I can see for large instance bare-metal and multiple VMs is if you switch between VMs a lot, and you want deterministic startup times.  EC2 can be slow at times to start VMs, but they seem to be getting better.

VirtualBox
Vagrant only supports VirtualBox, if you are happy with your current setup then leave it as is.  VirtualBox is a fairly robust solution for your problem so I don't see any reason to change it considerably.  If you come up with feature x that VirtualBox doesn't support (unlikely), then you would want to consider changing.


问:
Can I use MIT license to give some of my previous written code to employer so that I protect myself and don't lose my copyright?
My situation:

I have written a framework before I started my new job. I own the copyright.

It has a bunch of boilerplate logic inside of it, like any piece of software. (duh!)

I don't want to use the whole framework in my new job, but I do need to re-use some parts of it in a similar framework that I am building for my new job.

It is impractical to re-implement / re-think all the logic from scratch. It is a lot of logic and logic is logic, you can't make it much different. For example, how many different versions of a HashMap can you code? I bet they will be very similar and the third version can claim that you violated the copyright of the first version. :(

It is impractical to try to re-invent the API. Can you re-invent the API of a HashMap? Maybe you can change put(k,v) to add(k,v), but not much more than that.

My idea to protect myself and my previous code:

I will tell my employer that I am building the new framework based on a previous one that I have written under the MIT license. So in the future if I use my previous framework someplace else, or even another derived version of it, that has some pieces of code similar with this new framework I am building now for the employer, they won't be able to say I am using their code, the one I wrote for them.

My questions:

I am not distributing my code to anyone. I don't have to distribute my MIT licensed code to anyone, if I own the copyright, correct? I mean, can someone request that I release my code that I now claim it is under MIT license? It would not be the end of the world and I would certainly agree to do that under a legal threat.

Does this strategy make any sense? My final goal is to be able to use a derived version of my previous coded framework without losing the copyright to it. At the same time, i do not want to distribute this code as an open-source project to anyone. I have other open-source projects, that I freely distribute, but this one I would like to keep it to myself so I can use on my jobs (not contractor jobs).

It is like claiming that you have a framework under the MIT license, without actually distributing and/or showing to anyone. If it is out there, free and easily available, my employers don't need me anymore. They can just take the code and give it to someone else to use it.

Notes:

I have listed this framework as a previous invention before I started the job.

I have not released this code anywhere. It is on my private SVN repo I host in my private server.

My idea in a nutshel:

My plan is to keep the previous code to myself, use parts of it in this new framework I am building for the employer and tell the employer it is work derived from a MIT licensed framework I have coded before and have not distributed to anyone". I am not forced to distribute a software I coded under MIT license, am I? If later, some legal claim happens (hopefully not), i can immediately paste the license on all the sources and show/release the code.

答:
(I am not a lawyer.)

I see a few potential problems with this:

If worst comes to worst, you'll have to prove that you wrote this code before you started working there, and that when you used it in your project at work, your employer was aware that it was under your copyright and under the MIT license. As the primary goal of this is retaining your copyright, not setting redistribution terms, a written contract with your employer about the use of your previously written code seems a better idea.

You say you want to protect your copyright and the ability to build "even another derived version of it". Now it's likely that while at your current job, you'll have a few great ideas and implement them. It seems to me that this would get hairy when you leave your job and then 're-implement' those ideas to build another version of your library - since you can't do whatever you want with the code you wrote at your job (and to some extent, the ideas behind it).


问:
What's a good format for documenting hundreds of data feeds?
Several governments are starting to publish open data: datasets generated by the goverment, made freely available for citizens to use for value-added app development, analysis, and feedback. For instance, the City of Vancouver (Canada) Open Data Catalogue publishes 130 datasets. The subject matter ranges from tabular files of city councillor contact information to geographical datasets of zoning districts. Formats range from Comma-Separated Value (CSV) to SHP to KML and beyond.

It would be nice for each of these open data portals to have a dataset of datasets: their catalogue of datasets in structured data file form. The catalogue dataset should have metadata describing each dataset (name of dataset, URL of download page, the formats the dataset is available in, maybe a description of the dataset format and attributes or URL to same.

What is a good data model and a good format for such a catalogue dataset?  If this is a solved problem, I'd like to suggest that Vancouver reuse that solution, instead of inventing one.

Update: in response to the question, why is it desirable to to have a catalogue as a structured dataset, I can think of three classes of use case.

Analysis across all the datasets of a data provider. It is convenient to get a list of all datasets, with links to descriptions etc., which I can import into a spreadsheet and annotate. Someone else may want to count total number of records published, or breadth of government activity covered by the data. In my case, I'm working on a Vancouver Open Data language census.

Analysis of corresponding datasets across multiple data providers. For instance, one might want to aggregate a list of all zoning boundary datasets published by Canadian cities. That is easier if one can sift through dataset lists by machine instead of by hand.

Analysis of dataset catalogue change over time. It might be interesting to analyse the growth in Open Data from one year to the next.  Structured catalogues make this easier to automate.

答:
I think you are talking more about a presentation problem (a coherent list of all the data they provide) rather than a data-modelling problem.

Any "OK" software developer, with at least somewhat matured language will be able to process CSV, XML, JSON, any hue of different kind of data format\model.

Why do you think that this data should be structured? Who and for what would someone need such data in a machine-readable format?

It's not like open data with thousands of rows, tables, etc, is a data you need to crawl or find automatically. Finding the proper "download link" as you say is a single-time thing. Why should it be automated\structured\machine-readable?

Ask them to make a list with links and descriptions and make it a webpage, what more do you need?


问:
main() function prototypes
As far as I know,

```<code>main ()
</code>```

function has the following prototypes:

```<code>    int main();
    int main(int argc, char **argv);
</code>```

Now, C does not support overloading, then how are multiple prototypes of

```<code>    main ()
</code>```

supported?

答:
As a program can only contain one function called main, it is actually very simple for the compiler to support the multiple signatures.

In the call-sequence for main, the caller is made responsible for cleaning up any arguments that were provided.

And the compiler provides a piece of startup code that prepares the arguments for main and then invokes the one function of that name, without checking if it will actually use those arguments.

As a side note, the last two prototypes are identical and in a function definition, the first two would be identical as well. That leaves only two supported signatures for main.

Title: main() function prototypes


答:
C does not support overloading

C does support overloading, it doesn't support user defined overloading of functions but operators have a fixed set of standard defined overloads.

how are multiple prototypes of main () supported?

The compiler has to do the right things for different possible definitions of main(), but it has just to keep one prototype for recurse call checks; it hasn't to behave differently for main than for any other function excepted when compiling its definition.  You can't provide yourself a prototype which won't match the definition you use and expect things behave sanely.

BTW, note that has your two last lines are strictly equivalent and the difference between the two first may occurs in valid programs for other functions than main.

Title: main() function prototypes

Body:
As far as I know,

```<code>main ()
</code>```

function has the following prototypes:

```<code>    int main();
    int main(int argc, char **argv);
</code>```

Now, C does not support overloading, then how are multiple prototypes of

```<code>    main ()
</code>```

supported?


问:
How can you write tests for Selenium (or similar) which don't fail because of minor or cosmetic changes?
I've been spending the last week or so learning selenium and building a series of web tests for a website we're about to launch. it's been great to learn, and I've picked up some xpath and css location techniques.

the problem for me though, is seeing little changes break the tests - any change to a div, an id, or some autoid number that helps identify widgets breaks any number of tests - it just seems to be very brittle.

so have you written selenium (or other similar) tests, and how do you deal with the brittle nature of the tests (or how do you stop them being brittle), and what sort of tests do you use selenium for?

答:
Testing ensures that code behaves as expected.  If your tests break on a regular basis, then the tests are either not testing the right thing or the developers do not care about the tests.

Personally I think that if the presence of a
 tag breaks a test then the test is needlessly strictly dependent on the surrounding tags, and a more lenient approach should be taken.

ContentLicense: CC BY-SA 2.5

Body:
Testing ensures that code behaves as expected.  If your tests break on a regular basis, then the tests are either not testing the right thing or the developers do not care about the tests.

Personally I think that if the presence of a <div> tag breaks a test then the test is needlessly strictly dependent on the surrounding tags, and a more lenient approach should be taken.


问:
When to import names into the global namespace? (using x::y, from x import y etc.)
I've been programming in various languages for about 10 years now. And I still haven't figured out when it is a good idea to import something into the global namespace (using x::y in C++, from x import y in Python etc.), so I hardly ever do it.

It almost always seems like a bad idea to me, if only because it limits the set of variable names I can use. For example: Where I to use using namespace std; or using std::string;in C++, I couldn't use stringas a variable name anymore, which I occasionally do (e.g. for string utility functions).

But I'm wondering: Are there some situations where importing a name into the global namespace really makes sense? Any rules of thumb?

答:
It's up to programmer when to use it. IMHO it's better not use them at all, especially in header files. But there are several cases when I use it

When I want to introduce something to another namespace e.g.

```<code>namespace cg
{
  namespace details
  {
    //lots of stuff
    void some_cool_foo()
    {
      //uses a lot stuff from details, here because I don't want prefix everything with details::
    }
  }
  using details::some_cool_foo;
}
</code>```

To enable ADL for some algorithms from another namespace

```<code>namespace n1
{
//some general foo
}
namespace n2
{
  using n1::foo;
//some struct
}
namespace n3
{
  using n1::foo;
//some struct
}
</code>```

If I don't want write long names of namespaces at .cpp I can always make alias

```<code>namespace bl = boost::lambda;
namespace fs = boost::filesystem;
</code>```

Body:
It's up to programmer when to use it. IMHO it's better not use them at all, especially in header files. But there are several cases when I use it

When I want to introduce something to another namespace e.g.

namespace cg
{
  namespace details
  {
    //lots of stuff
    void some_cool_foo()
    {
      //uses a lot stuff from details, here because I don't want prefix everything with details::
    }
  }
  using details::some_cool_foo;
}

To enable ADL for some algorithms from another namespace

namespace n1
{
//some general foo
}
namespace n2
{
  using n1::foo;
//some struct
}
namespace n3
{
  using n1::foo;
//some struct
}

If I don't want write long names of namespaces at .cpp I can always make alias

namespace bl = boost::lambda;
namespace fs = boost::filesystem;


问:
How to run an applet like a desktop application without installing entire JDK?
I want to make a desktop application- an analog-clock with the option of setting alarms using java. For rendering all the graphics and the button features, a Swing applet is the answer.

But the problem is that I want to run the applet onto the desktop and so need an applet viewer like thing. Applet viewer comes with the JDK and I think installing entire JDK on a system for running just a simple alarm clock is really not a good idea at all because it will take a lot of space.

Is there a way out? Can I get just the applet viewer (or anything similar to that) instead of entire JDK so that I can run my applet?  Or is there any other way I can do my project using Java?

答:
You need appletviewer to debug java applets, if you want just to run them you need a Java Runtime Environment (JRE) and the Java plugin for your favourite browser.

But if you just need a clock, you can do it just with javascript and HTML5:
http://www.neilwallis.com/projects/html5/clock/index.php


答:
I'm reluctant to post this an answer however there isn't really any way of doing what you want. There is no way around it as the Java code needs the JVM to execute. Well, there is one way around it and that is to use a Java to EXE compiler such as Excelsior. I don't know too much about it other than it can take your Java code and once you have ran it through their compiler you are left with a native exe (I'm assuming you mean windows) that does not rely on a JVM.

Just to expand, I'm not really a Java developer so I'm unsure of how many other tools there are that do what Excelsior JET do; however do be careful as many Java-To-EXE tools don't actually compile your code into a native PE binary, but simply wrap your .jar file into an EXE and still require a JVM to run.

Title: How to run an applet like a desktop application without installing entire JDK?

Body:
I want to make a desktop application- an analog-clock with the option of setting alarms using java. For rendering all the graphics and the button features, a Swing applet is the answer.

But the problem is that I want to run the applet onto the desktop and so need an applet viewer like thing. Applet viewer comes with the JDK and I think installing entire JDK on a system for running just a simple alarm clock is really not a good idea at all because it will take a lot of space.

Is there a way out? Can I get just the applet viewer (or anything similar to that) instead of entire JDK so that I can run my applet?  Or is there any other way I can do my project using Java?


答:
One thing you have to understand about C or any other language that produces native object files is that the only time function prototypes matter is during compilation.  By the time the linker sees it, the only thing to be done is fill in the missing addresses of external functions.

Arranging the passing of function parameters is entirely up to the compilers, usually based on an architecture-specific convention.  Most implementations on machines with stacks push the parameters in reverse order followed by the return address.  Ergo, when code wants to call f(int a1, int a2, int a3), the stack would contain Return Address a1 a2 a3 if you were reading it from the top down.  This means the function can get at a1 by looking at the second item in the stack, a2 by looking at the third, etc.

Calling main() works exactly the same way, so from its perspective, the stack will contain Return Address argc argv envp.  (That last item is something Unix and other systems have done for decades, but it's not in any standard.  You'll see why this doesn't matter in a second.)

Section 5.1.2.2.1 of the C standard specifically says that no implementation will define a prototype for main() and that the two standard implementations are main() and main(int argc, char **argv).  Not having a pre-defined prototype allows you to declare main any way you like and not have the compiler balk at it.  A zero-argument version will ignore the stack entirely and the two-argument flavor will look at the second and third items.  You could also, do a one-argument version, main(int argc), which would work because it would consume argc and not know that argv is there.

As you might have guessed, this trick only works in the direction of a caller calling a function with more arguments than the called function consumes will just have pushed on more than the caller will see.  A called function with more parameters than the caller pushed will simply look further down the stack than it should and fall victim to the GIGO principle.  Since the caller undoes the adjustment to the stack pointer, the stack comes out of it unscathed after the called function returns.

Addendum, addressing Bart van Ingen Schenau's comment:

C++ mangles its symbol names to prevent collisions between same-named, differently-prototyped functions, as almost every native object file format on the planet differentiates symbols only by name.  That has the pleasant side effect of preventing mismatched calls between C++ object files, but only because a C++ compiler compiling a wrongly-prototyped call will emit a symbol that won't be present in the object file that would contain the called function.  It happens that you get human-readable C++ function names in linker error messages because many of them recognize and demangle C++ symbols.

An object file can refer to a C++ function in another object file by its mangled name and attempt to call it.  (I've actually done this experimentally and would never in a million years condone doing it in "real" code.)  The linker, which has no idea whether either object was produced by a C++ compiler or from some bit of hand-written assembly, will do nothing to prevent it as long as the symbol names match.  That makes the assertion that the linker plays any direct role in enforcing C++ language policies erroneous.

Title: main() function prototypes


问:
Workflow for building a RESTful API
I am building a RESTful API, and so far, to make sure that my resources work as I need them to, I am using a REST client called Postman. This makes it easy for me to store routes and quickly make requests to them for testing. My current collection of routes in Postman looks like this:

The trouble with testing the API is this way is I have to manually change resource IDs. For example, if I want to test the PUT method on my posts resource, I have to first create a resource, find the ID, and then paste it into the PUT URI. This is long!

What is considered professional practice for building a RESTful API? Should I be writing unit tests for each route, dynamically creating the post before testing methods like update?

答:
I would develop a client program for my REST API (I used to do Python, but nowadays why not using Node.JS). This is the best way to test, because you're actually using it, and, moreover, you can launch your program as much time as you want and automate the testing using a testing lib. This is not that long to write, and really, it gives you some interesting software quality point.

This is not unit testing, this is a pure functional testing, it's about giving some garanty to your user that it works as expected.

Extra point: if you want to test some more global website (not just API) under the same approach, I would suggest you to give a try at CasperJS.

Title: Workflow for building a RESTful API


答:
I am not a lawyer, but this would be my solution:

Release the code under the GNU GPL v3 license in a public repository, where all are able to see.

The GPL license does not allow other people to take your code and put it into their proprietary commercial software and close the code.

If the code was 100% created by you and does not contain work from others or derived work, then the GPL allows you to license your code under another license as well, in which case you are allowed to use it in your jobs for proprietary commercial code. However, you must make your employer a licensee of this alternative proprietary license.

This solution would prove that you wrote your code BEFORE you took the job.

You can advertise that your code is available under a proprietary license for sale (for money) and then interested parties can contact you to purchase it.

Title: Can I use MIT license to give some of my previous written code to employer so that I protect myself and don't lose my copyright?

Body:
My situation:

I have written a framework before I started my new job. I own the copyright.

It has a bunch of boilerplate logic inside of it, like any piece of software. (duh!)

I don't want to use the whole framework in my new job, but I do need to re-use some parts of it in a similar framework that I am building for my new job.

It is impractical to re-implement / re-think all the logic from scratch. It is a lot of logic and logic is logic, you can't make it much different. For example, how many different versions of a HashMap can you code? I bet they will be very similar and the third version can claim that you violated the copyright of the first version. :(

It is impractical to try to re-invent the API. Can you re-invent the API of a HashMap? Maybe you can change put(k,v) to add(k,v), but not much more than that.

My idea to protect myself and my previous code:

I will tell my employer that I am building the new framework based on a previous one that I have written under the MIT license. So in the future if I use my previous framework someplace else, or even another derived version of it, that has some pieces of code similar with this new framework I am building now for the employer, they won't be able to say I am using their code, the one I wrote for them.

My questions:

I am not distributing my code to anyone. I don't have to distribute my MIT licensed code to anyone, if I own the copyright, correct? I mean, can someone request that I release my code that I now claim it is under MIT license? It would not be the end of the world and I would certainly agree to do that under a legal threat.

Does this strategy make any sense? My final goal is to be able to use a derived version of my previous coded framework without losing the copyright to it. At the same time, i do not want to distribute this code as an open-source project to anyone. I have other open-source projects, that I freely distribute, but this one I would like to keep it to myself so I can use on my jobs (not contractor jobs).

It is like claiming that you have a framework under the MIT license, without actually distributing and/or showing to anyone. If it is out there, free and easily available, my employers don't need me anymore. They can just take the code and give it to someone else to use it.

Notes:

I have listed this framework as a previous invention before I started the job.

I have not released this code anywhere. It is on my private SVN repo I host in my private server.

My idea in a nutshel:

My plan is to keep the previous code to myself, use parts of it in this new framework I am building for the employer and tell the employer it is work derived from a MIT licensed framework I have coded before and have not distributed to anyone". I am not forced to distribute a software I coded under MIT license, am I? If later, some legal claim happens (hopefully not), i can immediately paste the license on all the sources and show/release the code.


问:
Explanation of Object-parameter-coupling as mentioned in Code Complete book
I have been reading up on the seminal and excellent book Code Complete. It discusses about the various kinds of couplings that can happen between modules(which may be classes as well as methods):

Simple-data-parameter-coupling

Simple-object-coupling

Object-parameter-coupling

Semantic coupling

The book has to say this about object-parameter coupling :

Two modules are object -parameter coupled to each other if Object1
  requires Object2 to pass it an Object3. This kind of coupling is
  tighter than Object1 requiring Object2 to pass it only primitive
  data types because it requires Object2 to know about Object3.

What is the author trying to mean here?

答:
an example: imagine object1 requires object2 to pass it a time-stamp:

case 1 (tightly coupled):

object2 passes a custom Time-instance (object3):

therefore object1 must know how to extract the necessary data form this object

case 2 (less coupled):

object2 passes seconds_since_epoch (integer), object does not have to know the internals of another object.


问:
Lambda Calculus Free Variable
Here's something from Slonneger's "Syntax and Semantics of Programming Languages":

A variable may occur both bound and free in the same lambda
  expression: for example, in λx.yλy.yx the first occurrence of y is
  free and the other two are bound.

I assume the free variable is the y right after the λx. and the bound y's are the λy.y which I can sort of intuitively grasp. So ((λx.yλy.yx)a)b) would reduce to (yλy.ya)b) then to bba ? Can someone explain how this came to be? In the end it's the expression b twice. Can someone perhaps provide more examples of bound and free variables?

答:
You correctly identified the first y as the free variable. Basically lambda abstractions define a scope for their bound variables. The scope overrides any other uses of the same variable names, so the same variable name can be used several times in different abstractions or as free variable.

(y(λy.ya))b can not be reduced any further. Unbound variables will never be substituted in a beta reduction.

If it was (y(λy.ya)b) you could reduce to y(ba).

Title: Lambda Calculus Free Variable


问:
Why shouldn't a GET request change data on the server?
All over the internet, I see the following advice:

A GET should never change data on the server- use a POST request for that

What is the basis for this idea?

If I make a php service which inserts data in the database, and pass it parameters in the GET query string, why is that wrong? (I am using prepared statements, to take care of SQL Injection). Is a POST request in some way more secure?

Or is there some historic reason for this? If so how valid is this advice today?

答:
If I make a php service which inserts data in the database, and pass
  it parameters in the GET query string, why is that wrong?

The simplest answer is "because that's not what GET means."

Using GET to pass data for an update is like writing a love letter and sending it in an envelope marked "SPECIAL OFFER - ACT NOW!" In both cases, you should not be surprised the recipient and/or intermediaries mishandle your message.


问:
No programmer will build my semi-adult website. Why?
I've been looking for get this website done for a long time.

I thought with a well organized write-up of what I wanted, as well as having clear examples done in photoshop of faux pages to give an idea of the vision, and no hidden surprises, I would be a programmer's dream job.

Unfortunately, no company will touch the website. There is nothing illegal about it or even remotely offensive. It's an adult listing for professional Dominatrices. I don't see what the big deal is, when there are way worse and more hard-core sites out there, and this is just a listing. Pro Domination is a legal occupation in the USA and most of the world. People just don't want to touch the site. It's really strange. I have all of the information and details of the site laid out perfectly and clearly. I just either get no response or people who tell me they won't touch anything remotely adult.

Is there a reason for this?

答:
Nobody wants to have this "project" show up later in their resume or portfolio. And apparently nobody wants to do a project they can't later mention in public.

Pro Domination is a legal occupation in the USA and most of the world.

Not everywhere. Don't ask Turkish or northern African (Algeria, Tunisia, Morocco) programmers to build you one (being Muslims they'll even get offended). It's also not that much legal in eastern Europe (Ukraine, Russia) to be engaged in distribution of such content (which building the website would constitute).

But mostly, the gaps in your resume is a killer. People assume it's either something illegal, government-related or you had a bad run with a company and you just don't want them to call it for a reference. They'll just prefer to pass over you. Here you go, a job from the bottom of the barrel.


问:
Analogy of a class being a cookie cutter and objects being cookies
I came across the analogy of the class being a cookie cutter and the cookies being objects while reading Code Complete. I fail to see why this analogy was drawn.How is it related to the concept of objects being run time instances of their classes?

答:
The analogy is a bad one, because it can convey the essence of classes and objects if you apply the right mental mapping, but that mapping is not obvious to arrive at, and perhaps not even the most convincing one.

A class is like a cookie-cutter in that it has the power to create multiple items that are alike in some ways: they all have the same number and type of fields, while their values can differ. You can compare this to all cookies having the same shape, but it is unclear how the differences between individual cookies map to the differences between objects that are class-mates; in my mind, two Cartesian coordinates with different X and Y values are much more different than similar, certainly much less alike than two cookies with the same shape.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Quoting Kent Beck:

Make It Work

  Make It Right

  Make It Fast

LastEditorDisplayName: Roger Pate


答:
I used to be an IP lawyer, so have experience with license-ese. I feel like the terms themselves are fairly readable and understandable, but then again, I'm marred by three years of law school and some lawyering time before getting my wits again and returning to hacking. Particularly since I'm not currently an active lawyer, this certainly isn't intended as legal advice in the slightest.

Lets start with the MIT license language itself. Then I'll lay out a few key points to understanding open source licenses, then address your questions and provide any high-level observations.

Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions: (that they leave this notice in it. The end. )

A few key things with most open source licenses (including BSD, MIT, GPL) for copyright owners are:

The license doesn't alter your ownership of the copyright itself. Its a non-exclusive license, not an assignment or forfeiture of ownership. Using an OS license is not "putting something into the public domain", although that is certainly one approach to open source.

Nothing "forces" you, the copyright owner, to make the code public in any way just because you attach a license to it.

But if you use an OS license, you can't prevent anyone who "obtains" your OS-licensed code from making it public in any way, which is explicitly within their rights under all of these licenses.

Copyleft (e.g., GPL) licenses do require obtainers (but not the owners) to make their derived works public and open source.  Permissive (MIT, BSD) don't. (this may be a bit of a simplification, but is the essential difference)

There isn't a "takeback" clause to most open-source licenses (e.g., MIT) so once someone has "obtained" your code, they have the right to use it perpetually, under the license terms under which they received it.

You can always distribute future versions of your code under a different license, or keep them completely proprietary.  That doesn't stop someone from starting with your previous, open-source version (assuming they "obtained it") and adding on their own new parts and distributing it.

You can remove a channel of "obtaining" for previous versions of your code, e.g., take it off github. However, as mentioned, that does not prevent others from using or distributing any previous versions you had open sourced, in any way.

With that basis, I'll move on to your questions.

I am not distributing my code to anyone. I don't have to distribute my
  MIT licensed code to anyone, if I own the copyright, correct? I mean,
  can someone request that I release my code that I now claim it is
  under MIT license? It would not be the end of the world and I would
  certainly agree to do that under a legal threat. ... At the same time,
  i do not want to  distribute this code as an open-source project to
  anyone.

As copyright holder, you don't have to distribute any code to anyone; you wouldn't have to honor such requests (even if it was GPL). You retain all rights. However, in the situation you describe, you would be distributing to your new company and licensing it to them perpetually under an OS license. Your employer (more likely ex-employer) could paste your code to the internet, and you wouldn't be able to do a thing about it besides grumble.

I assume you mean "anyone besides my employer".  If you don't want to give it to your employer "as open-source" and give them all the rights that are included in that license, including redistribution and perpetual use in whatever way they want, then you shouldn't be using an open source license. You should just licensing it directly to them under the terms you want. Bullet point out what you want, and have a lawyer bill you an hour or two to put them into a paragraph form. Or write it yourself.  Licenses are just contracts which are just agreements put into words.

My final goal is to be able to use a derived version of my previous coded framework without losing the copyright to it.

You can't lose the copyright unless you assign it to someone, license it exclusively (including excluding yourself) or forfeit it.  Open source license are none of these. You'll always be able to use derived versions you create, and can even license the derivations differently or retain all rights.

But, a primary, legitimate concern of yours seems to be that you continue to be able to retain copyright and use your code in the future without the employer claiming the code as theirs or that you're outside your rights to do so.  The keys to this is to create an irrefutable evidence that A) you retain copyright to your previous work and are providing it to them under X license terms (MIT works, if you're ok with the open-source aspect of it described above.) B) they agree to these terms, and C) what, exactly the previous work was.

For (A) and (B) you can get them to sign or agree in writing to something that references or includes the license and that they understand that you're bringing the code to the table under those terms.  As to (C) I'm not sure what the standard way of doing this would be, but be logical. If its not terribly massive you could just print the code out and include it in the addendum in copies of the agreement that both you and your employer sign. Keep your copy, with their signature on it. If it is too big to practically print,  it seems like an md5 hash would come in useful here.  Maybe you could refer to it as something like "the zip file named X in the private github repository /, (or ftp site, etc.), which has a md5 hash of XXXXXX... and was emailed to Y company reprentative on Z date".  Then you can email it to your manager or their lawyer or whoever from your personal email account and even if they delete their copy you still keep yours and they can't argue that you predicted the future md5 hash of code that isn't written yet. That would theoretically prevent them from claiming anything else down the road.


问:
"Public APIs are forever: Only one chance to get it right"?
In an OS book I just read that, "Public APIs are forever: Only one chance to get it right". Is it true? Is it applicable only in APIs of Operating Systems or other APIs too? For example, will this be true for the APIs of Android Applications such as Tasker, Locale and Pushover?</p>

答:
Anytime that you release any sort of communications protocol, which would obviously include an API, you have one chance to get it right in the sense that the protocol/interface must be backwards-compatible and extensible.

This allows you to add new functionality and release new versions without having to worry about breaking people who are using older versions.  Never in the software world are you going to have a situation where you can just have a hard cutover at a certain point in time, and everyone drops the old version and starts using the new version.


问:
Index independent character comparison within text blocks
I have the following task:  developing a program where there is a block of sample text which should be typed by user.  Any typos the user does during the test are registered.  Basically, I can compare each typed char with the sample char based on caret index position of the input, but there is one significant flaw in such a "naive" approach.  If the user typed mistakenly more letters than a whole string has, or inserted more white spaces between the string than should be, then the rest of the comparisons will be wrong because of the index offsets added by the additional wrong insertions.

I have thought of designing some kind of parser where each string (or even a char ) is tokenized and the comparisons are made "char-wise" and not "index-wise," but that seems to me like an overkill for such a task.  I would like to get a reference to possibly existing algorithms which can be helpful in solving this kind of problem.

答: Pretty much the only way to do this is to use grapheme clusters and then compare their normalized versions.</p>


答:
I just either get no response or people who tell me they won't touch
  anything remotely adult.

Pay more.

You might think that you're offering a competitive rate, but the fact that you can't get anyone interested means that the people who've looked at the job don't agree. It may be that you haven't factored the stigma associated with your industry into your pay rate, or it may be that there's just an abundance of interesting projects in your area right now, or a dearth of qualified developers, or whatever. The precise reasons that nobody's interested don't really matter that much; your task is to sweeten the deal enough to attract developers (and not just any old developers, but people who really know what they're doing).

Title: No programmer will build my semi-adult website. Why?

Body:
I've been looking for get this website done for a long time.

I thought with a well organized write-up of what I wanted, as well as having clear examples done in photoshop of faux pages to give an idea of the vision, and no hidden surprises, I would be a programmer's dream job.

Unfortunately, no company will touch the website. There is nothing illegal about it or even remotely offensive. It's an adult listing for professional Dominatrices. I don't see what the big deal is, when there are way worse and more hard-core sites out there, and this is just a listing. Pro Domination is a legal occupation in the USA and most of the world. People just don't want to touch the site. It's really strange. I have all of the information and details of the site laid out perfectly and clearly. I just either get no response or people who tell me they won't touch anything remotely adult.

Is there a reason for this?


答:
The most important thing when creating tests like this once you get past a trivial number is the idea of symmetric change - a small change in the code should result in a small change in the test suite.

For example, let's say you collect someone's name with two text boxes in 100 tests. If you write those tests niavely (or maybe are using record-playback) then you will have 100 tests to change. If instead you abstract out an 'enter name' step and use that in your tests instead of directly using selenium then you only have 1 place to make your change. It'll depend on your context how many layers of abstraction you use - but using abstraction will go a long way to making your tests maintainable.

A second important thing is to make sure your selectors are based on the thing which is most important and least likely to change. Sometimes this will be an id or a class or it could be the text in or surrounding an element. Always prefer the simplest selector (e.g. an id) but sometimes to achieve this you will have to use something like xpath.

Gojko Adzic has lots of great advice on his blog when it comes to this sort of testing - check out his Sine of Death and how to avoid it in particular.

Title: How can you write tests for Selenium (or similar) which don't fail because of minor or cosmetic changes?

Body:
I've been spending the last week or so learning selenium and building a series of web tests for a website we're about to launch. it's been great to learn, and I've picked up some xpath and css location techniques.

the problem for me though, is seeing little changes break the tests - any change to a div, an id, or some autoid number that helps identify widgets breaks any number of tests - it just seems to be very brittle.

so have you written selenium (or other similar) tests, and how do you deal with the brittle nature of the tests (or how do you stop them being brittle), and what sort of tests do you use selenium for?


问:
Security and code execution
If I am taking data from a website, for example status updates from Facebook and showing them on my website. What possible damage can be caused if I am not taking into account that the code written as status update would execute on my website?

For example,
Mr. Simon has putted his status update,

```<code>"<p style="color:red;">I love to code</p>"
</code>```

Now, when I display this on my website, it transforms into the text I love to code written in red.

答:
Basically you will be vulnerable to XSS - the element might as well be a script element or the paragraph element could have an onmouseover etc attributes to run a script.

If you are not using HttpOnly session cookies, XSS can be used to steal sessions.

All security measures against CSRF are useless if you are vulnerable to XSS.

The script can dynamically load malicious java, flash, pdf etc plugin files, which can exploit bugs in the respective browser plugins.

The script can redirect the user somewhere else, hide your page or make for a convincing phishing page since it's on your domain.

Probably many more - only your imagination is the limit :)

Title: Security and code execution


问:
Can we make it easier to add data flows between distant parts of a large codebase?
When making changes to large systems, I often face the problem that some piece of functionality needs to get some data from another piece, but they're in different parts of a deep and branching call tree, possibly flowing through event listeners, deferred calls, etc. In this way a simple change can balloon quickly.

A related quote from Yossi Kreinin's blog post at http://www.yosefk.com/blog/i-want-a-struct-linker.html:

You have some kind of data structure that you pass around a lot. Soon, the most valuable thing about the structure isn't the data it keeps, but the fact that it's available all the way through some hairy flow of control.

Global variables are one classic way to let code "shout out" to distant code, but they're known to be problematic. Dynamically scoped variables are a more restricted way, but they're problematic as well.

Is there any programming language research aimed at solving this problem? Can we make it easier to add unanticipated flows of data to a large codebase, while still having static checking, easy unit testing and other goodies?

答:
You are referring to CDI (Context Dependency Injection) AKA IoC (Inversion of Control). Java JSF and Spring Framework are some examples. ASP.NET MVC has plugins like Unity. Javascript is beginning to have organized structures using libraries like RequireJS, which has injection behavior seen in many modern JS frameworks. That is for wiring up local and remote applications.

For loose coupling across networks, companies like to use Web Services with SOAP, REST, AJAX, or regular remote method calling with RPC. In Java you can use JAX-WS or .NET WCF to build distributed services. Then you line them up in a service bus or "data flow" from any language or platform as a client. Ruby, Python, Scala, Java, C#, ... anything.

Loose coupling allows you to divide and conquer problems, and services are often the entry point to a database for pulling data. Stepping up the ladder we have the beast called Message Queue. That road leads to enterprise and infrastructure type frameworks.

If your project insists on no network, though, there are languages like Scala, Akka, NodeJS etc.. that are designed for a high flow of data within a single application. They also work with some or all of the previously mentioned technologies for complex projects. For example, Scala can be used with JAX-RS REST services for pulling sort of "global data" from a data source, and have Spring for the IoC internal wiring. There are also many business execution or workflow frameworks in JBoss, .NET, and GUI tools like MuleESB. In development, Eclipse and Netbeans lets you drag and drop services in a visual flow chart screen.

Finally, Java has Singleton beans still. For adjusting your methods at run-time, use proxy or reflection frameworks. But honestly, that is so 1999.

If you're making that many calls to send a user a message based on their timezone, in my opinion, there's probably a 2-step way to achieve the same effect that the user sees. But yeah, CDI frameworks are worn by existing languages like a coat that gives them all of the flexible powers you mentioned. I like to call it my program's subconscious, taking care of dirty work seamlessly.


答:
If you define a function named foo, you can give it any (legal) prototype you like:

```<code>int foo(void);
int foo(int argc, char *argv[]);
void foo(long double this, const unsigned short ***that, struct thingie the_other);
</code>```

You're defining foo yourself, so you can define it any way you like.

Similarly, you're defining main yourself; the implementation doesn't define it for you.  What's different about main is not that it can have one of two different prototypes, it's that it's restricted to have one of only those two different prototypes (or equivalent). And that's to ensure that the compiler and the calling environment know how to invoke your main function. (For foo, any calls will be your own.)

(main may also be defined in some other implementation-defined form, but such forms are not portable.)

As for why those two are permitted, rather than, say, requiring exactly the second form, it's mostly for historical reasons.  Early C compilers didn't have prototypes (they were introduced in the 1989 C standard, borrowed from C++).  In pre-standard C, defining

```<code>main() { /* ... */ }
</code>```

probably just meant that the calling environment would pass argc and argv values (and possibly envp) to main, and main would simply ignore them. It was convenient to omit the definitions of argc and argv if your program wasn't going to use them. Calling conventions were such that the two forms were effectively compatible.

For historical reasons, modern calling conventions are likely to work similarly, but since the 1989 ANSI standard compilers have been permitted to make the two forms incompatible -- but if they are, then the implementation has to do whatever is necessary to make both forms work.

Title: main() function prototypes

Body:
If you define a function named foo, you can give it any (legal) prototype you like:

int foo(void);
int foo(int argc, char *argv[]);
void foo(long double this, const unsigned short ***that, struct thingie the_other);

You're defining foo yourself, so you can define it any way you like.

Similarly, you're defining main yourself; the implementation doesn't define it for you.  What's different about main is not that it can have one of two different prototypes, it's that it's restricted to have one of only those two different prototypes (or equivalent). And that's to ensure that the compiler and the calling environment know how to invoke your main function. (For foo, any calls will be your own.)

(main may also be defined in some other implementation-defined form, but such forms are not portable.)

As for why those two are permitted, rather than, say, requiring exactly the second form, it's mostly for historical reasons.  Early C compilers didn't have prototypes (they were introduced in the 1989 C standard, borrowed from C++).  In pre-standard C, defining

main() { /* ... */ }

probably just meant that the calling environment would pass argc and argv values (and possibly envp) to main, and main would simply ignore them. It was convenient to omit the definitions of argc and argv if your program wasn't going to use them. Calling conventions were such that the two forms were effectively compatible.

For historical reasons, modern calling conventions are likely to work similarly, but since the 1989 ANSI standard compilers have been permitted to make the two forms incompatible -- but if they are, then the implementation has to do whatever is necessary to make both forms work.


问:
Are Request/Response Parameter Wrappers Good Practice?
I've seen several different ways to design WCF services, and it seems some developers prefer parameter wrappers while others favor 'naked' parameters. To explain what I mean, consider the following service interfaces:

'Naked' Parameters

```<code>[ServiceContract]
public interface IService
{
    [OperationContract]
    string[] GetValuesByType(string groupName, ValueTypeEnum valueType)
}
</code>```

Parameter Wrappers

```<code>[DataContract]
public class GetValuesByTypeRequest
{
    [DataMember]
    public string GroupName { get; set; }

    [DataMember]
    public ValueTypeEnum ValueType { get; set; }
}

[DataContract]
public class GetValuesByTypeResponse
{
    [DataMember]
    public string[] Result { get; set; }
}

[ServiceContract]
public interface IService
{
    [OperationContract]
    GetValuesByTypeResponse GetValuesByType(GetValuesByTypeRequest request)
}
</code>```

I suppose there are cases where parameter wrappers make it easier to maintain the service over different versions of the software, since you can control serialization of each member a bit more directly than you can with the first method. But to be honest, parameter wrappers just seem like a lot more code for very little benefit. Am I wrong here?

答:
You are correct, in that in terms of how the code will change over time, I typically lean toward parameter wrappers so that later, when I need more information to perform the same function when adding a new feature, I can preserve signatures, and add one more property to the existing wrapper object.

When it comes to building communication contracts like you do when working with WCF, this will preserve the contract, and allow clients working with the old object to continue to function as they used to -- they just won't get the benefit the new property offers. Serialization will simply ignore the property, and happily pass the object along. As clients are updated to "know about" the new property, they can migrate their code accordingly.

If you were to change the signature of that method by adding a parameter, you will break the contract you have with all your clients, forcing them all to synchronously release updates with your signature change.

If your code has clients for which you do not control the deployment cycle, do future you (or future developers on your code) a favor and design with parameter wrappers. If you control all client code and deployments and can force them all out at once, then it probably doesn't matter. But in the grand scheme of things, it's not a ton of extra code and it's a good habit (IMHO).

OwnerDisplayName: John Hasenmyer


问:
Is MSDN / Azure Active Directory information available in different formats?
I'd like to read the documentation of Azure Active Directory on my kindle (or similar device), but don't want to use "Print to Kindle" for each and every page.

Is the Microsoft documentation for this technology available in other formats?  (.chm, PDF, etc).

If an alternative format is available, then I can adapt that to my needs.

http://msdn.microsoft.com/en-us/library/jj673460.aspx

答:
There is some information in e-book format (English and other languages) located here:

E-Book Gallery for Microsoft Technologies

Download content for ASP.NET, Office, SQL Server, Windows Azure, SharePoint Server and other Microsoft technologies in e-book formats. Reference, guide, and step-by-step information are all available. All the e-books are free. New books will be posted as they become available.

Not sure the all information you were looking for is here. It also appears that it's necessary to create a profile to download books.

I am a Microsoft employee and write developer documentation for the MSDN site, we don't republish all our online documentation in e-book formats. MSDN is trying to use a continuous publishing model for online content and encourages users to go online to get the latest content. To my knowledge very little of the content for developers is being published in e-book format.


问:
Why does automated testing keep failing in my company?
We have tried to introduce developer automated testing several times at my company. Our QA team uses Selenium to automate UI tests, but I always wanted to introduce unit tests and integration tests. In the past, each time we tried it, everyone got excited for the first month or two. Then, several months in, people simply stop doing it.

A few observations and questions:

Does automated testing actually work? Most of of my colleagues who used to work at other companies have tried and failed to implement an automated testing strategy. I still haven't seen a real-life software company that actually uses it and doesn't just talk about it. So many developers see automated testing as something that is great in theory but doesn't work in reality. Our business team would love developers to do it even at a cost of 30% extra time (at least they say so). But developers are skeptics.

No one really knows how to properly do automated testing. Yes we have all read the unit testing examples on the internet, but using them for a big project is something else altogether. The main culprit is mocking/stubbing the database or anything else that is non-trivial. You end up spending more time mocking than writing actual tests. Then when it starts taking longer to write tests than code, that's when you give up.

Are there any good examples of unit tests/system integration tests used in a complex data centric web applications? Any open source projects? Our application is data centric but also has plenty of domain logic. I tried the repository approach at some point and found it pretty good for unit testing, but it came at the price of being able to optimize data access easily and it added another layer of complexity.

We have a big project undertaken by 20 experienced developers. This would seem to be an ideal environment to introduce unit testing/integration testing.

Why doesn't it work for us? How did you make it work at your company?

答:
First, if your developers don't see the value of your tests, then it's probably because your tests aren't valuable, not because your developers are blind to their value, or to the value of tests in general.  Among its evangelists, there is a tendency to believe that test driven development cannot fail, it can merely be failed by lazy, lazy developers.  I think this is wrong and counterproductive.

When I was introduced to test driven development, it meant, effectively, writing a test to verify that a method that will never fail never fails.  Which is nice, at first, because you get a lovely green check and a sense of accomplishment.  Later, after you refactor the code, you have tens of infuriating red Xes, none of which say anything more than that the code has changed, that the tests are no longer valid, and that you wasted a lot of time writing them.

You want to avoid that.

Since then, I've taken a different approach to tests.  Instead of an interface implementation pair, I have an interface, implementation, test triple.  The interface specifies the behavior, the implementation performs the behavior, the test checks the behavior.

I suppose it seems obvious, but to me, it distinguishes between the code you must prove works as specified and the code you may test as much or as little as you consider appropriate.  The code you must prove is the interface you offer to the outside; the rest is your concern alone.

In this case, I would ask the developers whether they see a natural division in the code where this sort of test would be appropriate.  Is there an interface that Team A implements and Team B uses?  In that case, it is in the interest of Team B to ensure that the interface behaves as they expect.  Ask Team B to write a test for it, then tell Team A to ensure that their implementation conforms to the test; or, if it doesn't, and it intentionally doesn't, to discuss the unexpected change with the other team, so that they can prepare for it.

I think this would illustrate the value of the test.  It isn't an end in itself, lovely green checks notwithstanding.  It exists to make explicit the promise made by one developer to another, and to ensure that the promise is kept to the satisfaction of both.


答:
If you use (or quote) the words

```<code>hairy flow of control
</code>```

then I assume that your code really is a mess. You should drop it immediately. If you use modularization/separation of concerns, there is no such thing as a "hairy flow of control". Your code simply lacks simplicity which is also inferrable by the fact that you referred to global variables :-).

Title: Can we make it easier to add data flows between distant parts of a large codebase?

Body:
When making changes to large systems, I often face the problem that some piece of functionality needs to get some data from another piece, but they're in different parts of a deep and branching call tree, possibly flowing through event listeners, deferred calls, etc. In this way a simple change can balloon quickly.

A related quote from Yossi Kreinin's blog post at http://www.yosefk.com/blog/i-want-a-struct-linker.html:

You have some kind of data structure that you pass around a lot. Soon, the most valuable thing about the structure isn't the data it keeps, but the fact that it's available all the way through some hairy flow of control.

Global variables are one classic way to let code "shout out" to distant code, but they're known to be problematic. Dynamically scoped variables are a more restricted way, but they're problematic as well.

Is there any programming language research aimed at solving this problem? Can we make it easier to add unanticipated flows of data to a large codebase, while still having static checking, easy unit testing and other goodies?

Body:
If you use (or quote) the words

hairy flow of control

then I assume that your code really is a mess. You should drop it immediately. If you use modularization/separation of concerns, there is no such thing as a "hairy flow of control". Your code simply lacks simplicity which is also inferrable by the fact that you referred to global variables :-).


问:
Is it considered bad practice to have PHP in your JavaScript
So many times on this site I see people trying to do things like this :

```<code><script type="text/javascript">
  $(document).ready(function(){

     $('<?php echo $divID ?>').click(funtion(){
       alert('do something');
     });

  });
</script>
</code>```

I don't think that this is some sort of pattern that people naturally fall into. There must be some sort of tutorial or learning material out there that is showing this, otherwise we wouldn't see it so much. What I'm asking is, am I making too big a deal of this or is this a really bad practice?

EDIT :
Was speaking to a friend of mine about this who often puts ruby in his JavaScript and he brought up this point.

Is it ok to dynamically place application wide constants in your JavaScript so you don't have to edit two files. for example...

```<code>MYAPP.constants = <php echo json_encode($constants) ?>;
</code>```

also is it OK to directly encode data you plan to use in a library

```<code>ChartLibrary.datapoints = <php echo json_encode($chartData) ?>;
</code>```

or should we make an AJAX call every time?

答:
It's not a bad practice ONLY if it's used for javascript code initialisation, (in my WordPress themes, I initialize my javascript objects with php functions like site_url() because it's the only way to handle that (maybe we could use an ajax request to get a json, and so... but it's a pain in the ass).

Good practice:

new javascriptObject("");

Bad practice:

/* some code*/
document.get_element_by_id();
/* some code*/

OwnerDisplayName: Greg Guida


问:
What discipline does Computer Science belong to?
Is Computer Science science, applied mathematics, engineering, art, philosophy? "Other"?

To provide background, here is Steven Wartik's blog posting for Scientific American titled "I'm not a real scientist, and that's okay." The article covers some good topics for this question, but it leaves open more than it answers.

If you can think of the discipline, how would computer science fit into its definition? Should the discipline for Computer Science be based on what programmers do, or what academics do? What kind of answers do you get from people who've seemed to think deeply about this? What reasons do they give?

答:
Programmers rarely "do computer science".  They mostly use results of "software engineering", which is an engineering discipline, obviously.

Other than that, Computer Science is Applied Mathematics.  If you compare CS with something indubitably belonging to applied maths, you'll notice a lot of resemblance.

Computer scientists design and study ways of computation (algorithms), taking most of theory from Mathematics (logic, graph theory, combinatorics, etc)—and contributing to it at the same time.  Just like the rest of applied mathematics.

They evaluate properties of these models and algorithms theoretically, and carry on modeling experiments (write test programs).  Like applied mathematicians simulate flow of liquid in tubes on clusters, computer scientists use computers to experiment with implementations of their algorithms.  The results of these experiments go directly into production: either to an oil refinery or to a software for stock analytics.

In the university I finished there isn't even a special department for computer science: among other, non-computer domains, computer science chair is a part of Department of Applied Maths.

ContentLicense: CC BY-SA 4.0


问:
Why is the usage of string keys generally considered to be a bad idea?
This has been bugging me for a while. Most of the time, when it comes to storing data in structures such as hashtables, programmers, books and articles insist that indexing elements in said structures by String values is considered to be bad practice.
Yet, so far, I have not found a single such source to also explain WHY it is considered to be bad practice.
Does it depend on the programming language? On the underlying framework? On the implementation?

Take two simple examples, if it helps:

An SQL-like table where rows are indexed by a String primary key.

A .NET Dictionary where the keys are Strings.

答:
It all has to do with the two things basically:

1) The speed of lookup (where integers for instance fare much better)

2) The size of indexes (where string indexes would explode)

Now it all depends on your needs and the size of the dataset. If a table or a collection has like 10-20 elements in it, the type of the key is irrelevant. It will be very fast even with a string key.

P.S. May not be related to your question, but Guids are considered bad for database keys too (16 byte Guid vs. 4 byte integer). On large data volumes Guids do slow down lookup.


问:
Redmine (or Trac) integration with customer issue-tracking system
I'm working in a software development area in my university, and we've noticed we need some system to track errors and bugs, who and when it is dealt with. I've researched some software management/bug tracking applications, with Redmine being the one that appeals to me the most because of its simple UI (actually I discovered that our server has one system, Trac, already installed, but it has never been used at its time and my colleagues told me it would take the same time to use any).

However, a colleague told me also that he has the idea of implementing a customer issue-tracking system in the medium/long term (he told me about creating tickets for users' problem, search into a knowledge base of common problems, and mark frequent problems to deal with them. It seems that things like OTRS are close to what he was thinking about. He's also researching about ITIL).

As far as I know, the developer issue-tracking system and the client problem-tracking system are different, and they must have some kind of integration between them. Or aren't they?  In case it does, my question is:

Is it possible to integrate Redmine (or Trac, if it's easier, or in general a project management/bug-tracking system) with this kind of customer issue-tracking systems? Do I have to worry about changing my project management system in the future to implement that? Or is the implementation easier with some of them?

答:
I'm writing this from the perspective of Redmine.  I haven't used Trac and only massaged the source with my eyes (not even reading it). At a high level, it appears to be similar to Redmine so many of the things that I say may apply to it too.

The first question that you need to look at is the integration between the bug tracking (and code change) side and the "customer facing" issue tracking. Different places may allow for a degree of openness that is not available in others.

A closed-source software product certainly won't let the code changes get anywhere near the customer facing bug tracking system. The risk of having some code getting out is a worry for many of them.

An open-source software product will often host the source code and bug tracking right alongside the customer issue tracking (they are one and the same). This can be seen in both Redmine and Trac.

An academic setting... well, its probably somewhere in between.

That last point is key - is it a problem if the source gets out? Or for that matter, is it a problem if people see the discussion between developers of the product in the notes of an issue?

Redmine has the ability to restrict which certain users can read. You may have individual notes marked private or things such as "only people with the programmer role can see the repository."

If this is acceptable, the easiest thing is to integrate the end user issue tracking and bug tracking in the same system. You will likely want to separate "bugs" and "issues" from each other, though note that there is a relationship between them. An end user issue may be caused by a bug, or it may be something the end user doesn't understand.

Issues and bugs have different work flows - issues may go through something like "new -> confirmed -> waiting for fix -> resolved" while a bug may go through "new -> assigned -> working -> code review -> working -> code review -> deployed -> closed" or something like that. There are likely as many work flows as there are installations. Having a "blocked by" relationship from the issue to the bug allows you to easily relate the two systems together.

All of that was assuming that it was acceptable to have one system host both, you will then find yourself with two different systems - one that is customer facing, one that is developer facing. This may involve a bit more work - somehow, someone needs to bridge the gap between the two - developers need to be aware of bugs that are discovered by the end user in their bug tracking system.

I haven't found a modern bug tracking system that plays nicely with others. Everything tries to be self contained and when commercial products have bug tracking systems, they make it so that it's easy to migrate to it and use everything within its own product line. You may find an API that lets you do some things, but for the most part - nope.

The question here becomes what is the workload and how does one want to integrate the two (picture two spoiled children sitting with their backs to each other not wanting to play)?  Is it enough just to have a link from one system to the other? Is the amount of new issues low enough that this can be done by hand? or will you need to start exploring some way to poll from one and update the other?

Make sure that when integrating the two systems that you use the API rather than trying to go behind its back and tinker with the database with updates directly. There are dangers to that - the table structure of modern bug trackers is a big large and they are managed in the application. Going behind the back of the application may cause issues with data integrity.  As mentioned before, instead of updating and inserting at the database, use the public API for the application (Redmine's API for issues for example).

The extent of the business logic and the integration points are something that needs to be examined before jumping off and doing it. Which way does the data flow (both ways gets very interesting at times) and what data flows. Are you copying issues into bugs once they reach a certain state? How do you keep track to make sure you don't create the same issue again and again (need to update the data model of the bug tracking system)? What happens when an issue is marked as closed in a bug tracking system - does that flow back?

All in all, its probably simplest to try to use the same system and manage the permissions / customize it so that it works the way you want it to if it is not critically bad if some bit of knowledge from the developers leaks out.


答:
There is one more issue with using strings as keys, or more accurately, using string literals as keys, setting aside pure performance/efficiency reasons. Typos. If you use string literals as keys in a dictionary, you're setting yourself up for a nasty surprise when one "ReceiverId" becomes a "RecieverId". Set up constants to store the key values and reuse them whenever you access the dictionary.

Trivial and obvious, you can say, yet a stunning number of .NET code examples around the web uses string literals, propagating this dubious practice. ASP.NET with all the Sessions, ViewStates and QueryParams strewn across the codebase is particularly guilty here.

Title: Why is the usage of string keys generally considered to be a bad idea?

Body:
This has been bugging me for a while. Most of the time, when it comes to storing data in structures such as hashtables, programmers, books and articles insist that indexing elements in said structures by String values is considered to be bad practice.
Yet, so far, I have not found a single such source to also explain WHY it is considered to be bad practice.
Does it depend on the programming language? On the underlying framework? On the implementation?

Take two simple examples, if it helps:

An SQL-like table where rows are indexed by a String primary key.

A .NET Dictionary where the keys are Strings.


答: It sounds like what you need is equivalent to doing a 'diff' on two files. There are many ways to do this, but I'd look into Google's diff-match-patch algorithm.</p>

Title: Index independent character comparison within text blocks

Body:
I have the following task:  developing a program where there is a block of sample text which should be typed by user.  Any typos the user does during the test are registered.  Basically, I can compare each typed char with the sample char based on caret index position of the input, but there is one significant flaw in such a "naive" approach.  If the user typed mistakenly more letters than a whole string has, or inserted more white spaces between the string than should be, then the rest of the comparisons will be wrong because of the index offsets added by the additional wrong insertions.

I have thought of designing some kind of parser where each string (or even a char ) is tokenized and the comparisons are made "char-wise" and not "index-wise," but that seems to me like an overkill for such a task.  I would like to get a reference to possibly existing algorithms which can be helpful in solving this kind of problem.


问:
Software agreement for farming out development work
I'm looking for guidance from someone who has successfully hired a freelancer to assist with writing software they later marketed publicly. Simply, what kind of software agreement should I have the freelancer sign so I have full rights over the code and cannot be sued later. I'm currently independent but have plans to launch a software company once I've perfected my software products. </p>

答:
As a former lawyer, and as someone who sometimes hires contractors, I'd say you have two broad concerns in this type of arrangement:

Intellectual property

Confidentiality

As to 1) you're generally going to want a perpetual, royalty-free assignment in full of all copyrightable material, patentable concepts & ideas, potential trade-secrets, or any know-how that the person obtains or creates while working for you. Additionally you'll want to prohibit them from using any creations created for you for any other purpose, including from creating derivative works without your permission, or after the term of the contract is over. Sometimes, I also see these contracts try to tie up anything these guys create that could arguably have something to do with their work for you or that has stemmed from anything they've done for you. There may be other things I'm not remembering and there are probably better ways to word these things that legitimate lawyers have spent days poring over to get the wording just right.

As to 2) You want them to make clear that anything you reveal to them about your business or product(s) that isn't public knowledge, including the stuff they create for you, is to be deemed confidential and can be used by them for no purposes other than completing the job they are given, and can't be disclosed for any reason other than as required by law. Additionally they generally have to return all materials (including digital "materials") to you when the job is done and destroy their own copies. If you're worried about it you can throw some non-competition language in there if you're worried they'll go into business against you based on stuff they figure out while working for you (this includes elements of both ownership and confidentiality, and overreaches are unenforceable.) Once again, there may be other concepts around the fringe here, but that's the basic gist.

These are off the top of my head, and this isn't legal advice... either get a lawyer to draft you a contract, pay for a contract from something like LegalZoom, roll the dice with stuff you can find on the internet (or your own hybrid of stuff), or try your hand at drafting your own. I've never never heard of anyone suing someone else for copying their contract, but I'm sure there's probably a case to be made that contracts themselves are copyrighted.

Good contracts are structured like well-written code: easy to read & understand without outside context, cleanly organized, and soundly logical. Most are not well-written. Knowing what bases need to be covered is the tricky part.