问:
Why don't "multi-infinite" list comprehensions work with lazy evaluation?
As a simple demonstration of the efficiency of Haskell style, I thoughtlessly ran the following:

take 100 [(a, b, c) | a <- [1..], b <- [1..], c <- [1..], a^2 + b^2 == c^2]

This should be a way of deriving the first 100 Pythagorean triples, with duplicates. In practice however, it never halts, because the algorithm itself defies lazy evaluation.

To think about it in terms of actual implementation, the following should be something similar to how the list comprehension is actually evaluated, in an imperative style:

```<code>results = []
for (a = 0; a < ∞; a++) {
  for (b = 0; b < ∞; b++) {
    for (c = 0; c < ∞; c++) {
      if (a^2 + b^2 == c^2) {
        results[] = [a, b, c]
      }
    }
  }
}
</code>```

When written like this, it becomes obvious that the function can never yield results, because infinite time will be spent testing whether 1^2 + 1^1 == c^2, as only the innermost for loop will advance, and a and b will remain '1'.

The common solution in this particular case is to constrain the values of the smallest two variables to that of the largest:

take 100 [(a, b, c) | c <- [1..],a <- [1..c], b <- [1..c],a^2 + b^2 == c^2]

However, this seems like an obvious oversight for implementors of the language. When you think about it, any list comprehension with more than one infinite source of search space will never halt, for the same reason, except some will yield useful results when (1, 1, x) is useful. There are questions discussing this problem, but most discuss specific cases, rather than the problem overall. Why isn't fixing this within the language with a different iteration pattern trivial?

答:
It is certainly possible to define an iteration order for x1 <- [1..], x2 <- [1..], ..., xK <- [1..] that will reach any tuple (c1, c2, ..., cK) after some finite amount of steps, and tries each tuple only once. Take any computable bijection between the natural numbers N and the k-tuples of natural numbers, N^k. Such a bijection exists, as the Cartesian product of countable sets is again countable. One example would be repeatedly applying the (inverse of the) Cantor pairing function. The precise bijection being used would have to be specified by the Haskell report, because it affects the order in which results are found.

However, this is of limited utility, because it would only cover the very specific pattern with [1..]. There are countless other ways to produce infinte lists, and not only is it far more involved to define a suitable iteration order for those cases, it is also impossible for the compiler to detect infinite lists in all cases (Rice's theorem). So you'd have to define some heuristic for when this transformation applies. In the interest of being feasible to describe and implement across multiple interpreters and compilers, this would likely be a very simplistic heuristic.

So what you are left with is a subtle change to the semantics of a program, with no indication in the program source code, that only happens when some arcane and limited heuristic fires. Thanks, I'll pass. Just explicitly write the program to do what you want.


问:
Manuals - How Up To Date?
If you have a product that has been in the market for a long time, but it is still in active development daily - how often should the manuals be updated? If your users are constantly updated to the bleeding edge version due to the fact that your organization sees fit that the latest bug fixes are always in the shipped version. Meaning, you could fix a bug one day and next day it is hitting production.</p>

答:
In my organization, we typically have 3 kinds of releases:

Engineering Release -- basically hot fix for some specific customer or some feature only a particular customer has requested on an immediate basis.

Minor Release -- bug fixes, incremental support

Major Release -- new feature support etc.

By definition, Major Release must have the relevant documentation in place both online and offline. Our tracking system ensures that documentation is very much a part of the checklist.

Minor releases need documentation only on anything new that has been added at the user perception level. So if you've included yet another heuristic that might reduce time complexity in some specific scenarios it may or may not be a significant call to put it in the pdf.

Engineering releases could do without documentation. Some informal use notes should be good enough to get started.

ContentLicense: CC BY-SA 2.5

Title: Manuals - How Up To Date?


问:
Rest APIs - mobile specific challenges
I'm working on a new iOS app project, on the mobile side. Some architecture changes are happening and it turns out we will have to rely on a custom built private API that will be used by the app we are building and also by other clients such as a website.

The API being designed follows the Rest style of resources-centric URI and CRUD operations mapped to HTTP verbs. things like:

```<code>GET www.example.com/books
DELETE www.example.com/books/482094
POST www.example.com/users/6793
</code>```

The problem is that this style often leads to the need for the mobile client to do many requests for loading a single app screen or managing a single user UI action. This leads to the app being in loading mode for 8 seconds till it has everything needed. A slow and unresponsive app.

Mobile clients have serious limitations when it comes to connectivity and so ideally, we should follow that sort of rule:

1 screen == 1 API call

1 save == 1 API call.

There are many situations where this puts you on a collision course with the REST design principles, for examples:

let's say your app has been offline for a day and you need to sync
with four tables of the back-end databases and you need a call like
www.example.com/sync_everything?since=2015-07-24

let's say there is a screen where the user can edit many of his
objects, for example ticking tasks in his todo list. There should be
a way to edit all those tasks records in one single batch API call
rather than one API call per edit.

let's say there is a screen that
mixes information from the ORDER, SALESMEN and PRODUCT db tables, I
should get that data in one call instead of three.

the risk is that we might end up with the most Restful API there is and also the most useless unresponsive mobile app there is.

The thing is I'm only a new contractor there and what I need is something that help me makes those points, some articles from well respected  sources or something like that. Major players compromising with the REST style for their mobile client (e.g.: by using composite aggregate API end points).

Or any solution for this general problem. Thanks!

答:
The API being designed follows the Rest style of resources-centric URI and CRUD operations mapped to HTTP verbs.

This is your problem right here.

You have limited your resources to (I'm assuming) the models in your database. As such it is taking ages to load all these resources because your server has no concept of resources that don't have a representation in the database.

For example might have

```<code>www.example.com/books/482094
www.example.com/books/582045
www.example.com/books/427454
www.example.com/books/319343
</code>```

that all have to be loaded to get my library

This isn't a problem with RESTful design, this is actual a REST anti-pattern. There is absolutely nothing in REST that says our resources must have a one to one mapping with anything else in your system, including database models.

The solution is to create more resources that better match what you want to load. If you have 5 resources that always end up together create a new resource that contains the info for those 5 resources.

What you should have is something like this

```<code>www.example.com/users/334/my_library
</code>```

which just loads all the books for that user. "my_library" isn't a model in your database, but it is a resource. The server creates it based on models in the database but there is no 1-to-1 mapping and the server has flexibility to create this resource without changing your DB model.

You might also have

```<code>www.example.com/users/334/favioured_books
www.example.com/users/334/books_ordered_last_week
www.example.com/users/334/wishlist
</code>```

none of which have to exist as model in your database or domain space.

There is a wide spread misconception that this is the wrong thing to do because frameworks like Rails taught people to map resources in a 1-to-1 fashion to models in the domain space which map again 1-to-1 with database rows. This is not necessary nor is it recommended.

Resources should be numerous, cheap and lightweight. It should be easy to create them, and they should be abstracted from your domain model. If you find you need a new one you just make a new one. If you have problems doing that it is your frameworks fault not a fault with REST.

Now the big caveat with that of course is whether your framework allows you to do this. Frameworks like Rails and Django which have taken the course to map 1-to-1 in order to "save you time" make it hard to do this. But that is a flaw with the frameworks, not with RESTful design.

Here is Jim Webber discussing this is more detail (including a few digs at Rails as well!)

https://yow.eventer.com/yow-2011-1004/domain-driven-design-for-restful-systems-by-jim-webber-1047

ContentLicense: CC BY-SA 4.0

Title: Rest APIs - mobile specific challenges

Body:
The API being designed follows the Rest style of resources-centric URI and CRUD operations mapped to HTTP verbs.

This is your problem right here.

You have limited your resources to (I'm assuming) the models in your database. As such it is taking ages to load all these resources because your server has no concept of resources that don't have a representation in the database.

For example might have

www.example.com/books/482094
www.example.com/books/582045
www.example.com/books/427454
www.example.com/books/319343

that all have to be loaded to get my library

This isn't a problem with RESTful design, this is actual a REST anti-pattern. There is absolutely nothing in REST that says our resources must have a one to one mapping with anything else in your system, including database models.

The solution is to create more resources that better match what you want to load. If you have 5 resources that always end up together create a new resource that contains the info for those 5 resources.

What you should have is something like this

www.example.com/users/334/my_library

which just loads all the books for that user. "my_library" isn't a model in your database, but it is a resource. The server creates it based on models in the database but there is no 1-to-1 mapping and the server has flexibility to create this resource without changing your DB model.

You might also have

www.example.com/users/334/favioured_books
www.example.com/users/334/books_ordered_last_week
www.example.com/users/334/wishlist

none of which have to exist as model in your database or domain space.

There is a wide spread misconception that this is the wrong thing to do because frameworks like Rails taught people to map resources in a 1-to-1 fashion to models in the domain space which map again 1-to-1 with database rows. This is not necessary nor is it recommended.

Resources should be numerous, cheap and lightweight. It should be easy to create them, and they should be abstracted from your domain model. If you find you need a new one you just make a new one. If you have problems doing that it is your frameworks fault not a fault with REST.

Now the big caveat with that of course is whether your framework allows you to do this. Frameworks like Rails and Django which have taken the course to map 1-to-1 in order to "save you time" make it hard to do this. But that is a flaw with the frameworks, not with RESTful design.

Here is Jim Webber discussing this is more detail (including a few digs at Rails as well!)

https://yow.eventer.com/yow-2011-1004/domain-driven-design-for-restful-systems-by-jim-webber-1047

ContentLicense: CC BY-SA 3.0


问:
Calendar/Planning algorithm
I'm facing a problem I'm not sure how to approach. I have to generate a calendar for employees, each of them having specific work constraints (some personal, some common)

What I'm working with :

I have Doctors

Each doctor has to work 5 day/week.

Each doctor has to work 1 night/week

Each doctor has to work an equal amount of nights compared to other doctors (or as close as possible)

Each doctor has to work an equal amount of thursday nights and sunday nights compard to other doctors (or as close as possible)

Some doctors can't work certain days/nights (input by user)

Some doctors would like to work certain days/nights (input by user)

Some doctors would like to not work certain days/nights (input by user)

The user in question is the person dealing with the calendar, I'm trying to build a solution that will automatically generate a calendar that obeys all constraints. The solution is just a big settings input "add doctors" and "add constraints" for each doctor, then a "generate calendar" button. It's really basic for the user.

My problem :

I'm not sure how to generate the actual planning, I've been reading about Neural Networks, Genetic Algorithms, and so on, and they all seem kind of the right solution but also not really.

When I look at GA's, they're made to find a solution with a given population (my problem), but the starting population has to already obey the given set of constraints, which would then be optimized. In that case, my starting population is already the solution. I don't need it to be "optimized". It doesn't matter that a single person works 3 monday nights in a row, as long as it's actually correct and that others work the same amount, that means others will also work 3 monday nights at some point and it's fine. Which makes me think that GA's are too "advanced" for me, as my problem is already solved with the starting point of a GA.

But then again, GA's really really looks like they're made for this, so I might not be understanding it correctly ?

Anyway, as I've never used GAs (or neural networks, or anything of the kind), I'd like to be sure I'm going for the correct approach before engaging in a learning curve like that one.

My question :

What do you think is a good approach / algorithm / technique for a problem like mine? GA's? Neural networks? Something else entirely different?

I'm all ears and open for more details if necessary, but I think i've made myself pretty clear :)

答:
Genetic Algorithms and Neural Networks are not suitable here. They are meta-heuristics for finding a good-enough, approximate solution to a problem. Notably, both require you to find a cost function to rate candidate solutions. Once you have such a cost function, it might be easier to manually come up with an algorithm that optimizes for this cost.

This is an important thought: given two schedules, we need a way to decide whether schedule A or schedule B is “better”. You have listed various criteria, but it's not clear how they relate. Does failing to fulfil one criterion fail the whole solution? Or does partially failing a constraint just make it a worse solution than others?

At a most basic level, you can just partition the week into discrete time slots, and brute-force all slot–doctor combinations. However, you can use hard-failing constraints to reduce this search space to a more manageable size. The restrictions on work time and night shifts seem to be suited for such a search space limiting. You are then left with hundreds of candidate solutions.

To select the best candidate solution, you will need to rank them. This is fairly easy if one soft constraint has clear precedence over all other soft constraints, e.g. if a doctor can't work a certain shift, that is given more importance than a doctor not wanting to work that shift. But I can't decide these rules for you – that is a managerial decision. It is more difficult if two soft constraints don't have clear precedence, in which case you will have to come up with some kind of cost function that unifies the importance of two constraints in a single metric.

I would probably construct a greedy algorithm that fills in a blank time table according to some prioritized criteria. This might not be the most optimal solution, but it's way easier than philosophising about what “optimal” actually means.

As a first step, you could fill in the night shifts on weekends, and trying to select those doctors that haven't done a weekend night shift for the longest time, also taking into account the “I can't work there” user wishes. Assuming that these wishes are per-week and not continuous, this means a doctor that can't work on weekend nights for one week would be picked next week.

A similar procedure can be used for the other nights: after trying to respect user wishes, you fill in doctors according to who hasn't been doing night shifts for the longest amount of time. The procedure repeats similarly for the third kind of time slot, the day shifts. If two user wishes can not be reconciled, you could keep track of how often a users wish was granted, and then prioritizing the doctor with fewer granted wishes.

Unfortunately, I can see a couple of ways to game this system: e.g. if a doctor would be picked to work a weekend night shift but puts in a “can't work there” request, their pick would be delayed one week – reducing their frequency of weekend night shifts at the cost of their colleagues. If a wish resolution procedure is implemented that looks at the number of turned down requests, a user could put in a couple of impossible requests to boost one request they want to go through. However, assuming good faith (and the flexibility for doctors to swap shifts among each other), such an algorithm should result in a good-enough solution.

Title: Calendar/Planning algorithm


答:
You can use simulated annealing.

I did something like that before I landed my first job - see https://vimeo.com/20610875 (demo starting at 2:50, algorithm explained from 6:15).

Simulated annealing is a type of a genetic algorithm, and maybe it was not suitable in theory (as @amon maintains in his answer), but it worked very well in practice, and it was about the same use case as yours.

Source code is available (C#), but while it works, it's terrible I'm afraid, it was a few years back and being an autodidact, I didn't know a thing about maintainability. It yielded very nice results though.

How it works in a nutshell anyway:

Generate 1 possible (it may be not very good, but physically possible) time schedule as a starting point. Genetic algorithm isn't necessary at this point - you can just bruteforce your way to the first solution you can find. I used backtracking. Computational complexity can be overcome by solving the rota for each day separately. If there is no solution at all (as the case might be), it is at this point that you detect it.

Make a pool of solutions - say, 100 copies of this entry-level solution for a start.

Mutate every solution at random: have doctors swap shifts between eachother, take a random doctor off their shift and put a random available person on it etc.

Evaluate each solution with a fitness function that determines how good it is. One guy works more nights than another? Subtract penalty points. Someone wanted to do Monday but they don't? Subtract penalty points again.

Take - say - 20 best solutions and copy each of them 5 times, overwriting the remaining 80 with them, thereby carrying them to the next generation. Survival of the fittest.

Rinse & repeat.

Numbers are obviously arbitrary, you may need to fiddle with parameters to find out the optimal settings for your scenario.

As for mutating a solution, simulated annealing introduces something called temperature. Basically it means that in the beginning you should mutate your solutions quite hard (say, always make 10 attempts of swapping shifts in one go) and gradually get less aggressive with subsequent iterations, so they become more of a fine-tuning (say, down to just 2 attempted tweaks per generation).

Title: Calendar/Planning algorithm

Body:
I'm facing a problem I'm not sure how to approach. I have to generate a calendar for employees, each of them having specific work constraints (some personal, some common)

What I'm working with :

I have Doctors

Each doctor has to work 5 day/week.

Each doctor has to work 1 night/week

Each doctor has to work an equal amount of nights compared to other doctors (or as close as possible)

Each doctor has to work an equal amount of thursday nights and sunday nights compard to other doctors (or as close as possible)

Some doctors can't work certain days/nights (input by user)

Some doctors would like to work certain days/nights (input by user)

Some doctors would like to not work certain days/nights (input by user)

The user in question is the person dealing with the calendar, I'm trying to build a solution that will automatically generate a calendar that obeys all constraints. The solution is just a big settings input "add doctors" and "add constraints" for each doctor, then a "generate calendar" button. It's really basic for the user.

My problem :

I'm not sure how to generate the actual planning, I've been reading about Neural Networks, Genetic Algorithms, and so on, and they all seem kind of the right solution but also not really.

When I look at GA's, they're made to find a solution with a given population (my problem), but the starting population has to already obey the given set of constraints, which would then be optimized. In that case, my starting population is already the solution. I don't need it to be "optimized". It doesn't matter that a single person works 3 monday nights in a row, as long as it's actually correct and that others work the same amount, that means others will also work 3 monday nights at some point and it's fine. Which makes me think that GA's are too "advanced" for me, as my problem is already solved with the starting point of a GA.

But then again, GA's really really looks like they're made for this, so I might not be understanding it correctly ?

Anyway, as I've never used GAs (or neural networks, or anything of the kind), I'd like to be sure I'm going for the correct approach before engaging in a learning curve like that one.

My question :

What do you think is a good approach / algorithm / technique for a problem like mine? GA's? Neural networks? Something else entirely different?

I'm all ears and open for more details if necessary, but I think i've made myself pretty clear :)


问:
C++11 Lambda vs Helper Member Functions
There are a bunch of methods in a class that I want to clean up. These just build up a data structure (with different values) over and over again and add them to a container passed in, like so:

```<code>SomeClass::Foo(ContainerType& cont)
{
   AnotherType dataItem;
   dataItem.item1 = true;
   dataItem.item2 = 42;
   // blah blah
   cont.addItem(dataItem);

   // ... snip ...

   AnotherType newItem;
   newItem.item1 = false;
   newItem.item2 = 128;
   // blah blah
   cont.addItem(newItem);
}
</code>```

It is rather convenient (relevant code within same function, so easy to get to and read) to have a lambda function local to each method and call it instead (future changes will be limited to one place), like so:

```<code>SomeClass::Foo(ContainerType& cont)
{
   auto buildData = [](ContainerType& cont, bool flag, int value){
       AnotherType dataItem;
       dataItem.item1 = true;
       dataItem.item2 = 42;
       // blah blah
       cont.addItem(dataItem);
   };
   buildData(cont, true, 42);
   // ... snip ...
   buildData(cont, false, 128);
}
</code>```

rather than adding a new private member function for doing the same:

```<code>SomeClass::Foo(ContainerType& cont)
{
    buildData(cont, true, 42);
    buildData(cont, false, 128);
}
SomeClass::buildData(ContainerType& cont, bool flag, int val)
{
   // blah blah
}
</code>```

Given that the internals of how to build AnotherType objects is not useful/necessary outside the method SomeClass::Foo(), here are the questions I seek guidance for:

Are there any other cleaner/better solutions to this?

Are there any non-obvious pitfalls to using the local lambda approach over the new private member approach?

Currently, I've used the local lambda approach and cut a lot of the repeating code out. I just want to ensure that this is an acceptable way to go.

答:
Both solutions make sense, and have different tradeoffs.

Lambdas

The style of using lambdas inside another function is very common across many languages. If it seems alien to you, that's just because lambdas weren't available in C++ until recently. The advantage of this style is that the whole implementation of the function is within that function, with the lambda grouping repeated behaviour into a single block. Since the lambda can capture local variables (cont in your case), you will not typically have to pass many arguments. Drawbacks are that this function can still grow rather longish, and that you can't independently test the extracted behaviour.

Named functions

If you use a proper function (either a free function in an anonymous namespace, or a private member function), then your main function becomes less cluttered, and the extracted behaviour is independently testable. This extract-function refactoring is incredibly common, and makes it a breeze to test and understand the code: Each function is only a couple of lines long. And with proper names, such code becomes highly self-documenting.

However, parts of the behaviour are now strewn all over the place, and forming a complete understanding of the behaviour requires a reader to stitch together all these bits and pieces – too much abstraction can result in a loss of maintainability. Also, the previously internal code can be now called from any other function within its scope, which means that invariants that are obvious within local usage are now not guaranteed and have to be re-checked if you are interested in correct code, e.g. asserting that a pointer is non-null. Finally, an important downside is that any context which the function operators on has to be passed explicitly as an argument. This can become tedious for 5–8 arguments, since C++ does not have named formal parameters :(

For-loops

Another possibility, more like creating a lambda, is storing the data you are operating on in a vector, and then performing an action on each item via a loop. E.g.:

```<code>std::vector<WorkItem> items {
  {true, 42},
  {false, 128},
};
for (const auto& item : items) {
  ...
}
</code>```

Often, the work item type might just be a tuple or pair. I'm not too fond of this solution since the ordering of the code is a bit unintuitive, but it's an effective method to get repeated code out of the way.

Personal opinion

When I extract behaviour into a separate function, I first tend to use a lambda since the advantage of capturing local variables is tremendous. However, in later refactorings I tend to use named functions so that I can test them more easily. For me, this outweighs the cost of losing context.

Title: C++11 Lambda vs Helper Member Functions

Body:
Both solutions make sense, and have different tradeoffs.

Lambdas

The style of using lambdas inside another function is very common across many languages. If it seems alien to you, that's just because lambdas weren't available in C++ until recently. The advantage of this style is that the whole implementation of the function is within that function, with the lambda grouping repeated behaviour into a single block. Since the lambda can capture local variables (cont in your case), you will not typically have to pass many arguments. Drawbacks are that this function can still grow rather longish, and that you can't independently test the extracted behaviour.

Named functions

If you use a proper function (either a free function in an anonymous namespace, or a private member function), then your main function becomes less cluttered, and the extracted behaviour is independently testable. This extract-function refactoring is incredibly common, and makes it a breeze to test and understand the code: Each function is only a couple of lines long. And with proper names, such code becomes highly self-documenting.

However, parts of the behaviour are now strewn all over the place, and forming a complete understanding of the behaviour requires a reader to stitch together all these bits and pieces – too much abstraction can result in a loss of maintainability. Also, the previously internal code can be now called from any other function within its scope, which means that invariants that are obvious within local usage are now not guaranteed and have to be re-checked if you are interested in correct code, e.g. asserting that a pointer is non-null. Finally, an important downside is that any context which the function operators on has to be passed explicitly as an argument. This can become tedious for 5–8 arguments, since C++ does not have named formal parameters :(

For-loops

Another possibility, more like creating a lambda, is storing the data you are operating on in a vector, and then performing an action on each item via a loop. E.g.:

std::vector<WorkItem> items {
  {true, 42},
  {false, 128},
};
for (const auto& item : items) {
  ...
}

Often, the work item type might just be a tuple or pair. I'm not too fond of this solution since the ordering of the code is a bit unintuitive, but it's an effective method to get repeated code out of the way.

Personal opinion

When I extract behaviour into a separate function, I first tend to use a lambda since the advantage of capturing local variables is tremendous. However, in later refactorings I tend to use named functions so that I can test them more easily. For me, this outweighs the cost of losing context.


答:
Genetics Algorithms do apply here. During my undergraduate program, one of my colleagues wrote a paper to very similar problem of yours.

You can look for Job Shop Scheduling and also Open Shop Scheduling or Flow Shop Scheduling can be interesting starting points

To use a genetic algorithm you don't need a perfect solution, you can start with N random candidates, and apply a fitness function to each of them, for example:

The difference of nights assigned between the most busy doctor and the less busy worked is a penalization in the cost function

Each time a doctor works more than 5 days per week or 1 night per week, you apply a penalty

Each of your constraints, etc...

Generating N candidates you would pick the X best of them, they would be the ones the inflict the constraints the less. Working with them, crossing and mutating over several generations one can end up with a good solution.

Having talked all of that, every time I used a Genetic Algorithm that relied more on mutation that on crossing, I could develop a Simulated Annealing that would perform far better, with an easier implementation. The cost/fitness and the mutation function for genetic algorithm will probably be very similar to one used in a Simulated Annealing. I would start there, look at @Konrad Morawski answer

Google search find good results for Job Shop and GA

Title: Calendar/Planning algorithm


问:
In the IEEE/EIA 12207.1-1997 Standard, what does "notation for description" refer to?
The IEEE 12207.1-1997 guide (Software life cycle processes - life cycle data) has a list of general content requirements for all description documents (section 5.1, page 12).  This includes "notation for description" (bullet f). Does this just refer to whatever system or structure is used for the description (e.g., design languages, diagrams, etc.), or is there another meaning?

The standard defines the purpose of a description as "Describe a planned or actual function, design, performance, or process" so it's very high-level. The specific context where I need to apply it is a Software Design Document.  We have a customer requirement to use sections of this IEEE standard, as well as another document, and I'm putting together a template that organizes all those requirements into a single document structure.

答:
The short answer to your question is, yes, this "notation for description" is stating your your description documents include a design language and sufficient information for a reader to understand that design language. A complete analysis, based on IEEE Std 1016-2009 IEEE Standard for Information Technology--Systems Design--Software Design Descriptions is below.

As of 13 August 2015, the current standard for software design descriptions is IEEE Std 1016-2009 IEEE Standard for Information Technology--Systems Design--Software Design Descriptions. I'm going to be basing the rest of this answer on that document and version.

The definition of a software design description (SDD), as presented in 1016-2009, is:

An SDD is a representation of a software design to be used for recording information and communicating that design information to key design stakeholders.

Unlike previous iterations of 1016, the 2009 release is very supportive of multiple development methodologies. For example, the wording of the 1998 revision was very much inclined toward a Big Design Up Front approach. The ideas in 2009 can be more readily applied to big design up front, iterative and incremental, and even reverse engineering approaches. In addition, it doesn't mandate a format - many older IEEE standards for software engineering are geared toward paper documents. The contents of 1016-2009 can be applied to "paper documents, automated databases, software development tools, or other media".

In 1016-2009, an SDD contains 1 or more design views. Each design view is governed by a design viewpoint, which is framed by one or more design concerns. A design viewpoint also defines one or more design elements, which are expressed in a given design language.

The following are experpts from Section 2 Definitions that apply to these terms:

3.2 design concern: An area of interest with respect to a software design.

3.4 design element: An item occurring in a design view that may be any of the following: design entity, design relationship, design attribute, or design constraint.

3.12 design view: A representation comprised of one or more design elements to address a set of design concerns from a specified design viewpoint.

3.13 design viewpoint: The specification of the elements and conventions available for constructing and using a design view.

All of this means that you start organizing your SDD based on the people who will use the information contained within the SDD. Different stakeholders will have different needs - consider network or system administrators who need to know about distributed components and communication protocols, database administrators who need to know about the data structures for databases to optimize them, quality assurance staff who will be testing the software, engineers implementing and maintaining the software, and so on. Each of these people have different concerns that need to be captured in the SDD. These concerns will be used to frame various viewpoints.

Table 1 in 1016-2009 provides a number of example design viewpoints. It identifies 12 different design viewpoints, but there is no indication that this is a comprehensive list nor is it all necessary for all projects. Some of these viewpoints are a context viewpoint, an information viewpoint, an interaction viewpoint, state dynamics viewpoint, and algorithm viewpoint. For each viewpoint, the table also gives example design concerns. As an example, the information viewpoint is used to address concerns regarding persistent information while the algorithm viewpoint provides procedural logical and the logical viewpoint captures static structure (classes, interfaces) and use of types and implementations (classes, primitive types).

Once you've identified the viewpoints, you define the design elements that are used to demonstrate that viewpoint, using a design language. The design elements that are appropriate depend on the viewpoint. For example, a design elements in a state dynamics viewpoint would be events, states, transitions, activities, triggers, and so forth. In an algorithm viewpoint, the design elements would be attributes, data, and processing steps. In an information viewpoint, the elements would be data types and classes, data storage formats and structures, and access mechanisms.

After defining your design elements, you represent them in a design language. 1016-2009 doesn't require any specific language or notation. They list several examples - the appropriate UML diagram types (if any) are often listed as examples for each viewpoint. However, the standard also mentions flowcharts and pseudocode as examples for the algorithm viewpoints or entity-relation diagrams for the information viewpoint. In a note in Section 4.9 Design Languages, the standard indicates that standardized design languages (IDEF0, IDEF1X, UML, Vienna Definition Language) are better than established languages without a formal definition (state machines, automata, decision tables, Warnier diagrams, Jackson Structured Design, HIPO models). However, the author is free to choose any design language that is appropriate.


问:
Will HTML5/JS Eventually Replace All Client Side Languages?
I'm just wondering about the future of it all. IMHO, there are 4 forces that define where technology goes: Microsoft, Apple, Google, Adobe.

It looks like in Apple's iPhone/iPad iADs can now be programmed in HTML5. So does that mean HTML5 will eventually replace objective-c?

Also, Microsoft has now shifted it's focus from WPF/Silverlight to HTML5 and I assume Visual Studio 2011 will be all about tooling support for HTML5. Because that's what Microsoft do. (Tools). In a few months IE9 the last major browser will support HTML5.

Similarly Adobe is getting on the HTML5 bandwagon and allows to export flash content to HTML5 in their latest tools.

And we all know how much in bed Google is with html5. Heck, their latest Operating System (Chrome OS) is nothing but a big fat web browser.

Apps for Mobile (i.e., iPhone, Android, WM7) are very hard for a company to program especially for many different devices (each with their own language) so I'm assuming this won't last too long. I.e., HTML5 will be the unifying language. Which is somewhat sad for app developers because now users will be able to play the "cool" html5 apps for free on the web and it'll be hard to charge for them.

So are strongly-typed languages really doomed, and in the future, say 5-10 years, will client side programming only be in HTML5? Will all of us become javascript programmers? :) Because the signs are sure pointing that way...

答:
Yes.

Here's why. Apps are composed of user interface code and back-end data. User interface code is run in HTML5/CSS3/Javascript. Back-end code can be proprietary and run in whichever language. Furthermore, jQTouch and similar libraries can be used to emulate iPhone-like UIs but open-source and written in Javascript/HTML5/CSS. jQTouch has shown that if the browser gives JS programmers access to the UI events of the device, JS programmers will emulate whichever UI style that is in fashion for the same platform.

Javascript programmers will be more in demand than ever. In a model-view-controller architecture, the model and controller are in the back-end, but the view code is best written in the browser. i.e. HTML5, Javascript, CSS. And you need to write JS code to access the back-end data, especially with heavy AJAX code.

The productivity gains will all go to the dynamic interpreted languages. As processors get faster and faster, programmer coding productivity, sysadmin productivity, and app-admin productivity are stronger influences on overall productivity. You simply don't have to worry about how fast your programming language's VM or compiler performs anymore. You need to worry more now about how much it costs to provision and support your app.

Most stand-alone apps are not that great in my opinion. Just like there are few great stand-alone PC apps, and the best ones are being transformed into web apps. It is actually better to give away the HTML/JS/CSS client app for free and charge a monthly fee for access to the back-end data and business logic. Programmers will do better selling subscriptions than one-shot apps.

BTW have a look at this video on writing a part of a standalone web app on a Webkit browser. It is interesting...

OwnerDisplayName: Shnitzel

LastEditorDisplayName: Shnitzel


问:
OOP Principles in Customer and Account classes of a Bank
I am designing a Bank Application which deals with Customers having FD Accounts.

There are two approaches to this :

Approach 1

In this the customer has a list of accounts. The bank application will manage the accounts through the customers.

My mentor feels this is the correct approach. :-P

```<code>class Customer
{
     String name;
     Date   dob;
     .
     .

     Account[] accounts = new Account[5];
}

class Account
{
     int   accNo;
     float amount;
     .
     .
}
</code>```

Approach 2

In this approach each account has its associated customer reference stored. The Bank application will now manage the accounts and customers independently.

I feel this is the correct approach. :-)

```<code>class Customer
{
     String name;
     Date   dob;
     .
     .
}

class Account
{
     Customer customer;
     int   accNo;
     float amount;
     .
     .
}
</code>```

Now my issues are :

Ideally the bank application should worry more about the account than the customer. For example, the bank should have methods like
addAccount() : which will add account and create a customer implicitly if it is the first account of the customer and
deleteAccount() : which will delete the account and delete the customer implicitly if it is the last account.

There can be a use case in the future where an account can have multiple customers. So that can be accommodated easily in the second approach than the first.

Considering all this, please can you say which is a better Object Oriented Approach here?

Also how is this actually implemented in a real Bank?

答:
This seems like a classical Has Many/Belongs To relationship type. What we usually do is kind of a merge between your 2 options, where:

A Customer has a list of the many Accounts he has.

An Account has a reference to the Customer it belongs to.

That being said, @James Anderson is accurate as he states the importance of customers rather than the account itself.


问:
How can I translate ML code to F#?
Recently I found a book, Purely Functional Data Structures and all the examples in this book are given in ML with Haskell versions in its appendix. But I only know one programming language with the functional paradigm: F#. And after a bit of research, I found out that F# is (or was) the .NET port of CAML, which is derived from ML. I've heard it mentioned that CAML is just a dialect of ML.

Given that, is it possible to translate ML to F# without a lot of knowledge of ML? What are the key differences from the languages? Or is my best bet to just learn ML instead?

答:
There's a project for this and other ML books https://code.google.com/p/book-samples-in-fsharp/ where they have converted much of the sample code already.

It's been noted in a comment that Google Code is going read-only very soon so worth grabbing that code now. I don't think they will kill it entirely at short notice but you can't tell.

I wouldn't normally post a "link-only" answer but there's a ton of good code there to look at.
(Sorry if referring to this as a "book project" mislead people).

Title: How can I translate ML code to F#?


答:
Object Oriented Modeling, its used to represent the real world in a Software Application.

In other times, a single account, had only, and only one customer, assigned. These days, several customers, can be assigned and removed from an account.

There are many ways to model an application, so there is not really a "100% bad" or "100% good" way.

Your example is a "many-to-many" associations.

And, usually an additional, intermediate class is added.

One way to start, is model each data set, or object, explicitly excluding relations to each other, and add those relations, later.

```<code>class CustomerClass
{
     int   CustNo;
     String name;
     Date   dob;
     .
     .
} // class CustomerClass

class AccountClass
{
     int   accNo;
     float amount;
     .
     .
} // class AccountClass

class AccountCustomerClass
{
     int   acccustNo;

  // How to relate both, added later
} // class AccountClass
</code>```

Later, pick one of the "edge" classes ("Account" or "Customer"), that better suits your needs, and add a "relationship" class collection or array.

In this example, let's take "Customer":

```<code>class AccountClass
{
     int   accNo;
     decimal amount;
     .
     .
} // class AccountClass

class AccountCustomerClass
{
     int   accustNo;
     DateTime RegistrationDate;
     .
     .
     AccountClass Account;
} // class AccountClass

class CustomerClass
{
     int   CustNo;
     String name;
     Date   dob;
     .
     .
     AccountCustomerClass Accounts[];
} // class CustomerClass
</code>```

Note, that using "AccountCustomerClass Accounts[]", in "AccountClass", instead of "CustomerClass" is not "bad", is just an alternative way.

Title: OOP Principles in Customer and Account classes of a Bank

Body:
I am designing a Bank Application which deals with Customers having FD Accounts.

There are two approaches to this :

Approach 1

In this the customer has a list of accounts. The bank application will manage the accounts through the customers.

My mentor feels this is the correct approach. :-P

```<code>class Customer
{
     String name;
     Date   dob;
     .
     .

     Account[] accounts = new Account[5];
}

class Account
{
     int   accNo;
     float amount;
     .
     .
}
</code>```

Approach 2

In this approach each account has its associated customer reference stored. The Bank application will now manage the accounts and customers independently.

I feel this is the correct approach. :-)

```<code>class Customer
{
     String name;
     Date   dob;
     .
     .
}

class Account
{
     Customer customer;
     int   accNo;
     float amount;
     .
     .
}
</code>```

Now my issues are :

Ideally the bank application should worry more about the account than the customer. For example, the bank should have methods like
addAccount() : which will add account and create a customer implicitly if it is the first account of the customer and
deleteAccount() : which will delete the account and delete the customer implicitly if it is the last account.

There can be a use case in the future where an account can have multiple customers. So that can be accommodated easily in the second approach than the first.

Considering all this, please can you say which is a better Object Oriented Approach here?

Also how is this actually implemented in a real Bank?

Body:
Object Oriented Modeling, its used to represent the real world in a Software Application.

In other times, a single account, had only, and only one customer, assigned. These days, several customers, can be assigned and removed from an account.

There are many ways to model an application, so there is not really a "100% bad" or "100% good" way.

Your example is a "many-to-many" associations.

And, usually an additional, intermediate class is added.

One way to start, is model each data set, or object, explicitly excluding relations to each other, and add those relations, later.

class CustomerClass
{
     int   CustNo;
     String name;
     Date   dob;
     .
     .
} // class CustomerClass

class AccountClass
{
     int   accNo;
     float amount;
     .
     .
} // class AccountClass

class AccountCustomerClass
{
     int   acccustNo;

  // How to relate both, added later
} // class AccountClass

Later, pick one of the "edge" classes ("Account" or "Customer"), that better suits your needs, and add a "relationship" class collection or array.

In this example, let's take "Customer":

class AccountClass
{
     int   accNo;
     decimal amount;
     .
     .
} // class AccountClass

class AccountCustomerClass
{
     int   accustNo;
     DateTime RegistrationDate;
     .
     .
     AccountClass Account;
} // class AccountClass

class CustomerClass
{
     int   CustNo;
     String name;
     Date   dob;
     .
     .
     AccountCustomerClass Accounts[];
} // class CustomerClass

Note, that using "AccountCustomerClass Accounts[]", in "AccountClass", instead of "CustomerClass" is not "bad", is just an alternative way.


问:
Multithreading with triple buffer, do I have to do the waiting for the condition variable?
I have a triple buffer implementation that is often used in threads in such a way that when new data is expected, there's always a WaitData(n) function called on the buffer (A condition variable's timed_wait(n) function is called) and afterwards a HasNewData() is called on the buffer.
If both return true, the buffer can be read.

When the buffer is successfully written to, the notify_all() of the condition variable notifies all the waiting functions.

Now I'm wondering, why do I have to do the waiting for the condition variable? Can't I just periodically poll the HasNewData() of the triple buffer?

Both seem to have the same purpose to me! Only with the WaitData() function my thread is stalling fo n seconds.

Here is a code example of a reading and a writing thread

```<code>::readThread()
{
  if(buffer.WaitData(3) && buffer.IsData())
  {
   data = buffer.GetRead();
   buffer.Release();
  }
}

::writeThread()
{
  data = buffer.GetWrite();
  data = FillBuffer();
  buffer.Release();
}
</code>```

答:
The whole point of condition variables is that you can suspend a thread until some (for that thread) external event occurs.

The advantage of suspending a thread over letting it run continuously and check if it can continue is that a suspended thread does not needlessly consume CPU time and allows the processor to be used to perform useful tasks.


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答:
I think it is dependent on what you are doing. If I'm writing a proof-of-concept application then I'm basically cowboy-coding my ass off and not looking back. If I'm working on an application that I'm actually going to be working on for a while, then I make sure I code it well enough as well as making it understandable a month from now.

I think that styling your code is a bit iffy. As some above have said, your job is to make a product, not formatted code but I would say at the very least one should stick with a defined style of commenting and coding things. I would hate to see half of the variables camel cased and the other half Hungarian.

But also, it depends on what you mean by 'clean-code'.

Title: Do you actually write 'clean code'?


问:
Is using object of main class better than using static main method?
I have noticed in java programs at least, that people tend to prefer to start their programs by creating and instance of the class that contains the main method, and activating a non-static method within it, like so

```<code>    class MainClass {
        void start() {
            //start the program flow
        }
        public static void main(String[] args) {
            new MainClass().start();
        }
    }
</code>```

Than to simply start the program flow through the main method from a static context, like so

```<code>    class MainClass {
        public static void main(String[] args) {
            //start the program flow
        }
    }
</code>```

I was wondering, why do people prefer the former method as the latter seems simpler, and is there something that should determine which one I should use?

答:
Both approaches, can be considered fine.

There are several causes for your question.

The "I come from another Programming Language" approach

Remember that some developers learnt other Object Oriented Programming Languages before learning Java, and keep some programming styles, while programming Java.

C++ Is good example. A C++ programmer that uses classes and objects, has to use a main function, where an independent object must be instantiated first.

Other Java only programmers, may use the ´static´ methods approach, that was designed by the original Java designers, and that appear in several books, and tutorials. To those programmers, allocating an independent object may be seen unnecessary.

The "Let's use some modularity" aproach

The "independent object" approach is also used as a modularity technique, as a way to keep programming logic more simple.


答:
Your first example seems to describe someone who perceives public static void main(String[] args) as merely an entry-point, a "punch-in" point for the operating system to call, and nothing more than that.  It's a perfectly valid point of view.

In my latter years as a Winforms developer, I began using form events as a "patch panel" instead of places to put logic. Rather than littering the Form class with business logic, I would declare a method such as "Submit.OnClick," and immediately defer the execution of that method to another method in another class.  This promotes decoupling and modularity; I can focus solely on form logic in my form class, and non-form logic in the methods I'm calling elsewhere.

In this particular example you provided, I'm not sure that it's buying you all that much.

Title: Is using object of main class better than using static main method?

Body:
I have noticed in java programs at least, that people tend to prefer to start their programs by creating and instance of the class that contains the main method, and activating a non-static method within it, like so

```<code>    class MainClass {
        void start() {
            //start the program flow
        }
        public static void main(String[] args) {
            new MainClass().start();
        }
    }
</code>```

Than to simply start the program flow through the main method from a static context, like so

```<code>    class MainClass {
        public static void main(String[] args) {
            //start the program flow
        }
    }
</code>```

I was wondering, why do people prefer the former method as the latter seems simpler, and is there something that should determine which one I should use?


问:
How to load environment configuration
In Java the typical way of storing configuration is by using property files. So I have several such files, one for each environment type (dev, test, prod, ...).

This configuration is needed in different parts of the code base, i.e. in different classes, but in order to avoid duplicating code for opening the right file into a Properties object and then asking for a specific property, I've decided to have a ConfigurationLoader class which loads the file and holds the Properties object in a static variable.

```<code>public class ConfigurationLoader {
    static Properties configuration = new Properties().load(new FileReader("/path/to/my/file"));
    public static String getProperty(String propertyName) {
        return configuration.getProperty(propertyName);
    }
}
</code>```

(This code is broken by an uncaught exception, but the idea is to load the configuration in a static block)

In this way all the configuration is loaded as soon as this class is loaded and it is available to any class by simply using ConfigurationLoader.getProperty(...). Of course it seems best not to load the same property in multiple places and to maybe create different "configuration domain" classes that do the parsing once and for all.

I then have two questions:

Is this a good design? In particular, do you see any major drawback in making configuration available globally?

What is the best way to specify which environment configuration to load (-D flag, environment variable, ...), i.e. which "/path/to/my/file" to use?

答:
I am assuming you are trying this outside of an application container, in a core java application. Or else, property files are not the right way to do it: deployment descriptors, configuration store, etc., is the right answer.

For configuration, the most common idea is to commons config, which allows you to store your configuration as XML/text. It has quite a few features: allows XPath like access of configuration, allows accessing multi-valued configuration element as a list, etc.,.

The least favored of all is the one you have specified. Even that seems to be broken, as it is from a specific relative/absolute path. Ideally, the file should be on classpath, and should be read from SystemClassLoader as InputStream into the Properties.

Hope this helps.

Title: How to load environment configuration


问:
Alternatives to the repository pattern for encapsulating ORM logic?
I've just had to switch out an ORM and it was a relatively daunting task, because the query logic was leaking everywhere. If i'd ever had to develop a new application, my personal preference would be to encapsulate all query logic (using an ORM) to futureproof it for change. Repository pattern is quite troublesome to code and maintain so i was wondering if there are any other patterns to solve the problem ?

I can foresee posts about not adding extra complexity before it's actually needed, being agile etc. but i'm only interested about the existing patterns solving a similar problem in a simpler way.

My first thought was to have a generic type repository, to which i add methods as needed to specific type repository classes via extension methods, but unit testing static methods is awfully painful. IE:

```<code>public static class PersonExtensions
{
    public static IEnumerable<Person> GetRetiredPeople(this IRepository<Person> personRep)
    {
        // logic
    }
}
</code>```

答:
I wrote a pretty neat query object pattern for NHibernate here: https://github.com/shaynevanasperen/NHibernate.Sessions.Operations

It works by using an interface like this:

```<code>public interface IDatabases
{
    ISessionManager SessionManager { get; }

    T Query<T>(IDatabaseQuery<T> query);
    T Query<T>(ICachedDatabaseQuery<T> query);

    void Command(IDatabaseCommand command);
    T Command<T>(IDatabaseCommand<T> command);
}
</code>```

Given a POCO entity class like this:

```<code>class Database1Poco
{
    public int Property1 { get; set; }
    public string Property2 { get; set; }
}
</code>```

You can build query objects like this:

```<code>class Database1PocoByProperty1 : DatabaseQuery<Database1Poco>
{
    public override Database1Poco Execute(ISessionManager sessionManager)
    {
        return sessionManager.Session.Query<Database1Poco>().SingleOrDefault(x => x.Property1 == Property1);
    }

    public int Property1 { get; set; }
}
</code>```

And then use them like this:

```<code>var database1Poco = _databases.Query(new Database1PocoByProperty1 { Property1 = 1 });
</code>```

Body:
I wrote a pretty neat query object pattern for NHibernate here: https://github.com/shaynevanasperen/NHibernate.Sessions.Operations

It works by using an interface like this:

public interface IDatabases
{
    ISessionManager SessionManager { get; }

    T Query<T>(IDatabaseQuery<T> query);
    T Query<T>(ICachedDatabaseQuery<T> query);

    void Command(IDatabaseCommand command);
    T Command<T>(IDatabaseCommand<T> command);
}

Given a POCO entity class like this:

class Database1Poco
{
    public int Property1 { get; set; }
    public string Property2 { get; set; }
}

You can build query objects like this:

class Database1PocoByProperty1 : DatabaseQuery<Database1Poco>
{
    public override Database1Poco Execute(ISessionManager sessionManager)
    {
        return sessionManager.Session.Query<Database1Poco>().SingleOrDefault(x => x.Property1 == Property1);
    }

    public int Property1 { get; set; }
}

And then use them like this:

var database1Poco = _databases.Query(new Database1PocoByProperty1 { Property1 = 1 });


问:
Proper Query Object Pattern - NHibernate
I was looking to an alternative to Repository Pattern and I've read about "Query object pattern" (http://lostechies.com/jimmybogard/2012/10/08/favor-query-objects-over-repositories/). However the implementation provided in the link above is not exactly what I was looking for - I look for something that can be easily injected, easily tested and easily extended/changed (only last point holds in the link-implementation). I thought a bit and I think "I have invented" solution. Suppose I have controller BlogEntriesController (i'm talking about mvc asp application with ORM) and I inject to constructor class:

```<code>public class BlogEntriesQueries
{
    IRetrieveQuery<BlogEntryEntity> PageBlogEntries { get; set; }
    IRetrieveQuery<BlogEntryEntity> ProposedBlogEntries { get; set; }
    IAddQuery<BlogEntryEntity> CreateNewBlogEntry { get; set; }
    ... etc..
}
</code>```

where IRetrieveQuery<T> is smth like:

```<code>public interface IRetrieveQuery<TEntity> where TEntity : EntityBase
     IQueryable<TEntity> CurrentQuery { get; }
     IRetrieveQuery<TEntity> InvokeQuery(IRetrieveQuery<TEntity> subQuery);
     IEnumerable<TEntity> GetQueryResults();
}
</code>```

Then all the work I'd have to do is proper configuration of IoC container to inject queries into controller and proper calls in controller like: _blogQueries.ProposedBlogEntries.GetQueryResults() The question is - it is good solution - are there any drawbacks that I don't see? I think i'd get testability (don't even have to mock ISession in case of NHibernate) and it'd be easily extensible but I'm not an expert (especially at database applications) by any means.

答:
I think you might like the query object pattern I wrote for NHibernate:https://github.com/shaynevanasperen/NHibernate.Sessions.Operations

It makes it easy to build and consume your own query objects, with support for "3rd level" caching and query-result transformation. It provides an IDatabases interface, which you use to invoke queries and commands. If you derive your query and command objects from the provided base classes, you can then mock calls to the IDatabases interface in your unit tests.

It works by using an interface like this:

```<code>public interface IDatabases
{
    ISessionManager SessionManager { get; }

    T Query<T>(IDatabaseQuery<T> query);
    T Query<T>(ICachedDatabaseQuery<T> query);

    void Command(IDatabaseCommand command);
    T Command<T>(IDatabaseCommand<T> command);
}
</code>```

Given a POCO entity class like this:

```<code>class Database1Poco
{
    public int Property1 { get; set; }
    public string Property2 { get; set; }
}
</code>```

You can build query objects like this:

```<code>class Database1PocoByProperty1 : DatabaseQuery<Database1Poco>
{
    public override Database1Poco Execute(ISessionManager sessionManager)
    {
        return sessionManager.Session.Query<Database1Poco>().SingleOrDefault(x => x.Property1 == Property1);
    }

    public int Property1 { get; set; }
}
</code>```

And then use them like this:

```<code>var database1Poco = _databases.Query(new Database1PocoByProperty1 { Property1 = 1 });
</code>```

Body:
I think you might like the query object pattern I wrote for NHibernate:https://github.com/shaynevanasperen/NHibernate.Sessions.Operations

It makes it easy to build and consume your own query objects, with support for "3rd level" caching and query-result transformation. It provides an IDatabases interface, which you use to invoke queries and commands. If you derive your query and command objects from the provided base classes, you can then mock calls to the IDatabases interface in your unit tests.

It works by using an interface like this:

public interface IDatabases
{
    ISessionManager SessionManager { get; }

    T Query<T>(IDatabaseQuery<T> query);
    T Query<T>(ICachedDatabaseQuery<T> query);

    void Command(IDatabaseCommand command);
    T Command<T>(IDatabaseCommand<T> command);
}

Given a POCO entity class like this:

class Database1Poco
{
    public int Property1 { get; set; }
    public string Property2 { get; set; }
}

You can build query objects like this:

class Database1PocoByProperty1 : DatabaseQuery<Database1Poco>
{
    public override Database1Poco Execute(ISessionManager sessionManager)
    {
        return sessionManager.Session.Query<Database1Poco>().SingleOrDefault(x => x.Property1 == Property1);
    }

    public int Property1 { get; set; }
}

And then use them like this:

var database1Poco = _databases.Query(new Database1PocoByProperty1 { Property1 = 1 });


问:
Makefile for library project to be able to compile the unit tests and the demo program using make
I am new to makefiles and I am developing a (non-executable) library in C++.

Additionally to the library I have (executable) unit tests and an (executable) demo program.
I would now like to be able to compile the unit tests and the demo program using make.

What is conceptually the correct way of doing this?

Does the library have a makefile which just generates a library (.a) file which is then linked to the demo-program and the unit tests in their corresponding makefiles, i.e., do I have 3 makefiles? Would it still be possible to create the executable in only one step?

Do only the demo-program and the unit tests have a makefile each?

答:
You have not specified a development environment (IDE) and mentioned in the comments that you want this to be a more conceptual problem, so here is a way to organize this that is not specific to any IDE. I have actually done this before when developing static libraries.

First, you create your library project with its own makefile and ensure it compiles correctly. You will need a .a file as its output.

Next, your unit tests and demo program are all sister projects to the static library. The structure looks like this:

```<code>root
|
+-- library
|   |
|   +-- include
|   |
|   +-- bin
|
+-- demo program
|
+-- unit tests
</code>```

Your other projects add "../library/include" to the include path. All modern compilers allow you to do this on the command line. In a similar way, you add "../library/bin" to the linker path. That way the linker can find the .a file.

Each project has its own makefile and its own IDE project files. They are separate, but used together. In an IDE you would set project dependencies so the library is built first.

Next, you can add a "master" makefile at the root level that simply goes into each subdirectory and builds each project using the makefile found therein. If you set up the makefile correctly it will also be sure to build in the correct order, all in one (user) step. Since this is the Internet, someone else has already said how to do this better than I can:

How to call other makefiles with dependencies

How to call Makefile from another Makefile?

Note: this same design works when using other build environments such as Ant and Maven, and other compiled languages as well. I have used this structure for a variety of combinations of languages and build tools.

Body:
You have not specified a development environment (IDE) and mentioned in the comments that you want this to be a more conceptual problem, so here is a way to organize this that is not specific to any IDE. I have actually done this before when developing static libraries.

First, you create your library project with its own makefile and ensure it compiles correctly. You will need a .a file as its output.

Next, your unit tests and demo program are all sister projects to the static library. The structure looks like this:

root
|
+-- library
|   |
|   +-- include
|   |
|   +-- bin
|
+-- demo program
|
+-- unit tests

Your other projects add "../library/include" to the include path. All modern compilers allow you to do this on the command line. In a similar way, you add "../library/bin" to the linker path. That way the linker can find the .a file.

Each project has its own makefile and its own IDE project files. They are separate, but used together. In an IDE you would set project dependencies so the library is built first.

Next, you can add a "master" makefile at the root level that simply goes into each subdirectory and builds each project using the makefile found therein. If you set up the makefile correctly it will also be sure to build in the correct order, all in one (user) step. Since this is the Internet, someone else has already said how to do this better than I can:

How to call other makefiles with dependencies

How to call Makefile from another Makefile?

Note: this same design works when using other build environments such as Ant and Maven, and other compiled languages as well. I have used this structure for a variety of combinations of languages and build tools.


问:
Program like NASA?: Margaret Hamilton's Three Primitive Control Structures
On slide 19 in a presentation Margaret Hamilton describes three primitive control structures. My goal is to reduce the probability of errors in my code by working with this "design framework". I am wondering if someone could explain to me how these structures work. Perhaps someone could point me to a simple implemented example in code.</p>

答:
These three "primitive control structures" are ways to describe the ways in which a manager (superior) and two (or more) worker (subordinate) procedures coordinate their work.

The Join primitive shows that the manager calls A with some arguments, A returns some values, and then the manager calls B with A's results.  A's output parameter signature matches B's input parameter signature.

The Include primitive is essentially a scatter/gather technique.  The manager partitions the work between A and B, and gathers up the results.  The subordinates have different parameter signatures and do different things.

The Or primitive is a decision-making process in which one of the subordinates is chosen based on a partition function to select the child.  The subordinates have identical parameter signatures.

She is using these primitive design patterns to impose a very strict layered architecture on the software.

It helps to remember that the Apollo development program started, ran, and essentially ended BEFORE Dijkstra wrote "The Structure of the T.H.E Multiprogramming System", which laid out the fundamental concept of layered designs, and incidentally introduced semaphores for mutual exclusion.  Recall that Apollo 7, the first manned Apollo flight, was in 1968, and Apollo 17, the last Apollo flight to the moon, was in December 1972.


答:
In 2010 are we still referring to printed documentation?  Why? ;)

In all seriousness, documentation (either "F1" application help, PDF, or online documentation) should be part of every single release.  Zero excuses.  It's that simple to "publish."  As a matter of fact, IMO, there is no excuse for not updating the documentation on a regular basis (online and PDF), even in between releases, as soon as issues are known and corrected.  It doesn't need the same level of QA -- not even close.

Title: Manuals - How Up To Date?

Body: If you have a product that has been in the market for a long time, but it is still in active development daily - how often should the manuals be updated? If your users are constantly updated to the bleeding edge version due to the fact that your organization sees fit that the latest bug fixes are always in the shipped version. Meaning, you could fix a bug one day and next day it is hitting production.</p>


问:
How to deal with dual servers and temporary files
Our application is hosted on a dual-server environment - when one server is overloaded with work, a secondary server will take its place in processing certain actions.  For most purposes, this isn't a huge problem.

However, our application generates documents and writes them to a database - and to do this, currently uses a temporary storage folder on the server side to write the document, send it to the server, and then display it to the user.  When the server decides it needs to shift processing over to the secondary server, this can cause a failure to write the document to the database.

How can we avoid this dual-server issue, without changing the structure of the server itself?  What can we change in the application that could allow us to retrieve the appropriate document every time?

I am not aware of any way for us to direclty reference which of the two servers to access, so that is not an option for us.

答: Either put the document in a central location (database or shared file system), using unique file names or identifiers for each document created, or recreate the document on each server, whenever it is found to be missing.</p>


问:
How can I manage trash users?
I created a system which hopefully will have many users. We are afraid our user database will be filled by "trash users" which take high-demand usernames, or maybe they just register and never come back.

I know this is common, I do this myself, as I have 3 google accounts, but I only use 1. How can a large website manage trash users or never coming back users like this?

答:
When an account is inactive for a long time send them an email notifying them that their account will be deactivated in a few month. On deactivation clear the user name and send a reset link by email.

The next time the user wants to log in make him choose a new name. He needs to use the reset link to choose a new name.

That way all users can keep their data but idle names are made available eventually.

Title: How can I manage trash users?


问:
What is the use of MSB and LSB?
I have a hard time understanding the use of MSB (Most significant bit) vs. LSB (Least significant bit) and why they're used at all. It is my understanding that it has to do with Endianness, but I cannot get my head around it.

Basically: If I read a specification on X and they specify that the data needs to be read LSB or MSB - ok I can do that - but why am I doing it.

Why don't we just send all data MSB?

答:
When a byte is serialized into a stream of bits and transmitted serially, it becomes important to know whether it's transmitted LSbit-first or MSbit-first.  The transmitter can send the bits in either order, and the contract whether it's LSbit-first or MSbit-first is established in the spec (or datasheet).  For example, the receiver receives this:

```<code>time: 01234567
bit:  01000000
</code>```

If the transmitter was sending LSbit-first, then the value is 0x02.  If the transmitter was sending MSbit-first, then the value is 0x40.  The receive has to know which one it is.

Title: What is the use of MSB and LSB?

Body:
When a byte is serialized into a stream of bits and transmitted serially, it becomes important to know whether it's transmitted LSbit-first or MSbit-first.  The transmitter can send the bits in either order, and the contract whether it's LSbit-first or MSbit-first is established in the spec (or datasheet).  For example, the receiver receives this:

time: 01234567
bit:  01000000

If the transmitter was sending LSbit-first, then the value is 0x02.  If the transmitter was sending MSbit-first, then the value is 0x40.  The receive has to know which one it is.


问:
C# async/await: Pedantry vs. the Debugger
I'm playing around with async and await, and they seem pretty intuitive, but some of the things I'm reading about these keywords doesn't make sense to me. In fact, some of it seems to me to be flat-out wrong, or at least misleading, even though it's coming straight from Microsoft. Consider the code below:

namespace AsyncExample2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            var t=new Task<int>(longRunningWork);
            t.Start();
            int r= await t;
            textBox1.Text += (r.ToString());
        }

        int longRunningWork()
        {
            Thread.Sleep(15000);
            return (new Random()).Next(10);
        }
    }
}
```

This is from a WinForms example application I created with a GUI consisting of a single button and a single textbox. When you press the button, 15 seconds later, a random digit is appended to the text in the textbox. During this 15 second period, the GUI remains interactive, e.g. the form can be maximized/minimized/moved. The button can even be clicked again.

The most basic way that this code seems to contradict what Microsoft says about await / async is that, according to them, my call to t.Start() should not be necessary. Consider the very first statement of the article at https://msdn.microsoft.com/en-us/library/hh696703.aspx: "[i]n an async method, tasks are started when they’re created." This does not seem to be the case in this particular async method (button1_Click), though I have seen it happen in other contexts.

Second, I've read a lot of what I would describe as aggressive attempts to differentiate between the old thread-based model of parallelism and async / await, and, like the "All New!" labels often applied to product packaging by corporate marketing departments, these attempts at differentiation seem to contain some unjustified bluster.

Consider the statement that "the async and await keywords don't cause additional threads to be created" (from https://msdn.microsoft.com/en-us/library/hh191443.aspx). This is not my observation; if I inspect Thread.CurrentThread.ManagedThreadId, I can see that longRunningWork() is not running on the GUI thread, though button1_Click certainly is. Furthermore, if I click the button rapidly in succession, and inspect Thread.CurrentThread.ManagedThreadId at the call to Thread.Sleep(), I see various, different managed thread IDs. And if I try to add anything to longRunningWork() that affects the GUI (say, sets textBox1.Text), I get the typical "illegal cross-thread call" error.

Can someone help me reconcile these seeming inconsistencies? My hunch is that the first inconsistency I highlight is a relatively minor example of sloppiness (though I'd really like to know when I need to call Start() manually).

The second inconsistency, I suspect, is just pedantry. People who know a little bit about async / await like to correct noobs who can't talk about these keywords without thinking in terms of threads. I get it; it's a different model of parallelism with a wholly different way of thinking. At the same time, though, it's a definite oversell to say that "the async and await keywords don't cause additional threads to be created." The debugger implies otherwise.

I suppose that technically it's possible that the threads I'm seeing are being grabbed from some sort of pool that exists throughout the program's execution. If that's the case, then, technically, nothing is getting created by async / await. This seems pretty trivial to me, and I'm not aware that WinForms programs have an ASP.NET-style thread pool.

答:
You could rewrite your code this way in a pure async/await paradigm.

    private async void button1_Click(object sender, EventArgs e)
    {
        int r = await longRunningWork();
        textBox1.Text += (r.ToString());
    }

    private async Task<int> longRunningWork()
    {
        await Task.Delay(15000);
        return (new Random()).Next(10);
    }
```

The fact a thread is created is up to the CLR to decide. What the await does in the button1_Click method is that it returns the control to the calling thread of button1_Click (UI thread) which can do other work. The compiler introduces automatic code everytime it sees await to add some goto at the end of the awaitable method whenever it is completed to continue the execution where it left.

My guess here why I think your code spawn a new thread is because you call Thread.Sleep(15000); which is a synchronous call, hence if the CLR wants to give control back to the UI thread, it knows it has to spawn a new thread.

Even your original longRunningWork method is synchronous so it definitely needs a new thread.

Body:
You could rewrite your code this way in a pure async/await paradigm.

    private async void button1_Click(object sender, EventArgs e)
    {
        int r = await longRunningWork();
        textBox1.Text += (r.ToString());
    }

    private async Task<int> longRunningWork()
    {
        await Task.Delay(15000);
        return (new Random()).Next(10);
    }

The fact a thread is created is up to the CLR to decide. What the await does in the button1_Click method is that it returns the control to the calling thread of button1_Click (UI thread) which can do other work. The compiler introduces automatic code everytime it sees await to add some goto at the end of the awaitable method whenever it is completed to continue the execution where it left.

My guess here why I think your code spawn a new thread is because you call Thread.Sleep(15000); which is a synchronous call, hence if the CLR wants to give control back to the UI thread, it knows it has to spawn a new thread.

Even your original longRunningWork method is synchronous so it definitely needs a new thread.


答:
Endianness for binary (base 2) is no different than endianness for any other base.

Without a specification telling you which side the most significant and least significant decimals were, you wouldn't know whether

```<code>1234
</code>```

is one-thousand-two-hundred-and-thirty-four or four-thousand-three-hundred-and-twenty-one.

Note for additional curiosity that "twenty-one" is MSD whereas "nineteen" is LSD, so it's certainly not that universally obvious even within the same community which one is the right one.

For dates, there are three different conventions (using Alan Turing's birthday as example):

least significant component first (e.g. in Germany): 23.06.12

most significant component first (e.g. ISO): 12-06-23

complete and utter confusion (US): 06/23/12

Again, you have to pick some order, and you have to communicate which order you picked, and there is no obviously "right" order. (I would argue though, that the US date format is obviously wrong :-D .)

Title: What is the use of MSB and LSB?

Body:
I have a hard time understanding the use of MSB (Most significant bit) vs. LSB (Least significant bit) and why they're used at all. It is my understanding that it has to do with Endianness, but I cannot get my head around it.

Basically: If I read a specification on X and they specify that the data needs to be read LSB or MSB - ok I can do that - but why am I doing it.

Why don't we just send all data MSB?

Body:
Endianness for binary (base 2) is no different than endianness for any other base.

Without a specification telling you which side the most significant and least significant decimals were, you wouldn't know whether

1234

is one-thousand-two-hundred-and-thirty-four or four-thousand-three-hundred-and-twenty-one.

Note for additional curiosity that "twenty-one" is MSD whereas "nineteen" is LSD, so it's certainly not that universally obvious even within the same community which one is the right one.

For dates, there are three different conventions (using Alan Turing's birthday as example):

least significant component first (e.g. in Germany): 23.06.12

most significant component first (e.g. ISO): 12-06-23

complete and utter confusion (US): 06/23/12

Again, you have to pick some order, and you have to communicate which order you picked, and there is no obviously "right" order. (I would argue though, that the US date format is obviously wrong :-D .)


答:
Bit order and byte order are two separate things, but they may affect your preferences.  Say you have a little-endian machine, and you want to transmit a 32-bit number.  Also transmitting the bits LSB-first means overall bit order for the entire int (with lsb numbered 0) is:

```<code>0 1 2 3 4 5 6 7 8 9 10 11 12 ... 31
</code>```

If you transmitted MSB-first, the overall bit order for the entire int would be:

```<code>7 6 5 4 3 2 1 0 15 14 13 11 ... 24
</code>```

Looking at this signal on an oscilloscope just got more difficult, and designing shift registers in hardware just got a little more tricky.

The reverse occurs for big-endian machines.  So endianness doesn't dictate bit order, but it sure does make one bit order easier to work with.

As far as preferring one endianness over another, it's more than picking one at random.  Big endian is easier to understand conceptually, but little endian means you don't have to offset the address in order to treat a byte as a word.

Title: What is the use of MSB and LSB?

Body:
Bit order and byte order are two separate things, but they may affect your preferences.  Say you have a little-endian machine, and you want to transmit a 32-bit number.  Also transmitting the bits LSB-first means overall bit order for the entire int (with lsb numbered 0) is:

0 1 2 3 4 5 6 7 8 9 10 11 12 ... 31

If you transmitted MSB-first, the overall bit order for the entire int would be:

7 6 5 4 3 2 1 0 15 14 13 11 ... 24

Looking at this signal on an oscilloscope just got more difficult, and designing shift registers in hardware just got a little more tricky.

The reverse occurs for big-endian machines.  So endianness doesn't dictate bit order, but it sure does make one bit order easier to work with.

As far as preferring one endianness over another, it's more than picking one at random.  Big endian is easier to understand conceptually, but little endian means you don't have to offset the address in order to treat a byte as a word.


答:
MSB and LSB can be thought of in terms of numeric properties of bit sequences.  For example, during addition, the carries flow from the addition of two LSB's toward the next higher bit.  The LSB itself receives no carry because it starts the addition; whereas all the other bits get a carry from the next least significant bit position.  Overflow is when a carry (of value 1) happens from the MSB, because there are no more bits (in the byte or word size) left to carry over to.  The MSB is also considered the sign bit for signed data types: if the MSB is 1 the value is negative, if 0 the value is positive (or zero).

Endianess is a matter of the storage (or transmission) order for bits within a byte and also more significantly (as it turns out) for the order of bytes within a word or long word.  These differences can be seen when data is moved from one system to another.  Fortunately bit order within a byte is standardized on hard drives and networks, so we don't have to worry about bit endianess.  However, byte order within a word is different for some processors than others, and bytes become swapped when changing architectures; as this causes problems it requires mitigation (e.g. software has to handle it).  Little endian stores least significant bytes first followed by more significant bytes in higher storage or packet address order, whereas big endian is the opposite.

Title: What is the use of MSB and LSB?


问:
Extract name of return variable from Python function
I have a python function x that returns some module
x():
return y

I would like to parse the file x is located in and learn that "x returns this thing called 'y'". I have no idea how.

I'm not trying to get the type of the return type, just what the programmer calls exactly what is being returned.

答:
It seems like you could hack something together with regexes pretty quickly.

Pseudocode:

```<code>import re
from collections import defaultdict
def findReturns(program_string):
    result = defaultdict(list)
    func_name = None
    for line in re.findall('def .+\w|(?<=return ).+', program_string):
       if line.startswith('def '):
           func_name = line[4:]
           continue
       result[func_name].append(line)
    return result
</code>```

Body:
It seems like you could hack something together with regexes pretty quickly.

Pseudocode:

import re
from collections import defaultdict
def findReturns(program_string):
    result = defaultdict(list)
    func_name = None
    for line in re.findall('def .+\w|(?<=return ).+', program_string):
       if line.startswith('def '):
           func_name = line[4:]
           continue
       result[func_name].append(line)
    return result


答:
It depends on what the Main class and what the start() method are supposed to represent.

Remember, public static void main(String[]) ultimately is just a hook for the JVM to start your application with:

```<code>java -cp ... Main [args]
</code>```

It could very well be that Main is an utility class inside a larger framework/library, that has its own main() method so that it can be started independently outside of its conventional usage. Or a main() method was simply supplied for some kind of debugging purposes (hypothetical scenario), which may be removed without notice in future releases. In other words, whatever is done within the main() method does not - and will not - affect the features of the Main class.

Alternatively, maybe you are just looking at too many "introduction to Object-oriented programming" sample classes, where the instantiation of the Main class and calling its start() method is meant to prepare learners on what OOP is about.

So how should you determine what to use? (not a hard-and-fast rule)

If you are creating a simple application with no need for OOP, such that all your methods are actually static and you no longer depend on a class's 'state' (fields), you should stick to the simpler approach as well. Otherwise, or if you are grasping the OOP concepts, then you should do it the more OOP-like way of new Main().start().

Body:
It depends on what the Main class and what the start() method are supposed to represent.

Remember, public static void main(String[]) ultimately is just a hook for the JVM to start your application with:

java -cp ... Main [args]

It could very well be that Main is an utility class inside a larger framework/library, that has its own main() method so that it can be started independently outside of its conventional usage. Or a main() method was simply supplied for some kind of debugging purposes (hypothetical scenario), which may be removed without notice in future releases. In other words, whatever is done within the main() method does not - and will not - affect the features of the Main class.

Alternatively, maybe you are just looking at too many "introduction to Object-oriented programming" sample classes, where the instantiation of the Main class and calling its start() method is meant to prepare learners on what OOP is about.

So how should you determine what to use? (not a hard-and-fast rule)

If you are creating a simple application with no need for OOP, such that all your methods are actually static and you no longer depend on a class's 'state' (fields), you should stick to the simpler approach as well. Otherwise, or if you are grasping the OOP concepts, then you should do it the more OOP-like way of new Main().start().


问:
Is using a lot of free third party libraries a good thing?
For your proprietary projects at work?

Problems I can imagine are: more dlls (can be a problem when for example you have to include a big DLL but you only need few functions in that library), a lot of license statements you have to take care of when releasing your product, the reliability of the library, etc.

Any other potential problems? What is your opinion?
(info: I'm using .NET at work)

答: Use libraries that are stable. What would the alternative be anyway? Rewriting the code from scratch?</p>


问:
How can you write an activation function in a neural network to handle a layer architecture of arbitrary dimensions?
I am making a neural network in Clojure that can take an array of integers,and return a data structure representing the layers of a neural network: so (make-layers [1 4 5]) would evaluate to:

```<code>[[0]          <-- input
 [0 0 0 0]    <-- hidden
 [0 0 0 0 0]] <-- output
</code>```

When I run my activation function on the weights of the network, however, I get a core.matrix error saying that it can't do the matrix multiplication on an input of a one-dimensional vector with the transpose of the weights:

```<code>(core.matrix.operators/* inputs (transpose weights))
 user=> Incompatible shapes, cannot broadcast [1] to [4 2]
</code>```

I understand why this is not working from the perspective of matrix multiplication, but I am not sure how to rewrite the function to deal with layers of arbitrary length.

Here is a gist that shows what I am working on: https://gist.github.com/gamma235/b8db845a512c60d123af

答:
It sounds like you are using * (elementwise multiplication) when you really want to be using mmul (matrix multiplication).

If you are computing a length 4 hidden layer from a length 1 input vector, then your weight matrix should be a 4x1 matrix, e.g.:

```<code>(def weights [[1.0] [2.0] [3.0] [4.0]]) ;; a 4x1 weight matrix
(def input [1.5])
(mmul weights input)
=> [1.5 3.0 4.5 6.0]
</code>```

Hope that helps!

Body:
It sounds like you are using * (elementwise multiplication) when you really want to be using mmul (matrix multiplication).

If you are computing a length 4 hidden layer from a length 1 input vector, then your weight matrix should be a 4x1 matrix, e.g.:

(def weights [[1.0] [2.0] [3.0] [4.0]]) ;; a 4x1 weight matrix
(def input [1.5])
(mmul weights input)
=> [1.5 3.0 4.5 6.0]

Hope that helps!


答:
Use the ast module

```<code>import ast

def extract_return(file, fname):
    for x in ast.walk(ast.parse(open(file).read())):
        if not(isinstance(x, ast.FunctionDef)):
            continue
        if not(x.name == fname):
            continue
        for b in x.body:
            if isinstance(b, ast.Return):
                if isinstance(b.value, ast.Name):
                    yield b.value.id
</code>```

This defines a function which takes some python source's filename and a function name fname (your "x") and yields each identifier returned by function fname. Here, I assume that you are only interested in return statements that occur at the first level of function x and consequently, I don't visit subexpressions. Also, I'am using yield because in more general cases this could work like a filter which could be composed with other ones. In more complex cases, it can be preferable to subclass ast.NodeVisitor.

This is equivalent in size with the regex approach but far more reliable.

Title: Extract name of return variable from Python function

Body:
I have a python function x that returns some module
x():
return y

I would like to parse the file x is located in and learn that "x returns this thing called 'y'". I have no idea how.

I'm not trying to get the type of the return type, just what the programmer calls exactly what is being returned.

Body:
Use the ast module

import ast

def extract_return(file, fname):
    for x in ast.walk(ast.parse(open(file).read())):
        if not(isinstance(x, ast.FunctionDef)):
            continue
        if not(x.name == fname):
            continue
        for b in x.body:
            if isinstance(b, ast.Return):
                if isinstance(b.value, ast.Name):
                    yield b.value.id

This defines a function which takes some python source's filename and a function name fname (your "x") and yields each identifier returned by function fname. Here, I assume that you are only interested in return statements that occur at the first level of function x and consequently, I don't visit subexpressions. Also, I'am using yield because in more general cases this could work like a filter which could be composed with other ones. In more complex cases, it can be preferable to subclass ast.NodeVisitor.

This is equivalent in size with the regex approach but far more reliable.


问:
How to really master MySQL?
I have been using mysql for the same amount of time I have been using PHP. However I feel about 10x more confident in PHP; or any other programming language. But I just can't seem to really really grasp SQL. I mean, I can select, update, insert, delete, join, etc. but when it comes to more complex stuff I am lost. How to write a more complicated select statement, how to use indexes properly, which engine to use, etc.

For some reason I really find the mysql docs hard to follow, but the php ones easy to follow.

I am starting to think that maybe my brain is just wired in a way that makes programming make since but sql confusing. I don't know. Most people think Regex is so confusing but to me it makes more scientific sense than how to construct an sql statement. Please don't get me wrong, I am not hating on SQL, I really like it, I just want to understand it better.

Whats the best/fastest way to really master MySQL?

When I say "master" I don't mean the guru among gurus, I mean smart enough to figure out most of the questions I ask on SO myself without needing help.

答:
Use it

Internalizing how relational databases work is difficult for a lot of people - but it's very valuable.  As you work with SQL more, it will work its way into your brain.  Keep pushing yourself.

When something seems odd, investigate

In Chrome, I set up this search engine so all I have to do is type "m [search query]" to search the docs (dev.mysql.com's search sucks): {google:baseURL}search?{google:RLZ}{google:acceptedSuggestion}{google:originalQueryForSuggestion}sourceid=chrome&ie={inputEncoding}&q=site:dev.mysql.com/doc/refman/5.1/en+%s

If the docs don't have an answer, pop into #mysql on freenode and see if someone can provide some insight.

Read!

Once you understand how relational databases do their thing, you'll want to know a bit more about what MySQL is doing with those magical queries you're writing.  I would highly recommend High Performance MySQL - it's very worth your time.

Title: How to really master MySQL?