答:
Static type systems are all about preventing incorrect uses of data.

There are obvious examples of types doing this:

you can't get the month of a UUID

you can't multiply two strings.

There are more subtle examples

you can't pay for something using the length of desk

you can't make an HTTP request using someone's name as the URL.

We may be tempted to use double for both  price and length, or use a string for both a name and a URL. But doing that subverts our awesome type system, and  allows these misuses to pass the language's static checks.

Getting pound-seconds confused with Newton-seconds can have poor results at runtime.

This is particularly a problem with strings. They frequently become the "universal data type".

We are used to primarily text interfaces with computers, and we often extend these human interfaces (UIs) to programming interfaces (APIs). We think of 34.25 as the characters 34.25. We think of a date as the characters 05-03-2015. We think of a UUID as the characters 75e945ee-f1e9-11e4-b9b2-1697f925ec7b.

But this mental model harms API abstraction.

The words or the language, as they are written or spoken, do not seem to play any role in my mechanism of thought.

Albert Einstein

Similarly, textual representations should not play any role in designing types and APIs. Beware the string! (and other overly generic "primitive" types)

Types communicate "what operations make sense."

For example, I once worked on a client to an HTTP REST API. REST, properly done, use hypermedia entities, which have hyperlinks pointing to related entities. In this client, not only were the entities typed (e.g. User, Account, Subscription), the links to those entities were also typed (UserLink, AccountLink, SubscriptionLink). The links were little more than wrappers around Uri, but the separate types made it impossible to try to use an AccountLink to fetch a User. Had everything been plain Uris -- or even worse, string -- these mistakes would only be found at runtime.

Likewise, in your situation, you have data that is used for only one purpose: to identify an Operation. It shouldn't be used for anything else, and we shouldn't be trying to identify Operations with random strings we've made up. Creating a separate class adds readability and safety to your code.

Of course, all good things can be used in excess. Consider

how much clarity it adds to your code

how often it is used

If a "type" of data (in the abstract sense) is used frequently, for distinct purposes, and between code interfaces, it is a very good candidate for being a separate class, at the expense of verbosity.

Title: Should we define types for everything?


问:
What makes a program (in a language like C++) cross-platform or not?
I have fairly basic programming experience with Java and I've tried C++ and Python. While it makes sense for Java, the basic programs I've written in C++ have run just fine on Windows and OS X. I've been able to just send the source file to the other computer, compile, and run. The programs are fairly basic, mostly just basic object oriented stuff I've been doing to try to learn C++.

Obviously though, you can't just compile any C++ program on any machine and have it run fine. At what point does that happen? At what level of complexity does the platform start to matter and the program won't just run anywhere? Is it when you use platform specific libraries? Could a program be made cross platform in C++ just using cross platform libraries?

I've been trying to figure this out on my own but everything I've found either goes over my head or simply doesn't answer the question, much of what comes up are emulators or people asking what languages are cross platform.

答:
At what level of complexity does the platform start to matter and the
  program won't just run anywhere?

Basically anything non-trivial. If you write a non-trivial program, you will end up accidentally depending on a compiler-specific way that it orders overloads, looks up names, and other complex things. Furthermore, practically all non-trivial programs depend on non-Standard platform-specific behaviour because the Standard doesn't really provide anything except a few containers.

However, non-trivial programs can vary widely in how easy they are to port to another platform. If you programmed it well and stuck to the rules, you can port fairly easily, and bonus if you can abstract the pieces into a library (which may have already been provided for you, e.g. Boost.Filesystem).

Programs mostly only become very difficult to port between platforms if they perform tasks that are inherently platform-specific, for example, writing data to disk with certain atomicity/consistency guarantees, or, if you were a moron and went around doing stupid things that were never what you should have done in the first place, like casting between ints and pointers.

ContentLicense: CC BY-SA 3.0


答:
There is a very clear line in the sand between cross-platform and mono-platform:

Does a program use only those APIs exposed by the Standard Library it is built on?

If you target a standard implementation, then any platform that implements that standard should, in theory, compile and run your program correctly. There are plenty of exceptions, but in general if you avoid clever tricks you should be able to avoid many of those exceptions.

The reason why this issue comes up specifically with C++ is that for the longest time the C++ Standard Library did not include many modules that are useful for non-trivial programs. Concurrency and GUI are the two big ones. This meant that a program built using only the C++ Standard Library could not have many of the features we expect from modern software.

How do we write cross-platform software that does stuff the Standard Library does not support?

You mention "cross platform libraries," which in practice are normally called "frameworks" or "toolkits" based on their scope. The way to write software in C++ that is cross-platform is to target not only the Standard Library, but a framework that builds on your target platforms.

Essentially, you end up externalizing the platform-specific bits to another library. For example, wxWidgets is a popular framework. You can use its classes to construct a GUI and related functionality (e.g. standard dialogs for selecting files). Under the covers, it uses conditional compiling to implement the GUI using the native GUI for each platform. But as the user of the library, none of that matters to you.

Historical note: here in 2015 C++ compilers and libraries are, for the most part, really good. Go back a few years, and that is not true. C++ did not have an official standard until 1998, many years after its inception. It took vendors a long time to update their compilers and libraries to implement the standard correctly. Vendor-specific extensions abounded (and are still around, actually). Some compilers had nonstandard headers and functionality. Code portability was virtually nonexistent. C++'s reputation in terms of portability still suffers.

Title: What makes a program (in a language like C++) cross-platform or not?

Body:
I have fairly basic programming experience with Java and I've tried C++ and Python. While it makes sense for Java, the basic programs I've written in C++ have run just fine on Windows and OS X. I've been able to just send the source file to the other computer, compile, and run. The programs are fairly basic, mostly just basic object oriented stuff I've been doing to try to learn C++.

Obviously though, you can't just compile any C++ program on any machine and have it run fine. At what point does that happen? At what level of complexity does the platform start to matter and the program won't just run anywhere? Is it when you use platform specific libraries? Could a program be made cross platform in C++ just using cross platform libraries?

I've been trying to figure this out on my own but everything I've found either goes over my head or simply doesn't answer the question, much of what comes up are emulators or people asking what languages are cross platform.


答:
In very simple terms, what makes a program cross-platform is your ability to take the sources from one environment, compile them in another and have the finished product work as expected.

In less simple terms, it's having full overlap between what the program expects to be available and what your target environments provide.  Once you do anything that makes the overlap less than 100%, such as using an environment-specific library or a language feature with undefined behavior, you've tied your program to the environments(s) that can supply the non-overlapping features.

("Platform" is a bit of a squishy word.  People can talk about Windows and Unix as platforms or Linux, OS X, BSD and Solaris as platforms even though they're all nominally Unix.  Stir in running any of the above on different hardware architectures and things become even more nebulous.  Having said that, I'll start using the word.)

Fortunately, there are standards to ease this problem:

Languages.  You're writing C++, which was first standardized by the ISO in 1998.  Any program you write that conforms to that standard can be compiled and run with the expected results on any platform with a conforming compiler and runtime.  There's no limit to the size or sophistication of the program as long as it doesn't deviate from the standard.  If a program that provably meets the standard doesn't run as expected on a given platform, the implementation of the language on that platform becomes suspect.  Many languages have carefully-designed test suites that can be used to verify conformance.

Java gets a special mention because not only does it standardize a language, it also standardizes object code, which makes its programs runnable anywhere without recompilation.  This is accomplished by pushing the point of conformance down an additional layer into a platform-customized virtual machine (or even hardware) which is capable of running the object code.

APIs.  The calls you make to have your program do certain things can be standardized as well.  Like languages, these APIs and the libraries that implement them can be set up to behave as the callers expect using an underlying implementation suitable for a particular platform.  One such API is the IEEE's POSIX standards, which arose as a way to stem the fragmentation that was happening in Unix during the 1980s.  (I was around then; that aspect of it wasn't fun.)  By defining standard calls and behavior, system vendors could give their customers confidence that migrating to their OS wasn't going to entail huge amounts of work as it had in the past.  POSIX was widely adopted and is still in wide use almost 30 years later.

I've done numerous projects which slavishly adhered to the standards because I knew they were going to have to run on multiple platforms.  What I got for my troubles was code that worked everywhere I'd planned to run it and pleasantly surprised me on a few where I hadn't.


问:
Different license for logo files
I'm working on software that I intend to release under the terms of the GPL 3. However, I'd like to exempt the name and logo: the images with the logo should only be used with official releases, and only the official releases should be allowed to use the original project name. Forks should use a different name and logo to avoid confusion.

How do I specify this license modification in my project's documentation?

答:
Names and logos are actually covered by trademark law, not copyright law (in almost all cases). If you want to stop someone from passing a derivative off as your project, the solution is to enforce a trademark on the name and logo; trademark is all about preventing confusion between your product and other products, while copyright is about preventing someone from making an exact copy of your creative work. Furthermore, the name actually probably can't be copyrighted, and the logo may well not be copyrightable.

The GPL v3 actually explicitly supports this, assuming you're the sole copyright holder on the code or have permission from the other holders. Section 7 allows specific sorts of additional restrictions which are allowed if the copyright holders all agree; one such restriction is declining to grant trademark rights for various trademarks in the program. While a derivative would be allowed to contain your logo in its files, they couldn't use the logo or your name to identify the program. This seems to achieve your goals.

The relevant text from section 7 of the GPLv3 is as follows:

c) Prohibiting misrepresentation of the origin of that material, or
  requiring that modified versions of such material be marked in
  reasonable ways as different from the original version; or

e) Declining to grant rights under trademark law for use of some trade
  names, trademarks, or service marks; or

Title: Different license for logo files


问:
How do I customize Bootstrap?
I am a desktop programmer but currently I am trying to develop a website. I know HTML, CSS, Javascript and PHP but writing the complete code from scratch isn't encouraged and well, I end up with weird website which messes up from screen to screen.

I switched to Bootstrap but it is predefined. I mean, the container and jumbotron and everything else has predefined attributes.

How can I use the same element on one page and another with different attributes (height, width, color). Should I use in-style CSS for things I want to change or should I keep on making different .CSS files for every page.

For example; in the following code, I am using a container to show something but now I want two containers. The second one should be wider and have a different color and font. Should I use in-style CSS or should I just create a new selector giving it a new name "container-2".

```<code><div class="jumbotron" style = "background-color:#18bc9c">
  <div class="container">
    <h1>Hello, world!</h1>
    <p>Just a test</p>
    <p>Learn more »</p>
  </div>
</div>
</code>```

答:
You question is a bit of a broad/opinionated "What's the best way to manage the whole CSS thing?".

It's a great question, but I don't think there is a single answer. I feel like the question is ultimately, "How do you work with Bootstrap?"

Bootstrap is a front-end framework. Frameworks generally include a lot of features but, by their nature, are a structure to build upon.

I'll divide my answer into two parts, each for a different scenario. You might be either:

A small to medium business or hobby website with little customisation required.

A large business or complex website requiring heavy modification.

Small-scale

Examples: AussieOutages, {less}

You might easily get away with a CSS file or two to deal with all of these things. If you mostly use the built-in Bootstrap features, but occasionally need to resize or lightly restructure a component, just make a new CSS file and add in the requirements.

Personally, when I am using Bootstrap for light-modification use, I might use a CSS file called bootstrap-mod.css or bootstrap-custom.css.

The purpose of this file is to directly modify bootstrap components so that I have them all in a central location.

In another CSS file I might have classes the compliment native Bootstrap components without actually overriding anything. For example I might create a CSS class called btn-flashy. The new class doesn't override any CSS styling, but maybe adds a new hover effect to make a button flash.

Large-scale

This is for websites that take Bootstrap and make heavy modifications to the extent that they may not be recognisable as Bootstrap users on initial viewing.

Here you will be taking the Bootstrap source and using tools like Grunt and CSS extention languages like {less}.

How can I use the same element on one page and another with different attributes (height, width, color). Should I use in-style CSS for things I want to change or should I keep on making different .CSS files for every page.

Inline styling is frowned upon. Use CSS files. A page can have its own CSS file, but it might be overkill. Instead try to name classes in a meaningful way. For example, if you need to change heights, widths and colours for a component, follow Bootstrap's example by using my-component-lg, my-component-wide and my-component-bright etc.

Title: How do I customize Bootstrap?

Body:
I am a desktop programmer but currently I am trying to develop a website. I know HTML, CSS, Javascript and PHP but writing the complete code from scratch isn't encouraged and well, I end up with weird website which messes up from screen to screen.

I switched to Bootstrap but it is predefined. I mean, the container and jumbotron and everything else has predefined attributes.

How can I use the same element on one page and another with different attributes (height, width, color). Should I use in-style CSS for things I want to change or should I keep on making different .CSS files for every page.

For example; in the following code, I am using a container to show something but now I want two containers. The second one should be wider and have a different color and font. Should I use in-style CSS or should I just create a new selector giving it a new name "container-2".

```<code><div class="jumbotron" style = "background-color:#18bc9c">
  <div class="container">
    <h1>Hello, world!</h1>
    <p>Just a test</p>
    <p><a class="btn btn-success btn-lg" href="#" role="button">Learn more »</a></p>
  </div>
</div>
</code>```


问:
What's the most important feature of quality software?
This question is along the same lines as this one, but instead of talking about quality of code, I'm talking about the final product from the users' perspective. If you had limited time / budget, and could only guarantee one attribute of the software (other than the basic requirements) that take it from decent software to good quality software, what would you consider most important?

Is it having as few bugs as possible? An intuitive interface? Helpful error messages? Good technical support and documentation? If we don't want our software looking like cheap crap to our users, what should we always remember to include?

答:
I my mind quality is a measure of the amount of concerns of the stakeholders that are adressed by the software.

In general my definition maps prety well with the RUP definition.

RUP defines quality as:

satisfies or exceeds an agreed upon set of requirements

Assessed using agreed upon measures and criteria

produced using an agreed upon process.

ContentLicense: CC BY-SA 2.5


问:
Does an Rcpp-dependent package require a GPL license?
I'm writing a commercial package that uses R (GPL) for its computation. The GPL FAQ clearly states that GPLed programming language interpreters do not impose licensing restrictions on the "program" (text file with R code). So far, so good.

Part of the package is compiled using Rcpp, which also uses the GPL. The next paragraph in the FAQ reads:

However, when the interpreter is extended to provide "bindings" to other facilities (often, but not necessarily, libraries), the interpreted program is effectively linked to the facilities it uses through these bindings.

It can be interpreted that R is providing a binding to the Rcpp libraries (Rcpp.dll in the windows package). The safe assumption is that this taints my code with the GPL, but is this really the right conclusion?

Part of my uncertainty is the tightness of the link between my code and Rcpp.dll. There are references to Rcpp in the dll, but I'm not proficient enough to know if these are references to the development environment or to calls being placed to symbols within the Rcpp library. If the former, then I believe that the Rcpp library is being linked by R and not by my library. I suspect the latter, though, since Rcpp provides a glue (sugar, actually) to simplify code-writing and execution.

There are countless related discussions related to the GPL in code distribution. To name a few:

Inside a virtual machine

Exposure of intellectual property

Consequences of GPL dependencies

Using a GPL library in commercial software

NB: I'm generally a big supporter of OSS and have participated in development and distribution in the past. Questions of "protecting code" often raise hackles of open-source programmers, frequently resulting in heated debates over software philosophy. I recognize value on both sides and want to ensure that I'm meeting the letter and (if possible) spirit of the laws. I'm not fishing for a loop-hole in the license; I'm looking for help interpreting and placing it into context.

Are R packages that depend on Rcpp required to use the GPL?

答:
I believe that R packages that depend on Rcpp are not required to use GPL but rather to use a GPL-compatible license.

Reading the Rcpp-FAQ Section 1.5 clearly states that:

you are free to license your work under whichever terms you find suitable (provided they are GPL-compatible, see the FSF site for details).

That would mean that if one chooses to use for example the BSD-3-clause license he is perfectly fine to do so.

To add an important caveat: As Dirk has pointed out in the comments the aggregation of GPL-compatible licensed code and GPL-licensed code will have to be GPL-ed.  One can find in gnu.org a good explanation of what is an aggregate and what is not. Notice that when you release a package you distribute only your code, that is why you can use any GPL-compatible license and not exclusively GPL.


问:
Thinking pragmatically about scalability
I was recently asked as an exercise to design a scalable graph.

My first intuition was how to seperate the graph and distribute it (sharding,consistent hashing..etc)

Turns out my thinking was on the wrong line, I know what scalability is, but it seems it is a bit hard to think about it pragmatically.

What is the pragmatic way of thinking about scalability. I know I need high-availability, replication, fault tolerance, but what are some of the common patterns/paradigms needed to  implement these key points?

答:
Answer to this question can get very complicated if you need to support parallel requests while you need to split single request across multiple processing nodes.

There are 2 types of scaling,

Vertical

Horizontal

For Vertical scaling (adding more CPU power / adding more memory).

Since the operation happens in single process, one of the consideration is about how to distribute the operation into different threads and combine the results.

If parallel requests needs to be processed then concurrency is also comes into play. And if the single graph is modified by multiple parallel requests this could very complicated, and you may need to think about a scenario like this,

If the graph has Node A,B and C where C has links to both A and B,
  and parallel requests wants to change A and B, then concurrency issue
  happens on C. One way to sort it is to determine which nodes are
  affected by each request and queue the conflicting requests, or just
  to merge the changes. But this depends on your graph

For Horizontal scaling (happens in multiple processes in different physical processing nodes), and when it comes to the graph processing you can improve processing in different ways,

1. Split your request across processing nodes to improve performance (load balancing) where one request is processed by one node

and the requirements are,

Store your object graph in a persistent storage such as a database so
that each processing node can read it.

Locking of the sections in the persistent storage based on the graph (similar to parallel requests of the single process) so that parallel writes does not happen and hence the graph is not getting stuffed.

2. Split request across nodes so that given request is processed by multiple processing nodes

All the steps done for the load balancing

Split the processing into multiple sections, and distribute over the different processing nodes

Combine the results of the results once the processing is completed


答:
Basically, when you 'touch' stuff outside your program. One particular case (I don't dare to say the only case) is when you use libraries related to the operating system. Things like using shared memory between process and printing fancy things on the console.  In the first case you access a piece of memory being handled by the operating system, in the second case the screen is also controlled by the operating system.

Doing a GUI is OS dependent, but there are GUI libraries made to be cross-platform, so you don't have to worry about that. At least in theory.

Is difficult to make anything non-trivial to be cross-platform. The good new is that if you use the right libraries and do proper testing is not that difficult to make software portable, at least if the code is not too big. How big is too big depends on your team's size, programming expertise, and so on.


问:
Predicting the output of PHP's rand()
I've read in numerous sources that the output of PHP's rand() is predictable as its a PRNG, and I mostly accept that as fact simply because I've seen it in so many places.

I'm interested in a proof-of-concept: how would I go about predicting the output of rand()? From reading this article I understand that the random number is a number returned from a list starting at a pointer (the seed) -- but I can't imagine how this is predictable.

Could someone reasonably figure out what random # was generated via rand() at a given moment in time within a few thousand guesses? or even 10,000 guesses? How?

This is coming up because I saw a auth library which uses rand() to produce a token for users who have lost passwords, and I assumed this was a potential security hole. I've since replaced the method with hashing a mixture of openssl_random_pseudo_bytes(), the orignal hashed password, and microtime. After doing this I realized that if I were on the outside looking in, I'd have no idea how to guess the token even knowing it was a md5 of rand().

答:
To visually illustrate how non-random the rand()function is, here is an image where all pixels are made of "random" red, green and blue values:

There normally shouldn't be any pattern in the images.

I've tried calling srand() with different values, it doesn't change how predictable this function is.

Note that both aren't cryptographically secure and produce predictable results.

Title: Predicting the output of PHP's rand()


问:
Should we define types for everything?
Recently I got into a problem with the readability of my code.

I had a function that did an operation and returned a string representing the ID of this operation for future reference (a bit like OpenFile in Windows returning a handle). The user would use this ID later to start the operation and to monitor its finish.

The ID had to be a random string because of interoperability concerns. This created a method that had a very unclear signature like so:

public string CreateNewThing()
```

<p>This makes the intent of the return type unclear. I thought to wrap this string in another type that makes its meaning clearer like thus:</p>

<pre class="lang-cs prettyprint-override"><code>public OperationIdentifier CreateNewThing()
</code>```

The type will contain only the string and be used whenever this string is used.

It's obvious that the advantage of this way of operation is more type safety and clearer intent, but it also creates a lot more code and code that isn't very idiomatic. On the one hand I like the added safety, but it also creates a lot of clutter.

Do you think it is a good practice to wrap simple types in a class for safety reasons?

答:
Idea behind wrapping primitive types,

To establish domain specific language

Limit mistakes done by users by passing incorrect values

Obviously it would be very difficult and not practical to do it everywhere, but it's important to wrap the types where required,

For example if you have the class Order,

Order
{
   long OrderId { get; set; }
   string InvoiceNumber { get; set; }
   string Description { get; set; }
   double Amount { get; set; }
   string CurrencyCode { get; set; }
}
```

<p>The important properties to look up an Order is mostly OrderId and InvoiceNumber. And the Amount and CurrencyCode are closely related, where if someone change the CurrencyCode without changing the Amount the Order no longer can be considered as valid.</p>

<p>So, only wrapping OrderId, InvoiceNumber and introducing a composite for currency makes sense in this scenario and probably wrapping description makes no sense. So preferred result could look like,</p>

<pre class="lang-cs prettyprint-override"><code>    Order
    {
       OrderIdType OrderId { get; set; }
       InvoiceNumberType InvoiceNumber { get; set; }
       string Description { get; set; }
       Currency Amount { get; set; }
    }
</code>```

So there is no reason to wrap everything, but things that actually matters.

Title: Should we define types for everything?

Body:
Idea behind wrapping primitive types,

To establish domain specific language

Limit mistakes done by users by passing incorrect values

Obviously it would be very difficult and not practical to do it everywhere, but it's important to wrap the types where required,

For example if you have the class Order,

Order
{
   long OrderId { get; set; }
   string InvoiceNumber { get; set; }
   string Description { get; set; }
   double Amount { get; set; }
   string CurrencyCode { get; set; }
}

The important properties to look up an Order is mostly OrderId and InvoiceNumber. And the Amount and CurrencyCode are closely related, where if someone change the CurrencyCode without changing the Amount the Order no longer can be considered as valid.

So, only wrapping OrderId, InvoiceNumber and introducing a composite for currency makes sense in this scenario and probably wrapping description makes no sense. So preferred result could look like,

    Order
    {
       OrderIdType OrderId { get; set; }
       InvoiceNumberType InvoiceNumber { get; set; }
       string Description { get; set; }
       Currency Amount { get; set; }
    }

So there is no reason to wrap everything, but things that actually matters.


问:
Is jQuery an example of "god object" antipattern?
I want to ask – I am slowly learning jQuery.

What I see is an exact example of a God Object anti-pattern. Basically, everything goes to the $ function, whatever it is.

Am I right and is jQuery really an example of this anti-pattern?

答:
$ is not an object, it's a namespace.

Would you call java.lang a god object because of the many classes it contains? It's absolutely valid syntax to call java.lang.String.format(...), very similar in form to calling anything on jQuery.

An object, in order to be a god object, has to be a proper object in the first place - containing both data and the intelligence to act upon the data. jQuery only contains the methods.

Another way to look at it: a good measure for how much of a god object an object is is cohesion - lower cohesion means more of a god object. Cohesion says ow much of the data is used by how many of the methods. Since there's no data in jQuery, you do the math - all methods use all the data, so jQuery is highly cohesive, thus not being a god object.


问:
Efficient range search for pair of numbers
Assume we have large list of pairs:

```<code>struct {x: double, y: double} pair;
vector<pair>
</code>```

What is the most effective way to find all pairs where (x1 < x < x2) AND (y1 < y < y2)?

O(n) is not acceptable, sorting by one variable and scanning another does not look good too.

Preprocessing is acceptable so trading additional memory for performance is OK

答:
I'm assuming you want low amortized cost, i.e. preprocessing is acceptable.

You're trying to find a data item with  specific property. Don't be misled by the fact that the property is expressed as four different numeric comparisons. It's really a property of the entire item. That means you need to sort your data according to a measure that takes all conditions into account and then search for the combined measure first.

In this instance, looking for a pair with 10 < x < 12 and 3 < y < 5 means looking for a pair where 13 < x+y < 17. You could just sort your list of pairs y their sum and quickly find all candidates that satisfy the combined condition.

Not all of them satisfy the individual conditions, but you can define a secondary sort criterion that takes e.g. the x value into account. This is often good enough that you can get by with the standard sorting an earching algorithms, without defining task-specific two-dimensional linked data structures.

(Note that whether that's fast enough for your purposes depends on what your purposes are. It's entirely possible that you do need more complicated preprocessing to meet your business goal. But in general I think it's often better to tweak existing, simple algorithms than to introduce a task-specific one, if only because standard library sorts and searches are likely to be tuned much better than you could do it yourself.)


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答:
I look for a couple of things in candidates that I have interviewed. For reason I can't describe online, we get pretty poor candidates, and I've come to expect it, so I'm pretty easy on them. Even still, I look for:

Awareness of design.

"Show me the table structure for an address book program that has Contacts with first and last names that can have multiple Phone Numbers with a description of the number (cell/home/work/etc.)"

I'm not looking for a UML 2.0 spec diagram here, a simple bubble diagram here is fine. As long as it's reasonable.

Knowledge of working with a database (ie. SQL)

Write a query to get all of the phone numbers for people with the last name "smith"

Write a query to get all of the customers in the database, and the phone numbers for the ones with the last name "smith"

Knowledge of testing

Assume a method with the signature public IEnumerable<PhoneNumber> GetPhoneNumbers(string lastName) exists that returns the results of your query from earlier. Assume that if you pass a null into the method, it throws a NullReferenceException. Write a test to demonstrate this functionality.

Write a test that demonstrates that GetPhoneNumbers will return a home phone number of (123)456-7890 for someone with the last name "smith".

Knowledge of how to write some code

Implement a method that will fulfill the requirements of the tests you wrote.

Considering the number and quality of the applicants we've gotten, I've interviewed everyone who's ever seriously applied. I've hired no-one.


问:
Why does C provide language 'bindings' where C++ falls short?
I recently was wondering when to use C over C++, and vice versa? Fortunately someone already beat me to it and although it took a while, I was able to digest all the answers and comments to that question.

However one item in that post keeps being addressed again and again, without any kind of example, verification or explanation:

"C code is good for when you want to have multiple language bindings for your library"

That's a paraphrase. I should note that several people point out that multiple language bindings are possible in C++ (via some extern functioning), but nevertheless, if you read that post in its entirety, it's pretty obvious that C is ideal for portability/language binding. My question is: why?

Can someone please provide concrete reasons why writing libraries in C allows for easier bindings and/or portability in other languages?

答:
There is no reason. If the semantics you're trying to express are fundamentally C-compatible and not something like templates, there is no reason you can bind easier if the implementation is written in C. In fact, it's pretty much by definition that a C interface can be filled out by any implementation that can meet the binary contract- including an implementation in another language. There are languages other than C++ that can implement C binary contracts that can work in this fashion.

What it really boils down to is people who don't want to learn new languages or ideas that have actually useful semantics or features desperately trying to pick any reason to stay in the dinosaur era.


答:
C has a much, much simpler interface, and its rules for converting a source code interface into a binary interface are straightforward enough that generating external interfaces to bind to is done in a well-established manner.  C++, on the other hand, has an incredibly complicated interface, and the rules for ABI binding are not standardized at all, neither formally nor in practice.  This means that pretty much any compiler for any language for any platform can bind against an external C interface and know exactly what to expect, but for a C++ interface, it's essentially impossible because the rules change depending on which compiler, which version, and which platform the C++ code was built with.

In C, there's no standard binary language implementation rules,
  either, but it's an order of magnitude simpler and in practice
  compilers use the same rules. Another reason making C++ code hard to
  debug is the above-mentioned complicated grammar, since debuggers
  frequently can't deal with many language features (place breakpoints
  in templates, parse pointer casting commands in data display windows,
  etc.).

The lack of a standard ABI (application binary interface) has another
  consequence - it makes shipping C++ interfaces to other teams /
  customers impractical since the user code won't work unless it's
  compiled with the same tools and build options. We've already seen
  another source of this problem - the instability of binary interfaces
  due to the lack of compile time encapsulation.

-- Defective C++

Title: Why does C provide language 'bindings' where C++ falls short?

Body:
I recently was wondering when to use C over C++, and vice versa? Fortunately someone already beat me to it and although it took a while, I was able to digest all the answers and comments to that question.

However one item in that post keeps being addressed again and again, without any kind of example, verification or explanation:

"C code is good for when you want to have multiple language bindings for your library"

That's a paraphrase. I should note that several people point out that multiple language bindings are possible in C++ (via some extern functioning), but nevertheless, if you read that post in its entirety, it's pretty obvious that C is ideal for portability/language binding. My question is: why?

Can someone please provide concrete reasons why writing libraries in C allows for easier bindings and/or portability in other languages?


问:
Ideas for scraping a home-brewed Php-powered bug system
I work at a large company, and we are stuck with a crappy home-baked bug tracking tool, which does too many things half-decently, but it search functionality is next-to-impossible to use (has about 80 fields that one has to / can fill out) and the search needs to be precise. We have many duplicate bugs filed that are never consolidated, plus pulling up all bugs filed against some product in some version just will not be easy AT ALL.

Getting rid of the current system is a political and strategical impossibility. Hundreds of people are tied into it. What I am hoping to do it iterate over bugs 1 through however many (there is a way, I believe) and then save the resulting HTML pages named 'bug000001.html', 'bug000002.html', etc. After that I would want some sort of Google-Style full text indexing going. What we have is so bad, that doing this would be worthwhile. Bugs do not change that much over time, so I am not that worried about being out-of-sync with the original - it will not be great.

So, my question is: suppose I have downloaded the html files in the same folder. What free and open source tool can I use then that would allow fuzzy search on the content? I realize that I can concoct a specific regex every time I search that would probably do the task, but I would like to make this even easier, where mis-spellings do not hurt. I realize that Google's full power of personalized, history-based search will probably not be accessible to me, but I will gladly settle for something close, that is free and easy to use.

If you have suggestions for a good free and open source tool/Python library that I can use to automate simple browser actions, such as entering text into a textbox, clicking the button and then saving the content into an HTML file, then please list that as well, although that probably should be a separate question.

EDIT I do not have access to the source code for PhP front end or back end; this is all locked away by socialists on another continent.

答:
Can you get access to database your internal bugtracker uses? Or does it have some API? If no to both questions, you can write API yourself by emulating GET/POST requests and parse resulting HTML. Or by using selenium.

Then get your favorite bugtracker that uses documented DB schema (i believe most do) and do ETL.


问:
I believe my solution is better than my boss's, so should I ignore him?
I'm working with php and sql.

I think that my method of implementing functions is better than what my boss proposes. Just now he explained me how to do a check on a list of email addresses, and I do not like his idea. I proposed mine which is better and quicker to implement, but he disagreed.

Now I think I will go ahead and implement my idea, because his idea was not clear enough to me. Do you think he will be mad?

答:
Your bosses job isn't to program better to you, it's to manage you. So putting aside the fact that given his apparent programming background and that he may know reasons why your solution isn't the best - show him you can take direction and he'll trust you more down the track when you come to him with better solutions.

I can almost guarantee it's your approach to telling him why he's wrong (what about saying how we can do it better?) that's stopping you from being heard.

... not to say there aren't real inexperienced dicks out there :)


答:
What you are looking for is called a Spatial Index.

In your case, you are looking for simplest case of getting all 2D points inside a rectangle. Even simple quad tree should be great improvement if you have lots of points.

The problem of those kind of indexing algorithms and structures is that they are highly dependent of shape of the data. While they all have nice theoretical complexity, it would be best if you invested some time into trying different algorithms, so you find one that best fits your real-world data.

Title: Efficient range search for pair of numbers

Body:
Assume we have large list of pairs:

```<code>struct {x: double, y: double} pair;
vector<pair>
</code>```

What is the most effective way to find all pairs where (x1 < x < x2) AND (y1 < y < y2)?

O(n) is not acceptable, sorting by one variable and scanning another does not look good too.

Preprocessing is acceptable so trading additional memory for performance is OK


问:
Azure table storage and SQL
I am in the middle of an architectural decision that down the line will be important.

I have a system where I use ATS (Azure Table Storage) as the store for simple and very little data. It's not written to, too often and it's not read to, too often.

Now I need to read/write data based on these ATS data. A lot of data. But I will not read the data in ATS before I write the "other" data.

My concern is that I cannot read the data fast enough from ATS, based on the needs I have. E.g I need to count rows fairly fast to give the users feedback, and count is not a function within ATS. I could gain something from the CQRS "pattern" but I would still need to count rows! And I am not looking for a solution where I need to add complexity to overcome a very simple thing on another platform (SQL).

So my thought is to save these data inside a SQL database where I also have all the data manipulation-features I need. But I would miss out on the scalability and end up maintaining that instead of an easy scalable datastore like ATS. And the data I am writing here is very simple, but it's a lot.

I would like to stay with ATS only but I would need a pattern to get around these limitations. Any ideas ?

Thanks!

答:
Is consistency important? If you consider saving data in SQL, why not go with SQL all the way?

Anyways... aggregate functions like count is not a feature of Table Storage, so you either need to fetch all rows and count "client side" (can be very slow), or figure out a way to cache the "count" in another entity. It really depends on your data and architecture, and sometimes this is not possible to select a good PartitionKey strategy.

You could also look at Lucene, Azure Search, Hadoop, which is optimized for reading. However, consistency is a problem.

We build a rather large architecture using table stores as a read/write/update solution, and to be honest, I will not recommend it. Table storage is great for write once scenario and solutions where performance is not an issue. But building a relational structure where performance is important is tuff. If you need to make queries where you receive more than 1000 rows you should make a design where you can query in parallel. And you should then expect 1+ second for queries, even if you query by partition key.

Table storage is really only fast if you make single entry lookup by PartitionKey and RowKey.

But yes, Table Storage scales well, even under load. But it comes with a price.

Title: Azure table storage and SQL


问:
Detect or Prevent Screen Capture Applications
I am building an app that displays very sensitive information and as such, I want to be able to either

Disable the ability to capture the screen

Redact the portion of my app that is on the screen during capture

Detect that a screen capture was made via an event, hook, log etc

Are any of the above even possible in Windows? if so, how?

UPDATE I have tried checking the windows event log for screen captures. I have searched for all over the web and I could not find any windows hooks that could do that. Any ideas would be highly appreciated

Context: There are two entities. An regular user (User A) who wants to use my app and a third party (User B) who has access to the machine before User A uses it. The intention of User B is steal the sensitive information using screen capture software during User A's session. So using VMs or anything that requires the current user's explicit action is not included

答:
I believe your best option is to permanently disconnect that particular computer from the Internet.

That way, even if a program did capture your screen of log your keyboard, then it will not be able to send it anywhere as there's no connection.

Of course, you should also disconnect from the network as well unless it's necessary to be connected and you are sure that all the computers on the network are disconnected from the Internet at all times.

This is the safest way so far.

P.S. If you need to access the Internet, then acccess from on a computer that has no sensitive information on it.


答:
If you're trying to communicate with a speaker of another language, pidgin is easier than Shakespearean English.

C's concepts - function calls, pointers, NULL-terminated strings - are very straightforward, so other languages can easily implement them well enough to call C functions. For historical reasons, many other languages are implemented in C, which makes calling C functions even easier.

C++ adds quite a bit of stuff - classes, with inheritance and vtables and access modifiers; exceptions, with stack unwinding and changing the flow of control; templates. All of this makes it harder for other languages to use C++ bindings: at best, there's more "glue" or interoperability code to implement, and at worst, the concepts don't translate directly (due to differences in class models, exception handling, etc.). For templates in particular, simply using (instantiating) them typically requires a compilation step with a C++ compiler, which vastly complicates using them from other environments.

With all of that said, it's possible to overstate the difficulty of providing bindings from a C++ library to another language:

C++ bindings can be just as compatible as C, if you're willing to work at it. As @DeadMG points out, C++ supports extern "C", so you can export C-style language bindings (with all of the simplicity and compatibility of C bindings) from a C++ library (with the limitation that you can't expose any C++-specific functionality).

Another common objection to C++ language bindings is the lack of ABI stability for C++, but this too is overstated; C++ ABIs are less standardized than C ABIs, but standards and de facto standards do exist (the Itanium C++ ABI, which is also used on OS X; GCC's de facto standard for Linux). Windows is worse, but even on Windows, staying within one Visual C++ version should work fine.


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答:
When a key developer on a project hasn't checked in any code for weeks and a serious milestone is coming up.

It was a contracting job and the more senior developer and PM on the job decided they wanted to team up to try to get a bigger cut so the other developer held 3 weeks of critical code hostage. In the end, we fired the incompetent PM (who had been spending 6 months putting the project on a course for ruin) and talked things out with the developer.

Suffice to say, the rest of the project was a masochistic death march, the spec freezing was delayed, the customer was given a bunch of concession features to make up for the terrible scheduling the PM left the project, and the quality of the project suffered all around because of it.

The PM even had the nerve to fly down for CDR (Critical Design Review) only to ditch the meeting with the client and throw a hissy fit. When he demanded that his travel expenses be paid for under the project he was politely told to go fornicate with himself.

I can easily identify with at least 5 of the other answers found here that affected that project. In short, I learned a lot of hard lessons on my first serious coding project.


答:
Yes he will be mad. So I'd advise you to email him a reason why your method is better. And ask him for an approval for going ahead with your method. My point of "email" is to ensure you list down and collate all your reasons before going into any further discussion.

Try wording it as "I trust this method suits the project/issue" - so unless he has a better way, he should go with you.

If you are really sure and have enough ammo to support your view, go with "I trust this method suits the project/issue because of 1,2,3.. reasons"

One more personal advise - saying "I am better than my boss" comes across as a bit arrogant, I understand you might be angry right now - but in a professional context this wont be well appreciated. Hope your boss doesnt read this post ;)

Title: I believe my solution is better than my boss's, so should I ignore him?

Body:
I'm working with php and sql.

I think that my method of implementing functions is better than what my boss proposes. Just now he explained me how to do a check on a list of email addresses, and I do not like his idea. I proposed mine which is better and quicker to implement, but he disagreed.

Now I think I will go ahead and implement my idea, because his idea was not clear enough to me. Do you think he will be mad?


答:
Leaving out the details other answers already provide:

The reason so many languages provides a C binding is that all *nix and Windows operating systems expose most of their OS API via a C interface. So the language implementation already needs to interface with C to be able to run on the major Oses. Therefore, it is straightforward to also offer directly communicating with any C interface from the language itself.


答:
I generally agree that many times you should create a type for primitives and strings, but because the above answers recommend creating a type in most cases, I'll list a few reasons why/when not to:

Performance. I must refer to actual languages here. In C#, if a client ID is a short and you wrap it in a class - you've just created a lot of overhead: memory, since it's now 8 bytes on a 64 bit system and speed since now it's allocated on the heap.

When you make assumptions on the type. If a client ID is a short and you have some logic that packs it in some manner - you usually already make assumptions on the type. In all those places you now have to break the abstraction. If it's one spot, it's not a big deal, if it's all over the place, you might find that half the time you're using the primitive.

Because not every language has typedef. And for languages that don't and code that's already written, making such a change could be a big task that might even introduce bugs (but everyone has a test suite with good coverage, right?).

In some cases it reduces readability. How do I print this? How do I validate this? Should I be checking for null? Are all questions that requires you drill into the definition of the type.

Title: Should we define types for everything?

Body:
Recently I got into a problem with the readability of my code.

I had a function that did an operation and returned a string representing the ID of this operation for future reference (a bit like OpenFile in Windows returning a handle). The user would use this ID later to start the operation and to monitor its finish.

The ID had to be a random string because of interoperability concerns. This created a method that had a very unclear signature like so:

public string CreateNewThing()
```

<p>This makes the intent of the return type unclear. I thought to wrap this string in another type that makes its meaning clearer like thus:</p>

<pre class="lang-cs prettyprint-override"><code>public OperationIdentifier CreateNewThing()
</code>```

The type will contain only the string and be used whenever this string is used.

It's obvious that the advantage of this way of operation is more type safety and clearer intent, but it also creates a lot more code and code that isn't very idiomatic. On the one hand I like the added safety, but it also creates a lot of clutter.

Do you think it is a good practice to wrap simple types in a class for safety reasons?


问:
Class Duplication Pattern?
I'm currently working as a solo developer on my current project. I inherited the project from another developer, who has since left the company. It's a model-view-controller style web application in C#. It uses Entity Framework for object relational mapping. And there are two different sets of classes for the types in the domain model. One set is used for interacting with the ORM and the other is used as the models in the MVC system. For example, there might be two classes as follows:

```<code>public class Order{
    int ID{get;set;}
    String Customer{get;set;}
    DateTime DeliveryDate{get;set;}
    String Description{get;set;}
}
</code>```

and

```<code>public class OrderModel{
    String Customer{get;set;}
    DateTime DeliveryDate{get;set;}
    String Description{get;set;}
    public OrderModel( Order from){
        this.Customer= from.Customer;
        // copy all the properties over individually
    }
    public Order ToOrder(){
        Order result =new Order();
        result.Customer = this.Customer;
        // copy all the properties over individually
    }

}
</code>```

I can think of several drawbacks to this approach (more places to change code if something changes, more objects  sitting around in memory, more time spent copying data around), but I'm not really sure what the advantages are here. More flexibility for the model classes, I suppose? But I could get that by subclassing the entity classes as well. My inclination would be to merge these two class groups, or possibly have the model classes be subclasses of the entity classes. So am I missing something important here? Is this a common design pattern I'm not aware of? Are there good reasons not to go through with the refactor I'm contemplating?

UPDATE

Some of the answers here are making me realize my initial description of the project was lacking some important details. There is also a third group of classes that exist in the project: the page model classes. They are the ones actually being used as the model backing the page. They also contain information that is specific to the UI, and would not be stored with an order in the database. An example page model class might be:

```<code>public class EditOrderPagelModel
{
    public OrderModel Order{get;set;}
    public DateTime EarliestDeliveryDate{get;set;}
    public DateTime LatestAllowedDeliveryDate{get;set;}
}
</code>```

I totally see the utility of this third group being distinct here, and have no plans to be merging it with something else (though I might rename it).

The classes in the model group are also currently used by the application's API, which I'd also be interested in hearing input on whether that is a good idea.

I should also mention that the customer being represented as a string here was to simplify the example, not because it's actually being represented that way in the system. The actual system has the customer as being a distinct type in the domain model, with its own properties

答:
So am I missing something important here?

YES

While these look like the same thing, and represent the same thing in the domain, they are not the same (OOP) objects.

One is the Order as known by the data storage part of the code. The other is the Order as known by the UI. While it's a pleasant coincidence that these classes have the same properties, they're not guaranteed to.

Or to take a look at it from another perspective, consider the Single Responsibility Principle. The key motivator here is that "a class has one reason to change". Especially when dealing with pervasive frameworks like an ORM and/or UI framework, your objects need to be well isolated since changes to the framework will often cause your entities to change.

By tying your entities to both frameworks, you're making it that much worse.

Title: Class Duplication Pattern?


答:
C is one of the oldest languages still around. Its ABI is simple, and virtually every operating system still in use today has been written in it. While some of those OS's may have added stuff e.g. in C#/.NET or whatever on-top, down below they're very much steeped in C.

That means that, in order to use the functionality provided by the OS, virtually every programming language out there needed a way to interface with C libraries anyway. Perl, Java, C++, they all natively provide ways to "talk C", because they had to if they didn't want to reinvent every single wheel there is.

This makes C the Latin of programming languages. (How many years of internet before that metaphor has to be "the English of progamming languages"?)

When you are writing your library in C, you get a C-compatible interface for free (obviously). If you are writing your library in C++, you can get C bindings, via extern "C" declarations as you mentioned.

However, you can get those bindings only for functionality that can be expressed in C.

So your library API cannot make use of...

templates,

classes,

exceptions,

any functions taking or returning objects.

One simple example, you would need to make your exported functions take and return arrays ([]) instead of std::vector (or std::string for that matter).

So, not only would you be unable to provide any of the good things C++ has to offer to your library's clients, you also would have to go to additional effort to "translate" your library API from C++ to "C compatible" (extern "C").

That is why the point could be made that C is the better choice for implementing a library. Personally, I think the benefits of C++ still outweigh the necessary effort for a extern "C" API, but that's just me.


答:
It's surely a quick and easy way to get fired.

My advice is to implement both and use the one your boss wants.

If there is a problem, tell him you have a fix, and show it to him, but don't tell him why you wrote it.


答:
The purpose of the View Model is to provide decoupling in two ways: by providing data in the shape that the View requires (independent of the model), and (especially in MVVM) by pushing some or all of the View logic back from the View to the View Model.

In a fully normalized model, Customer would not be represented in the Model by a string, but rather by an ID.  The Model, if it needs the name of the customer, would look up the name from the Customers table, using the CustomerID found in the Orders table.

A View Model, on the other hand, may be more interested in the Name of the customer, not the ID.  It has no need for the ID unless the Customer is being updated in the Model.

In addition, the View Model can, and usually does, take a different shape (unless it is pure CRUD).  An Invoice View Model object might have customer name, addresses and line items, but the model contains customers and descriptions.

In other words, invoices are normally not stored in the same way they are displayed.

Title: Class Duplication Pattern?

Body:
I'm currently working as a solo developer on my current project. I inherited the project from another developer, who has since left the company. It's a model-view-controller style web application in C#. It uses Entity Framework for object relational mapping. And there are two different sets of classes for the types in the domain model. One set is used for interacting with the ORM and the other is used as the models in the MVC system. For example, there might be two classes as follows:

```<code>public class Order{
    int ID{get;set;}
    String Customer{get;set;}
    DateTime DeliveryDate{get;set;}
    String Description{get;set;}
}
</code>```

and

```<code>public class OrderModel{
    String Customer{get;set;}
    DateTime DeliveryDate{get;set;}
    String Description{get;set;}
    public OrderModel( Order from){
        this.Customer= from.Customer;
        // copy all the properties over individually
    }
    public Order ToOrder(){
        Order result =new Order();
        result.Customer = this.Customer;
        // copy all the properties over individually
    }

}
</code>```

I can think of several drawbacks to this approach (more places to change code if something changes, more objects  sitting around in memory, more time spent copying data around), but I'm not really sure what the advantages are here. More flexibility for the model classes, I suppose? But I could get that by subclassing the entity classes as well. My inclination would be to merge these two class groups, or possibly have the model classes be subclasses of the entity classes. So am I missing something important here? Is this a common design pattern I'm not aware of? Are there good reasons not to go through with the refactor I'm contemplating?

UPDATE

Some of the answers here are making me realize my initial description of the project was lacking some important details. There is also a third group of classes that exist in the project: the page model classes. They are the ones actually being used as the model backing the page. They also contain information that is specific to the UI, and would not be stored with an order in the database. An example page model class might be:

```<code>public class EditOrderPagelModel
{
    public OrderModel Order{get;set;}
    public DateTime EarliestDeliveryDate{get;set;}
    public DateTime LatestAllowedDeliveryDate{get;set;}
}
</code>```

I totally see the utility of this third group being distinct here, and have no plans to be merging it with something else (though I might rename it).

The classes in the model group are also currently used by the application's API, which I'd also be interested in hearing input on whether that is a good idea.

I should also mention that the customer being represented as a string here was to simplify the example, not because it's actually being represented that way in the system. The actual system has the customer as being a distinct type in the domain model, with its own properties


问:
Why do methods that take an unlimited amount of parameters often define overloads with fewer parameters?
For instance, the System.IO.Path.Combine method in .NET has the following overloads:

```<code>Combine(params String[])
Combine(String, String)
Combine(String, String, String)
Combine(String, String, String, String)
</code>```

What is the point of the last three?

The first one would cover them all, as if you look closely, it uses the params keyword. The argument of backwards compatibility would only cover the Combine(String, String) variant, as it was the only version until .NET 4.

答:
Syntactic sugar.

When manipulating file paths, it is extremely common to have a small number of fixed values.  In these cases, it is more convenient to use them directly rather than having to package them into an array.


问:
gpl3 "or stated as exceptions"
At the end of section 7 of gpl v3:

7. Additional Terms

  ....

  Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.

In the top of the licence:

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

so: How should I understand "may be stated in the form of a separately written license, or stated as exceptions"? {[the form of a separately written license,] OR [stated as exceptions]} ? - so, "stated as exceptions" means "NOT the form of a separately written license" and so as exceptions in same licence file by modifying it? but additional terms MUST be only in separate file due to the "changing it is not allowed"?

or, "changing it is not allowed" does not mean changing file and allow putting licence in one file with other additional text? In that case "or stated as exceptions" means that the exceptions can be put in same text file with gplv3 licence itself's text, after it or before it?

答:
I was unable to find anything in the GPL FAQ that covers this, and the license itself does not say as far as I know.

What I do know is this:

The license must be verbatim, although the FSF do acknowledge that this "requirement" is not set in stone.

There is no requirement anywhere that I can find stating that the LICENSE documentation can only contain one license, or cannot have extra commentary or exceptions listed.

From a practical perspective the license must be self-contained. There is a convention in the open source world that license terms go in a file named LICENSE or COPYING in the root of your project. If you split license terms between files, it becomes plausible for someone to argue that they did not know about other license terms because you did not follow the convention.

What I would do is put all of the license details in a single file. I would keep the license text verbatim: if nothing else, these are legal documents crafted by lawyers who specialize in intellectual property law. Do you think your program would work correctly if a lawyer decided to "optimize" some loops? Do not mess with the licenses beyond the built-in exception mechanisms.

I have actually seen this. A LICENSE file says "my code is licensed using X, some third-party code I included in source folder Y uses license Z. I am modifying license X using exceptions A and B." Then list each license and the exceptions.

Disclaimer: I am a software engineer, not a lawyer. If you are ever in doubt, consult a lawyer who specializes in intellectual property law in your jurisdiction.

Title: gpl3 "or stated as exceptions"


答: The main reason is for performance. The "unlimited arguments" syntactical sugar is actually an array of Strings. If you are only passing one string, why create an array with only one string? Especially if ~90% of the invocations of this method will be with 3 or fewer arguments, there is no need for the heavier weight array object. It's a little lighter in memory and takes a little less processing time because you don't need a loop in order to define the method. If you have three strings, you just code for three strings.</p>

Title: Why do methods that take an unlimited amount of parameters often define overloads with fewer parameters?

Body:
For instance, the System.IO.Path.Combine method in .NET has the following overloads:

```<code>Combine(params String[])
Combine(String, String)
Combine(String, String, String)
Combine(String, String, String, String)
</code>```

What is the point of the last three?

The first one would cover them all, as if you look closely, it uses the params keyword. The argument of backwards compatibility would only cover the Combine(String, String) variant, as it was the only version until .NET 4.


答:
(Disclaimer: I only saw it being used in this way. I might have misunderstood the real purpose of doing so. Treat this answer with suspicion.)

Here is another missing bit: the conversion between Order and OrderModel.

The Order class is tied to your ORM, while the OrderModel is tied to the design of your View Model.

Typically, the two methods will be provide "in a magical way" (sometimes called DI, IoC,  MVVM, or yet another thing). That is, instead of implementing these two conversion methods as part of OrderModel, they will instead belong to a class dedicated to inter-conversion of these things; that class will be somehow registered with the framework so that the framework can easily look it up.

```<code>public class OrderModel {
    ...
    public OrderModel(Order from) { ... }
    public Order ToOrder() { ... }
}
</code>```

The reason for doing this is that whenever there is a crossing from the OrderModel to the Order or vice versa, you know that some data must have been loaded from or saved into ORM.

Title: Class Duplication Pattern?

Body:
(Disclaimer: I only saw it being used in this way. I might have misunderstood the real purpose of doing so. Treat this answer with suspicion.)

Here is another missing bit: the conversion between Order and OrderModel.

The Order class is tied to your ORM, while the OrderModel is tied to the design of your View Model.

Typically, the two methods will be provide "in a magical way" (sometimes called DI, IoC,  MVVM, or yet another thing). That is, instead of implementing these two conversion methods as part of OrderModel, they will instead belong to a class dedicated to inter-conversion of these things; that class will be somehow registered with the framework so that the framework can easily look it up.

public class OrderModel {
    ...
    public OrderModel(Order from) { ... }
    public Order ToOrder() { ... }
}

The reason for doing this is that whenever there is a crossing from the OrderModel to the Order or vice versa, you know that some data must have been loaded from or saved into ORM.


问:
What languages should I know if I'm interested in building web applications?
I'm interested in developing for the web and I'm curious what languages should I know besides html, css, javascript, php/python/ruby. I don't know much about c# or java to make a decision whether to learn them or not, are they used much in the field I'm interested in?
What other technologies should I look into ?</p>

答:
I think you should focus more on how to structure a well written website. That will follow all programming languages you'll ever learn. How should the site connect to the backend, what types of storage should you use?

Basically all programming langauges offer the same service, and most of them are so similar that once you learn enough you can quickly switch between them. Stop focusing on learning programming languages, they just come along for the ride. Focus on what it is you want to achieve.

OwnerDisplayName: webguy


答:
In some respect you are right: They both refer to the same domainobject, which is called order. But you are wrong in as far, it is not a real duplication than a different representation - originated from different purposes. If you want to persist your order, you e.g. want access to each and every column. But you do not want to leak that to the outside. Besides pushing whole Entities through the wire is not what you really want. I know of cases, where a collection of MBs of orders was shipped to the client where a few kb would be enough.

To make a long story short - here are the main reasons you want to do that:

1) Encapsulation - Information hiding of your application

2) Small Models are fast to serialize and easy to transmit

3) They serve different purposes, although the are overlapping, and therefore there should be different objects.

4) Sometimes it makes sense to have for different Queries different Value-Objects. I do not know how it is in C#, but in Java it is possible to use a POJO to collect results. If I need a single order I use the Order-Entity, but if I only need some columns filled with amounts on data, using smaller Objects is more efficient.

Title: Class Duplication Pattern?


答:
On the surface it looks like all you need to do is identify an operation.

Additionally you say what an operation is supposed to do:

to start the operation [and] to monitor its finish

You say it in a way as if this is "just how the identification is used", but I would say these are properties describing an operation.
That sounds like a type definition to me, there's even a pattern called the "command pattern" that fits very well..

It says

the command pattern [...] is used to encapsulate all information needed to perform an action or trigger an event at a later time.

I think this is very similar compared to what you want to do with your operations. (Compare the phrases I made bold in both quotes) Instead of returning a string, return an identifier for an Operation in the abstract sense, a pointer to an object of that class in oop for example.

Regarding the comment

It would be wtf-y to call this class a command and then not have the logic inside it.

No it wouldn't.
Remember that patterns are very abstract, so abstract in fact that they are somewhat meta. That is, they often abstract the programming itself and not some real world concept. The command pattern is an abstraction of a function call. (or method) As if somebody hit the pause button right after passing the values of the parameters and right before execution, to be resumed later.

The following is considering oop, but the motivation behind it should hold true for any paradigm. I like to give some reasons why placing the logic into the command can be considered a bad thing.

If you had all that logic in the command, it would be bloated and messy. You
would be thinking "oh well, all this functionality should be in
separate classes." You would refactor the logic out of the
command.

If you had all that logic in the command, it would be hard to test
and get in the way when testing. "Holy crap, why do I have to use
this command nonsense? I only want to test if this function spits
out 1 or not, I don't want to call it later, I want to test it now!"

If you had all that logic in the command, it wouldn't make too much
sense to report back when finished. If you think about a function to
be executed synchronously by default, it makes no sense to be
notified when it finishes executing. Maybe you are starting another
thread because your operation is actually to render avatar to cinema
format (may need additional thread on raspberry pi), maybe you have
to fetch some data from a server, ...whatever it is, if there's a
reason for reporting back when finished, it could be because there's
some asynchronousity (is that a word?) going on. I think running a
thread or contacting a server is logic that should not be in your
command. This is somewhat of a meta argument and maybe controversial. If you think it makes no sense, please tell me in the comments.

To recap: the command pattern allows you to wrap functionality
 into an object, to be executed later. For the sake of modularity (functionality exists regardless of being executed via command or not), testability (functionality should be testable without command) and all those other buzz words that essentially express the demand to write good code, you would not put the actual logic into the command.

Because patterns are abstract, it can be hard to come up with good real world metaphors. Here's an attempt:

"Hey grandma, could you please hit the record button on the TV at 12 so I don't miss the simpsons on channel 1?"

My grandma does not know what happens technically when she hits that record button. The logic is elsewhere (in the TV). And that's a good thing. The functionality is encapsulated and information is hidden from the command, it is a user of the API, not necessarily part of the logic ...oh jeez I'm babbling buzz words again, I better finish this edit now.

Title: Should we define types for everything?


答:
Depends on the person. If he's reasonable enough and you show him your solution and it is better, he won't probably be mad. But if he's not, then you're in trouble.

Now, for the non-generic bullshit part: He is your boss. He's not there to be a better programmer but to be a better manager/leader. Maybe he has reasons you haven't considered.

If you're a risk-taker, then go for it but don't be mad if you'll get fired. It's all a bet.


问:
How well am I writing my tests?
I've been coding as a career for about 2 years now but am just now writing my first "real" tests for a non-trivial application. I've been trying to follow best practices I've picked up from the internet here and there but I would like some feedback on whether I am heading in the right direction with what I am doing and what I can do to correct/improve my process.

The application is a headless API that will be seeing public (aka clients who want to integrate with our API, not totally public) consumption in a few months.

From top to bottom the stack and layers look like this:

RESTful API (JSON)

Oauth 2.0 authentication

(Mostly) CRUD controllers (PHP, Laravel 5)

Doctrine ORM for DAL

MySQL DB

I wanted to design my tests to be as simple but thorough as possible. However I don't have eternity and a day to write really fundamental test (unit tests I guess) for all controllers and all business logic so I decided to take advantage of laravel's built in mocking for routes and test all endpoints for our API.

My line of thinking is that, since we have standard data structures and formats for request/response (JSON, defined json schemas for objects, etc.) I could emulate requests knowing what the response should look like and compare the two.

EX. GET api/user/1 should return user 1 as a json object that I can compare for equality with the serialized json the actual object gives me.

So the actual testing looks like this (using PHPunit):

On application start Laravel sets the app environment to "testing" which changes the default DB connection to a SQLite file

On PHPunit boot Doctrine gets model metadata and creates tables for my domain in the DB, some extra scripts for extra-domain stuff (oauth tables) create those as well

Alice, an object generator for doctrine, creates a decently diverse set of domain entities with random data from Faker and hydrates the SQLite DB. All created entities are returned and I store these in a global variable for later use.

I make a copy of the hydrated, untouched DB to use in tests that involve write operations so I can reset the db after each test.

Oauth clients get generated for users with different roles so I can test oauth scopes and permissions across different users for each test

I use Laravel's route mocking to call each API endpoint and

For read-only tests (GETs) I use the json serialized form of objects stored earlier (step 3) to test the equality of responses,

For write tests I construct requests from our object json schemas, then build a real object that should equate it, make the request and then check the response for equality with the serialized form of the object (like step 7). After each write test the DB is overwritten with the original hydrated DB from step 4 for the next test.

So that's the gist of it. Using this approach has given me fantastic performance -- running 26 tests with 87 assertions takes ~12 seconds.

My questions/concerns

I don't mock anything. I feel like I'm doing something wrong because of this but at the same time I am actually providing a "real" environment for the whole application so nothing seems like it needs to be mocked. Is this okay?

Am I trying to do too much with each test? I've read articles that warn against having too many dependencies in a test because it makes the test fragile and less effective, but all of the "dependencies" in my tests are actual code -- so if a test breaks it means my actual code is broken which I feel I would want to know.

What else can you tell me? Suggestions? How can I improve this? Thanks!

答:
Concept is good enough!

Now, you must decide on what did you build - integration or acceptance tests and support/enhance them for single purpose. Here is the difference:

Integration tests are used by developers to verify that application is basically working and run often from dev machine. TDD tests and bug reproduction tests goes this way. Integration tests should be fast enough to do not bore developer.

Acceptance tests are used mainly by QA to ensure that application build is ready for production. They cover all application functionality including error conditions and tend to run for a while because of large number of tests

Also, you should automate them as most as possible so they can be run in single click - including database setup/restore.

Then you can add them to your Continuous Integration tool so they will run after each commit and have fun!

Regarding your concerns.

Actually concern - that you are testing too much in a single test. Do you have anything complex enough to be tested in isolation? DAL is good candidate since fast tests on DAL can really help when db schema changes. General rule when writing scoped tests is writing them when you believe this code can be broken/will break. Usually that falls to single functions or large isolated module. Tests will large amount of mocks tend to be a) fragile b) expensive to write and c) testing glue code that has no complexity and no value

Title: How well am I writing my tests?


问:
Is the regex syntax in .net 3.5 the same as the regex syntax in the latest version of .net framework in c#?
Is the regex syntax in .net 3.5 the same as the regex syntax in the latest version of .net framework in c#? </p>

答: Yes, from what I understand the .NET regex flavor has not changed since 1.0.</p>


问:
Why Java does not allow function definitions to be present outside of the class?
Unlike C++, in Java, we cannot have just function declarations in the class and definitions outside of the class. Why is it so?

Is it to emphasize that a single file in Java should contain only one class and nothing else?

答:
C++ requires that the entire text of class be compiled as part of every compilation unit which uses any members thereof or produces any instances.  The only way to keep compile times sane is to have the text of the class itself contain--to the extent possible--only those things which are actually necessary to its consumers.  The fact that C++ methods are often written outside the classes that contain them is a really nasty vile hack motivated by the fact that requiring the compiler to process the text of every class method once for every compilation unit where the class is used would lead to totally insane build times.

In Java, compiled class files contain, among other things, information which is largely equivalent to a C++ .h file.  Consumers of the class can extract all the information they need from that file, without having to have the compiler process the .java file.  Unlike C++, where the .h file contains information which is made available to both the implementations and clients of the classes contained therein, the flow in Java is reversed: the file the clients use isn't a source file used in the compilation of the class code, but is instead produced by the compiler using information the class code file.  Because there is no need to divide class code between a file containing information clients need and a file containing implementation, Java doesn't allow for such a split.


问:
Are header files actually good?
I find header files to be useful when browsing C++ source files, because they give a "summary" of all the functions and data members in a class.  Why do so many other languages (like Ruby, Python, Java, etc.) not have a feature like this?  Is this an area where C++'s verbosity comes in handy?</p>

答:
In many programming languages, when a program is subdivided into multiple compilation units, code in one unit will only be able to use things defined in another if the compiler has some means of knowing what those things are.  Rather than requiring that a compiler processing one compilation unit examine the entire text of every compilation unit which defines anything used within the present unit, it's best to have the compiler receive, while processing each unit, the full text of the unit to be compiled along with a little information from all of the others.

In C, the programmer is responsible for creating two files for each unit--one containing information which will only be needed when compiling that unit, and one containing information which will also be needed when compiling other units.  This is a rather nasty, hacky, design, but it avoids the need to have a language standard specify anything about how compilers should generate and process any intermediate files.  Many other languages use a different approach, wherein a compiler will generate from each source file an intermediate file describing everything in that source file which is supposed to be accessible to outside code.  This approach avoids the need to have duplicate information in two source files, but it requires that a compilation platform have defined file semantics in a way that is not required for C.

Title: Are header files actually good?


问:
Are Secure Desktop and separate process enough for hiding sensitive information in RAM?
In my program, I have an encrypted database on the file system with a password. It is decrypted in RAM, and the sensitive data get spread out too much in RAM for mistake to be auditable easily enough. (Which rule out zeroing memory manually and using SecureString all over the place)

So what I think about doing is spawning a new process in a new windows desktop, asking the user to enter his password here, then decrypting the database, doing my stuff, then closing the child process immediately.

This make the whole thing very easy to audit. The sensitive data never leave out the child process, and the timespan where sensitive data is in RAM is limited to some milli seconds.

The question is : My solution works great only if Windows is effectively zeroing the memory after the process is closed. Is it a safe thing to assume ? (I know that the OS free the memory, but freeing and zeroing is not the same thing)

Do you see a better solution ? (easy to audit)

答:
You must decide what you are protecting and against whom.

First, swap. Your application sensitive data can get to swap file and be extracted from there later. So, you must enable zeroing swap file on shutdown.

Second, who is attacking your application. I am pretty sure when ring3 application allocates memory it is already zeroed out. However, if attacker have Administrator access, he can:

patch your application binary file so it will dump password/secret data to file

patch your loaded application in memory, then see above

continuously watch memory of your application until it exposes sensitive data unencrypted

get direct access to physical memory and look there for sensitive data

Please notice - some of those scenarios do not require administrative privileges - running under the same user as your app will be enough!


问:
Style question: To use overloaded version or not?
Let's say I had an operator() overload that made temp_.matrix[k][j] and temp_(k+1, j+1) equivalent. In my class functions (where matrix belongs), would it be better to have

```<code>if (temp_.matrix[k][j] == 0) { /**do stuff*/ }
</code>```

or

```<code>if (temp_(k+1, j+1) == 0) { /**do stuff*/ }
</code>```

?

I like using the vanilla version. But the operator() version because it encapsulates the data inside the operator, which we use to access it. I'm not too sure if I'm correct in using the vanilla version due to this reasoning.

答:
Use operator overloading if it improves code clarity and maintainability.

Sometimes it helps clarity and maintainability: a + b is shorter and clearer than a.addTo(b), it makes it easier to write generic algorithms (e.g., templates) and change data types, etc.

Sometimes it hurts clarity and maintainability: overloaded operators can be surprising (surprising behavior, surprisingly expensive, etc.), it can be harder to find callers, etc.

Keep in mind that "operator overloading versus raw member access" isn't a binary decision; you can also use explicitly named functions (e.g., temp_.get(k, j)). Additionally:

Does temp_ do anything besides holding a matrix?

If temp_ is a matrix, then the fact that the matrix is a two-dimensional array should be encapsulated (whether via an overloaded operator or an explicit getter function).

If temp_ is not a matrix, then the entire matrix should be encapsulated (whether via an overloaded operator or an explicit getter function, with matrix changed to a private member variable).

Why use k+1,j+1 for operator() but k, j for matrix[][]? If the indexes are really supposed to be different depending on how the array is accessed, then that suggests a failure of encapsulation.


答:
A more fundamental question is whether to define the operator() (by the class) for this purpose or not. Alas, this decision has already been made by the author(s) of the matrix class, so we should consider its usage to be compatible with the intent of the author(s).

Indeed, this is what most matrix (or multi-dimensional array) libraries would choose to implement in C++.

Note that your first version of code may not be future-proof. There is no guarantee that Matrix.matrix exists in future versions of the library, or that Matrix matrix; mat.matrix[k][j] continues to be a valid expression due to future library changes.

Possibilities why such future breaking changes might happen:

The matrix library used to have compile-time constant (template-parameterized) matrix sizes, but was later upgraded to support run-time matrix sizes.

This means internally it is no longer declaring the matrix as T matrix[M][N]; anymore.

The matrix library used to maintain an array of pointers to the start of each row, but then decided to eliminate that in order to save a little bit of memory.

This means internally it is no longer declaring matrix as T** matrix;, therefore the field may have been removed, or that you cannot use matrix[row] to get the starting pointer to a particular row.

The matrix library may have implemented type erasure, therefore the class no longer knows the type of T at compile-time; instead, it only contains an untyped pointer to the start of the allocated memory block, as in void* matrix; or uchar* matrix;, where uchar has no relationship to the numeric type of the matrix.

However, if the matrix library is under your full control, that is: you wrote it, nobody else can change it, and you have sole discretion on what future changes to be made to it, then the "future-proof" issue does not apply to you.

Title: Style question: To use overloaded version or not?

Body:
Let's say I had an operator() overload that made temp_.matrix[k][j] and temp_(k+1, j+1) equivalent. In my class functions (where matrix belongs), would it be better to have

```<code>if (temp_.matrix[k][j] == 0) { /**do stuff*/ }
</code>```

or

```<code>if (temp_(k+1, j+1) == 0) { /**do stuff*/ }
</code>```

?

I like using the vanilla version. But the operator() version because it encapsulates the data inside the operator, which we use to access it. I'm not too sure if I'm correct in using the vanilla version due to this reasoning.


答:
Consider that your boss needs a few things from you:

The ability to program. By all rights, unless he's a developing manager, he (hopefully) hired you hoping that you'd be better than him.

The ability to work on a team: that means listening as well as explaining ideas.

The ability to do what you're told. When the final word has been said, after all of the back-and-forth discussing of a problem, you're not the boss. If you try to be a hotshot when you've been told specifically not to do something, you can't be trusted.

If you want to continue with the issue, you could implement your boss' idea, implement your own (on your own time if it'll take a while to do), and demonstrate them both to prove that yours is better. I'd leave the attitude in the shower when you do.


问:
How to properly apply a license
Take for example the GPL-3.0 license.

Near the end it states:

END OF TERMS AND CONDITIONS

How to Apply These Terms to Your New Programs

   ...

So I though that the "correct" way is to use the instructions there and use the small excerpt they provided:

<one line to give the program's name and a brief idea of what it does.>

   Copyright (C) <year>  <name of author>

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program.  If not, see http://www.gnu.org/licenses/.

Replace <year> etc and paste those in a LICENSE file. (but not on top of each file or 80% of my code would be licensing stuff...)

When looking at famous projects however, they seem to have just put the entire license in there with the "HOW TO APPLY..." still added and without even replacing <year>, <name of author> etc.

So I'm starting to wonder: if I remove everything after END OF TERMS AND CONDITIONS or if I actually follow the instructions, is it still the same license...

答:
If I remove everything after END OF TERMS AND CONDITIONS, is it still the same license?

No.

The complete text of the actual GNU GPL license can be found here:

http://www.gnu.org/licenses/gpl.txt

This is the "copy" that the "notice" refers to when it says:

You should have received a copy of the GNU General Public License along with this program.

As you can see, the license includes all three sections: the Preamble, the Terms and Conditions, and How to Apply These Terms to Your New Programs.  It is exactly the same text that is included on the page you linked, excluding the website header and footer.

You should provide this copy, unaltered, in a file called LICENSE.TXT (by convention) at the root folder of your distribution, and then follow the "How to Apply These Terms" instructions for each of your source files.

Title: How to properly apply a license