问:
When should one create a new py-function rather than tweaking another one?
Me and a co-developer are arguing when it's wise to cast a new function rather than tweaking another one. By tweaking I mean an option or a hidden check in an existing function. The question could be rephrased: How new/different should a new function be?

In the concrete case, it's about a string comparison. Currently, the procedure is written for one list of strings. We also want to compare strings from two different lists with each other. The docs would be very similar, and code changes include just a few lines.

答:
If a function performs two tasks, or one task in two different ways, it should be two functions.

This is the single responsibility principle. While the code may "compare strings" in both cases, the inputs might be different or the way in which it compares strings might be different.

The keys to remember when thinking about it being "clever" to overload a function or add parameters to make it work differently:

The public interface of a class or module (of which functions are members) should be simple and easy to use. Avoid parameters that control what a function does: write two functions. These parameters pollute the interface. On the inside of the module they functions might delegate to a single function and that is okay: the key is to avoid confusing users of the interface.

If possible, abstract the input to the function. Example: in C++, standard library algorithms typically accept iterators for the start and end range with which to work. This allows any container to work with the algorithm, as well as a subset of a container. This may remove the need to add more code whether inside the function or a second function.

Once a library or utility function is well-defined, tested, and documented, try to leave it alone unless there is a bug. Prefer to add another function (see my first point). This helps keep the interface stable.

Try to avoid "clever" solutions: that implies something difficult to understand, such as nested ternary operators or template metaprogramming. Go with a solution that is simple and easy to understand by someone who is not on your development team. Clever ideas grow into technical debt.


问:
Why does the TRACE level exist, and when should I use it rather than DEBUG?
In Log4J, Slf4J and a couple other logging frameworks in Java, you have two "developper" level for logging:

DEBUG

TRACE

I understand what DEBUG does, because the explanation is clear:

The DEBUG Level designates fine-grained informational events that are most useful to debug an application.

But the TRACE level is not very specific about its use case:

The TRACE Level designates finer-grained informational events than the DEBUG

(Source: the log4J JavaDoc)

This does not tell me how or when to use TRACE. Interestingly, this is not a severity level defined in the syslog standard. Googling for the difference between TRACE and DEBUG only seem to return "use DEBUG, oh, and there is TRACE too". I couldn't find a specific use case for the TRACE level. The best I could find was this old wiki page debating the merit of the existence of the level.

This, as an architect, raises a lot of flags and questions in my head. If a young developer asked me to add TRACE to my architecture, I would bombard him with questions:

What are some examples of information that should be logged with TRACE and not with DEBUG?

What specific problem do I solve by logging that information?

In those examples, what are the properties of the logged information that clearly discriminate between logging at the TRACE level rather than the DEBUG level?

Why must that information go through the log infrastructure?

What are the benefits of persisting that information in a logs journals rather than just using System.out.println ?

Why is it better to use log for this rather than a debugger?

What would be a canonical example of logging at the TRACE level?

What are the specific gains that have been made by logging at the TRACE level instead of DEBUG in the example?

Why are those gains important?

In reverse: What problems did I avoid by logging it at TRACE instead of DEBUG?

How else could I solve those problems? Why is logging at the TRACE level better than those other solutions?

Should TRACE level log statement be left in the production code? Why?

But given that it is present in most major framework, I am guessing it is useful for something? So... what is TRACE for, and what distinguishes it from DEBUG?

答:
Debug levels in general are entirely arbitrary and can vary between languages, libraries, and companies.

That being said, here is how I have seen them used:

TRACE: used for showing logic-level program flow. Entered a function? Did an "if" statement choose the main or "else" branch? That is a candidate for trace. In other words, trace logging is generally used for specifying "you are here." This is useful in the context of other logging statement that might log an error or other information. Trace logging can help pinpoint the location, in the code, of the error or other event logged at a different level.

DEBUG: used for dumping variable state, specific error codes, etc. For example: a web service might return error code 809214, which could be logged while the application tells the user "communication failed." Imagine a developer receiving a log from a user's system long after the error occurred and wondering "why did the failure occur?" that is a good thing to log at the debug level. Another example might be if a bug keeps occurring in production but is hard to reproduce, debug log certain variables or events in the troublesome module to help tell developers the program state when the error occurs to help troubleshooting.

Normally one would configure the application to log at a given level (or higher). For example, trace is often the lowest level: logging at that level logs everything. Debug level would omit trace but include high levels (e.g. warnings and errors).

The benefit to segregating log levels is to control the amount logged. For a complex application, trace logging might potentially log a tremendous amount of data, much of it useless most of the time. It is best only to log critical information (maybe some startup information, then only errors) unless one is trying to nail down how to cause a bug. Furthermore, this is generally only useful in a production environment were debuggers and other development tools are not present.

There are no real limits on this, no rules saying you have to log a certain way. Only broad conventions that some libraries or applications may or may not follow.

ContentLicense: CC BY-SA 3.0


答:
What are example of information that should be logged with TRACE and not with DEBUG?

If I have an algorithm that goes through a bunch of steps, trace level will print info about each of those steps at the finest level. Things like the literal inputs and outputs of every step.

In general, trace will include all debug (just like debug includes all warnings and errors).

What specific problem do I solve by logging that information?

You need to debug something that outputs way too much data to log outside of a specific build when you're targeting that particular thing and do not care about errors or other logging info (since the volume of trace info will obscure them). In some loggers, you will turn a certain module up to trace level only.

In those examples, what are the properties of the logged information that clearly discriminate between logging at the TRACE level rather than the DEBUG level?

In general, trace level logging cannot be on for sustained periods because it degrades the performance of the application greatly, and/or creates an abundance of log data that is unsustainable due to disk/bandwidth constraints.

Debug level logging can usually be on for a longer period without making the app unusable.

Why does that information must go through the log infrastructure?

It doesn't have to. Some frameworks have a separate tracelogger.

Usually it ends up in the logs since traceloggers and normal loggers have similar needs with regards to writing to disk/network, error handling, log rotation, etc.

Why is it better to use log for this rather than a debugger?

Because the debugger might not be able to attach to the problem machine. You might not know enough to know where to even set breakpoints, or to step through code. You might not be able to reliably reproduce the error in a debugger, so use the logs to catch it "if it happens".

But they're just names. Like any other label, they're just names people put on things, and will usually mean different things to different people. And the label itself is less important than the meaty bits that the label refers to.

Title: Why does the TRACE level exist, and when should I use it rather than DEBUG?

Body:
In Log4J, Slf4J and a couple other logging frameworks in Java, you have two "developper" level for logging:

DEBUG

TRACE

I understand what DEBUG does, because the explanation is clear:

The DEBUG Level designates fine-grained informational events that are most useful to debug an application.

But the TRACE level is not very specific about its use case:

The TRACE Level designates finer-grained informational events than the DEBUG

(Source: the log4J JavaDoc)

This does not tell me how or when to use TRACE. Interestingly, this is not a severity level defined in the syslog standard. Googling for the difference between TRACE and DEBUG only seem to return "use DEBUG, oh, and there is TRACE too". I couldn't find a specific use case for the TRACE level. The best I could find was this old wiki page debating the merit of the existence of the level.

This, as an architect, raises a lot of flags and questions in my head. If a young developer asked me to add TRACE to my architecture, I would bombard him with questions:

What are some examples of information that should be logged with TRACE and not with DEBUG?

What specific problem do I solve by logging that information?

In those examples, what are the properties of the logged information that clearly discriminate between logging at the TRACE level rather than the DEBUG level?

Why must that information go through the log infrastructure?

What are the benefits of persisting that information in a logs journals rather than just using System.out.println ?

Why is it better to use log for this rather than a debugger?

What would be a canonical example of logging at the TRACE level?

What are the specific gains that have been made by logging at the TRACE level instead of DEBUG in the example?

Why are those gains important?

In reverse: What problems did I avoid by logging it at TRACE instead of DEBUG?

How else could I solve those problems? Why is logging at the TRACE level better than those other solutions?

Should TRACE level log statement be left in the production code? Why?

But given that it is present in most major framework, I am guessing it is useful for something? So... what is TRACE for, and what distinguishes it from DEBUG?


答:
Take special note that slf4j specifically recommends against using trace ( http://slf4j.org/faq.html#trace ):

In short, although we still discourage the use of the TRACE level
  because alternatives exist or because in many cases log requests of
  level TRACE are wasteful, given that people kept asking for it, we
  decided to bow to popular demand.

Personally, my expectation would be for trace to log everything (e.g., even stuff like "entered function MyFunc with arguments A,B,C at time Y").  The downside of this is that not only is this incredibly noisy but also it tends to cause disk space problems; I would expect such logging to be disabled during normal operations.  The upside is that this gives you a level of info similar to what you would get when stepping through your program in cases where attaching a debugger may be less practical.

Generally, I find that trace is usually more effort than other approaches.


问:
Understanding VB.NET variable scope
What's the difference between this code snippet:

```<code>Sub Test()
  Dim i as Integer = 0
  Dim q as String = ""
  While i<10
    q=String.Format("Some text {0}", i)
    Console.WriteLn(q)
    i=i+1
  End While
End Dub
</code>```

and this one:

```<code>Sub Test()
  Dim i as Integer = 0
  While i<10
    Dim q as String = String.Format("Some text {0}", i)
    Console.WriteLn(q)
    i=i+1
  End While
End Dub
</code>```

in terms of memory allocation and performance ...

答:
In terms of memory allocation and performance, the first snippet contains a superfluous assignment of the empty string to q before entering the loop.

From a performance point of view this should not be of any concern whatsoever, but from a best software engineering practices point of view, the second snippet is definitely preferable, since the variable is declared within the scope in which it is used.

Readability and maintainability are far more important than performance in the vast majority of scenarios out there, and statistically speaking, the chances that your business is an exception to this rule are slim.

My recommendation would be to go ahead and build your software product properly, and if it turns out that there is a performance problem, (most probably there won't be any,) then throw the profiler at it to see precisely where the problem is, and once you have found the problem spots, then go ahead and improve only those spots that need improvement.

Being concerned about the performance of every tiny little thing all over the place, and tweaking and hacking things proactively here and there just in order to squeeze clock cycles blindly, without having any idea whether these clock cycles are actually needed, is no way of writing software.

Clock cycles will always be wasted.  Even if you abandoned Visual Basic in favour of Assembly Language you would soon discover that it is impossible not to waste clock cycles. The point is to only worry about clock cycles when you have a very good reason to do so, and in the vast majority of cases, you don't have any.  Poorly performing software performs poorly mostly due to algorithmic problems, not due to programmers being careless with clock cycles.

P.S.

I don't know about Visual Basic, but in most decent programming languages the compiler is capable of warning you if you attempt to use a variable which has not been initialized yet, but this ability of the compiler is compromised by the very prevalent and very misguided practice of initializing variables to nonsensical defaults like Dim q as String = "" above. So, I would recommend avoiding Dim q as String = "" like the plague.

Title: Understanding VB.NET variable scope


问:
Big O Question about an algorithm with (n^2 + n) / 2 growth rate
I'm asking this question because I am confused about one aspect regarding big O notation.

I am using the book, Data Structures and Abstractions with Java by Frank Carrano. In the chapter on the "Efficiency of Algorithms" he shows the following algorithm:

```<code>int sum = 0, i = 1, j = 1
for (i = 1 to n) {
    for (j = 1 to i)
        sum = sum + 1
}
</code>```

He initially describes this algorithm as having a growth rate of (n2 + n)/2. Which looking at it seems intuitive.

However, it is then stated that (n2 + n)/2 behaves like n2 when n is large. In the same paragraph he states (n2 + n)/2 also behaves much like n2/2. He uses this to classify the above algorithm as O(n2).

I get that (n2 + n)/2  is similar to n2/2 because percentage wise, n makes little difference. What I do not get is why (n2 + n)/2 and n2 are similar, when n is large.

For example, if n = 1,000,000:

```<code>(n^2 + n) / 2 =  500000500000 (5.000005e+11)
(n^2) / 2     =  500000000000 (5e+11)
(n^2)         = 1000000000000 (1e+12)
</code>```

That last one is not similar at all. In fact, quite obviously, it's twice as much as the middle one. So how can Frank Carrano say they are similar? Also, how is the algorithm classified as O(n2). Looking at that inner loop I would say it was n2 + n/2

答:
It's not that "(n² + n)/2 behaves like n² when n is large", it's that (n² + n)/2 grows like n² as n increases.

For example, as n increases from 1,000 to 1,000,000

```<code>(n² + n) / 2  increases from  500500 to  500000500000
(n²) / 2      increases from  500000 to  500000000000
(n²)          increases from 1000000 to 1000000000000
</code>```

Similarly, as n increases from 1,000,000 to 1,000,000,000

```<code>(n² + n) / 2  increases from  500000500000 to  500000000500000000
(n²) / 2      increases from  500000000000 to  500000000000000000
(n²)          increases from 1000000000000 to 1000000000000000000
</code>```

They grow similarly, which is what Big O Notation is about.

If you plot (n²+n)/2 and n²/2 on Wolfram Alpha, they are so similar that they're difficult to distinguish by n=100.  If you plot all three on Wolfram Alpha, you see two lines separated by a constant factor of 2.

Body:
It's not that "(n² + n)/2 behaves like n² when n is large", it's that (n² + n)/2 grows like n² as n increases.

For example, as n increases from 1,000 to 1,000,000

(n² + n) / 2  increases from  500500 to  500000500000
(n²) / 2      increases from  500000 to  500000000000
(n²)          increases from 1000000 to 1000000000000

Similarly, as n increases from 1,000,000 to 1,000,000,000

(n² + n) / 2  increases from  500000500000 to  500000000500000000
(n²) / 2      increases from  500000000000 to  500000000000000000
(n²)          increases from 1000000000000 to 1000000000000000000

They grow similarly, which is what Big O Notation is about.

If you plot (n²+n)/2 and n²/2 on Wolfram Alpha, they are so similar that they're difficult to distinguish by n=100.  If you plot all three on Wolfram Alpha, you see two lines separated by a constant factor of 2.


问:
Experimentally determined timing of function/method calls vs locks, signals. Anti-pattern name?
Here is some pseudocode and paraphrased comments:

```<code>// Allow time for screen to start before content reset.
// Delay time determined by testing with platform version 5.
delayCall(0.01, contentReset())
</code>```

Basically, the programmer figured out that on his specific test device after a dozen or so test runs that 1/100th of a second delay was just the right delay to accomplish what he wanted to have happen without causing any obvious problems for himself at the time.

Inevitably, this has led to occasional timing problems and instability.

Does this bad practice have a well known anti-pattern or code smell name?

What is the list of drawbacks for this practice?

答:
This sort of thing is so blatantly fragile it probably doesn't need a name; anti-patterns typically get names as part of the effort to teach people to recognize and avoid them. But I think temporal coupling might be what you're looking for.

That term is normally used for things like "You must call init() before doStuff()", but it seems reasonable to extend it to "You must wait 0.01s before calling doStuff()" as well.


问:
What is proven as a good maximum length of a function?
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.

答:
Maybe function length is not so a good metric. We try to use cyclomatic complexity, on methods too, and one of the future source control checkin rules that cyclomatic complexity on classes and methods must be lower than X.

For methods, X is set to 30, and that's pretty tight.

ContentLicense: CC BY-SA 4.0


问:
Does using a database server make sense if the application only does things locally?
I've seen some applications that are basically application software that run local to the system (so they don't have communicate much over the network). These applications seem to depend on database servers in order to store their data.

An example of an application is Amarok (a popular music player on Linux). I don't know if they still do this, but I remember there was a time where installing Amarok meant that you had to install a MySQL server and have it running in the background all the time.

What is the advantage of using a server for local storage compared to using a smaller embedded SQL solution like sqlite? I'm talking about application software in general, not necessarily amarok (that was just an example). Are there any situations where using a database server makes sense compared to an embedded database?

答:
Even for a single system with a single user, a "real" database server makes sense:

It uses a familiar language (SQL). SQLite does use SQL, but some embedded databases (e.g. object database, NoSQL) do not use SQL. Those tend to have a higher learning curve because they are less common.

It provides referential integrity, constraints, triggers etc. that products such as SQLite may not provide or at least provide not in full.

By targeting a true multi-user, ACID compliant network database, the application has the option of working in a single user/single workstation scenario, or as a multi-user, hosted application using the same codebase.

The user has the ability to examine the data offline using standard tools (e.g. SQL Developer, MySQL Workbench, SQL Server Management Studio), load or backup data using those tools, etc. While it is possible to do so with many embedded databases of various types, people maybe more familiar with those tools from the C/S database world.

The primary drawback is needing to install and maintain the database server software, which is a bit complex for nontechnical users (and even many technical users). Operating systems such as Linux make this easier: I have PostgreSQL and MySQL running on my Linux system. I have installed applications that hooked into them with little to no interaction on my part.


问:
Is this a race condition?
I have a friend arguing this is a race condition, but I'm struggling to understand how.

This is for a web application using PHP and MySQL where users can login and create tickets, these tickets have tasks which users can add. Each task has a time spend variable.

When the user submits a task, it adds a row with the task data to a table. After the entry has been added, it calculates the total time spent for all tasks for this particular ticket, and updates a field in a different table with that value.

The argument my friend puts forth is that with many users, there will be race condition issues as users are simultaneously adding tasks for tickets.

But my defence is that as long as the update for total time spent is run after the insert query, it will still update the field correctly regardless of how many users are adding tasks at the same time.

答:
No,this is not race condition.

Race condition means more than one user updating the value of same
  variable, and last assigned value will become the value for that
  variable.

For example,

```<code>if A assign value to variable X = 10, then
   B assign value to variable X = 12, then
   C assign value to variable X = 8, then

8 would became value for variable X. Means C will win.
</code>```

This race condition is actually opposite of the real world race condition,
"Who comes last, WINS".

And in your case there is no such condition on which multiple users are trying to change same record. So we can't call it race condition.

Title: Is this a race condition?

Body:
No,this is not race condition.

Race condition means more than one user updating the value of same
  variable, and last assigned value will become the value for that
  variable.

For example,

if A assign value to variable X = 10, then
   B assign value to variable X = 12, then
   C assign value to variable X = 8, then

8 would became value for variable X. Means C will win.

This race condition is actually opposite of the real world race condition,
"Who comes last, WINS".

And in your case there is no such condition on which multiple users are trying to change same record. So we can't call it race condition.


答:
I think it has to do with inertia.

Amarok is based on XMMS which is from 1997. To have to have good database capabilities you had to use a server, because it was so much more powerful then the file based solutions, which by no means had good database capabilities.

The upcoming and gaining popularity of good local embedded databases like SQLlite is something fairly recent.

Title: Does using a database server make sense if the application only does things locally?

Body:
I've seen some applications that are basically application software that run local to the system (so they don't have communicate much over the network). These applications seem to depend on database servers in order to store their data.

An example of an application is Amarok (a popular music player on Linux). I don't know if they still do this, but I remember there was a time where installing Amarok meant that you had to install a MySQL server and have it running in the background all the time.

What is the advantage of using a server for local storage compared to using a smaller embedded SQL solution like sqlite? I'm talking about application software in general, not necessarily amarok (that was just an example). Are there any situations where using a database server makes sense compared to an embedded database?


问:
What default features is Windows missing that are required for programmers?
What features is Windows missing that can improve the productivity of a programmer. I know a lot of people would want some features from Linux and OSX ported or being created for Windows as well. What is missing for you ?

An example would be the option to have multiple workspaces. When not having the possibility to use dual monitors that can come in handy.

答:
The ability to change UI to different level based users knowledge.

For example as developer/administrator you may need expert level on UI.

ContentLicense: CC BY-SA 2.5


问:
Simulating a Production Line
I'm trying to simulate a DVD production line in Java. The thing I have a problem with is the calculation of the time in this kind of simulation and the number of DVDs per hour.

The production line consists of 4 machines, each of which spends a certain random time working on 1 DVD. The third one can work on more than 1 DVD at the same time (max. 100). Also, the third one will always accept more DVDs  to work on, as long it's capacity is < 50%, which I plan to label as m3Capacity. But for now, let's just ignore the capacity characteristic.

What I have so far is that, with a random number generator (since each machine has random DVD processing time each time it starts working on a new DVD), I assigned a random processing time to each of the four machines, summed up their processing times for the total time spent in one-go production (totalProdTime = processTime1 + processTime2 + processTime3 + processTime4), and then I keep summing up those totalProdTime values until the total time of the whole simulation reaches the desired duration of the simulation specified by the user (totalProdTimeSim = totalProdTimeSim + mTotal.totalProdTime).  Later I just verify whether the totalProdTimeSim has reached the desired time and that's it.

Now, the problem is that, this way, the production of the DVDs waits for one instance of production to finish all the way until the very end of the machine 4, and then the work begins on the second DVD, etc. What I want to do is that after machine 1 finishes it's work, and the second one begins its work, machine 1 begins work on another DVD with it's newly generated time. The same goes for all other machines. After machine 2 finishes work on a DVD, it immediately begins working on another DVD.

Now, since all machines have random processing times each time they start working on another DVD, it will often happen that one machine 'wants to work on another DVD' while the previous one hasn't finished its work on the current one. In this case, the idle machine just 'waits' for the previous machine to finish processing and then accepts the DVD from the previous machine.

So, in my example, we have that all the machines work one by one, but I want them all to work constantly, even after they finish working on the current DVD (except  in the first iteration, where the further machines need to wait for the previous ones to forward them their DVD they previously worked on).

How do you think I should calculate the total simulation time and DVD output? I've been thinking last night about it, but haven't gotten any ideas.

My sketch of how it should work can be found in the picture below. In the sketch all machines behave as if they constantly have something to work on, but should wait from the input from the previous machine.

Thanks in advance!

答:
What you are looking for is called Discrete Event Simulation. There are multiple libraries you can use to help you.

Your situation is almost textbook example of this kind of simulation. Each of the lines is an "agent", that when it receives a DVD, it picks a random time it will take to process and asks the system to "notify it" (creates an event) when that time comes. When the system notifies the line, it will mark current DVD as processed, passes it to next line and picks next one. Each of those lines (or agents) is independent and behaves almost like a separate "thread". The system is then responsible to "progress the time" by picking next event in the queue and executing it. You can then repeat this simulation multiple time with different parameters or different random times to get some stochastic metrics about the system.

Title: Simulating a Production Line


答:
Unless you are running an embedded system with low memory and cpu, I don't think that running a server on the background is doing you any harm.

Running a database server locally is fine. The database is meant to access and manipulate data. The network access is a plus, which may or may not be needed. There are some engineering and scientific tools that do this.

Say you are using data, on a local application. Why shouldn't you use a database? as opposed to what?


问:
provability of while loop vs for loop
I have this teacher, he's quite smart (sometimes, haha) he said good programmers try to use while loops instead of for loops. the reason he gave for this is because while loops can be proven, as in, one can completely explain what happens in a while loop whereas you can't do that for a for loop. he also said something about NASA programmers only using while loops and not allowed to do for loops because of this.

I have quite a hard time understand this, for both loops one can explain how they work in detail right? for both you would always know what is going to happen?

can someone explain to me why while loops can be proven (And because of it, might be better than for loops, in some cases at least).

EDIT:

maybe he was reffering to:

2: All loops must have a fixed upper bound. It must be trivially possible for a checking tool to statically prove that a preset upper bound on the number of iterations of a loop cannot be exceeded. If the loop-bound cannot be proven statically, the rule is considered violated.

Though this still doesn't say anything about the difference between while and for loops.

答:
In the C language you can rewrite every for loop to an equivalent while loop and vice versa.

while -> for transformation:

Rewrite

while(condition) { instructions; }
```

<p>to</p>

<pre class="lang-c prettyprint-override"><code>for(; condition; ) { instructions; }
</code>```

for -> while transformation:

This is slightly more complicated, especially if you have continue statement in your loop.

Rewrite:

for(init; condition; next) { instructions; }
```

<p>to:</p>

<pre class="lang-c prettyprint-override"><code>{
    init;
    while(condition)
    {
        instructions;
    next_label:
        next;
    }
}
</code>```

but replace every continue; statement with goto next_label; statement. If condition is a null instruction, replace it with true.

As you can see, in C language neither is more "provable" (whatever that means) than the other, since even if one of the loop was, you could rewrite it in terms of another loop.

Now, there exist other languages where this while <-> for equivalency doesn't exist. For example, in Pascal, you can assume more about the for loop. This means that you can't express every concept when writing a for loop, but you can prove more about the flow of the code:

```<code>for i:=1 to n do
    instructions;
</code>```

Here, the n is saved at the beginning of the loop, so changes to n don't make any influence on iteration count, and you can't modify i in the body of the loop. This means you can trivially prove this loop will eventually end (as n is finite, and you can't modify i).

Title: provability of while loop vs for loop

Body:
In the C language you can rewrite every for loop to an equivalent while loop and vice versa.

while -> for transformation:

Rewrite

while(condition) { instructions; }

to

for(; condition; ) { instructions; }

for -> while transformation:

This is slightly more complicated, especially if you have continue statement in your loop.

Rewrite:

for(init; condition; next) { instructions; }

to:

{
    init;
    while(condition)
    {
        instructions;
    next_label:
        next;
    }
}

but replace every continue; statement with goto next_label; statement. If condition is a null instruction, replace it with true.

As you can see, in C language neither is more "provable" (whatever that means) than the other, since even if one of the loop was, you could rewrite it in terms of another loop.

Now, there exist other languages where this while <-> for equivalency doesn't exist. For example, in Pascal, you can assume more about the for loop. This means that you can't express every concept when writing a for loop, but you can prove more about the flow of the code:

for i:=1 to n do
    instructions;

Here, the n is saved at the beginning of the loop, so changes to n don't make any influence on iteration count, and you can't modify i in the body of the loop. This means you can trivially prove this loop will eventually end (as n is finite, and you can't modify i).


答:
Your teacher is correct!

The reason is the following is valid C

```<code>for (int x = 1 ; x < 20 ; x++ ) {
   x = x + 9;
}
</code>```

You cannot guarantee the condition variables have not been tampered with!

Title: provability of while loop vs for loop

Body:
I have this teacher, he's quite smart (sometimes, haha) he said good programmers try to use while loops instead of for loops. the reason he gave for this is because while loops can be proven, as in, one can completely explain what happens in a while loop whereas you can't do that for a for loop. he also said something about NASA programmers only using while loops and not allowed to do for loops because of this.

I have quite a hard time understand this, for both loops one can explain how they work in detail right? for both you would always know what is going to happen?

can someone explain to me why while loops can be proven (And because of it, might be better than for loops, in some cases at least).

EDIT:

maybe he was reffering to:

2: All loops must have a fixed upper bound. It must be trivially possible for a checking tool to statically prove that a preset upper bound on the number of iterations of a loop cannot be exceeded. If the loop-bound cannot be proven statically, the rule is considered violated.

Though this still doesn't say anything about the difference between while and for loops.

Body:
Your teacher is correct!

The reason is the following is valid C

for (int x = 1 ; x < 20 ; x++ ) {
   x = x + 9;
}

You cannot guarantee the condition variables have not been tampered with!


答:
It likely comes from early C programming where, by todays norms, loops were widely abused and misused, especially the conditional being modified. As programmers started to understand the effect certain programming styles had, the abuse and misuse of loop conditionals fell out of favor, and  the statement, while (arguably) once valid, no longer holds any truth.

The statement holds absolutely no truth if you look solely at the language definition and syntax and ignore how it was being used.

The statement itself does however offer a valuable lesson to anyone who wants to understand it, its history and why its no longer considered true. - Whats the expression about learning, mistakes and repeating them.....

Title: provability of while loop vs for loop


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
Language syntax: There are some good clues in pihipi and phpreboot of what developers are interested in (though phpreboot goes too far becoming JS).

Development methodology: It would greatly enhance the lifespan of PHP.net if such surveys were actually taken into account. Do not make any more willy-nilly afternoon IRC session syntax decisions.

Individual features: Some have been mentioned before, but I'll happily burn some karma to be extra blunt here:

Unicode string type.

Bigint (see Python).

Runkit builtin to remove/rename/override builtin functions and classes, which aren't always that well designed.

Modern OOP

multiple inheritance (instead of complexity to support seldom edge cases with clumsy traits syntax)

scalars can double as objects (see Python), e.g. array() works as ArrayObject, or strings as SplString (needs usable methods, all string funcs should be available as str::toupper())

Deprecate the shitty shit \ namespace syntax, fix the parser, and adopt :: as alternative. You know, like a real language.

Any variation of LINQ (allthough I don't trust you guys do devise a sensible syntax)

or XML literals.

Get rid of php.ini runtime behaviour and semantic switches. It takes out some of the excitement, true, but would benefit developers and user base.

Yes, magic_quotes are not gone yet.

Convert Zend Engine bytecode to PBC

Albeit, if this isn't obvious, I'd happily fund anyone else to do the latter, and kill off php.net as main implementation. :P

Oh, just noticed, it's community wiki. So there's a chance you're not actually here for the karma, but genuine interest. If so, look into the  issue  which seriously hurts the language (directoritis).

Body:
Language syntax: There are some good clues in pihipi and phpreboot of what developers are interested in (though phpreboot goes too far becoming JS).

Development methodology: It would greatly enhance the lifespan of PHP.net if such surveys were actually taken into account. Do not make any more willy-nilly afternoon IRC session syntax decisions.

Individual features: Some have been mentioned before, but I'll happily burn some karma to be extra blunt here:

Unicode string type.

Bigint (see Python).

Runkit builtin to remove/rename/override builtin functions and classes, which aren't always that well designed.

Modern OOP

multiple inheritance (instead of complexity to support seldom edge cases with clumsy traits syntax)

scalars can double as objects (see Python), e.g. array() works as ArrayObject, or strings as SplString (needs usable methods, all string funcs should be available as str::toupper())

Deprecate the shitty shit \ namespace syntax, fix the parser, and adopt :: as alternative. You know, like a real language.

Any variation of LINQ (allthough I don't trust you guys do devise a sensible syntax)

or XML literals.

Get rid of php.ini runtime behaviour and semantic switches. It takes out some of the excitement, true, but would benefit developers and user base.

Yes, magic_quotes are not gone yet.

Convert Zend Engine bytecode to PBC

Albeit, if this isn't obvious, I'd happily fund anyone else to do the latter, and kill off php.net as main implementation. :P

Oh, just noticed, it's community wiki. So there's a chance you're not actually here for the karma, but genuine interest. If so, look into the <b> issue </b> which seriously hurts the language (directoritis).


问:
How can you estimate time for tasks which primarily consist of figuring out a problem?
While it is relatively possible for an experienced developer to estimate how long it will take to implement code when the pattern and problem the code is solving is well understood, how can you make a good estimate when, while the end goal is well understood, the implementation is 95% theoretical/problem solving and has very small amounts of implementation?

My work often consists of tasks to accomplish well defined goals, however I have to find the way to reach that goal and until I understand the solution, it i6sn't clear what additional barriers there may be.  More specifically, I'm often working on code generation or automated code manipulation tools.  Once the solution is fully solved and the tool perfected, it will directly do 95% of the actual changes very quickly.  I don't, however, have any way to estimate how many additional issues may have to be resolved to make the generation or analysis tool deal with unforeseeable edge cases.

For planning purposes, my company wants a better idea of how long it will take, but since I don't know how many additional problems may come up while working through solving each step of the solution.  I'm not sure how I can approach giving a better estimate.

答:
With researchy questions where it's unclear that there is an answer at all, let alone a clear idea of what needs to be done, I usually propose to spend x amount of time on it as a start.

"I have no idea if this is even possible, but I could spend two days researching it. That probably won't give us a solution, but maybe I'll be able to rule out some things and I'll probably have an idea what some concrete next steps could be and what kind of time investment they would mean. Then we can decide whether it makes sense to take another step."

So put the uncertainty in the other direction -- the estimate is nicely precise (I'll spend two days), it's just very unspecified what will be achieved by then.

Timeboxing, basically.


问:
Is HTML 5 good enough for developers to switch from Flash?
Just curious, because many developers use Flash to do many things that HTML 4 (correct me if I'm wrong) or below cannot or had a hard time doing, like for example the rounded corners (Canvass) and that Video Thing and many more.

I have not actually explored all of HTML5, so might as well learn it from you.

thanks.

答: Rounded corners and stuff like this is not what flash is meant for, and these applications will die off very soon as more advanced CSS and HTML 5 kicks in. Where Flash really has advantage now is applications with very rich GUI, non-trivial user interaction (drawing, messing around with many different elements in various ways, rich maps, etc.). Now, you could probably make most of these things in HTML 5, but since Flash has tools, libraries, widgets, experienced developers and so on, it would take time until the same is developer for HTML 5. So if you're starting the project right now you may have better luck with Flash (if you task indeed requires the power of Flash - if you just need video/some CSS, go HTML 5), but that might change in a couple of years. </p>


答:
It depends on your data abstraction and overall application space, access management requirements, the investment you are planning on data maintenance, urgency of the required prototype, where you are in the learning curve, etc.

If you would like to ensure a tightly integrated database to an application which does not require access from other applications, creating islands of embedded database. The Mozilla Firefox Web Storage implementation with SQLite could be given as an example.

If you need even more efficiency with limited data, a design selection of In-Memory Databases is preferrable.

On the other hand, if you have many applications running multiple queries on the same data, and it requires better structuring of data storage to optimize the performance, a centralized DBMS is required. I will absolutely prefer it for scientific research, when it requires massive amount of data and where the query response time will impact overall user experience drastically.

For the Amarok case, I guess it was a selection of open-source DBMS at that time, before they pick the path of embedded databases.

If there is a specific system definition at your hand, it will be easier to weight cons and pros.

V/r,
Umut


答:
SQLite offers a pretty good rundown of when to use it or not vs alternatives:

https://www.sqlite.org/whentouse.html

This summary line captures the SQLite use-case extremely well in my experience:

SQLite does not compete with client/server databases. SQLite competes with fopen().

The article expands at length on this point. It also has a section titled "Situations Where A Client/Server RDBMS May Work Better". In a nutshell, they are:

Client/Server Applications: multiple users over a network.

High-volume Websites: either write intensive or read intensive enough to require sharding.

Very large datasets: larger than can be reasonably stored on one disk.

High Concurrency: in particular concurrent writes.


答:
The most important discriminating feature is concurrency.

If you have only one application that runs in one instance for the user, embedded solution (whether sqlite or some object storage) is usually OK.

However if you have multiple instances that need to manipulate the database concurrently, you need to have a server to synchronize it. SQLite only allows one write at a time, in the whole database, and so do most other embedded solutions. And if you even have multiple applications, you are likely to need more detailed constraint specification that the embedded solutions generally don't allow either.


答:
In a nutshell: What your teacher probably meant is that the semantics of while is pretty much the same in most languages, while the semantics of for may change considerably (see discussion below). Hence, abstract language independent proof are more reliable with a while, but one should be careful that a proof with a for loop may not match the semantics of the for loop in many languages.

Your question is not precise enough (though that may not be your
fault).

The point is that, afaik, there is no official, ISO supported
standard, or otherwise officially accepted reference definition of
for and while loops. The definition depends on the programming
language.

Hence you cannot make any general statement regarding their
equivalence before you have defined precisely what each can do. I
adress that more precisely, since it is one of the main argument used
in other answers (and the discussion will be useful in what follows).

On intertranslatability of for and while loops

Summary: it depends on the programming language, but is always
possible a long as you can have one infinite loop and a way to get out
of it.

But you can make such a statement for a specific programming language,
and the answer will depend on the features fo the language.

That also means that there is no general proof, but only one for each
programming language.

One thing that is generally true is that a while loop can generally
mimic a for loop, because the while loop can do the exit condition
testing of the for loop, doing the initialisation of the control
variable with an assignment before entering the loop, and doing the
incrementation at the end of the loop body, so that

```<code>for i from 1 by 2 to 10 do { xxx }
</code>```

becomes

```<code>i=1
while i≤11 do { xxx; i←i+2 }
</code>```

This more or less works for most languages, but it is not as obvious as
it seem, and there may be many "details" to worry about.

For example, in many languages, the for loop evaluates it 3
arguments (initial value, increment, and final value) as strict
arguments, evaluated once before entering the loop, while others will
take then as thunk arguments to be reevaluated at each turn, or
possibly as lazy argument to be evaluated only when first needed.

Another point may be that the increment variable may be local to the
for loop, or have to be a local variable of the function where the
loop appears.

Depending on such issues, the translation of a for to a while may
vary widely, though it is usually possible to achieve it.

The same holds for the converse, thranslating a while into a for loop.

Th first problem is that a while loop will always reevaluate the
exit condition at each turn. But some for loops do not provide for a
condition that is reevaluated at each turn, other than comparison of
the control variable with some fixed value computed on loop entry.
Then the translation is not possible unless there is some other mean
to jump out of the loop on some arbitrary conditions.

That is achievable with various devices, usually starting with a
conditional statement testing the condition, followed by an a jump out
implemented, as available, by a loop exit statement, a return
statement (after encapsulating the loop in a function), a goto
statement or an exception raising.

In other words, it is again very dependent on languages, and possibly
on subtle features of languages.

This say, as answered by @milleniumbug, the intertranslation is easy
in the language C, because a for lopp is essentially a while loop
plus some extra for an incremented control variable.

But this does not necessarily apply to other languages, and most
likely not in the same way.

This being said, programming languages are usually supposed to have
Turing power with only one of these loops, since all you need for it
is one infinite loop. So, as long as you have some way of looping for
ever, and possibly deciding to stop, you are pretty sure you can mimic
any other construct ... but not necessarily easily.

Regarding proofs

Summary: There is no reason known to me to assert that proofs should be significantly harder with one or the other (unless some weird feature of the language).

There is probably a misunderstanding, or your teacher had his mind on
something else.

Formals semantics can be defined for the various kinds of loops
defined in programming languages, and then used for proving
properties.

It may be, again depending on the language, that conducting formal
proofs regarding programs may be more complex in some cases. But that
depends on the language.

I cannot imagine a reason why proofs should be significantly harder with one construct more than with the other. The for loop may be more complex since it can offer, as in C, all that is done with a while plus other things. But if you did it with a while, you would have to add the extras in some other form.

I could use the formal general argument of intertranslatability, as long as there is the possibility for a single infinite loop. I will however refrain from doing that, as the constructions involved are nothing you want to deal with in a proof, and it would clearly be an unfair statement, at least in practice.

Following the above discussion, however, we have seen that the difficulties for intertranslatability come from the great variability of the for loop from language to language. Hence the following conclusion which is probably the right answer:

One possibility to understand your teacher's statement is that the semantics of the while loop is pretty much the same in all programming languages, while the syntax and semantics of the for loop can vary significantly from language to language. Hence, it is possible to make general "abstract" proofs with while loops that have language independent semantics to a good extent, while this is not possible for the for loop that has syntax and semantics changing too much from language to language. But this does not apply within a given language, when the semantics of both are precisely defined.

My best suggestion is that you should ask your teacher what he precisely meant, and whether he can give you an example. Misphrasing or misunderstanding is a common event.

Title: provability of while loop vs for loop

Body:
In a nutshell: What your teacher probably meant is that the semantics of while is pretty much the same in most languages, while the semantics of for may change considerably (see discussion below). Hence, abstract language independent proof are more reliable with a while, but one should be careful that a proof with a for loop may not match the semantics of the for loop in many languages.

Your question is not precise enough (though that may not be your
fault).

The point is that, afaik, there is no official, ISO supported
standard, or otherwise officially accepted reference definition of
for and while loops. The definition depends on the programming
language.

Hence you cannot make any general statement regarding their
equivalence before you have defined precisely what each can do. I
adress that more precisely, since it is one of the main argument used
in other answers (and the discussion will be useful in what follows).

On intertranslatability of for and while loops

Summary: it depends on the programming language, but is always
possible a long as you can have one infinite loop and a way to get out
of it.

But you can make such a statement for a specific programming language,
and the answer will depend on the features fo the language.

That also means that there is no general proof, but only one for each
programming language.

One thing that is generally true is that a while loop can generally
mimic a for loop, because the while loop can do the exit condition
testing of the for loop, doing the initialisation of the control
variable with an assignment before entering the loop, and doing the
incrementation at the end of the loop body, so that

for i from 1 by 2 to 10 do { xxx }

becomes

i=1
while i≤11 do { xxx; i←i+2 }

This more or less works for most languages, but it is not as obvious as
it seem, and there may be many "details" to worry about.

For example, in many languages, the for loop evaluates it 3
arguments (initial value, increment, and final value) as strict
arguments, evaluated once before entering the loop, while others will
take then as thunk arguments to be reevaluated at each turn, or
possibly as lazy argument to be evaluated only when first needed.

Another point may be that the increment variable may be local to the
for loop, or have to be a local variable of the function where the
loop appears.

Depending on such issues, the translation of a for to a while may
vary widely, though it is usually possible to achieve it.

The same holds for the converse, thranslating a while into a for loop.

Th first problem is that a while loop will always reevaluate the
exit condition at each turn. But some for loops do not provide for a
condition that is reevaluated at each turn, other than comparison of
the control variable with some fixed value computed on loop entry.
Then the translation is not possible unless there is some other mean
to jump out of the loop on some arbitrary conditions.

That is achievable with various devices, usually starting with a
conditional statement testing the condition, followed by an a jump out
implemented, as available, by a loop exit statement, a return
statement (after encapsulating the loop in a function), a goto
statement or an exception raising.

In other words, it is again very dependent on languages, and possibly
on subtle features of languages.

This say, as answered by @milleniumbug, the intertranslation is easy
in the language C, because a for lopp is essentially a while loop
plus some extra for an incremented control variable.

But this does not necessarily apply to other languages, and most
likely not in the same way.

This being said, programming languages are usually supposed to have
Turing power with only one of these loops, since all you need for it
is one infinite loop. So, as long as you have some way of looping for
ever, and possibly deciding to stop, you are pretty sure you can mimic
any other construct ... but not necessarily easily.

Regarding proofs

Summary: There is no reason known to me to assert that proofs should be significantly harder with one or the other (unless some weird feature of the language).

There is probably a misunderstanding, or your teacher had his mind on
something else.

Formals semantics can be defined for the various kinds of loops
defined in programming languages, and then used for proving
properties.

It may be, again depending on the language, that conducting formal
proofs regarding programs may be more complex in some cases. But that
depends on the language.

I cannot imagine a reason why proofs should be significantly harder with one construct more than with the other. The for loop may be more complex since it can offer, as in C, all that is done with a while plus other things. But if you did it with a while, you would have to add the extras in some other form.

I could use the formal general argument of intertranslatability, as long as there is the possibility for a single infinite loop. I will however refrain from doing that, as the constructions involved are nothing you want to deal with in a proof, and it would clearly be an unfair statement, at least in practice.

Following the above discussion, however, we have seen that the difficulties for intertranslatability come from the great variability of the for loop from language to language. Hence the following conclusion which is probably the right answer:

One possibility to understand your teacher's statement is that the semantics of the while loop is pretty much the same in all programming languages, while the syntax and semantics of the for loop can vary significantly from language to language. Hence, it is possible to make general "abstract" proofs with while loops that have language independent semantics to a good extent, while this is not possible for the for loop that has syntax and semantics changing too much from language to language. But this does not apply within a given language, when the semantics of both are precisely defined.

My best suggestion is that you should ask your teacher what he precisely meant, and whether he can give you an example. Misphrasing or misunderstanding is a common event.


问:
Multi platform password storage with retrieval for applications with authorization?
I'm working on a development tool that requires knowing one or more api passwords for a user to operate. Currently it works on Mac, and uses keychain to store the credentials for later re-use.

Are there any similar password store options that are cross-platform and have the following properties?

Store the credentials securely

Ability to authorize applications to access the credentials repeatedly without re-authenticating?

Credentials are accessible via an API (provided the user has authorized one-time or indefinite access)?

(Nice-to-have) Ability to authorize applications for a specific time period (i.e. a week or a month), after which the user is required to re-authorize the application.

(Nice-to-have) Support for multi-factor authentication during authorization

Keychain works great in this sense, since it allows me to let them be responsible for the security of the credentials, and allows the credentials to be used by other applications (provided a structured credential key) with authorization that can be one-time or indefinite.

I've attempted to the scour the web (probably poorly), but I'm having trouble with the fact I only get password managers, which are geared towards a user requesting the credentials, rather than an application, or I get instructions for how to properly store using bcrypt, which is great for verifying passwords, but not if I need to retreive it later. For instance, I have a proof of concept for storing the credentials in LastPass, but it requires enter a master password each time the credentials are requested unless I store the master password somewhere accessible, which kind of defeats the purpose of the password manager in the first place.

答:
What you are looking for is Symmetric encryption when the original data is required again.
ie Store the important data using Symmetric encryption.
Your application then provides access to external applications that can provide a User and password. The calling tools is authenticated against an Asymmetric stored hash.
Such as bcrypt for the Hash.

You can allocate a cookie if the caller is using http to reduce re-auth.

Take a look at Security exchange
You can post serious questions about good ways to do things safely regards security.


答:
Many of the other answers talk about concurrency as an advantage, but also since the db is running as a server, the database can run tasks without the need of the application running.  This could be maintenance, backups, synchronization with another server or any of scheduled task.

If you feel your app could turn into a client/server app, you may want to start with using an RDBMS from the start instead of porting it over later.

I have no idea if the example given takes advantage of this or not.


答:
Since I embarked on this crazy racket in 1970, I have seen exactly one module that really needed to be more than one printed page (about 60 lines). I have seen lots of modules that were longer.

For that matter, I have written modules that were longer, but they were usually large finite state machines written as big switch-statements.

Part of the problem appears to be that programmers these days are not taught to modularize things.

Coding standards that maximize the waste of vertical space appear also to be part of the problem. (I have yet to meet a software manager who has read Gerald Weinberg's "Psychology of Computer Programming". Weinberg points out that multiple studies have shown that programmer comprehension is essentially limited to what the programmer can see at any given instant. If the programmer has to scroll, or turn a page, their comprehension drops significantly: they have to remember, and abstract.)

I remain convinced that a lot of the well-documented programmer productivity gains from FORTH were due to the FORTH "block" system for source code: modules were hard-limited to an absolute maximum of 16 lines of 64 characters.  You could factor infinitely, but you could not under any circumstances whatsoever write a 17-line routine.

Title: What is proven as a good maximum length of a function?

Body:
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.


问:
Does using the Telegram API mandate releasing the source code under a GPL license?
Telegram has provided API, through which programmers can connect to telegram servers, enabling them to implement clients for the messaging system.

They also have released some open source client implementations, licensed under GPL.

It is apparent to me that any software, reusing the code, must release the new source code under the GPL too.

Now the question is if one does not reuse the open source client implementations and only uses the provided API to connect to the Telegram servers with new code, are they mandated to release the new code under GPL too? Or could one implement a closed-source client for Telegram?

答:
I am not a lawyer.  If you want a lawyer's answer, you should probably ask one.  The FSF is particularly helpful in providing guidance in understanding of the aspects of various free licenses, in particular the GPL.

The GPL is a license based on copyright. The rights that copyright grant the copyright holder allow them to enforce the license.

An API is a interface - a contract.  It says nothing about the code used to contact it.

Most relevant to this is Oracle vs. Google over the use of Java.

"So long as the specific code used to implement a method is different, anyone is free under the Copyright Act to write his or her own code to carry out exactly the same function or specification of any methods used in the Java API. It does not matter that the declaration or method header lines are identical."

It found that the API Oracle was claiming to be copyrighted wasn't copyrightable under section 102 of the Copyright Act.

(Yes, that's about reimplementing the Java API - but its still the most relevant thing I could find and speaks to the ability to copyright an API which is needed for a license based on copyright.)

That the company has released clients under GPL is great - it lets others use that code. If one makes use of the copyrighted code that is released under the GPL in their product, it is also GPL'ed.

The APIs remain APIs and are not (cannot be) copyrighted and thus there is no way to put them under the GPL.


问:
Do legal names matter with source code licensing in the USA?
If a project wishes to relicense its source code to a license that was incompatible with the original license, the project maintainers generally need to seek the express approval of its contributors if the contributors did not sign a Contributor License Agreement. If a contributor contributes code to a project under an anonymous alias, what does that mean for relicensing? Does contributing to a project anonymously mean the contributor loses copyright protection?</p>

答:
In this answer, I assume that someone has contributed code under a pseudonym (or under no name at all) and has not signed a contributor license agreement. Without delving too deeply into legal specifics (I'm not a lawyer), I will make a very simple point: ignorance of an author's identity does not diminish the author's rights under copyright, although it may severely complicate the author's attempts to assert those rights.

In all nations that are signatories to the Berne Convention, copyright protection is granted at the moment a work is fixed in a tangible medium. Therefore, whenever you encounter a work that contains copyrightable expression, you should assume it is already under copyright (assuming the copyright has not expired and the work does not predate the Berne Convention), and therefore it is your responsibility not to run afoul of that work's author's rights under copyright. If you need permission from the work's author to perform a particular action with that work, the onus rests on you to obtain permission from the author. Your inability to identify the author does not change your responsibility to respect that author's copyright.

To give a simple example, suppose you found a sheet of paper on the sidewalk with some code typed up on it. Surely, your inability to identify the author of this code does not mean the author forfeits copyright protection on the work.

Similarly, suppose someone slipped a piece of paper under your office door with some code on it, and attached a note saying it was released under the GNU GPL v3. Let's assume that the person who slipped it under your door really did have the right to license it under the GPL. (If they didn't, then you're quite a mess, but let's set aside this possibility and focus on the best case. Note that a good CLA would avoid this problem by forcing the contributor to bear the responsibility of any infringing material present in the contribution.) You can therefore reasonably use the work as permitted under the GPL, but you cannot relicense it without permission of the anonymous contributor, since that operation requires possession of copyright. If you attempt to distribute the code under a different license, you run afoul of the author's copyright.

There is, obviously, a serious practical obstacle to suing you for infringement, however: only the work's author can bring suit against an infringer. In order for a person to sue you for your unauthorized use of a work, that person must prove that he or she is the original author of the work. This may be a legal headache even in the best of times, and it may be all but impossible when the author has previously taken deliberate steps to obscure their connection to the work.

On a related note, the U.S. Copyright Office says this about pseudonyms:

An author of a copyrighted work can use a pseudonym or pen name. A work is pseudonymous if the author is identified on copies or phonorecords of the work by a fictitious name. Nicknames and other diminutive forms of legal names are not considered fictitious. Copyright does not protect pseudonyms or other names.

...

In no case should you omit the name of the copyright claimant [i.e., the declared copyright owner, when registering a copyright]. You can use a pseudonym for the claimant name. But be aware that if a copyright is held under a fictitious name, business dealings involving the copyrighted property may raise questions about its ownership. Consult an attorney for legal advice on this matter.

In short, a contributor's anonymity does not give you permission to use the contribution in ways that violate copyright, but it does complicate matters for a formerly-anonymous author who wishes to sue for infringement.


问:
Does TDD formally use black box testing to supplement unit tests?
Unit tests are never perfect at capturing functionality, particularly in certain parts of an application (such as the GUI), so everyone needs some measure black box testing. Does TDD have anything to say regarding black box testing? If it does not say much, could it be true that while writing unit tests is the developers job, functional black box tests fall into a different domain like that of a business analyst or a dedicated tester?

答:
IMHO TDD is primarily a whitebox technique, and, I think it is more an implementation technique than a testing technique.  It is applied by the developer who writes the code in very small iterations "write test, write code, refactor", so by someone who knows exactly the already implemented parts, and the missing parts of the "subject under test".

Whenever the developer who applies TDD creates a test for a function, he has full knowledge about the already existing implementation, the next missing feature, the next missing edge case, or the still uncovered code paths. That will undoubtly have a big influence which tests he creates and which not.

In fact, there is also a black box element in TDD: whenever you create a new public function to be tested, you have to think about the function signature or the API from the view point of a user of that function or API first. And whenever you add a new test for a functionality your "subject under test" does not support yet, you can do this without having decided about how to implement the functionality in detail. But IMHO that black box part is very different from a real "black box test", where an external tester who may not even be a developer does not have any knowledge about the implementation of a program.

See also: Black box or white box testing - which do you do first?


问:
Why doesn't git merge adjacent lines without conflict?
I recently learned that when merging two branches in git, if there are changes on two adjacent lines git declares this a conflict. For example, if file test.txt has this content:

```<code>Line 1: A
Line 2: B
Line 3: C
Line 4: D
</code>```

and in branch master we change this to

```<code>Line 1: A
Line 2: B1
Line 3: C
Line 4: D
</code>```

while in branch testing we change this to

```<code>Line 1: A
Line 2: B
Line 3: C1
Line 4: D
</code>```

and then attempt to merge testing into master, git declares a merge conflict. My naive expectation was that the merge would happen without conflict and yield this:

```<code>Line 1: A
Line 2: B1
Line 3: C1
Line 4: D
</code>```

I am sure there is a good reason why git doesn't merge this way. Can someone explain this reason?

答:
Assuming that this snippet of code

```<code>x=0
x+=1 if foo
x+=1 if bar
return x
</code>```

has been changed in one branch into this

```<code>x=0
x+=1 if foo && xyzzy
x+=1 if bar
return x
</code>```

and in another branch into this

```<code>x=0
x+=1 if foo
x+=1 if bar && xyzzy
return x
</code>```

then I would not want git to merge it into this

```<code>x=0
x+=1 if foo && xyzzy
x+=1 if bar && xyzzy
return x
</code>```

without alarming me.

In order to avoid causing such problems, git usually refuses to automatically merge changes touching nearby lines. It gives you a chance to verify whether the program logic would be broken or not.

This example is trivial, but when merging huge branches the risk of similar "logical" conflicts is much bigger. Sometimes I would even love the context to be even bigger than it currently is.

Body:
Assuming that this snippet of code

x=0
x+=1 if foo
x+=1 if bar
return x

has been changed in one branch into this

x=0
x+=1 if foo && xyzzy
x+=1 if bar
return x

and in another branch into this

x=0
x+=1 if foo
x+=1 if bar && xyzzy
return x

then I would not want git to merge it into this

x=0
x+=1 if foo && xyzzy
x+=1 if bar && xyzzy
return x

without alarming me.

In order to avoid causing such problems, git usually refuses to automatically merge changes touching nearby lines. It gives you a chance to verify whether the program logic would be broken or not.

This example is trivial, but when merging huge branches the risk of similar "logical" conflicts is much bigger. Sometimes I would even love the context to be even bigger than it currently is.


问:
How to use own REST API in web front end?
I have implemented a JSON-based REST API for a simple blog. The API allows for the creation, viewing, deletion and modification of user info, blogs, blog posts, comments, 'likes', etc. Some of these operations, such as deleting a blog post, require authentication. This is done using basic access authentication.

Now I need to implement a web front-end for the blog. The front end needs to be able to do all the same things as the JSON API, so it would make sense to use the API for the front end. The JSON API and the web front end are served by the same process on the same machine.

How should I use my JSON API for the front end? Should I use it at all? The options that I can think of are:

The server recieves the request for e.g. a certain blog post. The server does a HTTP request to the JSON API, and passes the results straight to the template renderer, which returns the rendered page to the client. This would require storing the user's password in plain text for the duration of the session, so that the operations requiring authentication can be completed.

An AJAX call is used to request the JSON, which is then rendered to the page. If the user has logged in successfully, the username is already associated with the session, so no password is required for calling the JSON API.

Both the web front end and the JSON api use common code to manipulate the database, and each are responsible for using it correctly. This would require some refactoring.

The JSON API and the web front end are totally separate, meaning that everything has to be implemented twice and maintained separately.

答:
You have many options:

Basic authentication over SSL
https://thoughtfulsoftware.wordpress.com/2014/06/30/pre-emptive-http-basic-authentication-with-jquery/

Create a UI with the ability to log-in, create, view and delete blog posts

JQuery has JSON and AJAX capabilities built-in

You just have to explore and decide which libraries to use and what to write yourself and integrate it all together with tests.


问:
Virtual machines versus containers, what use cases are suited to each?
I hear a fair amount of people using Docker these days, and I am wondering where they execl compared to virtual machines, and when a virtual machine would be a more suitable choice. </p>

答:
Docker allows you to easily create and distribute an environment. You can keep the environment identical on all systems. You can make snapshots of these images and docker will pull them down, and [[whatever]] in them the same on all systems.

It is considerably easier to keep this image the same across all users than a VM. It's also considerably more lightweight than a VM both in terms of resources required as well as size.

Virtual machines, however, are slower to startup and also much easier to have differences. They are normally larger as they require a full OS (docker does much less). You have updates and custom installations of software and user settings and all other types of things which may change your "consistent" image.

Some examples:

If you are just looking for a repeatable test environment, it's likely you want to use docker

If you want to test kernel functionality, don't use docker - it shares this with the host OS

If you need to spin up 100s of these for your [[whatever]], probably use docker, as it's much faster

If you need to dedicate resources to your [[whatever]], use a VM as docker is not guaranteed


答:
Unless I am mistaken, one of the biggest reasons to use a Virtual Machine is to virtualize an OS that is different than the hos on. Windows Host -> Linux VM or Linux Host -> BSD VM etc.

It is my understanding that the strength of containers is that that they make use of the underlying host system to reduce requirements. So, if you are using a container, you are basically running a limited instance of your main machine.

Title: Virtual machines versus containers, what use cases are suited to each?

Body: I hear a fair amount of people using Docker these days, and I am wondering where they execl compared to virtual machines, and when a virtual machine would be a more suitable choice. </p>


问:
Haskell AND Lisp vs. Haskell OR Lisp
I currently code with C, C++, and Python. I'm wanting to pick up a functional programming language, and right now I'm leaning toward Haskell. I do NOT want to start a "Haskell vs Lisp" war here; what I want to know is this: if I learn Haskell primarily for exposure to functional programming, what benefits, if any, will I gain from later learning Lisp?

答:
I originally came from a C/C++/Ruby background and I used FP concepts in Ruby whenever I could. State just kinda hurt my brain. One of my buddies called me up one day, and he asked me to write something in Haskell (my first - and hopefully not last - Haskell job!). I quickly learned the language and I threw together something that worked. It wasn't beautiful or anything, but it worked.

I took a month break from Haskell because I didn't have anything to use it for. But when I decided I needed to write my own blog software, I used Haskell (https://symer.io). Haskell is really cool because you can break a problem into parts and implement these parts differently based on input. Haskell also handles failure extremely well through intelligent boxing of values. There are so many tools to work with these boxes that you simply forget they exist.

My experience with lisp (Scheme) was completely negative. Not only did the language lack these intelligent, simple tools, it felt as dangerously loose as Ruby or JavaScript. It was a horrible experience and it offers nothing new beyond Ruby or Python.

C++ can't hold a candle to Haskell, outside of memory management. Haskell is just as fast (if not faster), significantly more terse, and much more safe. But Haskell's safety never gets in the way.

TL;TR Haskell is a breath of fresh air, and Lisp is a slightly more functional Ruby.

Title: Haskell AND Lisp vs. Haskell OR Lisp


答: While it is too early to say about near future, ultimately I think I think it is HTML5 which will be the new standard, I base this hunch on the fact most of the trend-setter like Apple, Google, MS are either making HTML5 their main area of thrust or alternatively making it one of their priorities. Which is why I think we will have mature, stable and fast platform for HTML5.</p>

Title: Is HTML 5 good enough for developers to switch from Flash?

Body:
Just curious, because many developers use Flash to do many things that HTML 4 (correct me if I'm wrong) or below cannot or had a hard time doing, like for example the rounded corners (Canvass) and that Video Thing and many more.

I have not actually explored all of HTML5, so might as well learn it from you.

thanks.


问:
How does printf write to stdout?
I've been looking for an answer to this for a couple days, and all of the results I've come up with are about how printf accepts an arbitrary number of arguments.

How does printf write to stdout? What is the most fundamental way to write to a file in C? How do the standard libraries work?

答:
printf( string, ... ) can be thought of (*1) as internally invoking vfprintf( stdout, string, va_list ) which in turn can be thought of as internally invoking fputs( string, stdout )

The implementation of fputs( string, stdout ) is operating-system specific.

So, (parts of the) standard libraries are rewritten on an operating system by operating system basis to make use of the native facilities provided by the underlying system in order to accomplish their purpose.

(*1) I say "can be thought of" because whether it does precisely that or something else which is equivalent to that is implementation-specific, and none of our concern.

Title: How does printf write to stdout?


问:
Access fields of super class from derived classes
There is an abstract BaseGame class that will be inherited by specific game classes.

This class has an attribute requestHandler that will be used in all subclasses and should be initialized in the constructor, so I put this constructor in superclass.

Is it better (make more sense) to keep requestHandler private (case 1) and access it in subclasses via accessors or make it protected (case 2) and access it directly? Are there any implications in the use of case 1 or case 2, or it just does not matter?

case1:

```<code>public abstract class BaseGame {

    private RequestHandler requestHandler;

    protected BaseGame(RequestHandler requestHand) {
        this.requestHandler = requestHand;
    }

    protected RequestHandler getRequestHandler() {
        return requestHandler;
    }
}

public class SoccerGame extends BaseGame {

    public SoccerGame(RequestHandler requestHand) {
        super(requestHand);
    }

    public void doSoccerGame() {
        getRequestHandler().submitScore(10);
    }

}
</code>```

case 2:

```<code>public abstract class BaseGame {

    protected RequestHandler requestHandler;

    protected BaseGame(RequestHandler requestHand) {
        this.requestHandler = requestHand;
    }
}

public class SoccerGame extends BaseGame {

    public SoccerGame(RequestHandler requestHand) {
        super(requestHand);
    }

    public void doSoccerGame() {
        requestHandler.submitScore(10);
    }
}
</code>```

答:
Contrary to popular belief, accessor methods do not provide any great advantage over direct field accesses, while in java they do tend to clutter the code with lots of gets and ()s.   (Compare with C#, which has an awesome feature called properties, which look like fields but behave like accessors, saving you from all the mindless getSuchAndSuch()s and setSuchAndSuch()s.)

However, "no great advantage" does not mean no advantage at all.  The advantages of using accessor methods instead of direct field access are as follows:

If you need to maintain binary compatibility, then you must use accessor methods, so that the class containing the fields can be modified without breaking code that has already been written to use the class.  (Binary compatibility means compatibility without the necessity to modify and recompile one of the two parties. Since you are writing both the base class and its descendants, this does not apply to you.)

Accessor methods are often inevitable, while direct field access is never inevitable, so going with the "always use accessors" doctrine simplifies things and introduces homogeneity over the entire code base.

As you refactor the code trying various what-if scenarios, sometimes you discover that you have a field which needs to be replaced by a computation, which in turn means that it has to be encapsulated by an accessor method, and sometimes you discover that you have a field which stores the result of a computation and therefore does not have to be hidden behind an accessor method, so the accessor can go and the field can be made protected or public.  If you keep doing this kind of refactoring a lot, then you might get to a point where you might say "aw, forget it!" and hide all fields behind accessor methods so that you don't have to keep refactoring more classes than the one you are working on.

When writing code in java and using a decent IDE, when you have an object and you want to get something from it, you tend to type myObject.get and then the IDE shows you a list of auto-completion options, so you have everything that you can "get" from the object right in front of you.  If you use fields, then you have to stop at myObject. and browse through a list which contains everything, not only just things that can be gotten from the object.  The same applies with myObject.set when you want to set something.

In either case, I would never make a non-final field anything but private.  Luckily, in your case, your requestHandler seems to be a prime candidate for being final, (it probably only gets set in the constructor and never again,) so it is quite legitimate to make it final and protected.


答:
At the lowest possible level from a user program running in some operating system, the libc is making system calls (or syscalls). These are often a single machine instruction (often SYSCALL or SYSENTER) which is given some parameters and which switches the microprocessor to supervisor mode in a controlled way. Then the kernel is processing the parameters and handling the syscall and finally returning to user space.  For Linux, you might read its Assembly HowTo and the x86-64 ABI spec.

BTW, you could install Linux and study the source code of some libc. Notice that musl-libc is quite readable.

Of course syscalls (and the protocol to invoke them) are operating system specific. You could read syscalls(2) to get a list of them (for Linux).

printf (and puts) would ultimately invoke the write(2) syscall. For performance reasons, <stdio.h> is buffering.

Notice that printf is standardized in C99 (a programming language standard) but write is standardized in the POSIX  Portable Operating System Interface standard (but Microsoft Windows is not POSIX compliant).

Often, printf does not call fputs, but will use some syscall (like  write on Linux). BTW, some implementations (notably the GCC compiler and GNU libc thru its __builtin__snprintf* builtins known by /usr/include/bits/stdio2.h included by <stdio.h>) are able to optimize some simple calls to printf  into calls to puts....

Title: How does printf write to stdout?

Body:
I've been looking for an answer to this for a couple days, and all of the results I've come up with are about how printf accepts an arbitrary number of arguments.

How does printf write to stdout? What is the most fundamental way to write to a file in C? How do the standard libraries work?


问:
WebAPI authorisation for other apps
I would like to create a WebAPI application that can serve some of my web sites. My goal is to abstract some common task such as email sending, address resolving etc by providing an API to all of my web sites.

I have created a WebAPI application that implements most of the above APIs but without any authorization. I would like to restrict the access only to my applications.

I could implement identity 2.0 or membership provider but all these are meant to be used from users and not from other web sites. My clients are web sites and not just users.

What would be a good and secure approach to this problem?

答:
You're trying to limit the use of your shared (Web) API so only your sites can use the API.

An alternative to OAuth mentioned by Joe would be to create API controllers in your sites that use your shared API. So, a client would send a request to an API controller on their site and that API controller would call your shared API method. Your site's API controller can then directly return the results to the client. So:

```<code>Client --> Site API --> Central API
Client <-- Site API <------|
</code>```

The advantages of this approach:

You can secure the requests to the central API with an IP-filter in IIS, because only the sites server's IP addresses are allowed to use the central API. This is probably less complex and quicker to implement than OAuth.

You won't have to deal with cross site requests in the client, which might get blocked by browsers.

You can modify or cache the response from the central API if you want to do that. This way you can have site specific modifications without the need to modify the central API.

Title: WebAPI authorisation for other apps

Body:
You're trying to limit the use of your shared (Web) API so only your sites can use the API.

An alternative to OAuth mentioned by Joe would be to create API controllers in your sites that use your shared API. So, a client would send a request to an API controller on their site and that API controller would call your shared API method. Your site's API controller can then directly return the results to the client. So:

Client --> Site API --> Central API
Client <-- Site API <------|

The advantages of this approach:

You can secure the requests to the central API with an IP-filter in IIS, because only the sites server's IP addresses are allowed to use the central API. This is probably less complex and quicker to implement than OAuth.

You won't have to deal with cross site requests in the client, which might get blocked by browsers.

You can modify or cache the response from the central API if you want to do that. This way you can have site specific modifications without the need to modify the central API.


答:
I think Oauth providers (twitter, google, fb) will give you what you want:

they (arguably store credentials securely

ability to authorise applications (not only users)

available from API

there's probably more features that interest you

All you need is to register your application and make some redirections for authentication. It might be not ideal to use 3rd party authentication, but these days who doesn't. Some users might even prefer to use their existing accounts.

If 3rd party doesn't work for you, you can always implement Oauth yourself.

Title: Multi platform password storage with retrieval for applications with authorization?

Body:
I'm working on a development tool that requires knowing one or more api passwords for a user to operate. Currently it works on Mac, and uses keychain to store the credentials for later re-use.

Are there any similar password store options that are cross-platform and have the following properties?

Store the credentials securely

Ability to authorize applications to access the credentials repeatedly without re-authenticating?

Credentials are accessible via an API (provided the user has authorized one-time or indefinite access)?

(Nice-to-have) Ability to authorize applications for a specific time period (i.e. a week or a month), after which the user is required to re-authorize the application.

(Nice-to-have) Support for multi-factor authentication during authorization

Keychain works great in this sense, since it allows me to let them be responsible for the security of the credentials, and allows the credentials to be used by other applications (provided a structured credential key) with authorization that can be one-time or indefinite.

I've attempted to the scour the web (probably poorly), but I'm having trouble with the fact I only get password managers, which are geared towards a user requesting the credentials, rather than an application, or I get instructions for how to properly store using bcrypt, which is great for verifying passwords, but not if I need to retreive it later. For instance, I have a proof of concept for storing the credentials in LastPass, but it requires enter a master password each time the credentials are requested unless I store the master password somewhere accessible, which kind of defeats the purpose of the password manager in the first place.


答:
support for enumerations (like java 1.5+)

Be able to define method return types, in interfaces and classes

support for annotations / metadata definition on properties and methods.

be able to do strict type hinting for method scalar arguments.

Title: What features would you like to have in PHP?

Body:
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.


问:
Can a the kind of load Uber handles be served from just one server?
http://techcrunch.com/2013/12/04/leaked-uber-numbers-which-weve-confirmed-point-to-over-1b-gross-revenue-213m-revenue/

This article says that Uber does about 1M requests a week. Which is about 1.65 reqs a sec.

So does this mean Uber can probably do with just one machine serving their requests? Or am I missing something here?

I realize traffic will be bursty but still doesn't seem like they'd need too many servers even at max load.

Edit: Let's assume we're building a bare bones version of uber where you don't do the realtime GPS locations of drivers & you don't have georeplication.

Say, the app has only this functionality: open the app, and order a cab. The phone triangulates your location and sends a request to the server who then responds with whether a driver was found or not

答:
I guess Requests is "request for service" or order. (because there is "completed requests" metric slightly lower)

Their servers also constantly get's pinged by drivers devices (GPS and other stuff), users looking at available cars, gps tracking of users, etc.

I can't even say how many requests it will be for 1 trip. But if every car pings with GPS every minutes - count it. And thats just one thing.

Servers need to process all this data.

No, it's not out of 1 server :)