答:
I've found that there are 2 secrets of relative happiness:

do not seek to have everything you want but seek to want everything you have

life it's tough - it doesn't matter how hard you can hit (good you are, personally and professionally); it will always hit back harder. it matters how much you can get hit and still be able to move on.

After all it's all a walk in the park and there are more important things than bits and bytes, and practices and stuff. Just enjoy all experiences as they are and fight back as much you can.

OwnerDisplayName: AZ


问:
False recursion vs. true recursion
I have been warned by my professor to avoid "false recursion", where a function behaves recursively, but does no useful recursive work.
I believe I understand recursion, but would like to double check.

I have written a short recursive sorting program that sorts (recursively I hope) the given array, ignoring the first element. After sorting all elements after the first, it places the first element in the correct place within the sorted sub-array (by shifting elements left).

The code is as follows:

```<code>#include <iostream> // for cout
using namespace std;

void RecSort(int*, int, int); //RecSort function declaration
int arr[8] = {4,1,2,7,5,9,0,2}; //global array to sort (just an example)

void RecSort(int* arr, int len, int curr)       { //RecSort definition
        if (curr < len - 2)     { //-1 to agrre with 0 indexing, -1 to stop 1 element before the end (terminating condition)
                RecSort(arr, len, curr + 1); //recursively sort all elements except first element
        }
        for (int i = curr; i < len - 2; i++)    { // once the rest of the array is sorted, shift elements to the left of the first element
                if (arr[i] > arr[i + 1])        { // while appropriate (in this case, sort ascending order)
                        int temp = arr[i + 1]; //swap array elements if needed
                        arr[i + 1] = arr[i];
                        arr[i] = temp;
                }
        }
}

int main()      {

int length, current;
RecSort(arr, length = 8, current = 0);// sort array (recursively?)
        for (int i = 0; i < length - 1; i++)    {
                cout << arr[i] << " "; //print array to verify functionality
        }
}
</code>```

Does this appear to be truly recursive?

答:
I've never come across the term "false recursion" before, and it sounds like it might be terminology original to your professor. As a consequence, its a bit hard to judge what he thinks qualifies. I'll assume he means that the function can be easily rewritten using a loop instead of recursion, thus it didn't need to be recursive.

As a general rule of thumb, if a function needs to be recursive, it'll call itself multiple times. When a function only calls itself once, it can usually be rewritten as a loop.

In your case, what you are doing is sorting the last element, then the last two elements, then the last three elements, etc. You can implement this as loop something like:

```<code>for (int startIndex = length - 1, startIndex >= 0; startIndex++) {
    // do what you would have done before.
</code>```

What you've done here is implemented an insertion sort, its not typically implemented in a recursive fashion.

ContentLicense: CC BY-SA 3.0

Title: False recursion vs. true recursion

Body:
I've never come across the term "false recursion" before, and it sounds like it might be terminology original to your professor. As a consequence, its a bit hard to judge what he thinks qualifies. I'll assume he means that the function can be easily rewritten using a loop instead of recursion, thus it didn't need to be recursive.

As a general rule of thumb, if a function needs to be recursive, it'll call itself multiple times. When a function only calls itself once, it can usually be rewritten as a loop.

In your case, what you are doing is sorting the last element, then the last two elements, then the last three elements, etc. You can implement this as loop something like:

for (int startIndex = length - 1, startIndex >= 0; startIndex++) {
    // do what you would have done before.

What you've done here is implemented an insertion sort, its not typically implemented in a recursive fashion.


问:
Is "string literal" always the same as "hard-coded string"?
I am learning programming and often see the term "string literal" being used in various places. From the looks of it, it seems to be a synonym for "hard-coded string", but on another hand the term looks quite specific.

Is "string literal" always the same as "hard-coded string"?

答:
A string literal is a hard-coded string, but not all hard-coded strings are string literals.

```<code>var greet = ", ".join("Hello", "Bob")
</code>```

The above code has three hard-coded string literals: the comma, Hello and Bob.  The variable greet is hard-coded to be "Hello, Bob", but it is not itself a string literal.  An interpreted language would never in memory have those characters stored as "Hello, Bob" prior to execution.  A compiled language could, if it were clever enough.

The connotation is that hard-coded means "doesn't change with input", and is generally a stepping-stone to modifying something like the above to this:

```<code>var greet = separator.join(greeting, name);
</code>```

In many cases, some things may still be hard-coded, for instance:

```<code>var greet = ", ".join(greeting, name);
</code>```

Although the comma is hard-coded, one would not normally call that fact out unless there were a need for a different separator.

Body:
A string literal is a hard-coded string, but not all hard-coded strings are string literals.

var greet = ", ".join("Hello", "Bob")

The above code has three hard-coded string literals: the comma, Hello and Bob.  The variable greet is hard-coded to be "Hello, Bob", but it is not itself a string literal.  An interpreted language would never in memory have those characters stored as "Hello, Bob" prior to execution.  A compiled language could, if it were clever enough.

The connotation is that hard-coded means "doesn't change with input", and is generally a stepping-stone to modifying something like the above to this:

var greet = separator.join(greeting, name);

In many cases, some things may still be hard-coded, for instance:

var greet = ", ".join(greeting, name);

Although the comma is hard-coded, one would not normally call that fact out unless there were a need for a different separator.


问:
Is 4-5 years the “Midlife Crisis” for a programming career?
I’ve been programming C# professionally for a bit over 4 years now. For the past 4 years I’ve worked for a few small/medium companies ranging from “web/ads agencies”, small industry specific software shops to a small startup. I've been mainly doing "business apps" that involves using high-level programming languages (garbage collected) and my overall experience was that all of the works I’ve done could have been more professional. A lot of the things were done incorrectly (in a rush) mainly due to cost factor that people always wanted something “now” and with the smallest amount of spendable money. I kept on thinking maybe if I could work for a bigger companies or a company that’s better suited for programmers, or somewhere that's got the money and time to really build something longer term and more maintainable I may have enjoyed more in my career. I’ve never had a “mentor” that guided me through my 4 years career. I am pretty much blog / google / self taught programmer other than my bachelor IT degree.

I’ve also observed another issue that most so called “senior” programmer in “my working environment” are really not that senior skill wise. They are “senior” only because they’ve been a long time programmer, but the code they write or the decisions they make are absolutely rubbish! They don't want to learn, they don't want to be better they just want to get paid and do what they've told to do which make sense and most of us are like that. Maybe that’s why they are where they are now. But I don’t want to become like them I want to be better. I’ve run into a mental state that I no longer intend to be a programmer for my future career. I started to think maybe there are better things out there to work on. The more blogs I read, the more “best practices” I’ve tried the more I feel I am drifting away from “my reality”. But I am not a great programmer otherwise I don't think I am where I am now. I think 4-5 years is a stage that can be a step forward career wise or a step out of where you are.

I just wanted to hear what other have to say about what I’ve mentioned above and whether you’ve experienced similar situation in your past programming career and how you dealt with it. Thanks.

答:
I have had the same questions and possibly looked at the same things you have (great startups, inspirational advice, motivated people creating amazing things, processes, algorithms that make your head heart) only to find none of it in my coworkers, current or former, nor in the people I know who are in the business. So this conundrum of matching this deep interest with a paid job has meant a lot of badly slept nights and a search for a project so ingenious that could be taken on the side and yet grow into its own thing quickly enough to provide a way out. Like a lot of people, I have a family to support, and I personally think the energy it takes to build something in a startup targeting the Brazilian market is not well spent if it's not completely IT-ish and boring. And seriously? I do IT-ish and boring things all day long.

So to me the answer has been keeping the will to learn and improve in one place and work in another. I've taken up processing.org and keep trying to draw, write and cook more. It's been great for me, to be honest: sometimes you're so caught up with matching the people you admire and being taken up to the Pantheon of great achievers that you ignore serious facts about who you are and what makes you feel life is worth living. And while work is something that takes a considerable chunk of your day, the minute you stop worrying about what it all means and where you're going is the moment you realize you don't need it to get there. Keep coding if it's what you love, write software at home, contribute to projects you're passionate about. That type of satisfaction hardly ever comes from a paycheck for most people, and maybe that's the case for you too.

OwnerDisplayName: Jeff

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: dodecaphonic


问:
Which programming language (or machine language) first used line numbers?
Fortran II (1958) was recorded using line numbers, from what I can tell.  For example, the first five columns of this IBM punch card are titled "statement number".

Punch card from a typical Fortran program. Arnold Reinhold (https://en.wikipedia.org/wiki/File:FortranCardPROJ039.agr.jpg)

Columns 1 to 5 may be used to write numbers by which the statement may subsequently be referenced.
  (Fortran II General Information Manual. 1963. p. 7)

Was Fortran 2 the first programming language (or machine language) to be recorded using line numbers?

Line numbers are not a requirement for a programming language (or machine language), but they are of such practical importance that I am curious if there ever was a language recorded without them.

Obviously, if a program is read into addressable memory, each instruction has a memory address. This question is not about memory addresses, it is about the recorded form of the program, on the media on which the program is recorded at rest, e.g. a punch card.

答: Probably Dartmouth BASIC (Beginner's All-purpose Symbolic Instruction Code), in 1964.  In the original language, every line was required to have a line number, you could only put one statement on a line, and lines were "interpreted" (in a general sense: Dartmouth BASIC, while having a nice interactive user environment, was in fact compiler-based) in ascending order by line number.</p>


答:
The PAF compiler on CAB500 (written by my late father Dimitri Starynkevitch in 1958-1960; see this paper in Chiffres 1961) generated a line number for every line of code interactively typed (while a teenager, I played on a CAB500 in the Palais de la Découverte museum in Paris, near 1975?)

CAB500 was a drum based machine built in France. AFAIK, it was only sold in Europe (and mostly in France).

(so I am one of the few persons in the world involved in compilers -thru my GCC MELT tool- whose father also wrote compilers.)

Title: Which programming language (or machine language) first used line numbers?

Body:
Fortran II (1958) was recorded using line numbers, from what I can tell.  For example, the first five columns of this IBM punch card are titled "statement number".

Punch card from a typical Fortran program. Arnold Reinhold (https://en.wikipedia.org/wiki/File:FortranCardPROJ039.agr.jpg)

Columns 1 to 5 may be used to write numbers by which the statement may subsequently be referenced.
  (Fortran II General Information Manual. 1963. p. 7)

Was Fortran 2 the first programming language (or machine language) to be recorded using line numbers?

Line numbers are not a requirement for a programming language (or machine language), but they are of such practical importance that I am curious if there ever was a language recorded without them.

Obviously, if a program is read into addressable memory, each instruction has a memory address. This question is not about memory addresses, it is about the recorded form of the program, on the media on which the program is recorded at rest, e.g. a punch card.


答:
The term string literal refers to how your language's parser interprets your program.  After the preprocessor (if any) is applied to your source code, tokens that look like "Hello world" will typically be interpreted as a string literals by the parser.

The term hardcoded string refers to a string that doesn't depend on the input to the program but it also has connotations of being hard to change, meaning that you might have to edit the code in one or more places to change it.

Here is a string that is both a string literal and it is hard-coded:

```<code>char * libPath = "/usr/lib";
</code>```

Here is a string that is still a string literal, but its definition comes from a preprocessor macro:

```<code>#define LIB_PATH "/usr/lib"
char * libPath = LIB_PATH;
</code>```

It's still a string literal, but I'm not sure if I would call it hard-coded.  The definition might depend on some #ifdefs, or the definition might be generated by your software's configuration scripts, which inspect your computing environment and configure the software to work properly on it.  If "/usr/lib" doesn't actually appear in your source code but it comes from your build system, I think most programmers would not call that "hard-coded", because hard-coded has connotations that it is difficult or not supported to change the variable.

Body:
I am learning programming and often see the term "string literal" being used in various places. From the looks of it, it seems to be a synonym for "hard-coded string", but on another hand the term looks quite specific.

Is "string literal" always the same as "hard-coded string"?

Body:
The term string literal refers to how your language's parser interprets your program.  After the preprocessor (if any) is applied to your source code, tokens that look like "Hello world" will typically be interpreted as a string literals by the parser.

The term hardcoded string refers to a string that doesn't depend on the input to the program but it also has connotations of being hard to change, meaning that you might have to edit the code in one or more places to change it.

Here is a string that is both a string literal and it is hard-coded:

char * libPath = "/usr/lib";

Here is a string that is still a string literal, but its definition comes from a preprocessor macro:

#define LIB_PATH "/usr/lib"
char * libPath = LIB_PATH;

It's still a string literal, but I'm not sure if I would call it hard-coded.  The definition might depend on some #ifdefs, or the definition might be generated by your software's configuration scripts, which inspect your computing environment and configure the software to work properly on it.  If "/usr/lib" doesn't actually appear in your source code but it comes from your build system, I think most programmers would not call that "hard-coded", because hard-coded has connotations that it is difficult or not supported to change the variable.


问:
Strategy for OS X and downlevel version of C++11 library?
I think I've found myself in a situation where things are quickly spiraling out of control, and I'd like to get some feedback to select a way to proceed.

BACKGROUND

I'm working with a library based upon C++03. The library is cross-platform and supports multiple compilers. There are no external dependencies or prerequisites (i.e., no need for Autotools, Cmake, Boost, etc). We started testing with std=c++11 and found some things needed to be fixed. For example, auto_ptr was deprecated, so we needed to switch to unique_ptr if __cplusplus >= 201103L.

The switch to unique_ptr was relatively easy, except on OS X. OS X advertises __cplusplus as 201103L, but its a woefully deficient C++11 runtime library (I'm not even going to use the word "standard" in that sentence). Worse, if someone builds the latest LLVM/Clang from sources on OS X without libcxx, then the same deficiencies exist because the new Clang uses the old libraries.

To resolve the auto_ptr issue, we jumped through some hoops that ended in the following code. While the code below looks clean, the preprocessor is working overtime to determine when it should to defined MYLIB_HAVE_UNIQUE_PTR and MYLIB_HAVE_TEMPLATE_ALIAS due to OS X.

```<code>// The result is MyLib::auto_ptr in both cases
#if defined(MYLIB_HAVE_UNIQUE_PTR) && defined(MYLIB_HAVE_TEMPLATE_ALIAS)
  template<typename T>
    using auto_ptr = std::unique_ptr<T>;
#else
  using std::auto_ptr;
#endif
</code>```

We are now trying to provide move semantics guarded on __cplusplus because there are two to five classes that would benefit. However, OS X is giving us trouble again because it lacks std::move. I suspect its going to have problems with Rvalues and Rvalue References, too.

We asked the Clang developers how to feature test for std::move at How to test for std::move (intersection of Apple and Clang). One of the Clang developers suggested we roll our own, but I'm beginning to think its a losing battle based upon GNU's source code for move.h. For example a quick grep -IR is_lvalue_reference /usr/include/c++/4.2.1/ reveals no hits.

STRATEGIES

I think our choices are (1) drop support for OS X altogether; (2) treat OS X as C++03; (3) roll our own implementation for missing C++11 features on OS X; or (4) switch to Autotools or Cmake for feature detection.

(1) is categorically not going to happen. (2) seems reasonable. (3) seems like a lot of work. (4) is not going to happen because it introduces external dependencies.

For (2), I believe the test is as easy as:

```<code>//  For Microsoft's cl.exe, pivot on _MSC_VER, not __cplusplus.
#if (_MSC_VER >= 1600) || (__cplusplus >= 201103L)
# define MYLIB_CXX11 1
#endif

// Ancient C++ runtime library; unset it because its too much trouble.
// Thanks to Jonathan Wakely for the `__has_include(<forward_list>)`
//     test. See http://stackoverflow.com/q/31655462.
// TODO: test under Xcode 3, where g++ is really g++.
#if defined(__clang__)
#    if !(__has_include(<forward_list>))
#        undef MYLIB_CXX11
#    endif
#endif
</code>```

Then back to canonicalized feature detection:

```<code>#if MYLIB_CXX11

  // Everyone appears to provide this list
  #define MYLIB_CXX11_UNIQUE_PTR 1
  ...

  // template aliases: MS at VS 2015 (v19.00); GCC at 4.7; Clang at 3.0; and Intel 12.1.
  #if (_MSC_VER >= 1900) || (__INTEL_COMPILER >= 1210)
  #  define MYLIB_CXX11_TEMPLATE_ALIAS 1
  #elif defined(__clang__)
  #  if (__has_feature(cxx_alias_templates))
  #    define MYLIB_CXX11_TEMPLATE_ALIAS 1
  #  endif
  #elif (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7))
  #  define MYLIB_CXX11_TEMPLATE_ALIAS 1
  #endif // template aliases

#endif // MYLIB_CXX11
</code>```

QUESTIONS

Are there any other strategies to deal with C++11 and OS X?

Has anyone tried strategy (3)? If so, how much work was it?

TESTING

If you have access to OS X, then try the following to test the built in compiler, the standard, and GNU's libstdc++ versus LLVM's libc++. After that, then test with a modern compiler by exporting CXX=/opt/local/bin/clang++.

```<code>$ cat test-clapple.cxx

// c++ -c test-clapple.cxx
// c++ -stdlib=libc++ -c test-clapple.cxx
// c++ -std=c++11 -c test-clapple.cxx
// c++ -std=c++11 -stdlib=libc++ -c test-clapple.cxx

# include <memory>

// Manage auto_ptr warnings and deprecation in C++11
#if (__cplusplus >= 201103L) || (_MSC_VER >= 1900)
  template<typename T>
    using auto_ptr = std::unique_ptr<T>;
#else
    using std::auto_ptr;
#endif // C++11

int main(int argc, char* argv[])
{
    return argc;
}
</code>```

答:
It is not MacOSX, it is the compiler that you use on it.

So, simply upgrade your compiler, perhaps by building from their source code a recent version of Clang/LLVM and/or GCC compiler(s).

(you don't need permission from Apple to compile and use a newer compiler. You just need to take time to read and follow the build instructions; in a few hours you can get the latest release of GCC or of Clang running on your computer)

In december 2015, the current GCC is GCC 5.3, and the current Clang is Clang 3.7; and you could configure them so that the compiler would be called g++-mine or clang++-mine   if you want so.


问:
Design activities / events logging (ex: fields update) in RDBMS
I am trying to implement a activity tracking system in Ruby on Rails for an API only application.

I have a table named letter with information as follow :

id (primary key)

sender_id (foreign_key on contact)

receiver_id (foreign_key on user)

owner_id (foreign_key on user)

re (string)

status (enum { ON_HOLD , CLOSED , OPENED })

Every time an update is done (title, ownership or state changes) I want to log it in an activity table which will be display along side the letter on the application.

It should look like GitHub issues, where we can see who did what. Being able to reference users, link to their profile, says that someone change the title from "something" to "another thing", etc.

The thing I want to log have different information layout :

transfer changes: from, to (both should be foreign_key)

metadata changes: field_name, old_value, new_value (strings)

status changes: old_status, new_status (enum )

All of these tables have id, author of the changes, creation date.

I am wondering what would be the best to keep track of this changes.

First idea

I started to create a activity table as follow :

id (primary key)

letter_id (foreign_key on letter)

created_at (datetime)

user_id (foreign_key on user)

type (enum { STATUS , TRANSFER , METADATA })

activity_id (integer pointing on table id)

And created one table for each enum entry in type column and load them manually using the activity_id. But I found it pretty ugly because:

I can't use joins properly

it disturbs Rails ORM capabilities

Come on, I am pretty sure it's the wrong way for RDBMS (no?)

I would end up with this kind of code :

```<code>activity = Activity.find(1)
if (activity.type == "STATUS")
  StatusActivity.find(activity.activity_id)
elsif (activity.type == "TRANSFER")
  TransferActivity.find(activity.activity_id)
...
</code>```

Second idea

Based on the activity layout of the first idea, instead of having on column with the  I thought about having additional nullable columns holding a foreign_key toward each enum entries tables :

id (primary key)

letter_id (foreign_key on letter)

created_at (datetime)

user_id (foreign_key on user)

type (enum { STATUS , TRANSFER , METADATA })

status_activity_id

transfer_activity_id

metadata_activity_id

Doesn't look great; if I want to add a new kind of activity event, I will have to create an extra column for each row...

It would end up with this kind of code :

```<code>activity = Activity.find(1)
if (activity.type == "STATUS")
  activity.status_activity
elsif (activity.type == "TRANSFER")
  activity.transfer_activity
...
</code>```

Third idea

Create 3 different tables: status_activity, transfer_activity and metadata_activity. Query them separately, sort them by creation date before serializing into JSON.

Despite all of this ideas, I can't figure out what would be great ? So do you have any idea or advices ?

答:
One easy way to do it is to create a new table called history which has an id, a date, perhaps also a user_id to know who made each modification, and then simply a string which contains JSON text explaining what happened.  The idea is that you won't really be using the historical fields in relations, probably not even in queries, so they do not have to be real fields.

Another (rather wasteful but fully relational) way to do it is to replace your letter table with a letter_history table, where you maintain all fields of table plus a date and perhaps also a user_id, so you never actually modify any existing rows, you only add new rows with the current date and the user who made the change.  Then, you create a view called letter which simply selects the most recent version of each letter.


问:
What is the purpose of chunking strings in natural language processing?
I see many examples of libraries that use a 'chunker' and also people asking how to write chunkers, but what is this for and why do we need it?  Isn't it enough to split a text by whitespace or other characters that delimit boundaries between words? </p>

答:
Isn't it enough to split a text by whitespace or other characters that
  delimit boundaries between words?

In many cases, natural language processing is used to pick out pieces of sentences without necessarily analyzing the entire sentence. However, those pieces may consist of several words, so using white space to simply break the sentence into words isn't very helpful. Imagine that you're building database of historical facts, and a tiny portion of the input text looks like this:

Tony Orlando was born on April 3, 1944 in New York City and later moved to New Jersey.

In that case it's probably useful to know that this fact involves a person, a date, two places, all of which consist of multiple words that aren't very useful by themselves. A chunker can break that sentence into phrases that are more useful than individual words, like Tony Orlando and New York City and even born on April 3, 1944. Identifying meaningful terms could speed up searching and yield better results.


答:
Well, you should learn another domain (mathematic, AI, data mining, BI, integration whatever).
Then after mastering this new domain chances are that you have new ideas which respond to real business needs.

At this stage if you are a great programmer, you just need to make a startup. Well it's risky, but way more fun.

Learn different skills and competencies, not just in programming, then combine them to create a new thing nobody has thought. That's easy, you already have the best hammer ever : Programming.

Title: Is 4-5 years the “Midlife Crisis” for a programming career?

Body:
I’ve been programming C# professionally for a bit over 4 years now. For the past 4 years I’ve worked for a few small/medium companies ranging from “web/ads agencies”, small industry specific software shops to a small startup. I've been mainly doing "business apps" that involves using high-level programming languages (garbage collected) and my overall experience was that all of the works I’ve done could have been more professional. A lot of the things were done incorrectly (in a rush) mainly due to cost factor that people always wanted something “now” and with the smallest amount of spendable money. I kept on thinking maybe if I could work for a bigger companies or a company that’s better suited for programmers, or somewhere that's got the money and time to really build something longer term and more maintainable I may have enjoyed more in my career. I’ve never had a “mentor” that guided me through my 4 years career. I am pretty much blog / google / self taught programmer other than my bachelor IT degree.

I’ve also observed another issue that most so called “senior” programmer in “my working environment” are really not that senior skill wise. They are “senior” only because they’ve been a long time programmer, but the code they write or the decisions they make are absolutely rubbish! They don't want to learn, they don't want to be better they just want to get paid and do what they've told to do which make sense and most of us are like that. Maybe that’s why they are where they are now. But I don’t want to become like them I want to be better. I’ve run into a mental state that I no longer intend to be a programmer for my future career. I started to think maybe there are better things out there to work on. The more blogs I read, the more “best practices” I’ve tried the more I feel I am drifting away from “my reality”. But I am not a great programmer otherwise I don't think I am where I am now. I think 4-5 years is a stage that can be a step forward career wise or a step out of where you are.

I just wanted to hear what other have to say about what I’ve mentioned above and whether you’ve experienced similar situation in your past programming career and how you dealt with it. Thanks.

OwnerDisplayName: Nicolas Dorier


问:
Daily standups- yea or nay?
How valuable (or not) do you think daily stand-up meetings are?

If you're not familiar with it, this refers to a daily meeting that is part of Scrum adherents (and some other agile methodologies).  The idea is that you hold a daily meeting, timeboxed to 15 minutes, and in which everyone must stand (to encourage people to be to-the-point).

In the meeting, you go around the room and each say:
- What you did yesterday
- What you plan to do today
- Any blockers or impediments to your progress.

Do you think this practice has value?  Has anyone worked at a place that's done it, and what did you think?

答:
In my experience pre planning what you will do in the next day leads to major productivity boosts.  So having these scrum like meetings are worth the lost time for that reason alone.

Try to keep them short though, or even do it in a group Skype chat everyday at the same time.  Just be sure to read eachothers updates though.

A daily status report at the end of each day before you go home has the same effect.

Title: Daily standups- yea or nay?


答:
IMO the dissatisfaction you obviously feel is not a crisis, but rather a sign that you reached a certain level. You outgrew "I am just a programmer" slot. You have enough understanding now to see the flaws in the current state of affairs and how it can be fixed.

The next step is find a connection between what you see as potential improvement and what the company you work for would see as such. Then you have to convince your boss(es) that this is the way to go.

It is not enough to understand things and know how to do things. You also should be able to convince people that you know what you are doing. And if it sounds like sales that is because it is. But this is absolutely necessary to become "great". You are working not with computers, you are working for people and with people, you have to be able to sell your ideas.

Of course some companies would be too conservative to accept your ideas, and your boss can reject them because of the color of the tie you are wearing. Just keep in mind that selling ideas is no easier than generating ones, and unsuccessful sale is not necessarily a result of your boss' ulterior motives it can be bad presentation on your part.

OwnerDisplayName: mfeingold


问:
Comparison Function Returns True or False
In my python CS class at school, we were given a true or false question as follows.

A comparison function returns either True or False.

When originally answering I thought about two things.  First, a function as follows (what I thought was a comparison function) returns true or false.

```<code>def comparison(valOne,valTwo):
    return valOne<valTwo
</code>```

Now, I know this isn't a comparison function, but a function with an operator.  In addition, I thought of another type of function when answering.

```<code>def someoneHasOne(scoreOne,scoreTwo):
    return scoreOne==15 or scoreTwo==15
</code>```

From what I know, this is a comparison function.

So, thinking of those two things, I marked this as True.

However, the correct answer, according to the teacher, was False.  After the answer was marked wrong, I started to do some research.  I found this about the operator module that has comparison functions that return True or False

My main question is, am I right (the answer is True)? Or is my CS teacher right (the answer is False)?

答:
If this is a python class, then yes, your CS teacher is correct.  A number of python functions take a "comparison function" as an argument.  For instance, see the sorted documentation:

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

How comparison functions work varies by language, though most follow a similar fashion.  But since this is specifically a question about python, the answer is unambiguously "false" in that comparison functions do not always return just True or False.


问:
Is there a standard pseudocode for parallel algorithms?
The common styles of pseudocode are largely intelligible, and it is more or less clear how to write pseudocode for sequential programs.

But if parallelism is not hidden behind a full library and is regarded as a regular part of programming, then it should be treated as the same way in regards to pseudo-code.

Is there a consistent and widely used style of pseudocode for parallel algorithms? Are there good, practical examples of this?

答: Fundamentally, pseudocode is about low level algorithms, and tends to be only useful when you are describing sequential operations. Parallelism tends to occur at the next level up and there are planting of diagramming tools that are better suited to that.</p>


问:
How supervised or unsupervised machine learning algorithms get better over new datasets
Using this Coursera's course about machine learning, I learned some things about supervised and unsupervised algorithms.

And from Wikipedia I've read that machine learning is "to get better performance/P at tasks/T with each task being done, that is experience/E".

Now, in those algorithms what I see is that they give it a set of data (either pre-labeled for supervised algorithms, or not for the other one) and the algorithms try to figure out the data and generate some output.

But I truly fail to find out WHERE and HOW in the process those algorithms BECOME BETTER with each new dataset they receive.

I really appreciate any help here. Did I miss something about machine learning? Without the getting-better-with-each-new-dataset part, how are these algorithms different from normal programs we write with a huge amount of conditional clauses and loops?

答: The Coursera course only covers "batch" or "offline" methods for machine learning. In batch methods you train the model once, and then use the trained model as a static resource. What you are looking for are online machine learning methods. Typically this involves finding an algorithm where the new data can be combined with the existing model to generate a new, improved model, but without simply tossing the new data into the same pot with the old data, and re-training from scratch.</p>


问:
Pros and Cons of Facebook's React vs. Web Components (Polymer)
What are the main benefits of Facebook's React over the upcoming Web Components spec and vice versa (or perhaps a more apples-to-apples comparison would be to Google's Polymer library)?

According to this JSConf EU talk and the React homepage, the main benefits of React are:

Decoupling and increased cohesion using a component model

Abstraction, Composition and Expressivity

Virtual DOM & Synthetic events (which basically means they completely re-implemented the DOM and its event system)

Enables modern HTML5 event stuff on IE 8

Server-side rendering

Testability

Bindings to SVG, VML, and <canvas>

Almost everything mentioned is being integrated into browsers natively through Web Components except this virtual DOM concept (obviously). I can see how the virtual DOM and synthetic events can be beneficial today to support old browsers, but isn't throwing away a huge chunk of native browser code kind of like shooting yourself in the foot in the long term? As far as modern browsers are concerned, isn't that a lot of unnecessary overhead/reinventing of the wheel?

Here are some things I think React is missing that Web Components will take care of for you. Correct me if I'm wrong.

Native browser support (read "guaranteed to be faster")

Write script in a scripting language, write styles in a styling language, write markup in a markup language.

Style encapsulation using Shadow DOM

React instead has this, which requires writing CSS in JavaScript. Not pretty.

Two-way binding

答:
Polymer is awesome. React is awesome.
They are not the same thing.

Polymer is a library for building backwards compatible web components.

React is the V in MVC. It's the View, and nothing else. Not by itself at least.

React is not a framework.

React + Flux + Node + (Gulp or Grunt) is more comparable to a framework, but 3 of those things aren't part of react at all.

There are many technologies, patterns, and architectural styles that react developers follow, but react itself is not a framework.

It's sad that no one took the time to say the simplest possible thing, that they should not be compared. They have some overlap, but they are more different than the same.

They both allow you to define web components, but in different ways. Beyond that they are very very different tools.


问:
What percentage of failed requests is "normal"
So I just launched my first "real" site that actually has a decent amount of interactions and whatnot. It's an ASP.net site with a SQL backend.

We've served 130k requests in the last 12 hours but 930 failed. Is this normal, bad, or "I should fire myself as a programmer" bad. While ideally this number would be 0, what's an acceptable percentage of failed requests?

答:
Percentage of requests is not the right way to look at it as it depends entirely what the failure is.  If you have one failure that exposes customer credit card information out of a million requests, that is utterly unacceptable.  On the other hand, 10% of calls resulting in a failure to show the correctly updated time is probably ok.

To determine if your situation is acceptable, you have to dig down, classify the errors, and decide for yourself.  The things to consider:

Does the failure destroy data?

Does the failure expose data?

Does the failure prevent the user from doing something that earns you money?

Does the failure prevent the user from doing what they want to do?

Is it obvious to the user how to recover from the error?

Is the error likely to give customers a negative opinion of your site?

Then for each discrete type of error, try to determine if the pain caused by the error is worth the cost of fixing the error.  If it is not worth the cost, then it is "acceptable", otherwise, it is not.  But it's a subjective question.

What I find works well is to simply measure these errors, prioritize them with questions like the above, and then work on fixing from the top, down until I reach cases that are either too hard to fix to be worth addressing.


答:
As a programmer you're always going to have to balance your desire for perfection and your employer's desire for a working product. At some companies these two desires will be closer to one another, at most companies the two desires will be far apart.

My best suggestion for dealing with the drain of your day job is to start a personal project on the side, one where there is no deadline, where you can work in areas that you don't usually work, one where you make all of the decisions. The most rewarding code that I've written was while working as a Wii developer, I can suggest that you write a game. You'll be able to touch on every different aspect of programming, 3D, networking, AI, etc... and since you're already working with .Net I'd suggest grabbing XNA or Unity

As far as Senior Programmers not knowing much, you're probably right. Most senior programmers at larger firms were promoted at a time that they did know a lot, or when they were able to get the job done. Now that they're senior they have different responsibilities, mainly as managers. It's expected that their coding skills will slip a little. Some are better than others, and some probably did just get promoted because of who they know, but most senior programmers that I've worked with in the past had a solid (although sometimes outdated) skill set.

So to wrap it up, do a personal project to relieve the day to day boredom, and take it easy on your seniors, just do the best work that you can in the time allotted and you'll be fine.

OwnerDisplayName: jessecurry


答:
You are not going to find an antecedent to the first published computer program, written by Ada Lovelace for Babbage's difference engine, published in 1841.

Note that leftmost column, "Number of Operation".

I think that beats the other answers by a full century though perhaps it loses points for never having actually been run.


问:
Javascript Closure Scope
I was reading the "Closures" section on the w3schools JavaScript tutorial and I don't understand how the last example works.

http://www.w3schools.com/js/js_function_closures.asp

The goal is to create a "private" variable counter that only the add function can manipulate. Here is the code:

```<code><!DOCTYPE html>
<html>
<body>

<p>Counting with a local variable.</p>

<button type="button" onclick="myFunction()">Count!</button>

<p id="demo">0</p>

<script>
var add = (function  outer() {
    var counter = 0;
    return function inner() {return counter += 1;}
})();

function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

</body>
</html>
</code>```

I edited the two anonymous functions and named them outer and inner so they can be more easily referenced. Here is a link of the code in action:

http://www.w3schools.com/js/tryit.asp?filename=tryjs_function_counter3

So initially the variable add is assigned to a self-invoking function expression. This would execute the outer function one time and set the counter to 0. When the button is clicked, myFunction is called and this puts the returned value of the add function, the updated counter value, inside the p tag. So clicking on the button increments the value of the counter variable by 1 on every onclick event of the button. I don't understand how the value of the counter value is affected by the outer and the inner functions. This is how I (wrongly) understand it:

When the add function is called by the myFunction function (upon an onclick event of the button), first the outer function would set the counter variable to 0 by the following statement:

```<code>var counter = 0;
</code>```

Intuitively I would think that the return value of the add function would invoke the inner function (especially because I can see this code works) but I don't get how. That is one question I have. If I just accept it then the inner function would increment the counter variable by 1. I can see how this makes sense for clicking the button that calls the myFunction function once. For the second time the button is clicked I don't understand how it doesn't reset. I feel that before the second click the counter variable is 1 and then on the click the outer function resets the counter variable back to 0 with this line again:

```<code>var counter = 0;
</code>```

and then the inner function is invoked. Since the inner function is nested in the outer function, it is in the scope to access the counter variable and then increases it from 0 back to 1. What am I not understanding about this?

I feel I might not quite understand how the return statement on a function works but I'm not sure. Is the add variable just the inner function only because that is what is returned? And how is it invoked if it is inside a return statement? I don't get how var counter = 0; is not executed on every click of the button when myFunction is invoked.

I thought myFunction invokes the add function and that executes outer function, which executes var counter = 0; and then the inner function gets returned and invoked and that increases the counter variable.

I don't quite get if returning a function would invoke the function either. I also don't know if the creation and assignment of the add variable had anything to do with how this works. I didn't think so at first but who knows? I don't understand this so anything is possible to me right now.

答:
I don't get how var counter = 0; is not executed on every click of the button when myFunction is invoked.

Because the code

```<code>var add = (function  outer() {
    var counter = 0;
    return function inner() {return counter += 1;}
})();
</code>```

only executes once.  It returns an immediate function, storing it into the add variable, which you then assign to something else later (using = Add()).  Notice the ending pair of parentheses?  That's what causes the outer function to execute immediately, one time.

When the function in the add variable is assigned, it returns the inner function.  That inner function is what gets executed when myFunction runs.

The only other thing you need to know is that the inner function has access to the counter variable in the outer function, due to the closure.

Title: Javascript Closure Scope

Body:
I don't get how var counter = 0; is not executed on every click of the button when myFunction is invoked.

Because the code

var add = (function  outer() {
    var counter = 0;
    return function inner() {return counter += 1;}
})();

only executes once.  It returns an immediate function, storing it into the add variable, which you then assign to something else later (using = Add()).  Notice the ending pair of parentheses?  That's what causes the outer function to execute immediately, one time.

When the function in the add variable is assigned, it returns the inner function.  That inner function is what gets executed when myFunction runs.

The only other thing you need to know is that the inner function has access to the counter variable in the outer function, due to the closure.


问:
What happens if Sprint Goal is not met?
I've been reading Scrum Guide and one part is missing for me.
What happens if Sprint Goal is not met at all?
Let's say the Sprint Goal is a big part of a functionality which cannot be broken into parts further so devs have, say 2 weeks (the Sprint duration) to accomplish it or not, but they fail to do it. What happens with this functionality?

Should it be tossed away? (unlikely)

Should it be continued in the next Sprint? If yes, doesn't it break the rule of creating an Increment of potentially releasable product in each Sprint and also the rule that the duration of Sprint is fixed (technically the rule will stand but practically there will be a Sprint of 4 weeks)?

答:
The sprint goal should be placed back into the backlog and then reevaluated along with all the other stories in the backlog.  In most cases, this will mean it will be prioritized to the top of the backlog and pulled into the next sprint.  In theory, if business needs have changed since the backlog was last prioritized, it could be left for a later sprint or even thrown out.  But the key concept is that it is just treated like any other story in the backlog.

If this happens often, you need to reevaluate how you are writing stories as this means you may not be creating fine-grained enough stories to be finished in a single sprint.  But the vagaries of development mean that it will happen from time to time to even the best team.

(I have seen some teams react to this situation by splitting the story into two at this point, the first being the work that was completed and the second being the new work required.  I dislike this because I think it makes things look artificially good after-the-fact.)

Title: What happens if Sprint Goal is not met?


答: Perhaps consider going to graduate school?  That might open up opportunities for a different, more long-term-oriented kind of work.</p>

OwnerDisplayName: Max Strini


答: I think this should be discussed and post mortem'ed in the Sprint Retrospective. Conclusions regarding the sprint goal will obviously vary, but ultimately the decision to give it up or carry it over to the next sprint should belong to the Product Owner.</p>

Title: What happens if Sprint Goal is not met?

Body:
I've been reading Scrum Guide and one part is missing for me.
What happens if Sprint Goal is not met at all?
Let's say the Sprint Goal is a big part of a functionality which cannot be broken into parts further so devs have, say 2 weeks (the Sprint duration) to accomplish it or not, but they fail to do it. What happens with this functionality?

Should it be tossed away? (unlikely)

Should it be continued in the next Sprint? If yes, doesn't it break the rule of creating an Increment of potentially releasable product in each Sprint and also the rule that the duration of Sprint is fixed (technically the rule will stand but practically there will be a Sprint of 4 weeks)?


答:
add is holding a reference to the function inner i.e. function returned from outer function.

Closures is when a function remembers is its lexical scope even when invoked from outside that lexical scope.

So inner remembers its scope and thus able to access the counter variable .
Thus , its inaccessible outside directly and acts as private.
But add or inner can  manipulate it.

As soon as you refer add to another type the scope in which counter resides gets garbage collected and gets lost.

I recommend you to read books from kyle simpson
www.ydkjs.eu/

Title: Javascript Closure Scope

Body:
I was reading the "Closures" section on the w3schools JavaScript tutorial and I don't understand how the last example works.

http://www.w3schools.com/js/js_function_closures.asp

The goal is to create a "private" variable counter that only the add function can manipulate. Here is the code:

```<code><!DOCTYPE html>
<html>
<body>

<p>Counting with a local variable.</p>

<button type="button" onclick="myFunction()">Count!</button>

<p id="demo">0</p>

<script>
var add = (function  outer() {
    var counter = 0;
    return function inner() {return counter += 1;}
})();

function myFunction(){
    document.getElementById("demo").innerHTML = add();
}
</script>

</body>
</html>
</code>```

I edited the two anonymous functions and named them outer and inner so they can be more easily referenced. Here is a link of the code in action:

http://www.w3schools.com/js/tryit.asp?filename=tryjs_function_counter3

So initially the variable add is assigned to a self-invoking function expression. This would execute the outer function one time and set the counter to 0. When the button is clicked, myFunction is called and this puts the returned value of the add function, the updated counter value, inside the p tag. So clicking on the button increments the value of the counter variable by 1 on every onclick event of the button. I don't understand how the value of the counter value is affected by the outer and the inner functions. This is how I (wrongly) understand it:

When the add function is called by the myFunction function (upon an onclick event of the button), first the outer function would set the counter variable to 0 by the following statement:

```<code>var counter = 0;
</code>```

Intuitively I would think that the return value of the add function would invoke the inner function (especially because I can see this code works) but I don't get how. That is one question I have. If I just accept it then the inner function would increment the counter variable by 1. I can see how this makes sense for clicking the button that calls the myFunction function once. For the second time the button is clicked I don't understand how it doesn't reset. I feel that before the second click the counter variable is 1 and then on the click the outer function resets the counter variable back to 0 with this line again:

```<code>var counter = 0;
</code>```

and then the inner function is invoked. Since the inner function is nested in the outer function, it is in the scope to access the counter variable and then increases it from 0 back to 1. What am I not understanding about this?

I feel I might not quite understand how the return statement on a function works but I'm not sure. Is the add variable just the inner function only because that is what is returned? And how is it invoked if it is inside a return statement? I don't get how var counter = 0; is not executed on every click of the button when myFunction is invoked.

I thought myFunction invokes the add function and that executes outer function, which executes var counter = 0; and then the inner function gets returned and invoked and that increases the counter variable.

I don't quite get if returning a function would invoke the function either. I also don't know if the creation and assignment of the add variable had anything to do with how this works. I didn't think so at first but who knows? I don't understand this so anything is possible to me right now.


问:
How To Extend Parent Methods in Children Classes?
There is a parent class with a method which many children use but many children extend the method, what is the best way to extend it without violating DRY?

Here are my 2 current solutions:

1: The parent has a method which calls the reusable code which is relevant for all subclasses (do_this), then it calls a class specific method which all subclasses override. e.g.

```<code>    class Parent(object):
        def method(self):
            self.do_this()
            self.do_this_unique_to_class()

        def do_this(self):
            print 'every child wants to print this'

        def do_this_unique_to_class(self):
            pass

    class Child(object):
        def do_this_unique_class(self):
            print 'Only class Child wants to print this'
</code>```

2: Just use super and every child overrides the parents method. I don't like this solution as much. e.g.

```<code>    class Parent(object):
        def do_this(self):
            print 'every child wants to print this'

    class Child(object):
        def do_this(self):
            # call parents do_this
            super(Child, self).do_this()
            # then extend it
            print 'Only class Child wants to print this'
</code>```

答:
The problem with your solution #1 is that you will never know if you later need some of do_this_unique_class done before do_this.

I would do something a bit different, but somewhat along the lines of #2, by splitting up the do_this method in the parent into methods that the parent makes available for the children and then have the children's 'do_this' method call the methods they need and add in their own logic.


答:
The second is better. It means you don't have methods in the parent class that have no contextual meaning for that class and which don't do anything if called from instances of that class.

If the child class has the same behaviour as the parent class but implements it differently just override the implementation in the child class. The rest of the system won't care so long as the behaviour is as expected. That keeps polymorphism and encapsulation, the user of the object knows it will carry out some behaviour but doesn't care how and they don't need to know if they are actually using an instance of the parent or child class. Remember that methods are contracts with the rest of the system, I will do this behaviour for you if you ask me, but I won't tell how I'm going to do it. The method name should indicate the behaviour the object will carry out for the rest of the system. If both the parent and child carry out the same behaviour they should advertise this using the same method.

Make sure though that from the perspective of the user of the object the behaviour is consistent. Never override a method that produces a different behaviour depending on whether it is the parent or child object being called (ie never make a "print_to_console" method suddenly start sending out emails instead)

Title: How To Extend Parent Methods in Children Classes?

Body:
There is a parent class with a method which many children use but many children extend the method, what is the best way to extend it without violating DRY?

Here are my 2 current solutions:

1: The parent has a method which calls the reusable code which is relevant for all subclasses (do_this), then it calls a class specific method which all subclasses override. e.g.

```<code>    class Parent(object):
        def method(self):
            self.do_this()
            self.do_this_unique_to_class()

        def do_this(self):
            print 'every child wants to print this'

        def do_this_unique_to_class(self):
            pass

    class Child(object):
        def do_this_unique_class(self):
            print 'Only class Child wants to print this'
</code>```

2: Just use super and every child overrides the parents method. I don't like this solution as much. e.g.

```<code>    class Parent(object):
        def do_this(self):
            print 'every child wants to print this'

    class Child(object):
        def do_this(self):
            # call parents do_this
            super(Child, self).do_this()
            # then extend it
            print 'Only class Child wants to print this'
</code>```


答:
My first computer was an IBM 1620 that used punched cards.  It was produced in the late 1950's.  When writing assembler (SPS) the first five columns of the card were for line number.

There was a practical use for those. If / when you dropped the cards you could take them to the sorter.  Been there, done that.


答:
I think you need five more years experience. Then you will be able to accept the compromises and be happy to fix what you can.

At least that was my experience. At about 5 years (about the time it takes to become an expert) I think I actually "got it". I realized my code was crap. I realized my shiny hacks that got the apps working were just that, hacks. I came to understand that I had been creating sub-par code just to make my bosses happy and keep the paychecks rolling.

At the same time I realized that the desires of the bosses were not going to change. They were always going to want it yesterday without spending any money on good tools. They never were going to care if I used a particular design pattern. Never would they be in awe because I increased the maintainability by applying the Single Responsibility Principle judiciously.

I also realized I would be fighting my younger self embodied by inexperienced programmers. The programmer that hacked the program to get it working fast. The young programmer that resisted all the silly things that took me years to understand. The young programmer that thinks having 5 classes is more confusing than have one huge class that does it all.

But now that I am at my 10 year point I have come to see that those frustrations are just like the frustrations I experienced in my first five years. It is the frustration associated with learning a new skill. But this time the skill are interpersonal. The skills are getting non-programmers to understand the limitations of going down the cowboy path. And these skills are maybe more important in the grand scheme of things than the coder skills I acquired during the first five years.

But what is really amazing about this job is that I can continue, and actually must continue, to developing by technical skills while also working with management.

So I say to you keep at it! Because you have become comfortable with the technology you can start working on your skills dealing with the mushy things called humans.

OwnerDisplayName: ElGringoGrande


答:
Neither solution is clearly superior over the other and both have their uses.

The first solution works best if the Parent class implements an algorithm that can be extended at one or more places (not necessarily right at the beginning or the end) and the extensions should only be inserted at those defined extension points.

The second solution is typical for the case where the Parent class does not foresee any extension to the algorithm (in a language where methods are virtual by default), or when the Parent class provides a default implementation that some children want to re-use in addition to their own modifications to that default.

Solution 2 is usually preferred if children can replace the method of the parent or add extra steps in front and/or after it, but they are not supposed to add steps in the middle of the operation that the Parent implementation does.


问:
Why is Array.prototype designed to be a fully functional array?
In the below visualisation,

There are two array objects(cars & bikes) that are created with below syntax,

```<code>var cars = new Array("Saab", "Volvo", "BMW");
var bikes = ["Honda", "Yamaha"];
</code>```

whose [[Class]] property value is Array.

In addition, we also have Array.prototype, which is fully functional array, as shown below,

```<code>> Object.prototype.toString.call(Array.prototype);
      "[object Array]"
> Array.prototype[0] = "Volvo";
      "Volvo"
> Array.prototype[1] = "BMW";
      "BMW"
> Array.prototype.length;
      2
</code>```

Generally, When you put something on the prototype, every instance of the object shares the same properties.

Question:

With length property as member, What is the idea behind Array.prototype being fully functional array?

答:
The Array-prototype is itself a fully functional array, because it need to contain all the functionality which is necessary for an object to function as an array. The Array-instances inherit all their functionality through the prototype.

According to the spec:

The Array prototype object is itself an array; its [[Class]] is
  "Array", and it has a length property (whose initial value is +0) and
  the special [[DefineOwnProperty]] internal method described in
  15.4.5.1.


问:
Encapsulate algorithm configuration in system hierarchy
Say, I'm building a system that uses various complex algorithms (k means, mean shift, a few others), all of which are parameterized.  I'm highlighting `uses', because the system is not just a thin layer around them; deep in its processing, these algorithms are instantiated and executed.

The 'dumb' parts of the system don't need to and shouldn't know about the specific parameters required by these algorithms, but somehow these algorithms need to get their parameters from some central configuration.

What are good strategies to determine the source of the configuration on a system level, but avoid passing individual parameters through several layers of the software to where they are needed?

I'm thinking either dependency injection magic or an unspecific configuration object (eg. a map) that is passed around.  The former seems a bit of a large liability for so trivial a task, the latter doesn't fully eliminate the need to have parameters handled by code that shouldn't be concerned with them.

答:
The way that I have been handling this in my projects is that first of all, I always maintain a clear distinction between what is application-specific (domain-specific) code and what is general-purpose code.  Your algorithms can be thought of, I suppose, as general-purpose code.

The configuration is loaded by the root application class (the 'application' object) and stored in an application-specific structure.  This is not a generic map, it is an actual structure with individual, strongly typed fields, with long names explaining precisely what each value stands for.  All application-specific code generally has a reference to the application object, so it is free to obtain this structure from it.

The application may consist of subsystems or modules.  Each module can be thought of in turn as another application, with its own configuration structure, which usually contains a subset of the fields of the main application's configuration structure.  For each module, I gladly suffer the pain of passing the pertinent fields of the main application's structure so they can be stored in the fields of the subsystem's configuration structure.  Luckily, the number of subsystems is not all that large, so this does not represent a major pain.

At the moment that I cross the boundary between application-specific code and general-purpose code, I always pass every single value as a distinct, strongly typed, properly named parameter to every single method or constructor that needs it, and from that moment on I gladly suffer the pain of propagating these parameters as many levels deep as necessary.

True, these parameters are often altered, (some are added, some are dropped, names or types change, etc.) so there is a bit of typing involved, but our main bottleneck in our profession is not typing; it is management of complexity.  Which requires clarity.  So, this mechanism pays.


答:
I have found similar things in my 10 years of programming, and I surmise that these are rather common occurrences.  In the business world (as opposed to academia), money (or lack of money) and time drive the schedule, features, and quality of the programming.  Often those resources are lacking for doing things fully correctly.  This is a prime motivator for finding the most efficient methods to solve problems.  This situation has also guided me to keep in mind that my programming should solve only the problem at hand (with some amount of future consideration) instead of building something that contains many more features than is required.  This is a crucial lesson to learn, in my opinion.

Your comments on "senior programmers" is also, sadly, common in my experience.  I think the reason for this is two-fold - first, many experienced programmers get lazy, using only the tools and methods they have used in their careers.  Technology keeps moving forward, however, and this leads these experienced programmers to become "dinosaurs".  Second, after programming for a while, it can become easy to fall prey to a bit of hubris ("my talents have gotten me this far, so I must be a pretty good programmer").  I try to combat both of these problems by continually trying to learn new methods or technologies to solve my problems.  Sometimes this contradicts the "build only what is required" lesson state above, but the goal is to strive for a healthy balance between the two.

I would suggest using the experiences you have as a motivator to continually improve yourself.  I have quit the programming industry myself after about 5 years because I lost the passion to engineer code.  But I couldn't get rid of the itch to build programs, and I came back to the industry several months later.  I did learn that you have to engage yourself doing what you enjoy doing - if you want to project manage, find a position that allows you to manage projects.  If you want to code all day, find a position to do that.  Finding a job that challenges you and fulfills your desires is a wonderful and necessary part of a happy existence - I wish you luck in finding that.


问:
Why is PHP so frequently used on web servers?
My web server uses PHP as do 77.7% of web servers according to W3Techs, as of 14/03/2022.

The reason I use PHP is an inertia born out of seeing everyone else using it on web servers. What is it about PHP that would make it so ubiquitous on web servers?

(Note that this question is similar to the following question but takes it in a different direction: Why isn't Java used for modern web application development?)

答:
There are two key points for PHP's success: The timing and the focus on shared hosting.

In the beginning the Web was static. Web-Servers could only distribute pre-generated HTML this obviously wasn't enough after some time so in 1993 the NCSA team extended their web server (the predecessor of Apache httpd) with a technology called CGI which allowed calling specific programs from the web server which could generated HTML (or other content) on the fly. This was great as people could do all the things. A commonly used language at that time for that purpose was Perl. Perl is a language strong in text processing which is a key property for handling HTTP request data and producing HTML. So people used it.

But there was a problem: For each and every request the web server had to run an external program, Perl had to initialize and run the script. This caused quite some headache. A solution was mod_perl coming ca. 1997. mod_perl is a module for the Apache webserver embedding the Perl interpreter directly into the web server process so no extra startup was need.

But again this approach had a problem: mod_perl was extremely powerful and had access to the complete server configuration. You couldn't use one server to host multiple independent clients as they could easily harm the other people - be it on purpose or by accident. And that's where PHP came.

PHP was built in a way that it could run as Apache module (thus not having the startup hit for each request) but provides a shared-nothing environment between requests. Once a request was done all information was lost and a subsequent request to another virtual host would be served independently. PHP also offered features to restrict access (safe_mode, open_base_dir). With that architectural choice companies could install PHP on their server and provide customers FTP (or similar) access to upload their files and by that host many many customers on a single machine without much work. This caused a competition leading to cheap prices for PHP-based hosting making PHP an ubiquitous platform.

Additionally PHP had a few benefits over Perl, like allowing to mix HTML and PHP code or direct access to request variables (see also register_globals) which in Perl was harder (custom parsing or dependency on CGI.pm) which developers liked.

Another aspect which made PHP successful in those days was good support on Windows. Getting Perl or other languages working on Windows was hard, but back at that time many developers where using Windows at home and virtualization or containers weren't a thing, yet. PHP did run easily on Windows so people could use it for development and then pack up the files and deploy on Linux. With Perl for instance you would have to get the correct perl distribution and then check which modules are available at all etc.

What about other languages? Compiled languages like C or C++ never got traction since scripting serves the rapid developing market better. Java existed, but Java Virtual machines required way more resources and shared hosting in the way PHP supports it was hardly doable. Investment in harddware was way higher. ASP (as predecessor of ASP.Net) was bound to the Windows platform, limiting it to organizations which already run Windows and who don't fear the licensing costs, and again no shared hosting support.

Different other technologies where produced but either were commercial (Cold Fusion or Netscape Server with server-side JavaScript) limiting their reach or didn't et out of their reach till Ruby-on-rails came, which probably was the first environment receiving lots of attention, but by that time PHP was already very popular with a large community and well-established software (like Wordpress or Drupal) making it hard to compete - especially as development of PHP never stopped and is still going on.

ContentLicense: CC BY-SA 4.0


问:
Why does the Windows Clipboard require an STA thread?
To copy something to the clipboard in Windows (at least in .NET as far as I know) it has to be done on a separate thread that is in STA Mode. One example I have used is this.

Thread thread = new Thread(() => Clipboard.SetText(s.Trim()));
thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
thread.Start();
thread.Join();
```
<p>Why do I have to do all of that instead of being able to just call:</p>
<pre class="lang-cs prettyprint-override"><code>Clipboard.SetText("text")
</code>```

答:
In a word, legacy.

In the article Why is STAThread required?, we're told:

When the STAThreadAttribute is applied, it changes the apartment state of the current thread to be single threaded.  Without getting into a huge discussion about COM and threading, this attribute ensures the communication mechanism between the current thread and other threads that may want to talk to it via COM.  When you're using Windows Forms, depending on the feature you're using, it may be using COM interop in order to communicate with operating system components.  Good examples of this are the Clipboard and the File Dialogs.

Said another way, communication with operating system components like the Clipboard are handled through COM and that requires changing the apartment state of the thread by using an STA thread.


问:
Is there a pattern to map a range of numbers to a string?
I need a function that will take the name of a town and return a specific range of numbers that is assigned to that town. I won't be using a database. The simplest way to do this is

```<code>    //Pseudocode
    public arr getTownNumbers(string town) {

      switch (town)
        case: "Pasadena"
          arr["min"] = 183
          arr["max"] = 194
          return arr
        case: "Charlotte"
          arr["min"] = 268
          arr["max"] = 270
          return arr
    }
</code>```

This seems dirty though. Is there a pattern for storing this kind of data?

答:
There are a lot of things that 'smell' about this code. It just feels awkward and forced. Having a 'switch' statement is one of those 'something is likely wrong around here' things that people point at unless it is clear that this is the right thing... and the String switch in Java just rubs me wrong every time I see someone try to put it into use.

You've got data. Putting data in code is a 'bad' thing. Data should be in some data format. Be it a database or a property file or some other storage system.

Lets do a property file for an example.

city.Pasadena.min=183
city.Pasadema.max=194
city.Charlotte.min=268
city.Charlotte.max=270
```

<p>You then read it with the Properties class.  Other approaches for reading from an actual database exist.</p>

<p>And there, now your data is separate from the code.</p>

<p>You could then have a nice little object that looks something like:</p>

<pre class="lang-java prettyprint-override"><code>class Range {
  private int min;
  private int max;

  public boolean in(int value) {
    return value <= max && value >= min;
  }
}
</code>```

And you could extend this with making iterators or disjoint ranges or a Set<Integer> butNotIn.

Body:
There are a lot of things that 'smell' about this code. It just feels awkward and forced. Having a 'switch' statement is one of those 'something is likely wrong around here' things that people point at unless it is clear that this is the right thing... and the String switch in Java just rubs me wrong every time I see someone try to put it into use.

You've got data. Putting data in code is a 'bad' thing. Data should be in some data format. Be it a database or a property file or some other storage system.

Lets do a property file for an example.

city.Pasadena.min=183
city.Pasadema.max=194
city.Charlotte.min=268
city.Charlotte.max=270

You then read it with the Properties class.  Other approaches for reading from an actual database exist.

And there, now your data is separate from the code.

You could then have a nice little object that looks something like:

class Range {
  private int min;
  private int max;

  public boolean in(int value) {
    return value <= max && value >= min;
  }
}

And you could extend this with making iterators or disjoint ranges or a Set<Integer> butNotIn.


问:
Is 4-5 years the “Midlife Crisis” for a programming career?
I’ve been programming C# professionally for a bit over 4 years now. For the past 4 years I’ve worked for a few small/medium companies ranging from “web/ads agencies”, small industry specific software shops to a small startup. I've been mainly doing "business apps" that involves using high-level programming languages (garbage collected) and my overall experience was that all of the works I’ve done could have been more professional. A lot of the things were done incorrectly (in a rush) mainly due to cost factor that people always wanted something “now” and with the smallest amount of spendable money. I kept on thinking maybe if I could work for a bigger companies or a company that’s better suited for programmers, or somewhere that's got the money and time to really build something longer term and more maintainable I may have enjoyed more in my career. I’ve never had a “mentor” that guided me through my 4 years career. I am pretty much blog / google / self taught programmer other than my bachelor IT degree.

I’ve also observed another issue that most so called “senior” programmer in “my working environment” are really not that senior skill wise. They are “senior” only because they’ve been a long time programmer, but the code they write or the decisions they make are absolutely rubbish! They don't want to learn, they don't want to be better they just want to get paid and do what they've told to do which make sense and most of us are like that. Maybe that’s why they are where they are now. But I don’t want to become like them I want to be better. I’ve run into a mental state that I no longer intend to be a programmer for my future career. I started to think maybe there are better things out there to work on. The more blogs I read, the more “best practices” I’ve tried the more I feel I am drifting away from “my reality”. But I am not a great programmer otherwise I don't think I am where I am now. I think 4-5 years is a stage that can be a step forward career wise or a step out of where you are.

I just wanted to hear what other have to say about what I’ve mentioned above and whether you’ve experienced similar situation in your past programming career and how you dealt with it. Thanks.

答:
Wow!
I like how valuable this conversation is.
I am a web developer with 5.5+ years of experience and I love it.
I can't vote but I will quote AZ's words.
I agree with that!

I've found that there are 2 secrets of
  relative happiness: - do not seek to
  have everything you want but seek to
  want everything you have - life it's
  tough - it doesn't matter how hard you
  can hit (good you are, personally and
  professionally); it will always hit
  back harder. it matters how much you
  can get hit and still be able to move
  on.

The book I'd recommend is:
http://www.amazon.com/Software-Measurement-Estimation-Quantitative-Engineering/dp/0471676225

OwnerDisplayName: lordspace


问:
Is there a limit to how often I should access a website programically to avoid DDOS?
I have my own website that displays some data I get from webscraping.  I run the webscraping script on my website host server.  I just realized that maybe I'm accessing other websites too quickly through this script. For example, I just wrote a script that accessed 15 websites on the same domain in about a second.  My own website server crashed shortly thereafter.  My webhost was having some other problems so I don't know if these two events are related or not.

But, I guess it brought up another question.  Do I need to limit how fast I access websites to prevent a denial of service (DOS) type warning from either the website I'm accessing or my own webserver host?  Is there some sort of safe rate of websites per second or per minute I should follow?  Just wondering,

EDIT: To clarify, yes I could slow down the collection process but I'm actually scraping a lot of small pieces of information from different sites so accessing a lot of websites might be unavoidable.  Also, based on what I'm doing, getting the information as quickly as possible would be beneficial.  So I can slow the process down but I guess I'm looking for how much I can "push" the limit to get the information in the optimal time.

答:
Yes you do, no there isn't. Be nice. --MichaelT

As @MichaelT says there is no set rule, but how often does the information on the foreign sites that you scrape change?  You might cache the results locally on your server (or some DB) and only update/rescrape every minute, hour, day etc.

For example, movie showtimes change slowly, only recheck them every hour.  A basketball game score changes often, you need to check every few seconds.


答:
I can relate in terms of the code written could be better but there has to be a line where one may be too much of a perfectionist as if something works 99.99999% of the time, isn't that close enough to 100% for most people?  Part of my struggles at times with negative thought patterns are perfectionism and intense self-criticism and judgement so maybe I can overly identify with that.

4-5 years is enough time, IMO, to figure out a few things:

What you want - What practices in your current position do you enjoy?

What works for you - This is slightly different in that what works may not always be what you want.

What are your dealbreakers - Could you go work for a company that wouldn't let you have an IDE?  Extreme example but I would hope that illustrates the point somewhat.

There are other questions like "Roadmap to a better programmer," and "How to become a 'faster' programmer," that may have suggestions for you if you do want to improve your skills.

I've also experienced where the senior title is given to someone merely for surviving in the field for so long, rather than achieving a level of skill.  You can either accept this as part of how the world works or you can try to find places that run differently.  How many actually exist I don't know, but I can say that sometimes you can find a good place in terms of how you like to work and what the company and co-workers use to get the job done.

"Sources of Insight" is one of my favorite blogs and I enjoy reading it nearly all the time.  The material is a bit head heavy in terms of there being a lot of intellectual elements to what is written but there are nuggets that one can take and make their life a little better or at least that has been my experience.

I can remember in school when I was a child that there were often transitions after 4-5 years as while my first school I was at for 8 years(Junior Kindergarten to grade 6), then it was 2 years(grades 7 and 8), 4 years(High school which was grades 9-13 where 11/12 was done in one year in my case), and 4 years(university bachelor's degree).

I can accept the idea of crisis coming at various points in life,e.g. finishing university can cause one to wonder who they are or after working for a while wondering if it is all worth it.

Some places can appear as awesome places to work and others can lead to burnout as that has been a question here a couple of times, "What causes developer burnout," and "Developer burnout stories," while other questions are the flip of that, "What is your motivation," and "Programming (de)motivation and further plans..."

Just for the sake of background in my answer here I've been developing web sites/applications for almost 12 years now as I got my first out of university job in February 1998 and aside from an 8 month drought where I wasn't working I have been doing this all the time in a few different environments: A couple dot-coms, an application service provider and now within the Information Systems department's web development team at a local technology company.  I realize this is a long answer, but I think the questions asked don't have short answers to my mind.

OwnerDisplayName: JB King


问:
How to implement a facade correctly
I have read multiple websites on this topic but none of them gave me a 'good' solution for the problem I am having. The problem is described in the following (related) questions:

How do I couple the UI package with the rest of the system without too much coupling with classes inside the other packages (I am thinking of the facade pattern).

I am having a lot of single instance classes but I don't want to use the Singleton Pattern to force the single instance. In some cases I need access to those classes in other packages.

See the figure below for a (simplified) class and package diagram of the system. I am having a class ProtocolParser (not the real name) that parses incoming data and raises events when certain packages are received. The events are handled by the AnchorManager and the TagManager. Those classes do almost the same thing. When the event is received they look in their list of Anchors or Tags if they find a Anchor or Tag with the same id they update it with new data otherwise they create a new Anchor or Tag. I also have class TrackingDeviceManager this class is responsible for keeping a list of all TrackingDevices in the system (so for example the UI can show a list of them).

It is not really useful to have multiple instances of the classes TrackingDeviceManger, AnchorManager and TagManager since they need to keep track of all the TrackingDevices, Anchors or Tags in the system. So I could potentially make them singletons. But I don't think the singleton pattern is the right way to go here.

So I am thinking to implement a TrackingFacade (singleton and a facade) this class will create instances of the three classes and initialize them. It also exposes some public methods and events so other classes in other packages can consume those. But I am wondering if this is a good approach. Or should I rethink my design?

Class diagram (simplified)

Package diagram

答:
Regarding singletons

None of the classes pictured here should be a singleton.

The only class which should be a singleton is the main application class, which instantiates the two major classes that we see here: the "Tracking" class, which is your application logic (domain logic) and the "UI" class, which is your UI.

And just so as to make sure we are on the same page, by "Singleton" I mean a class which has a private constructor and has a public static final TrackingApplication INSTANCE = new TrackingApplication(); member.

Regarding facades

The need you have discovered is actually that which the MVC and MVVM architectural patterns were invented to address.

Without too much jargon, what you have to the left of your "TrackingFacade" box is the classes that comprise your "model". What you want is an intermediate class between your model and your UI code which offers a uniform "presentation" of your model so that your UI can make use of it instead of being concerned with the details of your model.  Also, in this intermediate class you are likely to add "business" logic (application logic, domain logic) which receives commands from the UI and performs actions on your model. (That's why it is not just a facade.)

In MVC this intermediate class can roughly be thought of as the "Controller", while in MVVM it corresponds to the "ViewModel".  I would recommend reading up on these architectural patterns.

Title: How to implement a facade correctly


答:
There is no well defined limits, but by looking into the access log of my http://gcc-melt.org/ site (which is quite specialized and has only about a thousand hits per day, including robots), I see that well behaved bots:

are querying the robots.txt file and following it

are making requests spaced by a few seconds (typically 5) at least

I would advise your program to behave likewise. Don't query the same website more than once every few seconds (in a rate similar to what humans are browsing). Of course your webscraper can make requests to other sites before that.

If you are querying (programmatically) some particular website very often (e.g. more than once per second), I would suggest to at least try to contact (by email) its human webmaster. Some webmasters are blocking requests from hosts which query them too often.

Remember that some web sites (like mines) are paid by individuals, and their hosting contract may put some limits (typically on bandwidth or monthly data volume). So you should be nice with them.

Title: Is there a limit to how often I should access a website programically to avoid DDOS?

Body:
I have my own website that displays some data I get from webscraping.  I run the webscraping script on my website host server.  I just realized that maybe I'm accessing other websites too quickly through this script. For example, I just wrote a script that accessed 15 websites on the same domain in about a second.  My own website server crashed shortly thereafter.  My webhost was having some other problems so I don't know if these two events are related or not.

But, I guess it brought up another question.  Do I need to limit how fast I access websites to prevent a denial of service (DOS) type warning from either the website I'm accessing or my own webserver host?  Is there some sort of safe rate of websites per second or per minute I should follow?  Just wondering,

EDIT: To clarify, yes I could slow down the collection process but I'm actually scraping a lot of small pieces of information from different sites so accessing a lot of websites might be unavoidable.  Also, based on what I'm doing, getting the information as quickly as possible would be beneficial.  So I can slow the process down but I guess I'm looking for how much I can "push" the limit to get the information in the optimal time.


问:
Saga's and Query model transaction ordering
I have the following Ubiquitous language defined by our domain expert: A User can find UserGroups and add himself to it. A user can query a list of UserGroups where he is member of and remove himself from it. UserGroups are created by Users, where the creator is the first member. When there is no more User in the UserGroup, the UserGroup should be deleted from the views.

As UserGroups can become pretty big, by following "Effective Aggregate Design", I came to the following {AR}'s:

{User}<--(UserId)--{UserGroupMember}--(UserGroupId)-->{UserGroup}

All fine, except how to make the last rule (When there is no more User in the UserGroup, the UserGroup should be deleted from the views.) work with this model?

I've considered a saga that listens to UserGroupMemberLeft event, queuing the nr of members and if 0 delete the group. But as it queries the read-model, I have an ordering problem as the read-model is eventually updated as well. How to solve this? Should I consider a ReadModelUpdated event as well?

答:
All fine, except how to make the last rule (When there is no more User in the UserGroup, the UserGroup should be deleted from the views.) work with this model?

It's a constraint on the query executed by the read model to create the view.

This may mean that you need to update the read model to support the constraint.  For instance, in your original implementation, you might have have supported the view of user groups with a Set, where each group would be inserted into the set when it was created.

With the new requirement, the read model now needs to track total membership.  So you replace the Set with a Map, with you used to track the count of users added and removed from the group.  When you need a view of groups, you enumerate the entries in the hash to find the groups that satisfy the constraint (subscribedMembers > unsubscribedMembers).

Note that these details live purely in the read model -- the requirement as described didn't impose any restrictions on the write model.  Based on your comment about UserGroupMemberLeft, it looks like you are trying to introduce end of life to the model.

As pointed out by @JDT, some aggregate needs to be responsible for the end of life.  What state determines if the delete of a group is allowed?  The aggregate that controls that state is the one that should be responsible for the end of life operation, since it's the only one that knows if the retirement of the group is allowed.

I don't know your domain, but I'd guess that the group itself contains the required state.  For instance, if you aren't allowed to retire a group more than once, then it's probably the group that is tracking that.  Similarly, if you are only allowed to retire empty groups, its probably the state of the group that is tracking that.

So I assume the group is responsible for its own retirement.  At this point, you have two options available to you.  One is a process manager, which observes the membership counts and sends a command to retire the group when it observes that there are no members.  Because of eventual consistency, this command might be rejected -- for instance, if a new member joins the group after the last one has left.

If you need to retire the group in a transactionally consistent way, then the group locks itself against further enrollment as part of the transaction when the last member leaves.  For example, if the write model is broadcasting events to the read model, then the departure of the last user would generate two events, one describing the user leaving, and a second describing the retirement of the group.

Since the group locks itself when the last member leaves, you don't need to worry about the race condition.

Done this way around, your read model can use the Set implementation from earlier, adding groups to the set when they are first created, and removing them when the group is retired.


答:
My two points:

I hit mine after a mere 2 years in the industry. I overcame it by bettering myself and learning.

Most of the time, it will come because you are doing the same thing over and over. And if you're doing the same thing over and over... well... you're doing it wrong.

Always improve. Always learn. And hell, if your current company isn't giving you that atmosphere, go find one that will. I did and the last 2 years have been the best time of my life (I'm also probably 100x better at my job than I was 2 years ago too)

OwnerDisplayName: mendicant


答:
You are confused because you are thinking add is:

```<code>var add = (function  outer() {
             var counter = 0;
             return function inner() {return counter += 1;}
           })();
</code>```

but actually add is:

```<code>add= function inner() {return counter += 1;}
</code>```

 because this function is what outer self executing function is returning and it is assigned to add.

Outer function is executed only once (when it is returning inner function) and initialized variable "counter" to 0.

Child function can access parent function's variable, and each time we are calling add, it just increment "counter" by 1.

Title: Javascript Closure Scope

Body:
You are confused because you are thinking add is:

var add = (function  outer() {
             var counter = 0;
             return function inner() {return counter += 1;}
           })();

but actually add is:

add= function inner() {return counter += 1;}

 because this function is what outer self executing function is returning and it is assigned to add.

Outer function is executed only once (when it is returning inner function) and initialized variable "counter" to 0.

Child function can access parent function's variable, and each time we are calling add, it just increment "counter" by 1.