答:
The simple way to tell how "close" one solution is to another is to determine its standard error.

Standard error is the standard deviation of answers you get. Then you divide the distance between two solutions by the standard error.
If the answer is less than 1, that's pretty close, because you could get that big of a difference just by randomness.
If less than 2, that's still respectable.
Beyond 2, you say no, not close.

Another way is to get the second derivative of the solution with respect to whatever you're varying.
That second derivative represents the "sharpness" of the solution, and the standard error is proportional to the inverse square root of that.

If you like math, look here and here.

Title: How to measure algorithm accuracy?

Body:
I have a few optimization algorithms (for finding function minimum) and I'd like to check how good they are. Suppose I build test cases and compare the actual results to theoretical ones.
What measures should I use to estimate if the function minimum was actually found?

I thought about:

mean number of function evaluations (± standard deviation)

success rate (how often it actually finds minimum)

Are there any others that I have missed (let's say algorithm finishes 1e-4 from known solution. so is it success already or not?)

My main concern is not time complexity. It is algorithm accuracy in cases when exact solution might never be found (eg. multidimensional solution spaces). How do I calculate the rate of convergence?


问:
Multithreading: am I doing it wrong?
I'm working on an application that plays music.

During playback, often things need to happen on separate threads because they need to happen simultaneously. For example, the notes of a chord need to be heard together, so each one is assigned its own thread to be played in. (Edit to clarify: calling note.play() freezes the thread until the note is done playing, and this is why I need three separate threads to have three notes heard at the same time.)

This kind of behavior creates many threads during playback of a piece of music.

For example, consider a piece of music with a short melody and short accompanying chord progression. The entire melody can be played on a single thread, but the progression needs three threads to play, since each of its chords contains three notes.

So the pseudo-code for playing a progression looks like this:

```<code>void playProgression(Progression prog){
    for(Chord chord : prog)
        for(Note note : chord)
            runOnNewThread( func(){ note.play(); } );
}
</code>```

So assuming the progression has 4 chords, and we play it twice, than we are opening 3 notes * 4 chords * 2 times = 24 threads. And this is just for playing it once.

Actually, it works fine in practice. I don't notice any noticeable latency, or bugs resulting from this.

But I wanted to ask if this is correct practice, or if I'm doing something fundamentally wrong. Is it reasonable to create so many threads each time the user pushes a button? If not, how can I do it differently?

答:
Do not rely on threads executing in lockstep. Every operating system I know of does not make the guarantee that threads execute in time consistent with each other. This means that if the CPU runs 10 threads, they do not necessarily receive equal time in any given second. They could quickly get out of synch, or they could stay perfectly in synch. That is the nature of threads: nothing is guaranteed, since the behavior of their execution is non-deterministic.

For this specific application, I believe you need to have a single thread that consumes music notes. Before it can consume the notes, some other process needs to merge instruments, staffs, whatever into a single piece of music.

Let us assume that you have e.g. three threads producing notes. I would synchronize them on a single data structure where they can all put their music. Another thread (consumer) reads the combined notes and plays them. There may need to be a short delay here to ensure that thread timing does not cause notes to go missing.

Related reading: producer-consumer problem.

ContentLicense: CC BY-SA 3.0

Title: Multithreading: am I doing it wrong?


问:
Is MongoDB appropriate for systems that will be likely to change?
I've been using MongoDb (mainly with Meteor) and for me, it has been a great way to mock up prototypes and proof of concepts quickly.

I'm just wondering, after building the initial product, if your product is likely to grow and change, is it a good idea to stick with mongoDb?

Cause it seems like with MongoDb, you need to know a lot about how you're going to use the data upfront. From my experience only, I seemed to constantly be trying to decide whether a datatype should be a document in its own right or a sub-document.

Making it a document gives it flexibility, but if you have all your datatypes as documents, well then you pretty much just have an SQL database with foreign keys that have no foreign key constaints.

Making it a subdocument makes things perform better whilst being convenient - you don't need to join tables (which you seem to have to do manually) - but the problem seems to be if you need to query that datatype outside the context of the parent, it's very hard.

So for example, if I'm building a website with chatrooms, I might have two datatypes - chatrooms and textEntries.

Chatroom will be its own document. But textEntries can either be a document in its own right or a subdocument within Chatroom.

If I make TextEntries a document, then I would need to manually keep track of the relationship between chatroom and textEntries which defeats the purpose of using mongoDB at all.

If I make TextEntries a subdocument, this will make things easier but what if later on, I have a new requirement where I want to search across all TextEntries in all chatrooms for a particular word?

With a prototype, I know exactly what I'm building so these decisions tend to be based on just getting the product working. But longer term, I wouldn't know how or in what way I'm going to want to query the data so in light of that, would I be better off just moving to an SQL database?

答:
MongoDB is a NoSQL database that focuses on documents.

Document searching in general relies on arbitrary matches in the middle of large amounts of text, fuzzy logic/matching, and other tasks that are not cut and dry boolean logic comparisons that exist in SQL.

I personally know multiple developers at Hyland Software, the company behind OnBase which is a proprietary NoSQL database that efficiently searches millions of documents. To get data into the software, one must scan it in: OCR capabilities latch on to textual data which can later be searched. Rather than making an appeal to authority, I will say that this has enlightened me to the use of NoSQL databases in the enterprise and their proper role.

In a SQL database, you often must know the context of the data you want. Is it a name? Form number? Some other field? With a document-based NoSQL solution, you can search everything using logic that is less than ideal (for SQL) with minimal performance hit. You are not saying "find me records where field X contains Y" you are saying "find me documents containing Y" and the database is optimized for those types of queries. Documents often do not contain clear fields. While a letter (dear grandma) may contain an address, it is not annotated as such. In a RDBMS, the address fields would be split out and queryable. Want the street or city? It is distinct from other elements. In a document database, it is all jammed together. Searching for a specific postal code is not as clear of a query, but document databases are built for it.

Other times, relational databases perform better. Do you need records where you know the field is a specific value, or links to a specific record? SQL is the winner.

Martin Fowler states that each database type has its place, and often are used together. Based on his expert advice, I would not choose one database or the other: I would use both together, leveraging each where its strengths are greater than its weaknesses.

In the specific example of chat on a web site, it makes sense that a text entry would be a subdocument to a chat room (document). A text entry might be quoted out of context, but its identity is, in part, the chat room that contains it. Without the chat room, text entries are a jumbled, meaningless mess.


问:
Is method overloading anything more than syntactic sugar?
Is method overloading a type of polymorphism? To me it seems like simply the differentiation of methods with the same name and different parameters. So stuff(Thing t) and stuff(Thing t, int n) are entirely different methods as far as the compiler and runtime are concerned.

It creates the illusion, on the caller's side, that it's the same method that acts differently on different kinds of objects - polymorphism. But that's only an illusion, because actually stuff(Thing t) and stuff(Thing t, int n) are completely different methods.

Is method overloading anything more than syntactic sugar? Am I missing something?

A common definition for syntactic sugar, is that it is purely local. Meaning changing a piece of code to its 'sweetened' equivalent, or vice versa, involves local changes that don't affect the overall structure of the program. And I think method overloading precisely fits this criterion. Let's look at an example to demonstrate:

Consider a class:

```<code>class Reader {
    public String read(Book b){
        // .. translate the book to text
    }
    public String read(File b){
        // .. translate the file to text
    }
}
</code>```

Now consider another class that uses this class:

```<code>/* might not be the best example */
class FileProcessor {
    Reader reader = new Reader();
    public void process(File file){
        String text = reader.read(file);
        // .. do stuff with the text
    }
}
</code>```

Okay. Now let's see what needs to change if we replace the method overloading with regular methods:

The read methods in Reader change to readBook(Book) and readFile(file). Only a matter of changing their names.

The calling code in FileProcessor changes slightly: reader.read(file) changes to reader.readFile(file).

And that's it.

As you can see, the difference between using method overloading and not using it, are purely local. And that's why I think it qualifies as pure syntactic sugar.

I'd like to hear your objections if you have some, maybe I'm missing something.

答:
In some languages it is no doubt merely syntactic sugar. However, what it is a sugar of depends on your point of view. I'll leave this discussion for later in this answer.

For now I'd just like to note that in some languages it is certainly not syntactic sugar. At least not without requiring you to use a completely different logic/algorithm to implement the same thing. It's like claiming recursion is syntactic sugar (which it is since you can write all recursive algorithm with a loop and a stack).

One example of a very hard to replace use comes from a language that ironically doesn't call this feature "function overloading". Instead it's called "pattern matching" (which can be viewed as a superset of overloading because we can overload not just types but values).

Here's the classic naive implementation of the Fibonacci function in Haskell:

```<code>fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
</code>```

Arguably the three functions can be replaced with an if/else as it is commonly done in any other language. But that fundamentally makes the utterly simple definition:

```<code>fib n = fib (n-1) + fib (n-2)
</code>```

much messier and does not directly express the mathematical notion of the Fibonacci sequence.

So sometimes it can be syntax sugar if the only use is to allow you to call a function with different arguments. But sometimes it is much more fundamental than that.

Now for the discssion of what operator overloading may be a sugar for. You've identified one use-case - it can be used to implement similar functions that take different arguments. So:

```<code>function print (string x) { stdout.print(x) };
function print (number x) { stdout.print(x.toString) };
</code>```

can alternatively be implemented as:

```<code>function printString (string x) {...}
function printNumber (number x) {...}
</code>```

or even:

```<code>function print (auto x) {
    if (x instanceof String) {...}
    if (x instanceof Number) {...}
}
</code>```

But operator overloading may also be a sugar for implementing optional arguments (some languages have operator overloading but not optional arguments):

```<code>function print (string x) {...}
function print (string x, stream io) {...}
</code>```

may be used to implement:

```<code>function print (string x, stream io=stdout) {...}
</code>```

In such a language (google "Ferite language") removing operator overloading drastically removes one feature - optional arguments. Granted in languages with both features (c++) removing one or the other will have no net effect since either can be used to implement optional arguments.

Body:
In some languages it is no doubt merely syntactic sugar. However, what it is a sugar of depends on your point of view. I'll leave this discussion for later in this answer.

For now I'd just like to note that in some languages it is certainly not syntactic sugar. At least not without requiring you to use a completely different logic/algorithm to implement the same thing. It's like claiming recursion is syntactic sugar (which it is since you can write all recursive algorithm with a loop and a stack).

One example of a very hard to replace use comes from a language that ironically doesn't call this feature "function overloading". Instead it's called "pattern matching" (which can be viewed as a superset of overloading because we can overload not just types but values).

Here's the classic naive implementation of the Fibonacci function in Haskell:

fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

Arguably the three functions can be replaced with an if/else as it is commonly done in any other language. But that fundamentally makes the utterly simple definition:

fib n = fib (n-1) + fib (n-2)

much messier and does not directly express the mathematical notion of the Fibonacci sequence.

So sometimes it can be syntax sugar if the only use is to allow you to call a function with different arguments. But sometimes it is much more fundamental than that.

Now for the discssion of what operator overloading may be a sugar for. You've identified one use-case - it can be used to implement similar functions that take different arguments. So:

function print (string x) { stdout.print(x) };
function print (number x) { stdout.print(x.toString) };

can alternatively be implemented as:

function printString (string x) {...}
function printNumber (number x) {...}

or even:

function print (auto x) {
    if (x instanceof String) {...}
    if (x instanceof Number) {...}
}

But operator overloading may also be a sugar for implementing optional arguments (some languages have operator overloading but not optional arguments):

function print (string x) {...}
function print (string x, stream io) {...}

may be used to implement:

function print (string x, stream io=stdout) {...}

In such a language (google "Ferite language") removing operator overloading drastically removes one feature - optional arguments. Granted in languages with both features (c++) removing one or the other will have no net effect since either can be used to implement optional arguments.


问:
How to implement a genetic algorithm with distance, time, and cost
I want to make a solution to find the optimum route of school visit. For example, I want to visit 5 schools (A, B, C, D, E) in my city. Given the choice of five routes regarding what school I should visit first, then the second, then the third etc., how do I calculate the efficiency of each route with distance, time, and cost criteria?

Once I've done this, how do I use my calculations (distance with time and cost fuel usage) in a genetic algorithm to find the optimum route?

答:
For a genetic algorithm you need chromosomes and a fitness function.

The chromosomes represent choices of route. Looks like 5 chromosomes, one for each city in order, but there could be a smarter way.

The fitness function is calculated from the chosen route. Score higher for visiting more cities and for shorter distance and lower cost of the chosen route.

The feed it in and stand back. You should get an optimal answer eventually.


问:
gcc -S seems a bit misshapen with shifting and ANDing bits
Example:

```<code>int c = 4;
int p = 5;

if (p & (1 << c))
   printf("ok\n");
else
   printf("nop\n");
</code>```

gcc -S:

```<code>movl    -4(%rbp), %eax   /* eax holds the variable c  */
movl    -8(%rbp), %edx   /* and edx holds p  */
movl    %eax, %ecx       /* tmp(ecx) = c  */
sarl    %cl, %edx        /* edx(p) >>= c  */
movl    %edx, %eax       /* eax = p shifted right by c */
andl    $1, %eax         /* eax(p shifted right by c) &= 1  */
testl   %eax, %eax       /* test if p is 0  */
... jumps and such ...
</code>```

As you can see, GCC for some reason converted my code to:

```<code>p >>= c;
p &= 1
if (p != 0)
    ...
else
    ...
</code>```

Something fishy is going on here or I am missing something...  It kinda made the operation backwards, although I had brackets around the 1 << c so it should've done it separately then AND it with p correct?

Can someone explain why did GCC do this?  Is it some sort of optimization (I had no optimization enabled when I compiled this, so doubt it) Or is it how it should be done in assembly?

答:
```<code>(1<<c) set the fifth bit. == 0x10 (==16 dec)

p & (1<<c)
</code>```

The condition here is:
"Is the 5th bit set in the variable p?"

To achieve this test you can shift p right by 4 and ask "is the lowest bit set?"
so your code has been converted to
    if((p>>4) & 0x1)

Which is the same thing.

run gcc -S -O3
and the same logic collapses to

```<code>btl %edi, %esi
jc  .L4
</code>```

Body:
(1<<c) set the fifth bit. == 0x10 (==16 dec)

p & (1<<c)

The condition here is:
"Is the 5th bit set in the variable p?"

To achieve this test you can shift p right by 4 and ask "is the lowest bit set?"
so your code has been converted to
    if((p>>4) & 0x1)

Which is the same thing.

run gcc -S -O3
and the same logic collapses to

btl %edi, %esi
jc  .L4


答:
It looks like "syntactic sugar" sounds derogatory, like useless or frivolous.  That is why the question triggers many negative answers.

But you are right, method overloading doesn't add any feature to the language except for the possibility to use the same name for different methods.  You can make the parameter type explicit, the program will still work the same.

The same applies to package names.  String is just syntactic sugar for java.lang.String.

In fact, a method like

```<code>void fun(int i, String c);
</code>```

in class MyClass should be called something like "my_package_MyClass_fun_int_java_lang_String".  This would identify the method uniquely.  (The JVM does something like that internally).  But you don't want to write that.  That is why the compiler will let you write fun(1,"one") and identify which method it is.

There is however one thing you can do with overloading:  If you overload a method with the same number of arguments, the compiler will figure out automatically which version suits best the argument given by matching arguments, not only with equal types, but also where the given argument is a subclass of the declared argument.

If you have two overloaded procedures

```<code>addParameter(String name, Object value);
addParameter(String name, Date value);
</code>```

you don't need to know that there is a specific version of the procedure for Dates.  addParameter("hello", "world) will call the first version, addParameter("now", new Date()) will call the second one.

Of course, you should avoid overloading a method with another method that does a completely different thing.

Body:
Is method overloading a type of polymorphism? To me it seems like simply the differentiation of methods with the same name and different parameters. So stuff(Thing t) and stuff(Thing t, int n) are entirely different methods as far as the compiler and runtime are concerned.

It creates the illusion, on the caller's side, that it's the same method that acts differently on different kinds of objects - polymorphism. But that's only an illusion, because actually stuff(Thing t) and stuff(Thing t, int n) are completely different methods.

Is method overloading anything more than syntactic sugar? Am I missing something?

A common definition for syntactic sugar, is that it is purely local. Meaning changing a piece of code to its 'sweetened' equivalent, or vice versa, involves local changes that don't affect the overall structure of the program. And I think method overloading precisely fits this criterion. Let's look at an example to demonstrate:

Consider a class:

```<code>class Reader {
    public String read(Book b){
        // .. translate the book to text
    }
    public String read(File b){
        // .. translate the file to text
    }
}
</code>```

Now consider another class that uses this class:

```<code>/* might not be the best example */
class FileProcessor {
    Reader reader = new Reader();
    public void process(File file){
        String text = reader.read(file);
        // .. do stuff with the text
    }
}
</code>```

Okay. Now let's see what needs to change if we replace the method overloading with regular methods:

The read methods in Reader change to readBook(Book) and readFile(file). Only a matter of changing their names.

The calling code in FileProcessor changes slightly: reader.read(file) changes to reader.readFile(file).

And that's it.

As you can see, the difference between using method overloading and not using it, are purely local. And that's why I think it qualifies as pure syntactic sugar.

I'd like to hear your objections if you have some, maybe I'm missing something.

Body:
It looks like "syntactic sugar" sounds derogatory, like useless or frivolous.  That is why the question triggers many negative answers.

But you are right, method overloading doesn't add any feature to the language except for the possibility to use the same name for different methods.  You can make the parameter type explicit, the program will still work the same.

The same applies to package names.  String is just syntactic sugar for java.lang.String.

In fact, a method like

void fun(int i, String c);

in class MyClass should be called something like "my_package_MyClass_fun_int_java_lang_String".  This would identify the method uniquely.  (The JVM does something like that internally).  But you don't want to write that.  That is why the compiler will let you write fun(1,"one") and identify which method it is.

There is however one thing you can do with overloading:  If you overload a method with the same number of arguments, the compiler will figure out automatically which version suits best the argument given by matching arguments, not only with equal types, but also where the given argument is a subclass of the declared argument.

If you have two overloaded procedures

addParameter(String name, Object value);
addParameter(String name, Date value);

you don't need to know that there is a specific version of the procedure for Dates.  addParameter("hello", "world) will call the first version, addParameter("now", new Date()) will call the second one.

Of course, you should avoid overloading a method with another method that does a completely different thing.


答:
Depending on the language, it is syntactic sugar or not.

In C++ for instance, you can do things using overloading and templates which would not be possible without complications (write manually all instantiations of the template or add a lot of template parameters).

Note that dynamic dispatch is a form of overloading, dynamically resolved on some parameters (for some languages only a special one, this, but not all languages are so limited), and I would not call that form of overloading syntactic sugar.

Title: Is method overloading anything more than syntactic sugar?


问:
Synchronized access to network industrial equipment
I have an industrial equipment which is controlled by a software. The software connects to it using sockets, and keeps the connection all the time alive, while from time to time sending commands to the equipment. Now, this equipment is represented by a class which encapsulates the sending and receiving of data.

Next, I need to make a UI, that will show the state of the equipment, independent from the controlling software (controlling is on a different thread same solution). Refresh to the UI must be done lets say every second, but it can happen that UI wants to read data, and the controlling software wants to write.

The problem is that the equipment might respond from 50 ms to 1 second, we don't know, and during the response no one must interfere!

How can I best synchronize calls to the equipment communication class?

There might be at least 2 solutions:

Using simple lock(obj) {} statement in C#, for each method in the common. class

Using events and a message queue with a subscriber concept

While the first one might be simple, I assume for my case is the worst solution because it can block everything.

The second one seems more OK, but the problem is that there will be for sure some delay on receiving the results if many subscribers are, or dunno, I'm not really sure.

UPDATE:
I implemented using simple lock. The reason is that some equipment do not have (some do, but most not), on their controller side, the possibility to process multiple request, and their buffer will overflow. So to make sure nothing bad happens, exclusive READ/WRITE lock is best solution I have found so far, and it works.

答:
Either solution would work.  It is a generally good idea to apply a lock when writing to such values.  If you're expecting a lot of reads, then you could use ReaderWriterLockSlim to put a write lock on it, which would prevent other threads from writing the value, but it could be read with no locking whatsoever.  This assumes that the value, at any point in time in your critical area, accurately shows the state of the equipment (in other words, don't set it to zero temporarily, since another thread could read it in that moment).

I would personally favor the 2nd solution since it decouples the value being changed from thread/threads that wish to use it for some scope.  I use the ReaderWriterLockSlim in combination, however, you need not put the value change event publishing inside the critical area since you can't make any assumptions about how the event will be handled by the subscribers, even if in this case it is simply to update the UI.  Should your program change in the future, it would be easy to later adapt it to accomodate new uses for changes made to the value.

Hope that helps!


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
Most folks are focusing on cleverness from an aspect of "The code requires too much deciphering to figure out what it is doing" and all the bad things that go along with that such as

No one else can figure it out, let alone maintain it/debug it.

The person who wrote doesn't even know what it does.

It may actually be not all that brilliant to begin with

etc....

All good points, but there's another negative aspect of cleverness and that is the old ego problem. This causes issues along the lines of

Someone that is too "Smart" to use anyone else's solutions. Why look for what other people have done when you can invent your own way of skinning the same cat?

Someone who thinks they've invented the coolest solution to a problem will often refuse to take any input.

Won't let anyone modify "their" code even when there's obvious issues or a trivial change is needed.

Somewhat conversely, they think they're smart and need to use the "latest" technique to prove how smart they are but fail to get a good handle on it in either personal projects or otherwise non-production code before rolling it into critical parts of the system.

We're all guilty of too much ego sometimes, but when it gets in the way of the team it's a problem.

ContentLicense: CC BY-SA 2.5


答:
I think it is simple syntactic sugar in most languages (at least all I know...) since they all require an unambigous Function-call at compile time. And the compiler simply replaces the function call with an explicit pointer to the right implementation signature.

Example in Java:

```<code>String s; int i;
mangle(s);  // Translates to CALL ('mangle':LString):(s)
mangle(i);  // Translates to CALL ('mangle':Lint):(i)
</code>```

So in the end it could be completely replaced by a simple compiler-macro with search and replace, replacing overloaded Function mangle with mangle_String and mangle_int - since the argument-list is part of the eventual function-identifier this is practically what happens -> and therefore it is only syntactic sugar.

Now if there is a language, where the function is really determined at runtime, like with overridden Methods in objects, this would be different. But I don't think there is such a language, since method.overloading is prone to ambiguity, which the compiler cannot resolve and which has to be handled by the programmer with an explicit cast. This cannot be done at runtime.

Body:
I think it is simple syntactic sugar in most languages (at least all I know...) since they all require an unambigous Function-call at compile time. And the compiler simply replaces the function call with an explicit pointer to the right implementation signature.

Example in Java:

String s; int i;
mangle(s);  // Translates to CALL ('mangle':LString):(s)
mangle(i);  // Translates to CALL ('mangle':Lint):(i)

So in the end it could be completely replaced by a simple compiler-macro with search and replace, replacing overloaded Function mangle with mangle_String and mangle_int - since the argument-list is part of the eventual function-identifier this is practically what happens -> and therefore it is only syntactic sugar.

Now if there is a language, where the function is really determined at runtime, like with overridden Methods in objects, this would be different. But I don't think there is such a language, since method.overloading is prone to ambiguity, which the compiler cannot resolve and which has to be handled by the programmer with an explicit cast. This cannot be done at runtime.


答:
In Java type information is compiled in and which of the overloads is called is decides at compile time.

The following is a snippet from sun.misc.Unsafe (the utility for Atomics) as viewed in Eclipse's class file editor.

```<code>  // Method descriptor #143 (Ljava/lang/Object;I)I (deprecated)
  // Stack: 4, Locals: 3
  @java.lang.Deprecated
  public int getInt(java.lang.Object arg0, int arg1);
    0  aload_0 [this]
    1  aload_1 [arg0]
    2  iload_2 [arg1]
    3  i2l
    4  invokevirtual sun.misc.Unsafe.getInt(java.lang.Object, long) : int [231]
    7  ireturn
      Line numbers:
        [pc: 0, line: 213]
</code>```

as you can see type information of the method being called (line 4) is included in the call.

This means that you could create a java compiler that takes type information. For example using such a notation the above's source would then be:

```<code>@Deprecated
public in getInt(Object arg0, int arg1){
     return getInt$(Object,long)(arg0, arg1);
}
</code>```

and the cast to long would be optional.

In other statically-typed compiled languages you will see a similar setup where the compiler will decide which overload will be called depending on types and include it in the binding/call.

The exception is C dynamic libraries where the type information is not included and trying to create an overloaded function will cause the linker to complain.

Body:
In Java type information is compiled in and which of the overloads is called is decides at compile time.

The following is a snippet from sun.misc.Unsafe (the utility for Atomics) as viewed in Eclipse's class file editor.

  // Method descriptor #143 (Ljava/lang/Object;I)I (deprecated)
  // Stack: 4, Locals: 3
  @java.lang.Deprecated
  public int getInt(java.lang.Object arg0, int arg1);
    0  aload_0 [this]
    1  aload_1 [arg0]
    2  iload_2 [arg1]
    3  i2l
    4  invokevirtual sun.misc.Unsafe.getInt(java.lang.Object, long) : int [231]
    7  ireturn
      Line numbers:
        [pc: 0, line: 213]

as you can see type information of the method being called (line 4) is included in the call.

This means that you could create a java compiler that takes type information. For example using such a notation the above's source would then be:

@Deprecated
public in getInt(Object arg0, int arg1){
     return getInt$(Object,long)(arg0, arg1);
}

and the cast to long would be optional.

In other statically-typed compiled languages you will see a similar setup where the compiler will decide which overload will be called depending on types and include it in the binding/call.

The exception is C dynamic libraries where the type information is not included and trying to create an overloaded function will cause the linker to complain.


答:
It really depends by your defintion of "syntactic sugar". I'll try to address some of the definitions that come to my mind:

A feature is syntactic sugar when a program that uses it can always be translated in an other that doesn't use the feature.

Here we are assuming that there exist a primitive set of features that cannot be translated: in other words no loops of the kind "you can replace feature X using feature Y" and "you can replace feature Y with feature X". If one of the two is true than either the other feature can be expressed in terms of features that aren't the first one or it is a primitive feature.

Same as definition 1 but with the extra requirement that the translated program is as type-safe as the first, i.e. by desugaring you don't loose any kind of information.

The definition of the OP: a feature is syntactic sugar if its translation doesn't change the structure of the program but only requires "local changes".

Let's take Haskell as example for overloading. Haskell provides user-defined overloading via type classes. For example the + and * operations are defined in the Num type class and any type that has a (complete) instance of such class can be used with +. For example:

```<code>instance Num a => Num (b, a) where
    (x, y) + (_, y') = (x, y + y')
    -- other definitions

("Hello", 1) + ("World", 3) -- -> ("Hello", 4)
</code>```

One well-known thing about Haskell's type classes is that you can get rid of them. I.e. you can translate any program that uses type classes in an equivalent program that doesn't use them.

The translation is quite simple:

Given a class definition:

```<code>class (P_1 a, ..., P_n a) => X a where
    op_1 :: t_1   ... op_m :: t_m
</code>```

You can translate it into an algebraic data type:

```<code>data X a = X {
    X_P_1 :: P_1 a, ... X_P_n :: P_n a,
    X_op_1 :: t_1, ..., X_op_m :: t_m
}
</code>```

Here X_P_i and X_op_i are selectors. I.e. given a value of type X a applying X_P_1 to the value will return the value stored in that field, so they are functions with type X a -> P_i a (or X a -> t_i).

For a very rough anology you could think of the values for type X a as structs and then if x is of type X a the expressions:

```<code>X_P_1 x
X_op_1 x
</code>```

could be seen as:

```<code>x.X_P_1
x.X_op_1
</code>```

(It's easy to use only positional fields instead of named fields, but named
fields are easier to handle in the examples and avoid some boiler-plate code).

Given an instance declaration:

```<code>instance (C_1 a_1, ..., C_n a_n) => X (T a_1 ... a_n) where
    op_1 = ...; ...;  op_m = ...
</code>```

You can translate it into a function that given the dictionaries for
the C_1 a_1, ..., C_n a_n classes returns a dictionary value (i.e.
a value of type X a) for the type T a_1 ... a_n.

In other words the above instance can be translated to a function like:

```<code>f :: C_1 a_1 -> ... -> C_n a_n -> X (T a_1 ... a_n)
</code>```

(Note that n may be 0).

And in fact we can define it as:

```<code>f c1 ... cN = X {X_P_1=get_P_1_T, X_P_n=get_P_n_T,
                 X_op_1=op_1, ..., X_op_m=op_m}
    where
        op_1 = ...
        ...
        op_m = ...
</code>```

where op_1 = ... to op_m = ... are the definitions found in the instance declaration and the get_P_i_T are the functions defined by the P_i instance of the T type (these must exist because P_is are superclasses of X).

Given a call to an overloaded function:

```<code>add :: Num a => a -> a -> a
add x y = x + y
</code>```

We can explicitly pass the dictionaries relative to the class constraints and obtain an equivalent call:

```<code>add :: Num a -> a -> a -> a
add dictNum x y = ((+) dictNum) x y
</code>```

Note how the class constraints simply became a new argument. The + in the translated program is the selector as explained before. In other words the translated add function, given the dictionary for the type of its argument will first "unpack" the actual function to compute the result using (+) dictNum and then will apply this function to the arguments.

This is just a very quick sketch about the whole thing. If you are interested you should read the articles of Simon Peyton Jones et al.

I believe a similar approach could be used for overloading in other languages too.

However this shows that, if your definition of syntactic sugar is (1), then overloading is syntactic sugar. Because you can get rid of it.

However the translated program looses some information about the original program. For example it doesn't enforce that the instances for the parent classes exist. (Even though the operations to extract the parent's dictionaries must still be of that type, you can pass in undefined or other polymorphic values so you'd be able to build a value for X y without building the values for P_i y, so the translation doesn't loose all the type safety).
Hence it's not syntacti sugar according to (2)

As for (3). I don't know whether the answer should be a yes or a no.

I'd say no because, for example, an instance declaration becomes a function definition. Functions that are overloaded get a new parameter (which means it changes both the definition and all the calls).

I'd say yes because the two program still map one-to-one, so the "structure" isn't actually changed that much.

This said, I'd say that the pragmatic advantages introduced by overloading are so big that using a "derogatory" term such as "syntactic sugar" doesn't seem correct.

You can translated all Haskell syntax to a very simple Core language (which is actually done when compiling), so most of Haskell syntax could be seen as "syntactic sugar" for something that is just lambda-calculus plus a bit new constructs. However we can agree that the Haskell programs are much easier to handle and are very concise, whereas the translated programs are quite harder to read or think about.

Body:
It really depends by your defintion of "syntactic sugar". I'll try to address some of the definitions that come to my mind:

A feature is syntactic sugar when a program that uses it can always be translated in an other that doesn't use the feature.

Here we are assuming that there exist a primitive set of features that cannot be translated: in other words no loops of the kind "you can replace feature X using feature Y" and "you can replace feature Y with feature X". If one of the two is true than either the other feature can be expressed in terms of features that aren't the first one or it is a primitive feature.

Same as definition 1 but with the extra requirement that the translated program is as type-safe as the first, i.e. by desugaring you don't loose any kind of information.

The definition of the OP: a feature is syntactic sugar if its translation doesn't change the structure of the program but only requires "local changes".

Let's take Haskell as example for overloading. Haskell provides user-defined overloading via type classes. For example the + and * operations are defined in the Num type class and any type that has a (complete) instance of such class can be used with +. For example:

instance Num a => Num (b, a) where
    (x, y) + (_, y') = (x, y + y')
    -- other definitions

("Hello", 1) + ("World", 3) -- -> ("Hello", 4)

One well-known thing about Haskell's type classes is that you can get rid of them. I.e. you can translate any program that uses type classes in an equivalent program that doesn't use them.

The translation is quite simple:

Given a class definition:

class (P_1 a, ..., P_n a) => X a where
    op_1 :: t_1   ... op_m :: t_m

You can translate it into an algebraic data type:

data X a = X {
    X_P_1 :: P_1 a, ... X_P_n :: P_n a,
    X_op_1 :: t_1, ..., X_op_m :: t_m
}

Here X_P_i and X_op_i are selectors. I.e. given a value of type X a applying X_P_1 to the value will return the value stored in that field, so they are functions with type X a -> P_i a (or X a -> t_i).

For a very rough anology you could think of the values for type X a as structs and then if x is of type X a the expressions:

X_P_1 x
X_op_1 x

could be seen as:

x.X_P_1
x.X_op_1

(It's easy to use only positional fields instead of named fields, but named
fields are easier to handle in the examples and avoid some boiler-plate code).

Given an instance declaration:

instance (C_1 a_1, ..., C_n a_n) => X (T a_1 ... a_n) where
    op_1 = ...; ...;  op_m = ...

You can translate it into a function that given the dictionaries for
the C_1 a_1, ..., C_n a_n classes returns a dictionary value (i.e.
a value of type X a) for the type T a_1 ... a_n.

In other words the above instance can be translated to a function like:

f :: C_1 a_1 -> ... -> C_n a_n -> X (T a_1 ... a_n)

(Note that n may be 0).

And in fact we can define it as:

f c1 ... cN = X {X_P_1=get_P_1_T, X_P_n=get_P_n_T,
                 X_op_1=op_1, ..., X_op_m=op_m}
    where
        op_1 = ...
        ...
        op_m = ...

where op_1 = ... to op_m = ... are the definitions found in the instance declaration and the get_P_i_T are the functions defined by the P_i instance of the T type (these must exist because P_is are superclasses of X).

Given a call to an overloaded function:

add :: Num a => a -> a -> a
add x y = x + y

We can explicitly pass the dictionaries relative to the class constraints and obtain an equivalent call:

add :: Num a -> a -> a -> a
add dictNum x y = ((+) dictNum) x y

Note how the class constraints simply became a new argument. The + in the translated program is the selector as explained before. In other words the translated add function, given the dictionary for the type of its argument will first "unpack" the actual function to compute the result using (+) dictNum and then will apply this function to the arguments.

This is just a very quick sketch about the whole thing. If you are interested you should read the articles of Simon Peyton Jones et al.

I believe a similar approach could be used for overloading in other languages too.

However this shows that, if your definition of syntactic sugar is (1), then overloading is syntactic sugar. Because you can get rid of it.

However the translated program looses some information about the original program. For example it doesn't enforce that the instances for the parent classes exist. (Even though the operations to extract the parent's dictionaries must still be of that type, you can pass in undefined or other polymorphic values so you'd be able to build a value for X y without building the values for P_i y, so the translation doesn't loose all the type safety).
Hence it's not syntacti sugar according to (2)

As for (3). I don't know whether the answer should be a yes or a no.

I'd say no because, for example, an instance declaration becomes a function definition. Functions that are overloaded get a new parameter (which means it changes both the definition and all the calls).

I'd say yes because the two program still map one-to-one, so the "structure" isn't actually changed that much.

This said, I'd say that the pragmatic advantages introduced by overloading are so big that using a "derogatory" term such as "syntactic sugar" doesn't seem correct.

You can translated all Haskell syntax to a very simple Core language (which is actually done when compiling), so most of Haskell syntax could be seen as "syntactic sugar" for something that is just lambda-calculus plus a bit new constructs. However we can agree that the Haskell programs are much easier to handle and are very concise, whereas the translated programs are quite harder to read or think about.


问:
Why do we need to include the .h while everything works when including only the .cpp file?
Why do we need to include both the .h and .cpp files while we can make it work solely by including the .cpp file?

For example: creating a file.h containing declarations, then creating a file.cpp containing definitions and including both in main.cpp.

Alternatively: creating a file.cpp containing declaration/definitions ( no prototypes ) including  it in main.cpp.

Both work for me. I can't see the difference. Maybe some insight into the compiling and linking process may help.

答:
You may as well be asking why not just put all your code into one file.

The simplest answer is code maintenance.

There are times when it is reasonable to create a class:

all inlined within a header

all within a compilation unit and no header at all.

The time when it is reasonable to totally inline in a header is when the class is really a data struct with a few basic getters and setters and perhaps a constructor that takes values to initialise its members.

(Templates, that need to be all inlined, are a slightly different issue).

The other time to create a class all within a header is when you might use the class in multiple projects and specifically want to have to avoid linking in libraries.

A time when you might include a whole class within a compilation unit and not expose its header at all is:

An "impl" class that is used only by the class that it implements. It is an implementation detail of that class, and externally is not used.

An implementation of an abstract base class that is created by some kind of factory method that returns a pointer/reference/smart pointer) to the base class. The factory method would be exposed by the class itself would not be. (In addition if the class has an instance that registers itself on a table through a static instance, it doesn't even need to be exposed via a factory).

A "functor" type class.

In other words, where you do not want anyone to include the header.

I know what you might be thinking... If it's just for maintainability, by including the cpp file (or a totally inlined header) you are able to easily edit a file to "find" the code and just rebuild.

However "maintainability" isn't just having the code looking tidy. It is a matter of impacts of change. It is generally known that if you keep a header unchanged and just change an implementation (.cpp) file, it will not be required to rebuild the other source because there should be no side effects.

This makes it "safer" to make such changes without worrying about the knock-on effect and that is what really is meant by "maintainability".

ContentLicense: CC BY-SA 4.0


答:
If the dispatch is resolved at compile time, depending only on the static type of the argument expression, then you can certainly argue that it's "syntactic sugar" replacing two different methods with different names, provided that the programmer "knows" the static type and could just use the right method name in place of the overloaded name. It is also a form of static polymorphism, but in that limited form it's usually not very powerful.

Of course it would be a nuisance to have to change the names of the methods you call whenever you change the type of a variable, but for example in the C language it's considered a manageable nuisance, so C doesn't have function overloading (although it does now have generic macros).

In C++ templates, and in any language that does non-trivial static type deduction, you can't really argue that this is "syntatic sugar" unless you also argue that static type deduction is "syntactic sugar". It would be a nuisance not to have templates, and in the context of C++ it would be an "unmanageable nuisance", since they're so idiomatic to the language and its standard libraries. So in C++ it's rather more than a nice helper, it's important to the style of the language, and so I think you have to call it more than "syntactic sugar".

In Java you might consider it more than just a convenience considering for example how many overloads there are of PrintStream.print and PrintStream.println. But then,  there are as many DataInputStream.readX methods since Java doesn't overload on return type, so in some sense it is just for convenience. Those are all for primitive types.

I don't remember what happens in Java if I have classes A and B extending O, I overload methods foo(O), foo(A) and foo(B), and then in a generic with <T extends O> I call foo(t) where t is an instance of T. In the case where T is A do I get dispatch based on the overload or is it as if I called foo(O)?

If the former, then Java method overloads are better than sugar in the same way that C++ overloads are. Using your definition, I suppose in Java I could locally write a series of type checks (which would be fragile, because new overloads of foo would require additional checks). Aside from accepting that fragility I can't make a local change at the call site to get it right, instead I'd have to give up on writing generic code. I'd argue that preventing bloated code might be syntactic sugar, but preventing fragile code is more than that. For that reason, static polymorphism in general is more than just syntactic sugar. The situation in a particular language might be different, depending how far the language allows you to get by "not knowing" the static type.


问:
How can a new programmer impress the software engineer (boss)?
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.

答: As Steven says, Mason is right -- focus on your own game. The thing to bear in mind is that your boss just wants you to do your own job well. He probably actually likes the fact that he's better than you -- if he wasn't, he might well end up feeling insecure (bosses are human!). Right now, you're in an ideal position to learn from his experience -- don't waste time competing with him, ask his advice on things instead. If you've ever read the 48 Laws of Power, the key one is "Never outshine the master".


答:
Well, yes, you are doing something wrong.

The first thing is that creating Threads is expensive. It has much more overhead than just calling a function.

So what you should do, if you need multiple threads for this job is to recycle the threads.

As it looks to me you have one main thread that does the scheduling of the other threads. So the main thread leads through the music and starts new threads whenever there is a new note to be played.
So instead of letting the threads die and restarting them, better keep the other threads alive in a sleep loop, where they check every x milliseconds (or nanoseconds) if there is a new note to be played and otherwise sleep.
The main thread then doesn't start new threads but tells the existing thread pool to play notes. Only if there aren't enough threads in the pool it can create new threads.

The next one is the synchronization. Hardly any modern multithreading systems actually guarantee that all threads are executed at the same time. If you have more threads and processes running on the machine than cores (which is mostly the case), then the threads don't get 100% of the CPU time. They have to share the CPU. This means every thread gets a small amount of CPU time and then after it had it's share the next thread gets the CPU for a short time. The system doesn't guarantee that your thread gets the same CPU time as the other threads. This means, one thread might be waiting for another one to finish, and thus be delayed.

You should rather have a look if it isn't possible to play multiple notes on one thread, so that the thread prepares all the notes and then only gives the "start" command.

If you need to do it with threads, at least reuse the threads. Then you don't need to have as many threads as there are notes in the whole piece, but only need as many threads as the maximum number of notes played at the same time.

Title: Multithreading: am I doing it wrong?

Body:
I'm working on an application that plays music.

During playback, often things need to happen on separate threads because they need to happen simultaneously. For example, the notes of a chord need to be heard together, so each one is assigned its own thread to be played in. (Edit to clarify: calling note.play() freezes the thread until the note is done playing, and this is why I need three separate threads to have three notes heard at the same time.)

This kind of behavior creates many threads during playback of a piece of music.

For example, consider a piece of music with a short melody and short accompanying chord progression. The entire melody can be played on a single thread, but the progression needs three threads to play, since each of its chords contains three notes.

So the pseudo-code for playing a progression looks like this:

```<code>void playProgression(Progression prog){
    for(Chord chord : prog)
        for(Note note : chord)
            runOnNewThread( func(){ note.play(); } );
}
</code>```

So assuming the progression has 4 chords, and we play it twice, than we are opening 3 notes * 4 chords * 2 times = 24 threads. And this is just for playing it once.

Actually, it works fine in practice. I don't notice any noticeable latency, or bugs resulting from this.

But I wanted to ask if this is correct practice, or if I'm doing something fundamentally wrong. Is it reasonable to create so many threads each time the user pushes a button? If not, how can I do it differently?


答:
Interestingly, the answer to this question will depend on the language.

Specifically, there is an interaction between overloading and generic programming (*), and depending on how generic programming is implemented it might be just syntactic sugar (Rust) or absolutely necessary (C++).

That is, when generic programming is implemented with explicit interfaces (in Rust or Haskell, those would be type classes), then overloading is just syntactic sugar; or actually might not even be part of the language.

On the other hand, when generic programming is implemented with duck-typing (be it dynamic or static) then the name of the method is an essential contract, and therefore overloading is mandatory for the system to work.

(*) Used in the sense of writing a method once, to operate over various types in a uniform fashion.


问:
In which stage of compilation is "typedef" resolved by the compiler?
There are different stages of compilation

Such as

Preprocessing stage

Syntax analysis

Semantic analysis

Intermediate Code generation

Machine Code generation

Optimization

Linking

My question here is in which stage of compilation "typedef" is resolved.

答:
C and C++ don't have context-free grammars. Some of their grammar rules are ambiguous without knowing whether particular identifier identifies a type or not. Therefore the "syntactic" and "semantic" analysis are intermingled. Each statement that is parsed is immediately checked to see whether it introduces any new types and the information is fed back into the lexer so it can classify tokens in reads as either identifiers or type-identifiers. Templates present similar ambiguity with < and > tokens, so template declarations also need to be fed back to lexer.

This also explains why dependent names in templates have to be annotated with typename and/or template keywords. Compilers that build complete abstract syntax tree of templates when they are declared can't do so without knowing which identifiers will identify types and/or templates and they don't know yet when those identifiers depend on the template parameters.


问:
How do I move away from the “for-loop” school of thought?
This is a rather conceptual question, but I was hoping I could get some good advice on this. A lot of the programming I do is with (NumPy) arrays; I often have to match items in two or more arrays that are of different sizes and the first thing I go to is a for-loop or even worse, a nested for-loop. I want to avoid for-loops as much as possible, because they are slow (at least in Python).

I know that for a lot of things with NumPy there are pre-defined commands that I just need to research, but do you (as more experienced programmers) have a general thought process that comes to mind when you have to iterate something?

So I often have something like this, which is awful and I want to avoid it:

```<code>small_array = np.array(["one", "two"])
big_array = np.array(["one", "two", "three", "one"])

for i in range(len(small_array)):
    for p in range(len(big_array)):
        if small_array[i] == big_array[p]:
            print "This item is matched: ", small_array[i]
</code>```

I know there are multiple different ways to achieve this in particular, but I am interested in a general method of thinking, if it exists.

答:
To make things faster you have to read up on your data structures and use the ones appropriate.

For non trivial sizes of small array and big array (let's say small=100 elements and big=10.000 elements) one way to do it is to sort the small array, then iterate over big-array and use a binary search to find matching elements in the small array.

This would make the maximum time complexity, O(N log N) (and for small small-arrays and very big big-arrays it's closer to O(N)) where your nested loop solution is O(N^2)

However. what data structures are most efficient is highly dependent on the actual problem.


问:
Issues regarding new instances of controllers on view pages
Is there any issue with creating a new controller within the ascx view pages. I don't want to create a model, are there any issues with doing it this way.

Normally, the controllers control variables within the model, and the model is the middle point between them, but I am creating a new instance of a controller class within the ascx page itself. Is this ok?

**EDIT
I want to know the implications of putting an instance of a controller class directly into the asp.net ascx code on a view page

Thanks

答:
Your basically asking what the implications of breaking the MVC pattern are.  You can write an application in anyway you want.  However, the advantage of using a pattern like MVC is that it is widely known.  Any programmer who understands MVC can look at your application and say "Yes, I understand how the data flows throughout your application and I can add features to this existing application."  If you go off book and start using an unrecognized pattern then only you will know how it works.  You will have to spend time training someone else to learn how to modify your code.  Another downside is if you need help with your application, then your going to have to find someone who understands your code before they can help you.

If you've already written code using the MVC pattern, then you should continue to do so.  Changing the method by which data is being passed around your application after you have begun writing it is a bad idea.  The code will be confusing to anyone else and probably you after not working on it for a couple months.

If you are creating an instance of a controller class in your view, then you will need to test that.  This may be a pain to test.  I don't know how you are planning to use the controller once instantiated, but if your planning to do any logic in your view, then it will be difficult to test.  There is a reason that the controller modifies the view and not the other way around.  It's easier to test a controller than it is a view.

Those are some reasons why diverging from the MVC pattern and why creating a controller inside a view is a bad idea.  I'm certain there are some good reasons to do it, but I'll let someone else explore those.


答:
This is a common conceptual difficulty when learning to use NumPy effectively. Normally, data processing in Python is best expressed in terms of iterators, to keep memory usage low, to maximize opportunities for parallelism with the I/O system, and to provide for reuse and combination of parts of algorithms.

But NumPy turns all that inside out: the best approach is to express the algorithm as a sequence of whole-array operations, to minimize the amount of time spent in the slow Python interpreter and maximize the amount of time spent in fast compiled NumPy routines.

Here's the general approach I take:

Keep the original version of the function (which you are confident is correct) so that you can test it against your improved versions both for correctness and speed.

Work from the inside out: that is, start with the innermost loop and see if can be vectorized; then when you've done that, move out one level and continue.

Spend lots of time reading the NumPy documentation. There are a lot of functions and operations in there and they are not always brilliantly named, so it's worth getting to know them. In particular, if you find yourself thinking, "if only there were a function that did such-and-such," then it's well worth spending ten minutes looking for it. It's usually in there somewhere.

There's no substitute for practice, so I'm going to give you some example problems. The goal for each problem is to rewrite the function so that it is fully vectorized: that is, so that it consists of a sequence of NumPy operations on whole arrays, with no native Python loops (no for or while statements, no iterators or comprehensions).

Problem 1

```<code>def sumproducts(x, y):
    """Return the sum of x[i] * y[j] for all pairs of indices i, j.

    >>> sumproducts(np.arange(3000), np.arange(3000))
    20236502250000

    """
    result = 0
    for i in range(len(x)):
        for j in range(len(y)):
            result += x[i] * y[j]
    return result
</code>```

Problem 2

```<code>def countlower(x, y):
    """Return the number of pairs i, j such that x[i] < y[j].

    >>> countlower(np.arange(0, 200, 2), np.arange(40, 140))
    4500

    """
    result = 0
    for i in range(len(x)):
        for j in range(len(y)):
            if x[i] < y[j]:
                result += 1
    return result
</code>```

Problem 3

```<code>def cleanup(x, missing=-1, value=0):
    """Return an array that's the same as x, except that where x ==
    missing, it has value instead.

    >>> cleanup(np.arange(-3, 3), value=10)
    ... # doctest: +NORMALIZE_WHITESPACE
    array([-3, -2, 10, 0, 1, 2])

    """
    result = []
    for i in range(len(x)):
        if x[i] == missing:
            result.append(value)
        else:
            result.append(x[i])
    return np.array(result)
</code>```

Spoilers below. You'll get much the best results if you have a go yourself before looking at my solutions!

Answer 1

 np.sum(x) * np.sum(y)

Answer 2

 np.sum(np.searchsorted(np.sort(x), y))

Answer 3

 np.where(x == missing, value, x)

Title: How do I move away from the “for-loop” school of thought?

Body:
This is a rather conceptual question, but I was hoping I could get some good advice on this. A lot of the programming I do is with (NumPy) arrays; I often have to match items in two or more arrays that are of different sizes and the first thing I go to is a for-loop or even worse, a nested for-loop. I want to avoid for-loops as much as possible, because they are slow (at least in Python).

I know that for a lot of things with NumPy there are pre-defined commands that I just need to research, but do you (as more experienced programmers) have a general thought process that comes to mind when you have to iterate something?

So I often have something like this, which is awful and I want to avoid it:

```<code>small_array = np.array(["one", "two"])
big_array = np.array(["one", "two", "three", "one"])

for i in range(len(small_array)):
    for p in range(len(big_array)):
        if small_array[i] == big_array[p]:
            print "This item is matched: ", small_array[i]
</code>```

I know there are multiple different ways to achieve this in particular, but I am interested in a general method of thinking, if it exists.

Body:
This is a common conceptual difficulty when learning to use NumPy effectively. Normally, data processing in Python is best expressed in terms of iterators, to keep memory usage low, to maximize opportunities for parallelism with the I/O system, and to provide for reuse and combination of parts of algorithms.

But NumPy turns all that inside out: the best approach is to express the algorithm as a sequence of whole-array operations, to minimize the amount of time spent in the slow Python interpreter and maximize the amount of time spent in fast compiled NumPy routines.

Here's the general approach I take:

Keep the original version of the function (which you are confident is correct) so that you can test it against your improved versions both for correctness and speed.

Work from the inside out: that is, start with the innermost loop and see if can be vectorized; then when you've done that, move out one level and continue.

Spend lots of time reading the NumPy documentation. There are a lot of functions and operations in there and they are not always brilliantly named, so it's worth getting to know them. In particular, if you find yourself thinking, "if only there were a function that did such-and-such," then it's well worth spending ten minutes looking for it. It's usually in there somewhere.

There's no substitute for practice, so I'm going to give you some example problems. The goal for each problem is to rewrite the function so that it is fully vectorized: that is, so that it consists of a sequence of NumPy operations on whole arrays, with no native Python loops (no for or while statements, no iterators or comprehensions).

Problem 1

def sumproducts(x, y):
    """Return the sum of x[i] * y[j] for all pairs of indices i, j.

    >>> sumproducts(np.arange(3000), np.arange(3000))
    20236502250000

    """
    result = 0
    for i in range(len(x)):
        for j in range(len(y)):
            result += x[i] * y[j]
    return result

Problem 2

def countlower(x, y):
    """Return the number of pairs i, j such that x[i] < y[j].

    >>> countlower(np.arange(0, 200, 2), np.arange(40, 140))
    4500

    """
    result = 0
    for i in range(len(x)):
        for j in range(len(y)):
            if x[i] < y[j]:
                result += 1
    return result

Problem 3

def cleanup(x, missing=-1, value=0):
    """Return an array that's the same as x, except that where x ==
    missing, it has value instead.

    >>> cleanup(np.arange(-3, 3), value=10)
    ... # doctest: +NORMALIZE_WHITESPACE
    array([-3, -2, 10, 0, 1, 2])

    """
    result = []
    for i in range(len(x)):
        if x[i] == missing:
            result.append(value)
        else:
            result.append(x[i])
    return np.array(result)

Spoilers below. You'll get much the best results if you have a go yourself before looking at my solutions!

Answer 1

 np.sum(x) * np.sum(y)

Answer 2

 np.sum(np.searchsorted(np.sort(x), y))

Answer 3

 np.where(x == missing, value, x)


问:
UI Applications and operations in background threads
I am not really sure about what is the best way to deal with operations executed in background threads in an application I am writing.

I am writing it in C# and I am following the MVVM design pattern. Some user actions are expensive and I'd like to run them in a background thread, which is a quite straightforward approach.

The worker thread then modifies my model, which notifies the ViewModel that something changed and finally the change gets propagated to the View.

My problem is that the chain of events triggered would cause the modification of the View from the background thread, when it is only allowed in the UI thread.

I know I can use the UI thread dispatcher but I am not really sure where (could the view-model be the right place?) so I'd like to know if you follow any design pattern to address this situation.

答:
For scenarios like this, you should be using either BackgroundWorker or Task.

Example code for BackgroundWorker usage:

```<code>var bw = new BackgroundWorker();
bw.DoWork += LongRunningBackgroundWork;
bw.RunWorkerCompleted += LongRunningBackgroundWorkCompleted;
bw.RunWorkerAsync();

void LongRunningBackgroundWork(object sender, DoWorkEventArgs e)
{
    // Perform long running task/work
    // Stuff e.Result with results
}

// this runs on the thread that kicked off BackgroundWorker
void LongRunningBackgroundWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // Access results from e.Result
    // Any exceptions from e.Error
    // Update ViewModel and inturn UI with the results
}
</code>```

Refer to this MSDN How-to for step-by-step example on BackgroundWorker usage.

Example Code for Task Usage:

```<code>var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

Task.Run(() =>
{
    // Long running Background work
    // return Results
}).ContinueWith(task =>
{
    // access results from "task.Result"
    // any errors from task.Exception and task.Exception.InnerExceptions
    // Update ViewModel inturn UI with the results
}, uiScheduler); // Pass the UI Scheduler, so that this task runs on UI thread!
</code>```

And refer to this MSDN How-to for step-by-step example on scheduling work on UI thread.

Body:
For scenarios like this, you should be using either BackgroundWorker or Task.

Example code for BackgroundWorker usage:

var bw = new BackgroundWorker();
bw.DoWork += LongRunningBackgroundWork;
bw.RunWorkerCompleted += LongRunningBackgroundWorkCompleted;
bw.RunWorkerAsync();

void LongRunningBackgroundWork(object sender, DoWorkEventArgs e)
{
    // Perform long running task/work
    // Stuff e.Result with results
}

// this runs on the thread that kicked off BackgroundWorker
void LongRunningBackgroundWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // Access results from e.Result
    // Any exceptions from e.Error
    // Update ViewModel and inturn UI with the results
}

Refer to this MSDN How-to for step-by-step example on BackgroundWorker usage.

Example Code for Task Usage:

var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

Task.Run(() =>
{
    // Long running Background work
    // return Results
}).ContinueWith(task =>
{
    // access results from "task.Result"
    // any errors from task.Exception and task.Exception.InnerExceptions
    // Update ViewModel inturn UI with the results
}, uiScheduler); // Pass the UI Scheduler, so that this task runs on UI thread!

And refer to this MSDN How-to for step-by-step example on scheduling work on UI thread.


问:
Are there any downsides to replacing js confirm boxes with "mark record as deleted"?
I believe in the user experience of always having a confirm pop-up for deletions.
However (though we're very used to it), a separate small pop-up window is not ideal and for users on different browsing devices, using different input devices, they can be a nightmare.

So I was thinking of changing all my 'confirm delete?' pop-ups into NOT having a pop-up, deleting the record immediately BUT then offering a link to restore the record on whatever page they user is put on after the 'delete'.

This absolutely requires that I update the application so that instead of deleting the record, it is either marked as deleted, or moved to a 'deleted_original-table-name' and thus in either case can be deleted.

There may then be an 'admin' process available to periodically delete them permanently.

I am looking for thoughts on why this might be a bad idea and any pitfalls to watch for.

I'd like to know if there are any advantages/disadvantages to moving it to a separate table vs. marking it has deleted.

答:
TBH I wouldn't move it to a separate database or table as that would just be an extra layer of complication.

In my last job, who developed and maintained enterprise solutions for large clients, we would leave the records in place, just using a bit field/boolean to hide it from the user. A user with higher privileges could come along and then undelete a record if it was done in error.

After a period of time, a deletion service would run which would then do a hard delete on these records. You could add a "DeletedOn" field to decide whether a record was deleted long enough ago to justify a hard delete.

I'm going to be implementing something similar in my new project soon.


答:
If you write the whole code in the same file, then it will make your code ugly.

Secondly, you will not be able to share your written class with others. According to software engineering you should write client code separately. The client should not know how your program is working. They just need output If you write the whole program in the same file it will leak your program's security.

Title: Why do we need to include the .h while everything works when including only the .cpp file?

Body:
Why do we need to include both the .h and .cpp files while we can make it work solely by including the .cpp file?

For example: creating a file.h containing declarations, then creating a file.cpp containing definitions and including both in main.cpp.

Alternatively: creating a file.cpp containing declaration/definitions ( no prototypes ) including  it in main.cpp.

Both work for me. I can't see the difference. Maybe some insight into the compiling and linking process may help.


问:
Decoupling software components via naming convention
I'm currently evaluating alternatives to refactor a drivermanagement.

In my multitier architecture I have

Baseclass

DAL.Device //my entity

Interfaces

BL.IDriver //handles the dataprocessing between application and device

BL.IDriverCreator //creates an IDriver from a Device

BL.IDriverFactory //handles the driver creation requests

Every specialization of Device has a corresponding IDriver implementation and a corresponding IDriverCreator implementation.

At the moment the mapping is fix via a type check within the business layer / DriverFactory. That means every new driver needs a) changing code within the DriverFactory and b) referencing the new IDriver implementation / assembly. On a customers point of view that means, every new driver, used or not, needs a complex revalidation of their hardware environment, because it's a critical process.

My first inspiration was to use a caliburn micro like nameconvention

see Caliburn.Micro: Xaml Made Easy

BL.RestDriver

BL.RestDriverCreator

DAL.RestDevice

After receiving the RestDevicewithin the IDriverFactory I can load all driver dlls via reflection and do a namesplitting/comparing (extracting the xx from xxDriverCreator and xxDevice)

Another idea would be a custom attribute (which also leads to comparing strings).

My question: is that a good approach above layer borders? If not, what would be a good approach?

答: I would choose a custom attribute over a naming convention. This is the method used in most reflection based API's in .net. It prevents mistakes caused by accidental name matches or mismatches.</p>


问:
Is there a better alternative than abusing the IDisposable pattern?
Consider the following (Microsoft-sanctioned) code:

```<code><% using (Html.Form<HomeController>(action=>action.Index())) { %>

    <input type="text" id="search" />

    <input type="button" value="Submit" />

<% } %>
</code>```

The using statement has but one purpose here: to add a </form> tag to the end of the generated HTML.

This feels dirty to me, for what I hope are obvious reasons:

It's not using's raison d'etre.

It deliberately causes side-effects.

It's not intuitive that Html.Form would implement IDisposable.

The using statement is not actually required, but Html.Form will break without it (unless you emit </form> yourself, which kinda misses the whole point).

This is not the only abuse that people have heaped onto the using pattern.

The question is, is there a viable alternative that provides the same stylistic/readability benefits as using, without making you feel like taking a shower afterwards?

答:
No, not in .NET currently.

using (by design) is the only thing that's guaranteed to have that sort of deterministic two-part execution that you can actually work with. (lock does too, but it doesn't expose anything you can hook into - and would be dirtier)

AoP solutions can maybe help, but I've not seen any that work well at the sub-function level, let alone in html templates.

There's the option of passing an anonymous delegate into a function (which then executes the lambda and disposes of the resource), but that's ugly:

```<code>Using.Transaction(new Resource(), ()=>{
  Foo();
  Bar();
});
</code>```

And it has some limitations:

The compiler won't enforce that the resource is a previously undeclared resource like using blocks do.

You can't exit the lambda unconventionally like you can a using block (via return, break, continue, yield, goto)

(though the yield case is a known language bug and the other non-return cases are highly distasteful)

You can't access ref/out params from the lambda.

You can't use unsafe code in the lambda.

You can't "chain" the using blocks nicely.

Most of these can be circumvented by using named methods rather than anonymous, but that leads to its own problems.

Body:
No, not in .NET currently.

using (by design) is the only thing that's guaranteed to have that sort of deterministic two-part execution that you can actually work with. (lock does too, but it doesn't expose anything you can hook into - and would be dirtier)

AoP solutions can maybe help, but I've not seen any that work well at the sub-function level, let alone in html templates.

There's the option of passing an anonymous delegate into a function (which then executes the lambda and disposes of the resource), but that's ugly:

Using.Transaction(new Resource(), ()=>{
  Foo();
  Bar();
});

And it has some limitations:

The compiler won't enforce that the resource is a previously undeclared resource like using blocks do.

You can't exit the lambda unconventionally like you can a using block (via return, break, continue, yield, goto)

(though the yield case is a known language bug and the other non-return cases are highly distasteful)

You can't access ref/out params from the lambda.

You can't use unsafe code in the lambda.

You can't "chain" the using blocks nicely.

Most of these can be circumvented by using named methods rather than anonymous, but that leads to its own problems.


问:
C# - initialize variable inside method and use in whole class
this is a conceptual question, but if i initialize a variable in c# as public will it be able to be used in the class as I want a variable "player1" and a variable "player2" where either could be one of the two (or more)

Player

Computer

Here is what i would like to know how I would do:

```<code>public class Game
{
    //equivalent of initializing it here
    public bool islogging;
    public string[] log;
    public int draws, round;

    public Game(player p1, computer p2)
    {
        public player player1 = p1;
        public computer player2 = p2;
    }
    //other overloads here...
    ...
}
</code>```

trying this it doesn't work as the public keyword is rejected

```<code>public Game(player p1, player p2 )
{
     public  player player1, player2;
     player player3 = p1;
     player player4 = p2;

 }
</code>```

答:
It's a fundamental matter of scope.

Variables declared within a function are bound to the lifespan and accessibility of that function.*

C# doesn't allow you to declare variables that will persist as part of the class from within a function.

*Lambda expression can sometimes invalidate that statement, but that's well outside the scope of what you're asking.

To accomplish what you're asking, use this syntax.

```<code>public class Game
{
    //equivalent of initializing it here
    public bool islogging;
    public string[] log;
    public int draws, round;
    public player player1;
    public computer player2

    public Game(player p1, computer p2)
    {
        player1 = p1;
        player2 = p2;
    }
    //other overloads here...
    ...
}
</code>```

or you could also try the following.  But keep in mind that player1 and player2's scope will end with the constructor function.

```<code>public class Game
{
    //equivalent of initializing it here
    public bool islogging;
    public string[] log;
    public int draws, round;
    public player player1;
    public computer player2

    public Game(player p1, computer p2)
    {
        player player1 = p1;
        computer player2 = p2;
    }
    //other overloads here...
    ...
}
</code>```

Body:
It's a fundamental matter of scope.

Variables declared within a function are bound to the lifespan and accessibility of that function.*

C# doesn't allow you to declare variables that will persist as part of the class from within a function.

*Lambda expression can sometimes invalidate that statement, but that's well outside the scope of what you're asking.

To accomplish what you're asking, use this syntax.

public class Game
{
    //equivalent of initializing it here
    public bool islogging;
    public string[] log;
    public int draws, round;
    public player player1;
    public computer player2

    public Game(player p1, computer p2)
    {
        player1 = p1;
        player2 = p2;
    }
    //other overloads here...
    ...
}

or you could also try the following.  But keep in mind that player1 and player2's scope will end with the constructor function.

public class Game
{
    //equivalent of initializing it here
    public bool islogging;
    public string[] log;
    public int draws, round;
    public player player1;
    public computer player2

    public Game(player p1, computer p2)
    {
        player player1 = p1;
        computer player2 = p2;
    }
    //other overloads here...
    ...
}


问:
Implementing custom "Remember Me" with Stripe
Implementing remember me with Stripe, while not using their Checkout (not supported on PhoneGap), seems to be fine using the path:

First time:

Request token on the client side using card info.

Create customer on server side using token.

Upon confirm, charge customer.

Second time:

Check if current user is Stripe customer by requesting the info from our server.

If is Stripe customer, show "use credit card on file" instead of regular CC form.

Upon confirm, charge customer.

However, there is one important convenience items missing--last four digits of card number. Most sites inform you of the card you're using before making the payment, pretty important in case you have to switch out cards.

I have seen that you can retrieve charges which would allow me to get the last four digits. Is it bad practice to pull that and display it?

Are there alternative solutions anyone has in mind?

答:
I've implemented something very similar to what you describe. Any time the user wanted to fund his/her account, he/she had the option of either providing a credit card number, or, if applicable, re-using the last credit card.

In this implementation, I just stored the last four digits of the "default" card at Stripe locally, in my own database table. When building the credit card entry form, the server looked for this stored value, and, if present, the server rendered a checkbox back to the browser, labeled something like "Use Credit Card XXXX XXXX XXXX 1234". If the user checked the box, then my code would submit a transaction to Stripe indicating that the default card should be used.

Three factors led me to this design:

1) We wanted to be able to list funding transactions (both successful and failed) for our users. These listings needed to show the last four digits of the credit card number, to give the user necessary context information about each funding attempt. Perhaps we could have queried Stripe transaction by transaction when building this listing for the user, but that seems like a lot of back-and-forth. So we really wanted to store "last four digit" info anyway.

2) Storing the last 4 digits of the credit card did not seem like a big security risk. It's customary to show the last 4 digits in less secure situations. So, while we did not want to store full credit card numbers in the database, we thought that storing the last 4 digits of certain cards was acceptable.

3) It was simple. There was no need to manage a list of card numbers for each user, but the vast majority of use cases for something like that were (in my estimation) addressed anyway.

Presumably, if someone got the last 4 digits from our database, and then intercepted Stripe traffic from our site, they might have some sort of head start on decrypting this traffic. But this is a far smaller risk than storing real credit cards would be.


问:
Help identify terminology for pattern substituion?
This is a badly titled question...maybe a moderator can make it better.

Nearly two decades ago, I took a computer graphics class as an undergraduate.  We got to do whatever we wanted for a final project as long as it demonstrated what we learned about CG.

So, I read a book (I can't think of the name at all) that described a methodology to generate fractal images starting with a simple shape and mutating it using substitution.  It described abstract fractals and tree/flower fractals. I do recall implementing the Sierpinski Triangle in one of my sample imputs as well as a 3D tree.

The input to the program was basically a series of arbitrary symbols defined by the program.  -----= might represent a rose.  Then you apply some substitutions for a given pattern.  --= > -+=---= might represent a longer rose with thorns.  So, applying that pattern to the initial string you get ----+=---=. Finally you loop over this string N number of times to create some desired effect.

The book itself offered a ton of inputs with sample pictures, but no actual source code.  The implementation was completely left up to the developer.

I would like to know if somebody can help me with the terminology for this technique and bonus points for the name of the book (or a book) that described this process?

答:
My first guess is that you're thinking of L-systems: http://en.m.wikipedia.org/wiki/Lindenmayer_system

I found this example at http://en.m.wikipedia.org/wiki/Koch_snowflake , linked from the Sierpinski page:

```<code>The Koch Curve can be expressed by a rewrite system (Lindenmayer system).

Alphabet : F
Constants : +, −
Axiom : F++F++F
Production rules:
F → F−F++F−F

Here, F means "draw forward", + means "turn right 60°", and − means "turn left 60°".
</code>```

Body:
My first guess is that you're thinking of L-systems: http://en.m.wikipedia.org/wiki/Lindenmayer_system

I found this example at http://en.m.wikipedia.org/wiki/Koch_snowflake , linked from the Sierpinski page:

The Koch Curve can be expressed by a rewrite system (Lindenmayer system).

Alphabet : F
Constants : +, −
Axiom : F++F++F
Production rules:
F → F−F++F−F

Here, F means "draw forward", + means "turn right 60°", and − means "turn left 60°".


答:
What the program is most likely doing is taking the input pattern and interpreting each symbol as a "command", which are run in a looping sequence as modifications to a basic drawing pattern. For instance, "-" might be "draw the next line segment normally". "=" might be "draw this line segment thicker than normal", ">" might be "turn left" and "<" would be "turn right", and finally "+" could mean "start drawing in three directions in parallel".

So, it's basically just a command parsing algorithm. A relatively novel one, but on the whole no more complex than something written to parse more verbose commands.

Title: Help identify terminology for pattern substituion?

Body:
This is a badly titled question...maybe a moderator can make it better.

Nearly two decades ago, I took a computer graphics class as an undergraduate.  We got to do whatever we wanted for a final project as long as it demonstrated what we learned about CG.

So, I read a book (I can't think of the name at all) that described a methodology to generate fractal images starting with a simple shape and mutating it using substitution.  It described abstract fractals and tree/flower fractals. I do recall implementing the Sierpinski Triangle in one of my sample imputs as well as a 3D tree.

The input to the program was basically a series of arbitrary symbols defined by the program.  -----= might represent a rose.  Then you apply some substitutions for a given pattern.  --= > -+=---= might represent a longer rose with thorns.  So, applying that pattern to the initial string you get ----+=---=. Finally you loop over this string N number of times to create some desired effect.

The book itself offered a ton of inputs with sample pictures, but no actual source code.  The implementation was completely left up to the developer.

I would like to know if somebody can help me with the terminology for this technique and bonus points for the name of the book (or a book) that described this process?


答:
I don't see how you can get around the dependency on a common interface for plugins (IDriver in this example). Maybe I am not understanding that right. Anyway, naming convention is the preferred and modern way of structuring software over convention. Asp.net itself uses the pattern.

You may want to include a tool to validate the assemblies to make sure they comply with the convention, but otherwise I say go for it.

Title: Decoupling software components via naming convention

Body:
I'm currently evaluating alternatives to refactor a drivermanagement.

In my multitier architecture I have

Baseclass

DAL.Device //my entity

Interfaces

BL.IDriver //handles the dataprocessing between application and device

BL.IDriverCreator //creates an IDriver from a Device

BL.IDriverFactory //handles the driver creation requests

Every specialization of Device has a corresponding IDriver implementation and a corresponding IDriverCreator implementation.

At the moment the mapping is fix via a type check within the business layer / DriverFactory. That means every new driver needs a) changing code within the DriverFactory and b) referencing the new IDriver implementation / assembly. On a customers point of view that means, every new driver, used or not, needs a complex revalidation of their hardware environment, because it's a critical process.

My first inspiration was to use a caliburn micro like nameconvention

see Caliburn.Micro: Xaml Made Easy

BL.RestDriver

BL.RestDriverCreator

DAL.RestDevice

After receiving the RestDevicewithin the IDriverFactory I can load all driver dlls via reflection and do a namesplitting/comparing (extracting the xx from xxDriverCreator and xxDevice)

Another idea would be a custom attribute (which also leads to comparing strings).

My question: is that a good approach above layer borders? If not, what would be a good approach?


问:
What are the so-called "levels" of understanding multithreading?
I seem to remember reading somewhere some list of 4 "levels" of understanding multithreading. This may have been in a formal publication, or it may have been in an extremely informal context (even like in a Stack Overflow question, for example). Unfortunately I don't remember who referred to them or precisely what they were.

I seem to recall that they were roughly like:

Total ignorance

Awareness mixed with incompetence

Relative competence mixed with fear

True understanding

My intention is to refer to these levels in a blog post I'm writing, with a reference; but I can't for the life of me remember where I first encountered this list. Brief Google searches have proved unfruitful.

答:
Peter Van Roy specifies a hierarchy of competence specific to multithreading. Roughly, the stages are:

single-threaded

deterministic concurrency without the possibility of race conditions

asynchronous message passing

global mutable state

Convergence in Language Design: A Case of Lightning Striking Four Times in the Same Place


答:
I would think of the problem in the opposite way. Instead of "soft delete" think of it as an archive flag. You should never plan on restoring the record, since you will either have to circumvent your rules for new records, which may have changed since this record was created, or allow the record to slip past your "new record" business logic and possibly violate uniqueness rules and other such guidelines that are not established as database constraints.

I don't see a "restore" feature working very well, in fact working worse and worse as your business changes (but your "soft delete"-ed data stays the same). Unless you make all the plans for the undelete feature at the same time you design the soft delete feature and test it (as well as continuing to test it through time).

What's more realistic is that you will create an "archive" system that sits beside your production system. Every so often, archived rows will be sent there. When they are needed they can be swivel-chair entered into the new system by a data entry clerk, effectively being recreated from scratch.

It should be noted that either design will work for such a scenario.

Title: Are there any downsides to replacing js confirm boxes with "mark record as deleted"?

Body:
I believe in the user experience of always having a confirm pop-up for deletions.
However (though we're very used to it), a separate small pop-up window is not ideal and for users on different browsing devices, using different input devices, they can be a nightmare.

So I was thinking of changing all my 'confirm delete?' pop-ups into NOT having a pop-up, deleting the record immediately BUT then offering a link to restore the record on whatever page they user is put on after the 'delete'.

This absolutely requires that I update the application so that instead of deleting the record, it is either marked as deleted, or moved to a 'deleted_original-table-name' and thus in either case can be deleted.

There may then be an 'admin' process available to periodically delete them permanently.

I am looking for thoughts on why this might be a bad idea and any pitfalls to watch for.

I'd like to know if there are any advantages/disadvantages to moving it to a separate table vs. marking it has deleted.


答:
Here, use one of these (ViewBag, ViewData, etc):

http://forums.asp.net/t/1893283.aspx?What+is+ViewData+and+ViewBag+in+ASP+Net+MVC4+and+what+is+use+and+with+examle+

If you can't stick with the pattern at least work within it...

Title: Issues regarding new instances of controllers on view pages

Body:
Is there any issue with creating a new controller within the ascx view pages. I don't want to create a model, are there any issues with doing it this way.

Normally, the controllers control variables within the model, and the model is the middle point between them, but I am creating a new instance of a controller class within the ascx page itself. Is this ok?

**EDIT
I want to know the implications of putting an instance of a controller class directly into the asp.net ascx code on a view page

Thanks