问:
Creating a Predicate Builder extension method
I have a Kendo UI Grid that I am currently allowing filtering on multiple columns. I am wondering if there is a an alternative approach removing the outer switch statement?

Basically I want to able to create an extension method so I can filter on a IQueryable<T>  and I want to drop the outer case statement so I don't have to switch column names.

```<code>    private static IQueryable<Contact> FilterContactList(FilterDescriptor filter, IQueryable<Contact> contactList)
    {
        switch (filter.Member)
        {
            case "Name":
                switch (filter.Operator)
                {
                    case FilterOperator.StartsWith:
                        contactList = contactList.Where(w => w.Firstname.StartsWith(filter.Value.ToString()) || w.Lastname.StartsWith(filter.Value.ToString()) || (w.Firstname + " " + w.Lastname).StartsWith(filter.Value.ToString()));
                        break;
                    case FilterOperator.Contains:
                        contactList = contactList.Where(w => w.Firstname.Contains(filter.Value.ToString()) || w.Lastname.Contains(filter.Value.ToString()) || (w.Firstname + " " + w.Lastname).Contains( filter.Value.ToString()));
                        break;
                    case FilterOperator.IsEqualTo:
                        contactList = contactList.Where(w => w.Firstname == filter.Value.ToString() || w.Lastname == filter.Value.ToString() || (w.Firstname + " " + w.Lastname) == filter.Value.ToString());
                        break;
                }
                break;
            case "Company":
                switch (filter.Operator)
                {
                    case FilterOperator.StartsWith:
                        contactList = contactList.Where(w => w.Company.StartsWith(filter.Value.ToString()));
                        break;
                    case FilterOperator.Contains:
                        contactList = contactList.Where(w => w.Company.Contains(filter.Value.ToString()));
                        break;
                    case FilterOperator.IsEqualTo:
                        contactList = contactList.Where(w => w.Company == filter.Value.ToString());
                        break;
                }

                break;
        }
        return contactList;
    }
</code>```

Some additional information, I am using NHibernate Linq. Also another problem is that the
"Name" column on my grid is actually "Firstname" + " " + "LastName" on my contact entity. We can also assume that all filterable columns will be strings.

EDIT Remember this needs to work with NHibernate Linq and AST.

答:
I think a simple way to do this would be to create a map of property names to Func's:

e.g.

private static Dictionary<string, Func<Contact, IEnumerable<string>>> propertyLookup = new Dictionary<string, Func<Contact, IEnumerable<string>>>();

static ClassName()
{
   propertyLookup["Name"] = c => new [] { c.FirstName, c.LastName, c.FirstName + " " c.LastName };
   propertyLookup["Company"] = c => new [] { c.Company };
}
```

<p>And change your code to:</p>

<pre class="lang-cs prettyprint-override"><code> var propertyFunc = propertyLookup(filter.Member);

 case FilterOperator.StartsWith:
          contactList = contactList.Where(c => propertyFunc(c).Any(s => s.StartsWith(filter.Value));
</code>```

You could also eliminate the switch altogether by creating a lookup for the matching function as well:

matchFuncLookup[FilterOperator.StartsWith] = (c, f) => c.StartsWith(f);
matchFuncLookup[FilterOperator.Contains] = (c, f) => c.Contains(f);

var matchFunc = matchFuncLookup[filter.Operator];

contactList = contactList.Where(c => propertyFunc(c).Any(s => matchFunc(s, filter.Value));
```

<p>So, to put it all together:</p>

```public class ClassName
{
    private static readonly Dictionary<string, Func<Contact, IEnumerable<string>>> PropertyLookup
        = new Dictionary<string, Func<Contact, IEnumerable<string>>>();
    private static readonly Dictionary<FilterOperator, Func<string, string, bool>> MatchFuncLookup
        = new Dictionary<FilterOperator, Func<string, string, bool>>();

    static ClassName()
    {
        PropertyLookup["Name"] = c => new[] { c.FirstName, c.LastName, c.FirstName + " " + c.LastName };
        PropertyLookup["Company"] = c => new[] { c.Company };
        MatchFuncLookup[FilterOperator.StartsWith] = (c, f) => c.StartsWith(f);
        MatchFuncLookup[FilterOperator.Contains] = (c, f) => c.Contains(f);
        MatchFuncLookup[FilterOperator.IsEqualTo] = (c, f) => c == f;
    }

    private static IQueryable<Contact> FilterContactList(FilterDescriptor filter, IQueryable<Contact> contactList)
    {
        var propertyLookup = PropertyLookup[filter.Member];
        var matchFunc = MatchFuncLookup[filter.Operator];
        return contactList.Where(c => propertyLookup(c).Any(v => matchFunc(v, filter.Value)));
    }
}
```

NB - Is it not redundant to check c.FirstName if you are also checking (c.FirstName + " " c.LastName) ?

Body:
I think a simple way to do this would be to create a map of property names to Func's:

e.g.

private static Dictionary<string, Func<Contact, IEnumerable<string>>> propertyLookup = new Dictionary<string, Func<Contact, IEnumerable<string>>>();

static ClassName()
{
   propertyLookup["Name"] = c => new [] { c.FirstName, c.LastName, c.FirstName + " " c.LastName };
   propertyLookup["Company"] = c => new [] { c.Company };
}

And change your code to:

 var propertyFunc = propertyLookup(filter.Member);

 case FilterOperator.StartsWith:
          contactList = contactList.Where(c => propertyFunc(c).Any(s => s.StartsWith(filter.Value));

You could also eliminate the switch altogether by creating a lookup for the matching function as well:

matchFuncLookup[FilterOperator.StartsWith] = (c, f) => c.StartsWith(f);
matchFuncLookup[FilterOperator.Contains] = (c, f) => c.Contains(f);

var matchFunc = matchFuncLookup[filter.Operator];

contactList = contactList.Where(c => propertyFunc(c).Any(s => matchFunc(s, filter.Value));

So, to put it all together:

public class ClassName
{
    private static readonly Dictionary<string, Func<Contact, IEnumerable<string>>> PropertyLookup
        = new Dictionary<string, Func<Contact, IEnumerable<string>>>();
    private static readonly Dictionary<FilterOperator, Func<string, string, bool>> MatchFuncLookup
        = new Dictionary<FilterOperator, Func<string, string, bool>>();

    static ClassName()
    {
        PropertyLookup["Name"] = c => new[] { c.FirstName, c.LastName, c.FirstName + " " + c.LastName };
        PropertyLookup["Company"] = c => new[] { c.Company };
        MatchFuncLookup[FilterOperator.StartsWith] = (c, f) => c.StartsWith(f);
        MatchFuncLookup[FilterOperator.Contains] = (c, f) => c.Contains(f);
        MatchFuncLookup[FilterOperator.IsEqualTo] = (c, f) => c == f;
    }

    private static IQueryable<Contact> FilterContactList(FilterDescriptor filter, IQueryable<Contact> contactList)
    {
        var propertyLookup = PropertyLookup[filter.Member];
        var matchFunc = MatchFuncLookup[filter.Operator];
        return contactList.Where(c => propertyLookup(c).Any(v => matchFunc(v, filter.Value)));
    }
}

NB - Is it not redundant to check c.FirstName if you are also checking (c.FirstName + " " c.LastName) ?


问:
Unit test and Code Coverage of Ant build scripts
In our development environment We have more and more build scripts for ant to perform the build tasks for several different build jobs.

These build scripts sometimes become large and do a lot of things and basically is source code in and of itself.

So in a "TDD-world" we should have unit tests and coverage reports for the source code.

I found AntUnit and BuildFileTest.java for doing unit tests. But it would also be interesting to know the code coverage of those unit tests.

I have been searching google, but have not found anything. Does anyone know of a code coverage tool for Ant build scripts?

答:
If you convert your Ant scripts to gant (which has a lot of other advantages), then getting coverage would be trivial.

Gant is a tool for scripting Ant tasks using Groovy instead of XML to specify the logic. A Gant specification is a Groovy script and so can bring all the power of Groovy to bear directly, something not possible with Ant scripts. Whilst it might be seen as a competitor to Ant, Gant uses Ant tasks for many of the actions, so Gant is really an alternative way of doing things using Ant, but using a programming language rather than XML to specify the rules...

ContentLicense: CC BY-SA 3.0


问:
When should I make the first commit to source control?
I'm never sure when a project is far enough along to first commit to source control. I tend to put off committing until the project is 'framework-complete,' and I primarily commit features from then on. (I haven't done any personal projects large enough to have a core framework too big for this.) I have a feeling this isn't best practice, though I'm not sure what could go wrong.

Let's say, for example, I have a project which consists of a single code file. It will take about 10 lines of boilerplate code, and 100 lines to get the project working with extremely basic functionality (1 or 2 features). Should I first check in:

The empty file?

The boilerplate code?

The first features?

At some other point?

Also, what are the reasons to check in at a specific point?

答:
When I start a new project I usually start by committing that before any code has been added. A general rule of thumb I've always followed is: if your PC crashed and wiped all your data what code would you prefer not to have to write from memory. Ten years ago before TDD and better programming practice I was quite optimistic about what I could remember. Now, I tend to be more cautious. As a lot of other posters have said commit early and commit often. You are not losing anything by doing it.

I'm working on my own for most of the time so I must confess I'm getting slack but I generally commit before I go home. That way if I don't make it in tomorrow then my colleagues can pick up where I left off.

I'm currently using Tortoise/SVN at work.


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
Infinite Fibonacci Sequence (Haskell)

```<code>fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Infinite Fibonacci Sequence (Haskell)

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)


问:
When does "proper" programming no longer matter?
I've been building an android game in my spare time. It's using the libgdx library so quite a bit of the heavy lifting is done for me.

While developing, I carelessly selected datatypes for some procedures. I used a hashtable because I wanted something close to an associative array. Human readable key values. In other places to achieve similar things, I use a vector. I know libgdx has vector2 and vector3 classes, but I've never used them.

When I come across weird problems and search Stack Overflow for help, I see a lot of people just reaming the questions that use a certain datatype when another one is technically "proper." Like using an ArrayList because it does not require defined bounds versus re-defining an int[] with new known boundaries. Or even something trivial like this:

```<code>for(int i = 0; i < items.length; i ++)
{
    // do something
}
</code>```

I know it evaluates item.length on every iteration. However, I also know items will never be more than 15 to 20 items. So should I care if I evaluate items.length on every iteration?

I ran some tests to see how the app performs using the method I just described versus the proper, follow the tutorial and use the exact data types suggested by the community. The results: Same thing. Average 45 fps. I opened every app on the phone and galaxy tab. No difference.

So I guess my question to you is this: Is there a threshold when it no longer matters to be proper? Is it ok to say - "so long as it gets the job done, I don't care?"

答:
If you are programming at home for yourself then maybe you can cut a few corners; and when you are experimenting and trying things out this is completely justified.

However take care. In the example you give there's not really any need to cut that corner, and you need to be careful. This could  start a trend and bad habits that you do at home could creep into your code at work. Far better to practice and improve on good habits at home and let them seep into your code at work. It'll help you and it'll help others.

Any programming you do and any thinking you do about programming is exercise. Make it worthwhile, otherwise it'll come back and bite you.

Look on the good side though. You've asked about this so maybe you're already aware of the point I'm making.


问:
Help me understand a part of Java Language Specification
I'm reading part 17.2.1 of Java language specification: http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.2.1

I won't copy a text, it's too long, but I would like to know, why for third step of sequence they're saying that

If thread t was removed from m's wait set in step 2 due to an interrupt

Thread couldn't get to step 2 it wasn't removed from wait set, because it written for the step 1:

Thread t does not execute any further instructions until it has been removed from m's wait set

Thus thread can't be removed from wait set in step 2 whatever it's due to, because it was already removed.

Please help me understand this.

答:
This is a bug caused by mistake in updating from prior version JLS, Third Edition 17.8.1 Wait, missing number of the list item.

Prior version JLS had the respective sequence listed from 1 to 4, not from 1 to 3:

Thread t is added to the wait set...

Thread t does not execute any further instructions until...

Thread t performs n lock actions....

If thread t was removed from m's wait set in step 2...

As you may see, step 2 in original version document refers to the part other than currently marked 2.

Compared to original version, JLS Java SE 7 Edition 17.2.1. Wait has lost list number (likely lost
 in html) at the item Thread t does not execute...

As a result, whole sequence now lists from 1 to 3 and words "step 2" left unchanged from original version refer reader to wrong item that has been previously marked 3, not 2.

Body:
This is a bug caused by mistake in updating from prior version JLS, Third Edition 17.8.1 Wait, missing number of the list item.

Prior version JLS had the respective sequence listed from 1 to 4, not from 1 to 3:

Thread t is added to the wait set...

Thread t does not execute any further instructions until...

Thread t performs n lock actions....

If thread t was removed from m's wait set in step 2...

As you may see, step 2 in original version document refers to the part other than currently marked 2.

Compared to original version, JLS Java SE 7 Edition 17.2.1. Wait has lost list number (likely lost <li class="listitem"> in html) at the item Thread t does not execute...

As a result, whole sequence now lists from 1 to 3 and words "step 2" left unchanged from original version refer reader to wrong item that has been previously marked 3, not 2.


问:
should I extend or create instance of the class
I have two classes  Class A and Class B

In Class A, I have three methods that perform the save, delete and select operation based upon the object I pass them. In Class B I perform the logic operations, such as modification to the property of the object before being passed to the methods of Class A.

My problem is in Class B, should it extend Class A, and call the methods of class A , by parent::methodName or create instance of class A and then call

Class A does not includes any property just methods.

```<code>class A{
  public function save($obj){
         //code here
    }

   public function delete($obj){
         //code here
    }

    public function select($obj){
         //code here
    }
 }
</code>```

//Should I extend class A, and call the method by parent::methodName($obj)
   or create an instance of class A, call the method $instanceOfA->methodName($obj);

```<code> class B extends A{

    public function checkIfHasSaved($obj){
         if($obj->saved == 'Yes'){
                  parent::save($obj);   //**should I call the method like this**
                 $instanceOFA = new A();   //**or create instance of class A and call without extending class A**
                 instanceOFA->save($obj);
            }
             //other logic operations here
      }

 }
</code>```

答:
Without knowing the names and purposes of the real classes it's hard to say.  The decision hinges on whether class B is really a type of class A or whether class B just needs some service class A provides.  For example, a lot of programmers make the mistake of building model classes by extending a database access layer class on the grounds that they need to access the database in order to persist their state. This is almost always a mistake.  A model class needs a database connection but it almost certainly isn't a kind of database connection.

It boils down to whether the link between the classes A and B is an is-a relationship or a has-a relationship.  In the former it makes sense to think of class B as a kind of class A, and if it's impossible for class B to gain or lose the behaviour of class A during its lifetime then an is-a relationship (subclassing) makes sense.  If the behaviour of class A is something that class B only needs under some circumstances, or if it doesn't make sense to think of class B in terms of being a kind of class A then composition (has-a relationship) is the more sensible approach.

Say you're modelling a school and have Person, Student and Teacher classes.  At first glance you might think that Student and Teacher are kinds of Person, and therefore Student and Teacher should extend Person.  But what happens should a particular student get a job at the school as a teacher after they graduate?  Student and Teacher are in fact roles that a Person can take on, they can discard those roles at the right time too.  In some systems the same person could hold more than one role at once (suppose a doctor gets hit by a car when going to work in a hospital, she could end up as a patient at that hospital!)

On the other hand, if you have a Car class, a Ferrari class and a Bugatti class, then it makes sense for Bugatti and Ferrari to be subclassed from Car.  The reason is that Ferraris and Bugattis are both kinds of car, and a Ferrari is always going to be a Ferrari from the moment it leaves the factory to the moment it's scrapped.  There's no circumstance under which a Ferrari is going to become a Bugatti.

So basically, TL:DR, it depends.


问:
Is there a way to develop desktop software using PHP?
I have to develop a real estate marketing CRM software for my client - where the application is installed on desktop but can also be accessed from web.

2 reasons why they want the application to run from desktop :

So that it can work with/without internet connection

They don't want their complete data to be online

They want to access few of the data like property listing & inquiries (managed from desktop application) from their website through secure login & password.

The data that is entered in desktop application should be automatically synchronized with the website application. I was wondering if there is a way to develop this kind of software using PHP & MySQL.  If yes, it will be great if anyone can provide me the referral link.Else please suggest, which language should I use.

答:
When all you have is a hammer...

In theory, yes.  In practice I wouldn't.

There is a PHP-GTK extension that allows you to build GUI applications on top of PHP (though I've never used it).

However, PHP is not intended for building GUI apps and its architecture isn't conducive to such projects.  PHP is built to handle short-lived request/response application models and that's what it does best.

You should pick tools appropriate to the job you're doing rather than trying to force a given tool you're familiar with into a role it's not made for.  The result will never be anywhere near optimal if you do.

There are plenty of other languages that provide the functionality you need to build a CRM application, java, C#, C++ and a whole slew of other tools.  They're also better suited to building GUI applications than PHP is.  I'd seriously consider looking at one of those instead.


问:
How do people deal with Android fragmentation?
I've spent the past few years working on iOS apps, and I'm now giving some serious consideration to creating an Android port of one of my apps.

I'm sure that complaints about fragmentation are a frustrating cliche to experienced Android programmers, but as an iOS programmer, I'm quite honestly overwhelmed by the number of configurations and devices that my app might end up running on.

There are literally thousands of Android devices in the wild, but I know there are successful Android developers in the world and I know they're not testing or developing for thousands of different devices.

So how can a relatively small company deal with fragmentation? Is it possible to pick the five or six most popular devices, focus on those and prevent the app from being installed on any other devices? Are there any other strategies for practically dealing with the number of different configurations an app will face?

答:
I think the biggest difficulty is supporting various screen sizes, especially in very graphical interfaces. Display size can vary quite a lot and also h/w ratio and number of pixels. In Android you can specify different resources for each of these cases, and possibly for all their combinations (long/hi-res/small, square/mid-res/medium,...), which would mean a large amount of configurations - which would mean quite a mess of course.

So it might not be easy to come out with a layout and small set of resources that can support most configurations, and it's important that graphical designers learn the tools and tricks they can leverage to achieve this.

On the API side, I think Google does some good efforts in backward compatibility, also mantaining a nice backport of the most useful new features.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
If you talking about using a native language on programming language own statements and API, well, in this case I can say I see in the past a very popular product in Brazil derived from xBase but whole in Portuguese.

If -> Se
While -> Enquanto
Left -> Esquerda
Create -> Criar
etc

But I think this kind of languages doesn't get too much successful.


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
In decreasing order of importance.

Dual monitor or a very large monitor (e.g 27-30 inches)

Whiteboard for doodling

Bose noise cancellation headphones for e

A Reference library (physical or virtual like O'reilly safari)

Access to m&m and beverages


问:
Why does Java allow to implement different interfaces, each containing a method with the same signature?
I recently found out that I can have two interfaces, one containing a method with the same signature as a method in the other interface. And I can have an interface or class that implements both of afore-mentioned interfaces. So the descendant class/interface implicitly implements two different methods as one method.

Why is this allowed in Java?

I can see numerous problems arising from this. Eclipse, for example, can only find out about implementations for one interface method, but for the second one it doesn't show any implementations at all. Also, I believe that there would be problems with automatic refactoring, like when you want to change the signature of the method in one of the interfaces and the IDE will be unable to correctly change that signature in all implementations (since they implement two different interfaces, and the IDE cannot tell which interface method the implementation is referring to.)

Why don't just make a compiler error like 'interfaces method names clashes' or something like that?

答:
Why should that be a bad thing?

Just because it makes refactoring in Java harder, doesn't mean it is bad. For example, if I want refactoring in C++, it would be almost impossible in cases of some heavy template-dependent code, since the templates are Turing-complete. And in C++, templates are like the best thing in the language. Should we remove them to make refactoring easier?

The major concern in language design should be for the language to make the life/work of its users easier. I think your rule is too narrow, and not intuitive at that.

Plus this strikes me as too stringent: say I am using two libraries, closed source (as much as it's possible in Java anyway). I have a class that needs to implement two interfaces, one from each library. But the interfaces have a method with the same name/signature.

By your logic, I'm doomed! And to think of it, the library designers did nothing wrong: is it their job to know all method names in all classes of all other libraries? There is no chance to ensure this, even if you try hard...

You might say that this should be split in two classes, but what if the library designers actually meant the same thing with the two methods? Having a class implement both interfaces is the proper way in this situation.


答:
Technically there is nothing wrong with this from the language point of view. There would have been problems if you have inherited from two classes, where the base classes are implemented.

If you consider it a design issue where one interface has one contract for that method and the other interface has other contract then not allowing it would not solve the issue. The end solution would be to disallow multiple inheritance.

Regarding the automatic refactoring problem, there is a problem with the IDE (Intellij has the same behavior); it should ask you which base method do you want refactored.

Title: Why does Java allow to implement different interfaces, each containing a method with the same signature?

Body:
I recently found out that I can have two interfaces, one containing a method with the same signature as a method in the other interface. And I can have an interface or class that implements both of afore-mentioned interfaces. So the descendant class/interface implicitly implements two different methods as one method.

Why is this allowed in Java?

I can see numerous problems arising from this. Eclipse, for example, can only find out about implementations for one interface method, but for the second one it doesn't show any implementations at all. Also, I believe that there would be problems with automatic refactoring, like when you want to change the signature of the method in one of the interfaces and the IDE will be unable to correctly change that signature in all implementations (since they implement two different interfaces, and the IDE cannot tell which interface method the implementation is referring to.)

Why don't just make a compiler error like 'interfaces method names clashes' or something like that?


答:
There is no reason why this should be forbidden. The only point of an interface is to ensure that a method with particular signature exists in each implementing class. This is satisfied by any implementing class even if the condition is posed twice.

Granted, when you write an interface you presumably expect a certain meaning for the action of invoking the method, and presumably you document it above the declaration in the interface, but that is not the concern of the compiler. It cannot check whether the implementing class does the right thing, only whether it copies the signature exactly. Asking "Why doesn't the compiler forbid one method to satisfy two interface declarations?" boils down to "why doesn't the compiler prevent me from implementing the wrong semantics when I implement an interface?", and the answer to that question is much easier to see: because it can't! (If the compiler were able to judge your method implementation and forbid it if it contained a bug, then we wouldn't need programmers in the first place, we'd need only the specifications and the compiler.)

Obviously we would like it if implementing an interface guaranteed that the implementing class does the right thing, but that's not something that interfaces can do for you. In fact, I'd argue that it would be a bad thing to add a feature to the compiler that might give the impression that it is!


问:
Will C# merge with native C++ compiler?
According to this post :

http://channel9.msdn.com/Forums/Coffeehouse/MS-working-on-a-same-compiler-for-C-AND-C--Not-in-incubation-but-for-production-

How much truth is in this post? Should it be taken seriously by hardcore C++ programmers (game devs etc)??

Edit : There's another purpose to this question... Will C# be backward compatible with C++?

答: Probably incorrect in the specifics.  MS already has a native MSIL compiler in the form of Ngen. It wouldn't surprise me if both Ngen and cl used the same code gen back end so that they share improvements like the mentioned auto vectorization.</p>

Title: Will C# merge with native C++ compiler?


问:
Architecture : am I doing things right?
I'm trying to use a '~classic' layered arch using .NET and Entity Framework. We are starting from a legacy database which is a little bit crappy:

Inconsistent naming

Unneeded views (view referencing other views, select * views etc...)

Aggregated columns

Potatoes and Carrots in the same table

etc...

So I ended with fully isolating my database structure from my domain model. To do so EF entities are hidden from presentation layer. The goal is to permit an easier database refactoring while lowering the impact of it on applications.

I'm now facing a lot of challenges and I'm starting to ask myself if I'm doing things right.

My Domain Model is highly volatile, it keeps evolving with apps as new fields needs are arising. Complexity of it keeps raising and class it contains start to get a lot of properties.

Creating include strategy and reprojecting to EF is very tricky (my domain objects don't have any kind of lazy/eager loading relationship properties):

```<code>DomainInclude<Domain.Model.Bar>.Include("Customers").Include("Customers.Friends")
// To...
IFooContext.Bars.Include(...).Include(...).Where(...)
</code>```

Some framework are raping the isolation levels (Devexpress Grids which needs either XPO or IQueryable for filtering and paging large data sets)

I'm starting to ask myself if :

the isolation of EF auto-generated entities is an unneeded cost.

I should allow frameworks to hit IQueryable? Slow slope to hell? (it's really hard to isolate DevExpress framework, any successful experience?)

How can I lower the volatility of my domain model?

Precisions

EF Isolation and fields that should or should not be included on service calls

Here is how I isolate EF Entities. Presentation layer is an isolation layer as no presentation can access to repositories class.

```<code>// Inside a service class. For this sample Customer is defined in the service model
// And Person is autogenerated by Entity Framework
/// Get the customers who bought an item ///
IEnumerable<Customer> GetCustomers(Item item){
    var query = from person in _personRepository.GetItemBuyers(item.Id)
                select new Customer {
                  Id = person.CustomerId
                  , FirstName = person.FirstName
                  , LastName = person.LastName
                  , Sex = person.Sex == 'M' ? Sex.Male : Sex.Female};
    return query;
}
</code>```

It can get time consuming especially when you need to include (or not) some relationship properties.
There is multiple solutions for including:

```<code> 1. GetCustomersWithOrders(Item item);
 2. GetCustomers(Item item, IncludeStrategy<Customer> include);
 3. GetCustomers(Item item, params string[] fieldsIncluded);
</code>```

Will obvioulsy result in service class containing thousands of GetCustomersWith...With...

Will create a lot of IncludeStrategy inherited class. I'm still working on a dynamic fluent approach DomainInclude<Customer>.Include("Orders").Include("Friends")

Will need the creation of some mapping dictionnary "Orders" => "CustomerAccount.PayedOrders"

Framework hitting IQueryable

Repositories don't expose IQueryable, the goal is to hide entity framework.
Devexpress datagrids need an IQueryable to allow paging/filtering without loading the whole table in memory.

Finding a workaround is nearly impossible as it will be really time consuming and the portability of the workaround is not assured with new devexpress releases.

My question here is: Is it a big deal to allow devexpress going through the layers up to the EF context class. Should I drop Devexpress instead and use a more flexible datagrids (Sencha ExtJs, ...)

答:
You've got a number of questions in your overall question.  I'll try to touch upon each of them.

Overall, the answer is:
"Yes, you're doing things right."

Rarely are we given a clean and ideal architecture to work from.  Heck, rarely are we even given an architecture, period.  Small consolation, I realize.  But you're asking the right questions and taking the right approach.

One thing you may not have realized is that isolating the EF layer and the database access is a step towards encapsulating the changes the application is seeing.  Juval Lowy of iDesign is a huge advocate of encapsulating the change.  Change is good because it keeps us employed and keeps our applications alive, but we want to limit the impact any change can have upon the rest of the application.  So we encapsulate it.

You can't lower the volatility of your domain (note, I didn't say domain model) and you wouldn't want to even if you could.  All you can do is encapsulate that volatility.  Once you isolate the volatility of your domain, then your domain model will fall in line.

Identify the areas of your database that seem prone to most frequent change.  Isolate out those aspects so you can more easily make the changes while minimizing downstream impact.  Using a data access layer is a good start.  It might be time to consider a sub-layer for data access that allows you to create a composite of those for the main DA layer.

Some people love EF, some people really don't see much advantage to it when weighed against the costs.  Of those who use EF, they tend to work with the latest release of that toolset.  The recent (v4.5?) updates have made EF more usable / workable.  Wether or not it's a good technological decision for you is something that only you can decide.  Look at your alternatives; examine the cost to switch to those; and move forward.  As a suggestion, create a test branch in your repository, migrate away from EF on that branch and work through some of the challenges.  Then you'll know.

The performance issues within your database imply that you need to consider some restructuring.  Normalization, in moderation, is a good thing.  It's easy to go overboard with it, but restructuring your tables so that they are more easily indexed will likely help with the performance issues.  This could also help with encapsulating some of the change you're seeing from updates to the applications.

For example, you may have a table CustomerInfo with a primary key of CustomerID.  If App1 is adding / changing ancillary columns off of CustomerInfo then you can give App1 it's own subtable CustomerInfoExtensions keyed back to CustomerInfo with the CustomerID.

I don't know of any data access approach that will fix bad structure within the database tables.  So you may be "blaming" EF in this case when the root issue lies in the DB.  And there are no silver bullets when it comes to crunching huge data sets.  If DomainInclude<Customer>.Include("Orders").Include("Friends") creates a cartesian product across your largest tables, well, then that will simply be your least performant query.  Fix the query before worrying about the data access method.

Exposing an IQueryable isn't necessarily a bad thing.  If you need (want) a more concrete expression of that Interface, then pick an appropriate generic container.  We pass collections around like that all the time, and it makes using the MVVM pattern a lot simpler to implement when displaying the data.  I think your concern here is that you feel there should be something "more" to what the EF layer is returning.  If an IQueryable is sufficient, then use one.  If you need a first class data object on the return, then create one.  But don't create a first class data object just to have one if the IQueryable is good enough.  That would be extra work.

The question of DevExpress vs. other datagrids leads me to an answer of "meh."  You've got bigger challenges to resolve first before worrying about that one.  Consider the UI (View) as an area that will change.  Encapsulate it.  When you decide you hate FooBar-Grid (or whatever is your current flavor of UI) then you can get rid of it more easily.  Personally, I would worry about enhancing the DB and data access layers first, but I'm an engineer who appreciates the simple elegance of the command line.  Call me biased.

OwnerDisplayName: Jeremy D

Title: Architecture : am I doing things right?


答: Not a chance in hell. It would take the most drastic refactoring of a language ever to make it work with C++ and it would break every inch of existing C# code. They're most likely just trying to share the same native code generation framework.</p>

Title: Will C# merge with native C++ compiler?

Body:
According to this post :

http://channel9.msdn.com/Forums/Coffeehouse/MS-working-on-a-same-compiler-for-C-AND-C--Not-in-incubation-but-for-production-

How much truth is in this post? Should it be taken seriously by hardcore C++ programmers (game devs etc)??

Edit : There's another purpose to this question... Will C# be backward compatible with C++?


问:
Cache While Developing or Finish Development then Cache?
I'm new to cache and haven't used it on my projects. I would like to know about what is best practice in caching.

Should caching be done while developing or finish development then cache everything?

答:
You should build in the Caching of data whenever it logically comes up in development, but its true that you don't want to be sitting around waiting for the Cache to expire while you are doing dev.

One solution would be to set the Cache duration in a configuration setting (xml, etc), and once you are satisfied that it works with whatever production setting you will likely use (10min, 1 hour, 1 day, whatever), turn it down to something like 1 second in the config, so that you can continue with dev. That way, changing the Cache expiration back up to the 'real' value won't involve a code change.


问:
Creating and assigning console.log a new object
I have seen code like this in several places:

```<code>(function() {
    var method;
    var noop = function noop() {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());
</code>```

Specifically I am interested in this line of code

```<code>var console = (window.console = window.console || {});
</code>```

Why are we creating a new window.console object if window.console is not defined ?

So why are we setting window.console={}?

答: This creates a dummy windows.console for older browsers to prevent them from throwing errors. First an empty function is created and then the missing function calls are added (without any real functionality).</p>


问:
What follows after lexical analysis?
I'm working on a toy compiler (for some simple language like PL/0) and I have my lexer up and running. At this point I should start working on building the parse tree, but before I start I was wondering: How much information can one gather from just the string of tokens? Here's what I gathered so far:

One can already do syntax highlighting having only the list of tokens. Numbers and operators get coloured accordingly and keywords also.

Autoformatting (indenting) should also be possible. How? Specify for each token type how many white spaces or new line characters should follow it. Also when you print tokens modify an alignment variable (when the code printer reads "{" increment the alignment variable by 1, and decrement by 1 for "}". Whenever it starts printing on a new line the code printer will align according to this alignment variable)

In languages without nested subroutines one can get a complete list of subroutines and their signature. How? Just read what follows after the "procedure" or "function" keyword until you hit the first ")" (this should work fine in a Pascal language with no nested subroutines)

In languages like Pascal you can even determine local variables and their types, as they are declared in a special place (ok, you can't handle initialization as well, but you can parse sequences like: "var a, b, c: integer")

Detection of recursive functions may also be possible, or even a graph representation of which subroutine calls who. If one can identify the body of a function then one can also search if there are any mentions of other function's names.

Gathering statistics about the code, like number of lines, instructions, subroutines

EDIT: I clarified why I think some processes are possible. As I read comments and responses I realise that the answer depends very much on the language that I'm parsing.

答:
You've got one minor problem with your definitions there. Auto-formatting and recursive function definition (and even variable detection) should not be possible in a lexer, because a lexer, by definition, is linear and context free.  Its job is to read, identify and validate one single token, and then do it again and again and again until reaching the end of the file, and that's it.

Any recursive analysis, and anything that requires remembering state from before the beginning of the current token is beyond the scope of a lexer and should be undertaken in the parser instead.  This separation of concerns makes your code cleaner and less likely to contain subtle bugs that are hard to track down.

Title: What follows after lexical analysis?


问:
Using machine learning to aim mirrors in a solar array?
I've been thinking about solar collectors where several independent mirrors to focus the light on a solar collector, similar to the following design from Energy Innovations.

Because there will be flaws in the assembly of this solar array, I am proceeding with the following assumptions (or lack thereof):

The software knows the "position" of each mirror, but doesn't know how this position relates to the real world or to other mirrors.  This will account for poor mirror calibration or other environmental factors which may effect one mirror but not the others.

If a mirror moves 10 units in one direction, and then 10 units in the opposite direction, it will end up where it originally started.

I would like to use machine learning to position the mirrors correctly and focus the light on the collector.  I expect I would approach this as an optimization problem, optimizing the mirror positions to maximize the heat inside the collector and the power output.

The problem is finding a small target in a noisy high-dimensional space (considering each mirror has 2 axis of rotation).  Some of the problems I anticipate are:

cloudy days, even if you stumble upon the perfect mirror alignment, it might be cloudy at the time

noisy sensor data

the sun is a moving target, it moves along a path, and follows a different path every day - although you could calculate the exact position of the sun at any time, you wouldn't know how that position relates to your mirrors

My question isn't about the solar array, but possible machine learning techniques that would help in this "small target in a noisy high dimensional-space" problem.  I mentioned the solar array because it was the catalyst for this question and a good example.

What machine learning techniques can find such a small target in a noisy high-dimensional space?

EDIT:

A few additional thoughts:

Yes, you can calculate the suns position in the real world, but you don't know how the mirrors position is related to the real world (unless you've learned it somehow).  You might know the suns azimuth is 220 degrees, and the suns elevation is 60 degrees, and you might know a mirror is at position (-20, 42); now tell me, is that mirror correctly aligned with the sun?  You don't know.

Lets assume you have some very sophisticated heat measurements, and you know "with this heat level, there must be 2 mirrors correctly aligned".  Now the question is, which two mirrors (out of 25 or more) are correctly aligned?

One solution I considered was to approximate the correct "alignment function" using a neural network which would take the suns azimuth and elevation as input and output a large array with 2 values for each mirror which correspond to the 2 axis of each mirror.  I'm not sure what the best training method is though.

More thoughts:

The mirrors do have a coordinate system which the software has access to, but the software doesn't know how this coordinate system relates the the real world.  Let's say a mirror is at position (4, 42); what does that mean?  I don't know and neither does the software.  But I do know that if I move the mirror around and then move it back to (4, 42) the mirror will be in the same position it was previously.  Additionally, two mirrors may be at position (4, 42) but be pointing in opposite directions in the real world.

Yes, with a lot of quality sensors the problem is easy to solve.  Energy Innovations is out of business as best I can tell, probably because they used a bunch of really awesome sensors and people said "I'll just buy solar panels, they're cheaper."

The only sensors in the system are in the collector head.

答:
I almost hate to write this.

Determine from a solar cell whether or not the sun is shining.

If the sun is shining, start with the mirror at (0, 0).

Rotate the mirror to 0 on the x axis.

Rotate the mirror along the entire Y axis.  At each step, measure to see if the heat output of your solar collector increases.  If so stop, and move to the next mirror in the array.

Rotate the mirror along the X axis one step.  Repeat the previous step.

If the mirror has been rotated along the entire x and y axis without increasing the heat output, mark the mirror as needing maintenance, and move to x = 0 and y = 0.

Repeat all of the steps with every mirror in the mirror array.

Wait an hour, and repeat all of the steps.


答: euler's identity which links the most beautiful numbers in math universe: 1, 0, e, i and π : e^i(π) + 1 = 0

Title: What are some famous one-liner or two-liner programs and equations?

Body:
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!


问:
CSS vs codebehind, if I have to do part of the style in codebehind, should I do all of it there?
I'm working with ASP.Net and trying to style an ImageButton.  I tried to do this via CSS only to discover that for some reason, .Net writes out an inline style setting the border width to 0 automatically.  This overrides the border width from CSS, so I have to set it manually in the codebehind.

My question is, should I do all the styling in the codebehind to keep it all in one place, or only do the border width there and do the rest in a style sheet?

For clarification, I mean all the styling for that object not for the whole site.

答: The best way may be to try and remove the inline style with JavaScript, though I'm not 100% sure that would work. The biggest problem with doing all the styling in the code behind is that you must redeploy the actual code for a style change, which may or may not be an issue, if you put all the other styling in the style sheet it can be changed only by replacing that file. When you are working with CSS though getting it to work in any way is a victory, your options all suck in some way, splitting up styling information or working with CSS in the codebehind or hacking it together with JavaScript.</p>


问:
MATLAB: Best fitness vs mean fitness, initial range

Based on the example of Rastrigin's function. At the plot function, if I chose 'best fitness', on the same graph 'mean fitness' will also be plotted. I understand well about 'best fitness' whereby it plots the best function value in each generation versus iteration number. It will reach value zero after some times.

I don't understand about 'mean fitness'in the graph plotted. What do those 'mean fitness' values mean? How does the 'mean fitness' graph help to understand Rastrigin's function?

What are the meaning of the term initial population, initial score and initial range? I wish to have a better understanding of these terms.

The default value for initial range is [0,1]. Does it mean that 0 is the lower bound (lb) and 1 is the upper bound (ub)? Do these values interfere with the lb and ub values I set in the constraints?

I try to better understand about lb and ub. If my lb is 0 and ub is 5, does it mean that my final point values will be within 0 and 5?

If I know the lb and ub for my problem is between 0 and 5, do I just set the initial range as [0,5] at all times and may I assume that this is the best option for initial range, and I need not try it with any other values?

答:
Genetic algorithms are population-based optimization methods. So you have a population of candidate solutions at any given time.

Suppose you're trying to solve the one-max problem -- a simple problem where the goal is to maximize the number of 1-bits in a binary string of length L. With L=8, each candidate solution looks like

```<code>00101101  ==> fitness = 4
</code>```

To solve this problem with a GA, you need to create a population of such individuals at random. Let N=10 be the population size. Then you might get the following 10 individuals (fitness values in [] after the bit strings).

```<code>11011001 [5]
00100110 [3]
11010110 [5]
10010110 [4]
01010110 [4]
11101100 [5]
01001001 [3]
11001011 [4]
10111101 [6]
01001010 [3]
</code>```

This is the "initial population". The GA will then select parents from this population, breed them, possibly mutate the offspring, and produce a new population from the offspring, possibly including the existing parent population as well. This process is then iterated until you decide to stop the algorithm, typically at a maximum number of evaluations of the objective function or after a maximum number of generations.

Best fitness refers to either the fitness of the best individual in your current population or the fitness of the best individual you have found so far during the run. Depending on the type of GA you're using, these may or may not be the same thing. For instance, the best fitness for my example population above is 6. However, if the best offspring I create has a fitness of 5 and I don't allow parents to survive more than one generation, then the best fitness in the next generation could be either 5 or 6, depending on how we interpret "best fitness". I'm not that familiar with MATLAB's GA toolbox to be able to tell you which one it means, but my guess is that it's the overall best fitness the algorithm has encountered during the run at any time.

The average fitness is simply the mean of the fitness values across the entire population. Each generation, the population changes and you get a new average population fitness. Generally, you're most interested in the best fitness, as you only need one solution and you'll obviously choose the best one. Average fitness however is useful in showing you what the algorithm is doing. If the average fitness reaches the best fitness, it likely means that the population contains N copies of the best individual and further search is likely to be wasted effort without a restart or large-scale mutation operation.

So what you generally see is that best fitness tends to get better over time, quickly at first, and then slowing down as the algorithm finds better and better solutions that are harder and harder to improve upon. The average fitness will always be no better than the best fitness, and it is typically quite a bit worse, with the difference between the two usually decreasing over time until the algorithm completely converges (the population is uniform, containing N copies of the same "best" individual).

The [ub,lb] questions I can't really answer. I'm guessing it's the allowed range on your input variables, but you'll need to consult the documentation for the toolbox you're using to know for sure what those parameters mean.

Body:
Genetic algorithms are population-based optimization methods. So you have a population of candidate solutions at any given time.

Suppose you're trying to solve the one-max problem -- a simple problem where the goal is to maximize the number of 1-bits in a binary string of length L. With L=8, each candidate solution looks like

00101101  ==> fitness = 4

To solve this problem with a GA, you need to create a population of such individuals at random. Let N=10 be the population size. Then you might get the following 10 individuals (fitness values in [] after the bit strings).

11011001 [5]
00100110 [3]
11010110 [5]
10010110 [4]
01010110 [4]
11101100 [5]
01001001 [3]
11001011 [4]
10111101 [6]
01001010 [3]

This is the "initial population". The GA will then select parents from this population, breed them, possibly mutate the offspring, and produce a new population from the offspring, possibly including the existing parent population as well. This process is then iterated until you decide to stop the algorithm, typically at a maximum number of evaluations of the objective function or after a maximum number of generations.

Best fitness refers to either the fitness of the best individual in your current population or the fitness of the best individual you have found so far during the run. Depending on the type of GA you're using, these may or may not be the same thing. For instance, the best fitness for my example population above is 6. However, if the best offspring I create has a fitness of 5 and I don't allow parents to survive more than one generation, then the best fitness in the next generation could be either 5 or 6, depending on how we interpret "best fitness". I'm not that familiar with MATLAB's GA toolbox to be able to tell you which one it means, but my guess is that it's the overall best fitness the algorithm has encountered during the run at any time.

The average fitness is simply the mean of the fitness values across the entire population. Each generation, the population changes and you get a new average population fitness. Generally, you're most interested in the best fitness, as you only need one solution and you'll obviously choose the best one. Average fitness however is useful in showing you what the algorithm is doing. If the average fitness reaches the best fitness, it likely means that the population contains N copies of the best individual and further search is likely to be wasted effort without a restart or large-scale mutation operation.

So what you generally see is that best fitness tends to get better over time, quickly at first, and then slowing down as the algorithm finds better and better solutions that are harder and harder to improve upon. The average fitness will always be no better than the best fitness, and it is typically quite a bit worse, with the difference between the two usually decreasing over time until the algorithm completely converges (the population is uniform, containing N copies of the same "best" individual).

The [ub,lb] questions I can't really answer. I'm guessing it's the allowed range on your input variables, but you'll need to consult the documentation for the toolbox you're using to know for sure what those parameters mean.


答:
In this case, caching is an example of premature optimization.  So that would imply it's a bad idea.

You don't know where your performance bottlenecks will be yet, so applying caching now would be a mistake.

Get the application working first, run some performance analysis, and then start using caching were appropriate.

So that means to get the development mostly done, and as part of your refactoring / refinement work you'll identify where the performance issues are.

Title: Cache While Developing or Finish Development then Cache?

Body:
I'm new to cache and haven't used it on my projects. I would like to know about what is best practice in caching.

Should caching be done while developing or finish development then cache everything?


答:
It seems like doing all of your styling in code-behind because of one particular bug issue is like throwing out the baby with the bathwater.

I say you should fix the one issue in code-behind, with a comment explaining why it's done that way, and perhaps a comment in the CSS file explaining why it's not done there. Then go on with life. :)

Title: CSS vs codebehind, if I have to do part of the style in codebehind, should I do all of it there?

Body:
I'm working with ASP.Net and trying to style an ImageButton.  I tried to do this via CSS only to discover that for some reason, .Net writes out an inline style setting the border width to 0 automatically.  This overrides the border width from CSS, so I have to set it manually in the codebehind.

My question is, should I do all the styling in the codebehind to keep it all in one place, or only do the border width there and do the rest in a style sheet?

For clarification, I mean all the styling for that object not for the whole site.


答: Does it need to be an imagebutton? Personally I'd use the more accessible real button and then use CSS to put the background image in. </p>


问:
If you have several SCRUM teams working on one backlog, how do you divide story point estimation between those teams?
I'm asking because approach in my company looks as follows:

stories in the backlog are not estimated

team that picks the story estimates it in story points during sprint planning part two

答:
Each team will have its own velocity and measurement for story points. Remember story points are not absolute, they are relative measures of complexity. If team A has a 20 point velocity and team B has a 40 point velocity, giving team A 20 points as estimated by team B might result in team A being underutilized or it might be way more than team A might be able to handle in a sprint.

Allow the teams to select which stories they will work on and estimate the points for those stories independently.


答:
The way we approach this is on our Sprint Planning Day we have the teams all sit own and play a bit of Planning Poker with each task. Since our backlog is already well ordered by importance by our product owners and our development teams this is a simple process for us to work down that backlog and estimate until the sprint is full for each team with what they are going to work on.

Each team as a velocity so when doing the planning sessions that team knows roughly how much will fit into their sprint. All teams work together on that day to determine which team is best at getting what they are good at. No team estimates another teams work and if for some reason one team picks up a task from another team they will re-estimate it. Often in our organization the story points come out roughly the same, but not always and any issues are raised to the Scrum Master and Product Owner.

During the planning though I do make sure all the teams are working together for the estimation. This means that although Team A is going to be doing the particular story and they estimated it for X story points, someone from Team B for instance can mention have you thought about such and such as I think the estimate would be larger/smaller because of this. Our Sprints are only a couple weeks and we only have 3 sprint teams so this entire process never consumes more than a day, and usually only 4-5 hours.

The sprint planning session is part of our regular corporate heartbeat now and it works very well for us. We haven't run into a problem of one team estimating all the story points for another team to complete as stated above. I would make sure you let the teams that are doing the work estimate the work, but have everyone as engaged as necessary without it becoming burdensome.

Title: If you have several SCRUM teams working on one backlog, how do you divide story point estimation between those teams?

Body:
I'm asking because approach in my company looks as follows:

stories in the backlog are not estimated

team that picks the story estimates it in story points during sprint planning part two


问:
Does async/await makes simple thing unnecessary complicated?
After exposing to Windows App Store development for a month, I begin to feel that async / await programming model does more harm than good. It makes simple thing complicated.

Take an example, folder creation. In Java or Desktop .NET, I can simply do

Java

```<code>public Constructor()
{
    new File("c:\\folder").mkdirs();
    System.out.println("I am pretty sure c:\\folder is ready now");
}
</code>```

Desktop .NET

```<code>Constructor()
{
    System.IO.Directory.CreateDirectory("c:\\folder");
    Console.WriteLine("I am pretty sure c:\\folder is ready now");
}
</code>```

But when comes to

Windows App Store .NET

```<code>Constructor()
{
    // Damm it! Another async function? I don't need aysnc!
    Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("c:\\folder", CreationCollisionOption.OpenIfExists);
    // I am not sure c:\\folder is ready right now!
    // OK. I know I can use ContinueWith. No no no. I don't want.
    // Why I have to use ContinueWith with such a simple operation?
}
</code>```

So, my question is, do you find the newly introduced async / await programming model in Windows App Store,

Improve your productivity?

Make programming life easier?

For me, I don't! Perhaps I have been missing out certain useful techniques.

I know, Microsoft says, it helps us to write responsive UI code.

But I would say, No thanks! Hey look, my code is already in non-UI code!

Most of my current operation code is fast enough and doesn't block UI. When my operation code is not fast enough, I am pretty comfortable in making those slow operation code run in separate Thread/ Task.

Forcing me to use async / await which I do not need, only makes my code more complicated.

Message to Microsoft : May I beg to you, besides async functions, can you provide a same set of non-async functions, please? I already build up my habit of running code in non-UI thread. I promise I will continue make your Windows App perform as smooth as iOS :)

答:
await was introduced with .NET v4.5 and is actually a way to break the pure asynchronous approach.  So it's there as a way to simplify coding with asynchronous methods / calls.

It can also be abused if you put await on every single one of your calls.  At that point, you're back to "traditional" coding styles where you have to wait for all actions to return.

Asynch is a useful approach when you're making calls across a network or when other actions can continue while awaiting the results of the call.  It's equivalent to using a background thread to handle some form of data processing.  The rest of the app continues along until the task is done.

As you noted in your example, there are some cases where you simply have to wait until a call completes before operations can continue.  That's where the await keyword comes in handy.  An alternative was to have a callback method that the performed the rest of the processing.  Honestly, that alternative is less than elegant, and I'm glad that await was offered up.

So, just like with any other tool:

Use asynchronous methods as appropriate for the calls your app is making.

Use the await keyword judiciously when there are calls that really must block the rest of the operations.  Don't overuse the keyword as that will hamper your application.


答:
I think, in something of a departure for Microsoft, they have thought about what makes for the best user experience rather than what makes for the easiest developer experience.

Certainly adopting the async model requires more work on the part of the developer, but just maybe gives that developer a better chance of producing something that will be responsive to the user.

You only need to use Outlook to see how bad the user experience can be if you follow a synchronous programming model too much.

Title: Does async/await makes simple thing unnecessary complicated?

Body:
After exposing to Windows App Store development for a month, I begin to feel that async / await programming model does more harm than good. It makes simple thing complicated.

Take an example, folder creation. In Java or Desktop .NET, I can simply do

Java

```<code>public Constructor()
{
    new File("c:\\folder").mkdirs();
    System.out.println("I am pretty sure c:\\folder is ready now");
}
</code>```

Desktop .NET

```<code>Constructor()
{
    System.IO.Directory.CreateDirectory("c:\\folder");
    Console.WriteLine("I am pretty sure c:\\folder is ready now");
}
</code>```

But when comes to

Windows App Store .NET

```<code>Constructor()
{
    // Damm it! Another async function? I don't need aysnc!
    Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("c:\\folder", CreationCollisionOption.OpenIfExists);
    // I am not sure c:\\folder is ready right now!
    // OK. I know I can use ContinueWith. No no no. I don't want.
    // Why I have to use ContinueWith with such a simple operation?
}
</code>```

So, my question is, do you find the newly introduced async / await programming model in Windows App Store,

Improve your productivity?

Make programming life easier?

For me, I don't! Perhaps I have been missing out certain useful techniques.

I know, Microsoft says, it helps us to write responsive UI code.

But I would say, No thanks! Hey look, my code is already in non-UI code!

Most of my current operation code is fast enough and doesn't block UI. When my operation code is not fast enough, I am pretty comfortable in making those slow operation code run in separate Thread/ Task.

Forcing me to use async / await which I do not need, only makes my code more complicated.

Message to Microsoft : May I beg to you, besides async functions, can you provide a same set of non-async functions, please? I already build up my habit of running code in non-UI thread. I promise I will continue make your Windows App perform as smooth as iOS :)


答:
You're probably holding it wrong (just some context for the statement).

Unfortunately I haven't had a chance to play with Win8 yet, but based on code examples I've seen, your code should look more like

```<code>Constructor()
{
    // Damm it! Another async function? I don't need aysnc!
    var result = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("c:\\folder", CreationCollisionOption.OpenIfExists);
    // by the time your code gets to this line, the folder will have been created
}
</code>```

The other option (if you can't make your method async) is to block the thread until async opertation completes by calling GetResults.  Probably something along the lines of

```<code>Constructor()
{
    // Damm it! Another async function? I don't need aysnc!
    var result = Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("c:\\folder", CreationCollisionOption.OpenIfExists);
    result.GetResults();
    result.Close(); // According to documentation, you should call this when done
    // Voila,
}
</code>```

Though it looks like you're doing file IO inside a constructor and you probably can't have async constructors, so the first option is out.  I assume this this is just some contrived example and not representative of your code, but my feeling is if you find yourself doing IO inside a constructor and you're not writing a framework class (like FileInfo), you should take a second look at your design.  I generally don't expect newing up a class to start creating/locking system resources.

There are a couple of related questions on StackOverflow regarding constructors and async

Can constructors be async

start async method within object constructor - bad practice?

Body:
You're probably holding it wrong (just some context for the statement).

Unfortunately I haven't had a chance to play with Win8 yet, but based on code examples I've seen, your code should look more like

Constructor()
{
    // Damm it! Another async function? I don't need aysnc!
    var result = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("c:\\folder", CreationCollisionOption.OpenIfExists);
    // by the time your code gets to this line, the folder will have been created
}

The other option (if you can't make your method async) is to block the thread until async opertation completes by calling GetResults.  Probably something along the lines of

Constructor()
{
    // Damm it! Another async function? I don't need aysnc!
    var result = Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("c:\\folder", CreationCollisionOption.OpenIfExists);
    result.GetResults();
    result.Close(); // According to documentation, you should call this when done
    // Voila,
}

Though it looks like you're doing file IO inside a constructor and you probably can't have async constructors, so the first option is out.  I assume this this is just some contrived example and not representative of your code, but my feeling is if you find yourself doing IO inside a constructor and you're not writing a framework class (like FileInfo), you should take a second look at your design.  I generally don't expect newing up a class to start creating/locking system resources.

There are a couple of related questions on StackOverflow regarding constructors and async

Can constructors be async

start async method within object constructor - bad practice?


答:
The problem here isn't the async/await keywords but the fact that many WinRT APIs are only offered in an async form. In the past, APIs have been offered in a blocking form, or your choice of blocking and non-blocking, and developers were supposed to make sure the UI didn't hang. Well guess what? Developers didn't bother. I've waited multiple minutes for a Print dialog in an Office product to finish timing out on contacting whatever printer I used last time, before I could specify that I don't want that printer, usually because that printer is now thousands of miles from me. The vast majority of applications were written the easy way for the developer even though that might create a bad experience for the user.

So the new API has no blocking form. You have to learn how to do it asynchronously, like it or not. You could set up a completed handler and then start the process, or you could use the new C# keywords. Your choice. But developers will no longer be trusted to keep the promise you offer to make. And rightly so, since almost no-one did.


答: Actually, Async/Await makes an unnecessarily complicated thing much simpler.  (Just imagine if you had to do all that without Async/Await!)  The unnecessarily complicated part is Microsoft's decision to make all those APIs async-only, instead of leaving it up to the discretion of the developers.


问:
Time allocated to code reviews
If you are doing code reviews

How much time do you spend on code reviews, compared to implementation?

How much of the changes undergo code review?

you think it's to much / should be more?

Are there any studies about effectiveness?

[edit] thank you all for the answers, it's hard to pick a "winner" for such a question, there is lots of valuable info in the other replies, too.

答:
In our project, every significant change to the system is reviewed by the team leader or together with another developer who's gonna be the main "consumer" of the new module. We talk on skype and either use Rudel in Emacs (a plugin for collaborative editing, basically it allows several users to edit the same file live), or TypeWith.me (Piratepad), or one of us shares his screen in skype.

It's hard to quantify this, because mundane changes, like new views, pages, etc. are not reviewed. We do review new modules, major updates and refactorings. As for big changes, code review can take from 10% to 30% of time, but it's worth that.

I can say pair programming, when 2 programmers do edit the same file at the same time, not just sit at the same computer, is a lot better than the usual office practice of sitting behind one's shoulder.

For simple things like naming conventions and scope errors we use our own or open source automatic tools (jslint, pylint, pyflakes, pep8). And we don't limit commits and pushes: we use Mercurial which has very easy branching and merging (I have to say, easier than in Git). Bugs are not a code review matter.

We do team meetings where the changes and new things are announced, but there, not everyone really pays attention. Probably we should do a bit more code reviews.

Title: Time allocated to code reviews


答:
Your question doesn't seem to relate to machine learning so much as it does to automatic calibration of a group of devices. You've got a device (a mirror) with position sensors, and you know where you want to point the device, but you don't know how the sensor output relates to the real world. So you really just need to calibrate the device -- find the correct position so that you can determine how the sensor readings relate to actual position. Once calibrated, it sounds like you can rely on the sensors to position the device.

Given all that, you should probably calibrate each of the devices individually. You can do it automatically using some sort of a search algorithm. Gilbert Le Blanc describes one that should work. Another way would be to assume that the sensor data is correct and use it to point the mirror approximately in the right position; then move the mirror in a pattern that spirals outward until you hit the target.

If you really want to adjust all the mirrors at once, a genetic algorithm might be called for:

Choose a random setting for each mirror and store them in an array. Repeat, so that you have some number of mirror field configurations.

Next, run through the mirror field configurations, setting the all the mirrors for each one and then measuring the heat generated.

Remove the mirror field configurations that generate the least heat from the list.

Generate some new configurations by recombining parts of the configurations that remain in the list.

Repeat until the configurations converge to a single solution or the improvement at each iteration drops below some threshold (i.e. you've reached "good enough").

Also, I should point out that if you try the method above, the thing you're trying to optimize is the mirror sensor calibration, not position. Each step will take some time, so you'll need to account for the movement of the sun as the process goes on. The "setting" for each mirror is not the position but the sensor error, i.e. difference between sensor reading and the ideal reading.

Title: Using machine learning to aim mirrors in a solar array?

Body:
I've been thinking about solar collectors where several independent mirrors to focus the light on a solar collector, similar to the following design from Energy Innovations.

Because there will be flaws in the assembly of this solar array, I am proceeding with the following assumptions (or lack thereof):

The software knows the "position" of each mirror, but doesn't know how this position relates to the real world or to other mirrors.  This will account for poor mirror calibration or other environmental factors which may effect one mirror but not the others.

If a mirror moves 10 units in one direction, and then 10 units in the opposite direction, it will end up where it originally started.

I would like to use machine learning to position the mirrors correctly and focus the light on the collector.  I expect I would approach this as an optimization problem, optimizing the mirror positions to maximize the heat inside the collector and the power output.

The problem is finding a small target in a noisy high-dimensional space (considering each mirror has 2 axis of rotation).  Some of the problems I anticipate are:

cloudy days, even if you stumble upon the perfect mirror alignment, it might be cloudy at the time

noisy sensor data

the sun is a moving target, it moves along a path, and follows a different path every day - although you could calculate the exact position of the sun at any time, you wouldn't know how that position relates to your mirrors

My question isn't about the solar array, but possible machine learning techniques that would help in this "small target in a noisy high dimensional-space" problem.  I mentioned the solar array because it was the catalyst for this question and a good example.

What machine learning techniques can find such a small target in a noisy high-dimensional space?

EDIT:

A few additional thoughts:

Yes, you can calculate the suns position in the real world, but you don't know how the mirrors position is related to the real world (unless you've learned it somehow).  You might know the suns azimuth is 220 degrees, and the suns elevation is 60 degrees, and you might know a mirror is at position (-20, 42); now tell me, is that mirror correctly aligned with the sun?  You don't know.

Lets assume you have some very sophisticated heat measurements, and you know "with this heat level, there must be 2 mirrors correctly aligned".  Now the question is, which two mirrors (out of 25 or more) are correctly aligned?

One solution I considered was to approximate the correct "alignment function" using a neural network which would take the suns azimuth and elevation as input and output a large array with 2 values for each mirror which correspond to the 2 axis of each mirror.  I'm not sure what the best training method is though.

More thoughts:

The mirrors do have a coordinate system which the software has access to, but the software doesn't know how this coordinate system relates the the real world.  Let's say a mirror is at position (4, 42); what does that mean?  I don't know and neither does the software.  But I do know that if I move the mirror around and then move it back to (4, 42) the mirror will be in the same position it was previously.  Additionally, two mirrors may be at position (4, 42) but be pointing in opposite directions in the real world.

Yes, with a lot of quality sensors the problem is easy to solve.  Energy Innovations is out of business as best I can tell, probably because they used a bunch of really awesome sensors and people said "I'll just buy solar panels, they're cheaper."

The only sensors in the system are in the collector head.


问:
Is it useful to unit test methods where the only logic is guards?
Say I have a method like this:

```<code>public void OrderNewWidget(Widget widget)
{
   if ((widget.PartNumber > 0) && (widget.PartAvailable))
   {
        WigdetOrderingService.OrderNewWidgetAsync(widget.PartNumber);
   }
}
</code>```

I have several such methods in my code (the front half to an async Web Service call).

I am debating if it is useful to get them covered with unit tests.  Yes there is logic here, but it is only guard logic.  (Meaning I make sure I have the stuff I need before I allow the web service call to happen.)

Part of me says "sure you can unit test them, but it is not worth the time" (I am on a project that is already behind schedule).

But the other side of me says, if you don't unit test them, and someone changes the Guards, then there could be problems.

But the first part of me says back, if someone changes the guards, then you are just making more work for them (because now they have to change the guards and the unit tests for the guards).

For example, if my service assumes responsibility to check for Widget availability then I may not want that guard any more.  If it is under unit test, I have to change two places now.

I see pros and cons in both ways.  So I thought I would ask what others have done.

答:
It would simplify unit testing if the guard logic and the actual ordering were separate methods.

In the Widget class

```<code>public bool IsReadyForOrdering { get { return PartNumber > 0 && PartAvailable; } }
</code>```

or an equivalent method somewhere else

```<code>public bool IsWidgetReadyForOrdering(Widget widget)
{
    return widget.PartNumber > 0 && widget.PartAvailable;
}
</code>```

The order method

```<code>public void OrderNewWidget(Widget widget)
{
   if (IsWidgetReadyForOrdering(widget)) {
        WigdetOrderingService.OrderNewWidgetAsync(widget.PartNumber);
   }
}
</code>```

Now testing IsWidgetReadyForOrdering became easy. Don't think a long time about it any more. Test it!

Body:
It would simplify unit testing if the guard logic and the actual ordering were separate methods.

In the Widget class

public bool IsReadyForOrdering { get { return PartNumber > 0 && PartAvailable; } }

or an equivalent method somewhere else

public bool IsWidgetReadyForOrdering(Widget widget)
{
    return widget.PartNumber > 0 && widget.PartAvailable;
}

The order method

public void OrderNewWidget(Widget widget)
{
   if (IsWidgetReadyForOrdering(widget)) {
        WigdetOrderingService.OrderNewWidgetAsync(widget.PartNumber);
   }
}

Now testing IsWidgetReadyForOrdering became easy. Don't think a long time about it any more. Test it!


答:
Part of me says "sure you can unit test them, but it is not worth the time" (I am on a project that is already behind schedule).

It's three very short tests. You spent as much time asking yourself the question.

But the other side of me says, if you don't unit test them, and someone changes the Guards, then there could be problems.

Listen to this side.

But the first part of me says back, if someone changes the guards, then you are just making more work for them (because now they have to change the guards and the unit tests for the guards).

If your maintainer is a TDD nut, you're making it more difficult for them. Any change I make without there being a related change or addition of tests leads to my having to think hard. In fact, I would probably add the tests before I go ahead and make the change.

The first part of you is just plain wrong. Give the second part a pat on the back and stop thinking about it.

Title: Is it useful to unit test methods where the only logic is guards?

Body:
Say I have a method like this:

```<code>public void OrderNewWidget(Widget widget)
{
   if ((widget.PartNumber > 0) && (widget.PartAvailable))
   {
        WigdetOrderingService.OrderNewWidgetAsync(widget.PartNumber);
   }
}
</code>```

I have several such methods in my code (the front half to an async Web Service call).

I am debating if it is useful to get them covered with unit tests.  Yes there is logic here, but it is only guard logic.  (Meaning I make sure I have the stuff I need before I allow the web service call to happen.)

Part of me says "sure you can unit test them, but it is not worth the time" (I am on a project that is already behind schedule).

But the other side of me says, if you don't unit test them, and someone changes the Guards, then there could be problems.

But the first part of me says back, if someone changes the guards, then you are just making more work for them (because now they have to change the guards and the unit tests for the guards).

For example, if my service assumes responsibility to check for Widget availability then I may not want that guard any more.  If it is under unit test, I have to change two places now.

I see pros and cons in both ways.  So I thought I would ask what others have done.


答:
If you don't have time in your schedule for unit testing but you have time put aside for solid QA usage, then ask if you can steal some of that QA time to write unit tests, or if you can spend some of the QA period doing unit tests, or perhaps just deal with non-unit tested code.. Unfortunately schedules that are immovable force you to make concessions or work yourself to death, I generally suggest the first option because the second one will result in you incapable of supporting/maintaining the system correctly for the term of it.

That said, to your general question of testing guard statements; Yes! Absolutely test guard statements! Those are important parts of the behaviour of that method, you wouldn't want to find out somebody misunderstood something doing a bug-fix and removed your guards or changed the && to an || would you? Unit tests will ensure that a) you actually got the logic on your guards correct and b) nobody breaks that logic later without getting a complaint when they run the unit tests telling them it should be that way for some reason.


问:
Hierarchical View/ViewModel/Presenters in MVPVM
I've been working with MVVM for a while, but I've recently started using MVPVM and I want to know how to create hierarchial View/ViewModel/Presenter app using this pattern.

In MVVM I would typically build my application using a hierarchy of Views and corresponding ViewModels e.g. I might define 3 views as follows:

The View Models for these views would be as follows:

```<code>public class AViewModel
{
    public string Text
    {
        get { return "This is A!"; }
    }

    public object Child1 { get; set; }
    public object Child2 { get; set; }
}

public class BViewModel
{
    public string Text
    {
        get { return "This is B!"; }
    }
}

public class CViewModel
{
    public string Text
    {
        get { return "This is C!"; }
    }
}
</code>```

In would then have some data templates to say that BViewModel and CViewModel should be presented using View B and View C:

```<code><DataTemplate DataType="{StaticResource local:BViewModel}">
    <local:BView/>
</DataTemplate>
<DataTemplate DataType="{StaticResource local:CViewModel}">
    <local:CView/>
</DataTemplate>
</code>```

The final step would be to put some code in AViewModel that would assign values to Child1 and Child2:

```<code>public AViewModel()
{
    this.Child1 = new AViewModel();
    this.Child2 = new BViewModel();
}
</code>```

The result of all this would be a screen that looks something like:

Doing this in MVPVM would be fairly simple - simply moving the code in AViewModel's constructor to APresenter:

```<code>public class APresenter
{
    ....
    public void WireUp()
    {
        ViewModel.Child1 = new BViewModel();
        ViewModel.Child2 = new CViewModel();
     }
}
</code>```

But If I want to have business logic for BViewModel and CViewModel I would need to have a BPresenter and a CPresenter - the problem is, Im not sure where the best place to put these are.

I could store references to the presenter for AViewModel.Child1 and AViewModel.Child2 in APresenter i.e.:

```<code>public class APresenter : IPresenter
{
    private IPresenter child1Presenter;
    private IPresenter child2Presenter;

    public void WireUp()
    {
        child1Presenter = new BPresenter();
        child1Presenter.WireUp();
        child2Presenter = new CPresenter();
        child2Presenter.WireUp();

        ViewModel.Child1 = child1Presenter.ViewModel;
        ViewModel.Child2 = child2Presenter.ViewModel;
    }
}
</code>```

But this solution seems inelegant compared to the MVVM approach. I have to keep track of both the presenter and the view model and ensure they stay in sync. If, for example, I wanted a button on View A, which, when clicked swapped the View's in Child1 and Child2, I might have a command that did the following:

```<code>var temp = ViewModel.Child1;
ViewModel.Child1 = ViewModel.Child2;
ViewModel.Child2 = temp;
</code>```

This would work as far as swapping the view's on screen (assuming the correct Property Change notification code is in place), but now my APresenter.child1Presenter is pointing to the presenter for AViewModel.Child2, and APresenter.child2Presenter is pointing to the presenter for AViewModel.Child1. If something accesses APresenter.child1Presenter, any changes will actually happen to AViewModel.Child2. I can imagine this leading to all sorts of debugging fun.

I know that I may be misunderstanding the pattern, and if this is the case a clarification of what Im doing wrong would be appreciated.

EDIT - this question is about WPF and the MVPVM design pattern, not ASP.NET and MVP.

答:
So I think you have some minor violation of MVVM | MVPVM patterns due to linkage you're creating between the views.  Neither pattern is all that verbose with respect to child windows though, so it's a bit of a murky area.

I think it's worth pointing out that the big advantage of MVPVM vs. MVVM is because of separating out business logic.  The VM becomes a data container and the P handles logic plus DAL access.  Bill Kratochvil's article on MVPVM was a very good read.

Bill makes a comment regarding child windows and re-use that I think is apt:

In cases where a Presenter can be reused across enterprise applications, it’s likely a module would be better suited for the task—that is, you could create a login module (project) that could be reused by all of your enterprise applications.

Which kind of reinforces that you're in murky territory with two child components.

Regardless of MVVM or MVPVM, I think you would need either

B-VM and C-VM when using MVVM

B-P and C-P and B-VM and C-VM when using MVPVM

because they are functionally separate from A.  If they're not functionally separate, then why do they need their own Views?

I think the challenges you bring up with swapping ViewB and ViewC is because there is some blurring between object ownership and responsibilities.  Which is really just another way of asking if B and C are functionally separate from A or not.  If they are, then make them that way and if not, then don't set them up as independent.

For lightweight stuff without a lot of business logic that could be re-used, I think that MVPVM is more effort than it's worth with MVVM.  That's clearly a generality, and the business logic of your application may lend itself to being expressed more elegantly with MVPVM.  Based upon your question though, it sounds like MVVM may be sufficient for what you need.


答:
It seems like it would imply a certain lazyness, but not really be a problem.

If you have two interfaces, each with methods you need for a given scenario then you either need to have interfaces implement each other, cast between them (yuck) or have them declare each others methods redundantly.

I guess I could imagine cases where extending wasn't practical or possible, so perhaps in that case you'd go for the option you are describing.

The better way to do it would probably be interface inheritance where one interface might implement 2 or 3 more specific interfaces, but this would annoy many people...


问:
Algorithm to optimize grouping
I would like to know if there's a known algorithm or best practice way to do the following:

I have a collection with a subcollection, for example:

```<code>R1 R2 R3
-- -- --
M  M  M
N  N
L  L
   A
</code>```

What i need is an algorithm to get the following result:

```<code>R1, R2: M N L
R2: A
R3: M
</code>```

This is -not- what i want, it has more repeating values for R than the above:

```<code>R1, R2, R3: M
R1, R2: N L
R2: A
</code>```

I need to group in way that i get the most optimized groups of R.
The least amount of groups of R the better so i get the largest sub collections.

Another example (with the most obvious result):

```<code>R1 R2 R3
-- -- --
M  M  A
V  V  B
L  L  C
</code>```

Should result in:

```<code>R1, R2: M V L
R3: A B C
</code>```

I need to do this in LINQ/C#.

Any solutions? Tips? Links?

答:
I think since you want the least total R's, you want to reverse your K/V and use the values as keys so your initial list becomes:

M: R1, R2, R3

N: R1, R2

L: R1, R2

A: R2

Then you can say the count of members intersecting ( http://msdn.microsoft.com/en-us/library/system.linq.enumerable.intersect.aspx ) of M and N is 2, which means you get n-(2 sets * 2 members) number of R's, and if you intersect L you get n-(3*2) number of R's. and if you intersect A as well you get n-(4*1) number of R's, so obviously your best choice is the second intersection set. Unfortunately this is a naive implementation with O(n!) time because you have to interset all possible sets to find the greatest set of intersections which will yield the largest minimization of R's to portray all sets.

After you find the best optimization in this technique where the largest intersection count * sets crossed, remove all the R's in the intersection set from the sets you intersected, then repeat the terribly inefficient combinatoric intersection comparisons against the sets as they are left. Rinse and repeat the comparisons to find largest intersections and remove them from the sets until no Rs are left in any sets.

There is surely a more efficient comparison technique than to intersect each set combination as I'm suggesting. I'm just suggesting an algorithm that should work (I believe) which is likely the naive approach.

Title: Algorithm to optimize grouping


问:
Can someone provide a short code example of compiler bootstrapping?
This Turing award lecture by Ken Thompson on topic "Reflections on Trusting Trust" gives good insight about how C compiler was made in C itself.

Though I understand the crux, it still hasn't sunk in. So ultimately, once the compiler is written to do lexical analysis, parse trees, syntax analysis, byte code generation etc, a separate machine code is again written to do all that on compiler?

Can anyone please explain with a small example of the procedure? Bootstrapping on wiki gives good insights, but only a rough view on it.

PS: I am aware of the duplicates on the site, but found them to be an overview which I am already aware

答:
Lets say you are writing a new programming language named "XYZ".  The first step is to write a compiler for this language.  Since this new language doesn't exist yet, you write the compiler in... lets say java.  We'll call it jxyz.  Doing this process is a typical class in college.

Now you have a java program (jxyz) that takes an XYZ source file and produces an executable.  It is then possible to undertake writing a compiler for XYZ in XYZ that is complied by jxyz.

At this point, you have a complier for XYZ that was complied with jxyz.  Well call this program 'xyzFromJ'.

'xyzFromJ' should be able to take itself as an input and and compile itself completely removing anything created by jxyz from the dependencies and definition of the language.  From this point on, any changes to the XYZ language can be done on the compiler written in XYZ and compiled using itself.


问:
What is a "complimentary license" for a software product?
I don't really understand the term.

I got a survey about either getting gift card or a complimentary license for a SDK control set.

But I really wonder what's complimentary license means?

I tried to search in their official site but didn't say anything about it...

Is it last for the life and I can use the controls in all my personal software and publish it?

答: "Complimentary" means free of charge, i.e. for free. Whether that means "free for X days", or "free for this version but not for any updates", or "here's a free product key that you can use just like a key bought for money" isn't said. In general, companies only give away things for free if they think they will somehow get a net profit from it. Most normal products are given away for free in the hope that the user will like it and buy more; with SDKs, the marketshare among programmers is often quite valuable to the vendor, so it might actually be a completely free, unrestricted one. But it's impossible to tell just from that phrase alone.</p>


答:
In short, that means free, aka without any charge like freeware or shareware.

Here is a reference information that states it in Wikipedia.

Many companies would often provide complementary goods and services
  free of charge (i.e., on a complimentary basis). For example,
  coffeehouses often provide Internet access free of charge to attract
  more customers. Hotels often provide free shuttle services.
  Restaurants often provide valet parking service free of charge.

Title: What is a "complimentary license" for a software product?

Body:
I don't really understand the term.

I got a survey about either getting gift card or a complimentary license for a SDK control set.

But I really wonder what's complimentary license means?

I tried to search in their official site but didn't say anything about it...

Is it last for the life and I can use the controls in all my personal software and publish it?