问:
Capitalization convention for C# protected fields
What is the capitalization conventions for protected field names in C#?

Is it _myVar (like private field) or MyVar (like properties)?

答:
There is something that is called Design Guidelines for Developing Class Libraries which is written by Microsoft.

It says the following:

Do not provide instance fields that are public or protected.

Public and protected fields do not version well and are not protected by code access security demands. Instead of using publicly visible fields, use private fields and expose them through properties.

As well as:

Do use Pascal casing in field names

Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields.

As for the _ prefix, it's used just as often as the this. convention (as far I've seen browsing source code in CodePlex/GitHub). ReSharper, for instance, promotes _ in its naming checks.

ContentLicense: CC BY-SA 4.0


问:
How do developers find the time to stay on top of latest technologies?
I was a freelance web developer until circa 2004 when I started going down the management route but have decided to try to get back into development again (specifically JavaScript and HTML5 web/mobile web apps) and I really get the impression to be truly good at these and similar fast moving technologies a constant amount of time is required to be set aside to invest in getting better at existing skills in addition to learning new skills.

I understand right now since I am getting back into things there is a pretty steep learning curve, but seeing how good many guys are out there - the only way I see of getting up there is putting in a serious amount of time.

For those working as fulltime developers, what I am trying to understand is this - on most days, how much time in the office is spent actually grinding out code compared to learning/research. I could easily spend 2-4 hours daily getting on top of the best ways to go about doing things.

Do most good developers who are employed full time invest significant hours outside of work sharpening their skills?

Or maybe I'm looking at all of this completely wrong?

答:
I put the most useful information that I come across in an Anki deck. Every morning I spend 5-10 minutes going over the material. Just this week, for instance, Anki asked me this question which I had not dealt with for some time:

PHP: What must be done after a foreach on a referenced array?

I didn't remember if the answer was unset($value) or reset($value), so that kept me sharp. Sure enough, this very morning I had to use that in code.

I keep some snippets of information regarding AWS, PHP, Bash and other technologies that I use in there. At the very least, Anki keeps the info fresh in my mind or easy to find if I forget.

EDIT: I should also mention, for me programming was a hobby that developed into a software development career. I find that people whose careers are also their hobbies tend to naturally stay abreast as it their personal interest, not just professional interest. This goes for artists, doctors, gardeners, and most other skilled professions, not just programmers.

ContentLicense: CC BY-SA 3.0


答:
To be honest I use newsfeed reader.  I subscribe to a number of blogs and technology related sites.  I'll read my feed during lunch, before work and sometimes after work.  However I use my tablet for that and will constantly review news sources for if they provide a good time to value ratio. I probably get 1-2 hours a day reading about new things.

Generally I will not waste time on reading comments or commenting unless its a real knowledge transfer.

Title: How do developers find the time to stay on top of latest technologies?

Body:
I was a freelance web developer until circa 2004 when I started going down the management route but have decided to try to get back into development again (specifically JavaScript and HTML5 web/mobile web apps) and I really get the impression to be truly good at these and similar fast moving technologies a constant amount of time is required to be set aside to invest in getting better at existing skills in addition to learning new skills.

I understand right now since I am getting back into things there is a pretty steep learning curve, but seeing how good many guys are out there - the only way I see of getting up there is putting in a serious amount of time.

For those working as fulltime developers, what I am trying to understand is this - on most days, how much time in the office is spent actually grinding out code compared to learning/research. I could easily spend 2-4 hours daily getting on top of the best ways to go about doing things.

Do most good developers who are employed full time invest significant hours outside of work sharpening their skills?

Or maybe I'm looking at all of this completely wrong?


问:
What is constructor injection?
I have been looking at the terms constructor injection and dependency injection while going through articles on (Service locator) design patterns.

When I googled about constructor injection, I got unclear results, which prompted me to check in here.

What is constructor injection? Is this a specific type of dependency injection? A canonical example would be a great help.

Edit

Revisiting this questions after a gap of a week, I can see how lost I was... Just in case anyone else pops in here, I will update the question body with a little learning of mine. Please do feel free to comment/correct.

Constructor injection and property injection are two types of Dependency Injection.

答:
Suppose that you have a class A each instance of which that needs an instance of another class B.

```<code>class A
{
   B b;
}
</code>```

Dependency injection means that the reference to B is set by the object that manages the instance of A (as opposed to having the class A managing the reference to B directly).

Constructor injection means that the reference to B is passed as a parameter to the constructor of A and set in the constructor:

```<code>class A
{
    B b;

    A(B b)
    {
        this.b = b;
    }
}
</code>```

An alternative is to use a setter method (or a property) to set the reference to B. In this case, the object that manages an instance a of A must first call the constructor of A and later call the setter method to set the member variable A.b before a is used.
The latter injection method is necessary when objects contain cyclic references to each other, e.g. if an instance b of B that is set in an instance a of A contains a back reference to a.

** EDIT**

Here are some more details to address the comment.

1. Class A manages B instance

```<code>class A
{
    B b;

    A()
    {
        b = new B();
    }
 }
</code>```

2. B instance is set in the constructor

```<code>class A
{
    B b;

    A(B b)
    {
        this.b = b;
    }
}

class M
{
    ...
    B b = new B();
    A a = new A(b);
}
</code>```

3. B instance is set using setter method

```<code>class A
{
    B b;

    A()
    {
    }

    void setB(B b)
    {
        this.b = b;
    }
}

class M
{
    ...
    B b = new B();
    A a = new A();

    a.setB(b);
}
</code>```

Title: What is constructor injection?

Body:
Suppose that you have a class A each instance of which that needs an instance of another class B.

class A
{
   B b;
}

Dependency injection means that the reference to B is set by the object that manages the instance of A (as opposed to having the class A managing the reference to B directly).

Constructor injection means that the reference to B is passed as a parameter to the constructor of A and set in the constructor:

class A
{
    B b;

    A(B b)
    {
        this.b = b;
    }
}

An alternative is to use a setter method (or a property) to set the reference to B. In this case, the object that manages an instance a of A must first call the constructor of A and later call the setter method to set the member variable A.b before a is used.
The latter injection method is necessary when objects contain cyclic references to each other, e.g. if an instance b of B that is set in an instance a of A contains a back reference to a.

** EDIT**

Here are some more details to address the comment.

1. Class A manages B instance

class A
{
    B b;

    A()
    {
        b = new B();
    }
 }

2. B instance is set in the constructor

class A
{
    B b;

    A(B b)
    {
        this.b = b;
    }
}

class M
{
    ...
    B b = new B();
    A a = new A(b);
}

3. B instance is set using setter method

class A
{
    B b;

    A()
    {
    }

    void setB(B b)
    {
        this.b = b;
    }
}

class M
{
    ...
    B b = new B();
    A a = new A();

    a.setB(b);
}


答:
Sharpen the saw is a must for all involved in any knowledge based work.  How to do that is left to individual.
Here are some thing I do

Listen to podcasts, pick up links are learn about the technology and
its relevance is specific areas
(http://www.javaposse.com/, http://www.se-radio.net/ and many more)

I read quite heavily (management and technology)

Do small project to get feel of new things, that is not directly used
in my normal work.

Google tech talks - This is much more involved than plain podcasts,
but more useful.


答: Some companies have policies that the employee can spend 20% of time on the other activities, than the day-to-day work. One can use this time to sharpen the saw or to keep on top of technology. </p>


答:
Just try to make the most of your free time. You could spend 3 hours every day learning about new technologies, but you still probably want to have some social life.. So it might not be the best approach.

What I usually do is learn during those moments when (in normal conditions) I would be 'lazy'..
Reading technology books in the train, watching podcasts before going to bed (insted of watching TV), reading StackOverflow, technology blogs or other sources when I need a rest at work (instead of being on Facebook), talking about technology with my workmates during lunch time..


答:
I'm no expert, but I think I can help. And yes, it's a specific type of Dependency Injection.

Disclaimer: Almost all of this was "stolen" from the Ninject Wiki

Let’s examine the idea of dependency injection by walking through a simple example. Let’s say you’re writing the next blockbuster game, where noble warriors do battle for great glory. First, we’ll need a weapon suitable for arming our warriors.

```<code>class Sword
{
    public void Hit(string target)
    {
        Console.WriteLine("Chopped {0} clean in half", target);
    }
}
</code>```

Then, let’s create a class to represent our warriors themselves. In order to attack its foes, the warrior will need an Attack() method. When this method is called, it should use its Sword to strike its opponent.

```<code>class Samurai
{
    readonly Sword sword;
    public Samurai()
    {
        this.sword = new Sword();
    }

    public void Attack(string target)
    {
        this.sword.Hit(target);
    }
}
</code>```

Now, we can create our Samurai and do battle!

```<code>class Program
{
    public static void Main()
    {
        var warrior = new Samurai();
        warrior.Attack("the evildoers");
    }
}
</code>```

As you might imagine, this will print Chopped the evildoers clean in half to the console. This works just fine, but what if we wanted to arm our Samurai with another weapon? Since the Sword is created inside the Samurai class’s constructor, we have to modify the implementation of the class in order to make this change.

When a class is dependent on a concrete dependency, it is said to be tightly coupled to that class. In this example, the Samurai class is tightly coupled to the Sword class. When classes are tightly coupled, they cannot be interchanged without altering their implementation. In order to avoid tightly coupling classes, we can use interfaces to provide a level of indirection. Let’s create an interface to represent a weapon in our game.

```<code>interface IWeapon
{
    void Hit(string target);
}
</code>```

Then, our Sword class can implement this interface:

```<code>class Sword : IWeapon
{
    public void Hit(string target)
    {
        Console.WriteLine("Chopped {0} clean in half", target);
    }
}
</code>```

And we can alter our Samurai class:

```<code>class Samurai
{
    readonly IWeapon weapon;
    public Samurai()
    {
        this.weapon = new Sword();
    }
    public void Attack(string target)
    {
        this.weapon.Hit(target);
    }
}
</code>```

Now our Samurai can be armed with different weapons. But wait! The Sword is still created inside the constructor of Samurai. Since we still need to alter the implementation of Samurai in order to give our warrior another weapon, Samurai is still tightly coupled to Sword.

Fortunately, there is an easy solution. Rather than creating the Sword from within the constructor of Samurai, we can expose it as a parameter of the constructor instead. Also known as Constructor Injection.

```<code>class Samurai
{
    readonly IWeapon weapon;
    public Samurai(IWeapon weapon)
    {
        this.weapon = weapon;
    }
    public void Attack(string target)
    {
        this.weapon.Hit(target);
    }
}
</code>```

As Giorgio pointed out, there's also property injection. That would be something like:

```<code>class Samurai
{
    IWeapon weapon;

    public Samurai() { }

    public void SetWeapon(IWeapon weapon)
    {
        this.weapon = weapon;
    }

    public void Attack(string target)
    {
        this.weapon.Hit(target);
    }

}
</code>```

Hope this helps.

Title: What is constructor injection?

Body:
I have been looking at the terms constructor injection and dependency injection while going through articles on (Service locator) design patterns.

When I googled about constructor injection, I got unclear results, which prompted me to check in here.

What is constructor injection? Is this a specific type of dependency injection? A canonical example would be a great help.

Edit

Revisiting this questions after a gap of a week, I can see how lost I was... Just in case anyone else pops in here, I will update the question body with a little learning of mine. Please do feel free to comment/correct.

Constructor injection and property injection are two types of Dependency Injection.

Body:
I'm no expert, but I think I can help. And yes, it's a specific type of Dependency Injection.

Disclaimer: Almost all of this was "stolen" from the Ninject Wiki

Let’s examine the idea of dependency injection by walking through a simple example. Let’s say you’re writing the next blockbuster game, where noble warriors do battle for great glory. First, we’ll need a weapon suitable for arming our warriors.

class Sword
{
    public void Hit(string target)
    {
        Console.WriteLine("Chopped {0} clean in half", target);
    }
}

Then, let’s create a class to represent our warriors themselves. In order to attack its foes, the warrior will need an Attack() method. When this method is called, it should use its Sword to strike its opponent.

class Samurai
{
    readonly Sword sword;
    public Samurai()
    {
        this.sword = new Sword();
    }

    public void Attack(string target)
    {
        this.sword.Hit(target);
    }
}

Now, we can create our Samurai and do battle!

class Program
{
    public static void Main()
    {
        var warrior = new Samurai();
        warrior.Attack("the evildoers");
    }
}

As you might imagine, this will print Chopped the evildoers clean in half to the console. This works just fine, but what if we wanted to arm our Samurai with another weapon? Since the Sword is created inside the Samurai class’s constructor, we have to modify the implementation of the class in order to make this change.

When a class is dependent on a concrete dependency, it is said to be tightly coupled to that class. In this example, the Samurai class is tightly coupled to the Sword class. When classes are tightly coupled, they cannot be interchanged without altering their implementation. In order to avoid tightly coupling classes, we can use interfaces to provide a level of indirection. Let’s create an interface to represent a weapon in our game.

interface IWeapon
{
    void Hit(string target);
}

Then, our Sword class can implement this interface:

class Sword : IWeapon
{
    public void Hit(string target)
    {
        Console.WriteLine("Chopped {0} clean in half", target);
    }
}

And we can alter our Samurai class:

class Samurai
{
    readonly IWeapon weapon;
    public Samurai()
    {
        this.weapon = new Sword();
    }
    public void Attack(string target)
    {
        this.weapon.Hit(target);
    }
}

Now our Samurai can be armed with different weapons. But wait! The Sword is still created inside the constructor of Samurai. Since we still need to alter the implementation of Samurai in order to give our warrior another weapon, Samurai is still tightly coupled to Sword.

Fortunately, there is an easy solution. Rather than creating the Sword from within the constructor of Samurai, we can expose it as a parameter of the constructor instead. Also known as Constructor Injection.

class Samurai
{
    readonly IWeapon weapon;
    public Samurai(IWeapon weapon)
    {
        this.weapon = weapon;
    }
    public void Attack(string target)
    {
        this.weapon.Hit(target);
    }
}

As Giorgio pointed out, there's also property injection. That would be something like:

class Samurai
{
    IWeapon weapon;

    public Samurai() { }

    public void SetWeapon(IWeapon weapon)
    {
        this.weapon = weapon;
    }

    public void Attack(string target)
    {
        this.weapon.Hit(target);
    }

}

Hope this helps.


答:
When time is limited, you are better to focus on the highest quality material.

Books (the good ones) are more likely to have higher quality material than blogs. Books with high average customer review scores on Amazon usually have the highest quality material. Get a Kindle and download a few highly rated books on the subject - keep it with you whereever you go. Maybe an hour a day of reading? - thats what I do anyway, not sure what is a good time guideline.

If you are getting back into the saddle and have the budget, better again is to attend a decent training course (or conference) for a kickstart. A few days of intense training = months of reading.


答: To be blunt, yes. Good developers do spend some amount of non-work time programming. Often times that is some pet project, where they can play around with new and interesting things. Oftentimes things that are not applicable for work use to broaden the mind and keep up with the (relatively) cutting edge.


答:
"Grinding out code" IS the best learning tool. When given something that can use a new method, I pound away at it till it works. If a customer requested something that required the new tech, I'll bill them for it, but if it's something I just hadn't gotten around to learning, I don't bill them.

The web stuff is moving at a good pace. In my little company I use freelancers for things I don't know or don't have time for. Usually they teach me but it has gotten harder to keep up with what works today but you couldn't use yesterday or it will work tomorrow so you should learn it today and on and on.

For non-web stuff things were more stable. You wrote code in one language on one platform. Now you need to know HTML/CSS/Javascript/Java/SQL/PHP/*nix/all those APIs....and then there's Internet Explorer....sigh.

It is a struggle for one developer.


问:
What are your thoughts on Periods/Full Stops in code comments?
I saw this asked in the SO Tavern, so I'm posting the question here. I thought it an interesting question. (Of course it doesn't belong on SO, but I think it's OK here.)

Do you add periods (or, as the OP wrote, "full stops") in your code comments?

To keep it relevant, why?

答:
It depends. If I write up a big, proper paragraph explaining what a block of code does, then I punctuate it properly, like any other piece of proper writing. OTOH, when I just comment a single line of code, then I don't.

Why? - Similar to why I write emails using proper writing, while I might use shorthand sentences in SMS messages. In one case I'm sitting down to write a proper block of text, so I just automatically "do it properly", while in the other it's just a brief note to get a point across.

Real examples from my code:

Quick note comment:

```<code>// check for vk_enter
</code>```

"Proper" method documentation:

```<code>// This method sets up a workspace tab with the given name. Each MDI window has a parent
// workspace specified when it's saved. The code which loads each MDI window then point it to
// the correct workspace.
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It depends. If I write up a big, proper paragraph explaining what a block of code does, then I punctuate it properly, like any other piece of proper writing. OTOH, when I just comment a single line of code, then I don't.

Why? - Similar to why I write emails using proper writing, while I might use shorthand sentences in SMS messages. In one case I'm sitting down to write a proper block of text, so I just automatically "do it properly", while in the other it's just a brief note to get a point across.

Real examples from my code:

Quick note comment:

// check for vk_enter

"Proper" method documentation:

// This method sets up a workspace tab with the given name. Each MDI window has a parent
// workspace specified when it's saved. The code which loads each MDI window then point it to
// the correct workspace.


答:
As AC/DC would say: "It's a long way to the Top if you wanna Rock and Roll".

It's not going to be easy if you're aiming to the top. The main problem of trying to get back on the horse is to feel outdated - not to mention stupid.

You try to understand TDD, then you stumble on Dependency Injection and then on Inversion of Control containers. The latest thing to pop under my radar was CQRS. Trying to grasp all of that at once is really hard. Small steps.

And it doesn't help the fact the some of it can be considered just a fad. Boy, do we like to boast this new shiny thing that will solve all of our problems.

Couple of things to try:

http://www.safaribooksonline.com/ they have (it's kinda hidden) a 5 slot subscription per $ 9.99 per month. They have a mobile app. You can study wherever you are.

Subscribe to some video classes. I subscribed to http://tekpub.com/ once and loved. I also know of https://peepcode.com and http://pluralsight.com. You can watch on the go.

Choose a few good newsfeed and follow it. Choose quality over quantity. Otherwise you'll just feel crushed by too much information.

Use https://getpocket.com to store those interesting pages that you might want to view later. Stop opening new Tabs to view it later and forgetting about them. They have mobile apps that allow to view your stored pages on the go.

Use https://ifttt.com to make your life easier. I for one make it so that when I star an item on Google Reader, it saves automatically for me on Pocket.

http://www.class-central.com/ List of MOOC offered by institutions like Stanford and MIT. Some of it can be really interesting.

Anyway, the best programmers probably spend a lot of time outside work hours learning new things. But they do that because they love coding. It's easy to find time to improve your coding skills when you love coding. :)


问:
Order of executions in C++ streams
It is obvious that first cout prints 7 7 but why the second one prints  8 8 7 ? Why not 7 8 8? How does such constructions work in c++?

int ink(int *x){
     *x += 1;
     return *x;
}
```

<pre class="lang-c prettyprint-override"><code>int main(){
    int *a;
    int b = 6;

    a = &b;

    cout << ++b << " " << b << endl;
    cout << b << " " << ink(a) << " " << b;

    return 0;
</code>```

}

答:
Because the code contains side effects. You can't be sure in what order the elements will be executed.

Here is some more info:
http://en.wikipedia.org/wiki/Sequence_point

EDIT: Here is the output on my machine:

```<code>7 6
8 8 7
</code>```

As you can see it's different from yours. The correct approach is to make all calculations before the cout and then pass the values only.

Title: Order of executions in C++ streams

Body:
Because the code contains side effects. You can't be sure in what order the elements will be executed.

Here is some more info:
http://en.wikipedia.org/wiki/Sequence_point

EDIT: Here is the output on my machine:

7 6
8 8 7

As you can see it's different from yours. The correct approach is to make all calculations before the cout and then pass the values only.


问:
How to structure classes in the filesystem?
I have a few (view) classes.

Table, Tree, PagingColumn, SelectionColumn, SparkLineColumn, TimeColumn.

currently they're flat under app/view like this:

```<code>app/view/Table
app/view/Tree
app/view/PagingColumn
...
</code>```

I thought about restructuring it, because the Trees and Tables use the columns, but there are some columns, which only work in a tree, some who work in trees and tables and in the future there are probably some who only work in tables, I don't know.

My first idea was like this:

```<code>app/view/Table
app/view/Tree

app/view/column/PagingColumn
app/view/column/SelectionColumn
app/view/column/SparkLineColumn
app/view/column/TimeColumn
</code>```

But since the SelectionColumn is explicitly for trees, I have the fear that future developers could get the idea of missuse them.

But how to restructure it probably?

Like this:

```<code>app/view/table/panel/Table

app/view/tree/panel/Tree
app/view/tree/column/PagingColumn
app/view/tree/column/SelectionColumn

app/view/column/SparkLineColumn
app/view/column/TimeColumn
</code>```

Or like this:

```<code>app/view/Table
app/view/Tree

app/view/column/SparkLineColumn
app/view/column/TimeColumn

app/view/column/tree/PagingColumn
app/view/column/tree/SelectionColumn
</code>```

答: I'd recommend your first idea, with the an additional partial class "BaseColumn" from the various column classes can inherit from.  This would allow you to define the common methods and properties within the "BaseColumn" and implement the differences in the Paging, Selection, Spark and Time column classes.</p>


答:
Without going too much into detail regarding to your specific scenario, here are a couple of guidelines when structuring classes.

Usually your file structure should follow the namespaces of your classes, so this question doesn't really relate as much to file structure as you make it seem, but rather to how to organize classes and about creating the proper abstractions.

Place classes in the least specific namespace possible. When you created a class for a certain class within a specific namespace, this doesn't necessarily mean it's the most logical place to place it. It might be relevant to place it higher up the hierarchy.

When creating proper abstractions, classes become reusable in a wide set of scenarios, and the namespace should reflect that. Instead of placing a class in a specific application namespace, you could move it to e.g. a common user control namespace.

Following the cohesion principle, place logically related classes together. E.g. when a set of classes are logically related it might be worthwhile creating a specific namespace and grouping them together within this namespace.

Applying this to your specific scenario the first thing that comes to mind is:

Common/Layout/Columns/AbstractColumn

Common/Layout/Columns/PagingColumn

Common/Layout/Columns/SparkLineColumn

Common/Layout/Columns/TimeColumn

Common/Layout/Table

Common/Layout/Tree

Common/Layout/Tree/SelectionColumn (could be an inner class)

Title: How to structure classes in the filesystem?

Body:
I have a few (view) classes.

Table, Tree, PagingColumn, SelectionColumn, SparkLineColumn, TimeColumn.

currently they're flat under app/view like this:

```<code>app/view/Table
app/view/Tree
app/view/PagingColumn
...
</code>```

I thought about restructuring it, because the Trees and Tables use the columns, but there are some columns, which only work in a tree, some who work in trees and tables and in the future there are probably some who only work in tables, I don't know.

My first idea was like this:

```<code>app/view/Table
app/view/Tree

app/view/column/PagingColumn
app/view/column/SelectionColumn
app/view/column/SparkLineColumn
app/view/column/TimeColumn
</code>```

But since the SelectionColumn is explicitly for trees, I have the fear that future developers could get the idea of missuse them.

But how to restructure it probably?

Like this:

```<code>app/view/table/panel/Table

app/view/tree/panel/Tree
app/view/tree/column/PagingColumn
app/view/tree/column/SelectionColumn

app/view/column/SparkLineColumn
app/view/column/TimeColumn
</code>```

Or like this:

```<code>app/view/Table
app/view/Tree

app/view/column/SparkLineColumn
app/view/column/TimeColumn

app/view/column/tree/PagingColumn
app/view/column/tree/SelectionColumn
</code>```


答:
What I do is I organize lunchmeetings at work every now and then.

I find some video (e.g. from channel 9) and just schedule it during lunch, get a beamer and a room and invite everyone who might be interested. A great way to spend lunch with colleages. Also a great way to show initiative.


问:
How to check if 4 points form a square?
Assume I have 4 points (they are 2-dimension), which are different from each other, and I want to know whether they form a square. How to do it? (let the process be as simple as possible.)</p>

答:
this is not an answer according to the standards set, but I hope this helps:

[Copied from the link below so you don't have to open the link]
Python  76 characters

```<code>def S(A):c=sum(A)/4.0;return set(A)==set((A[0]-c)*1j**i+c for i in range(4))
</code>```

Function S takes a list of complex numbers as its input (A). If we know both the centre and one corner of a square, we can reconstruct the square by rotating the corner 90,180 and 270 degrees around the centre point (c). On the complex plane rotation by 90 degrees about the origin is done by multiplying the point by i. If our original shape and the reconstructed square have the same points then it must have been a square.

This was taken from :
Determine if 4 points form a square

If you like the answer, I say, take some moments out to thank the person, or up-vote his answer on that page.

Title: How to check if 4 points form a square?

Body:
this is not an answer according to the standards set, but I hope this helps:

[Copied from the link below so you don't have to open the link]
Python  76 characters

def S(A):c=sum(A)/4.0;return set(A)==set((A[0]-c)*1j**i+c for i in range(4))

Function S takes a list of complex numbers as its input (A). If we know both the centre and one corner of a square, we can reconstruct the square by rotating the corner 90,180 and 270 degrees around the centre point (c). On the complex plane rotation by 90 degrees about the origin is done by multiplying the point by i. If our original shape and the reconstructed square have the same points then it must have been a square.

This was taken from :
Determine if 4 points form a square

If you like the answer, I say, take some moments out to thank the person, or up-vote his answer on that page.


答:
If I write a full sentence (or more), then yes. If I don't, then sometimes no, but usually still yes.

I also sometimes go crazy and use exclamation points, question marks, etc. ;)

As for why, it's partly because I'm just particular like that and partly because I find that appropriate punctuation can add a lot of clarity.

Title: What are your thoughts on Periods/Full Stops in code comments?

Body:
I saw this asked in the SO Tavern, so I'm posting the question here. I thought it an interesting question. (Of course it doesn't belong on SO, but I think it's OK here.)

Do you add periods (or, as the OP wrote, "full stops") in your code comments?

To keep it relevant, why?


问:
Is code that terminates on a random condition guaranteed to terminate?
If I had a code which terminated based on if a random number generator returned a result (as follows), would it be 100% certain that the code would terminate if it was allowed to run forever.

```<code>while (random(MAX_NUMBER) != 0): // random returns a random number between 0 and MAX_NUMBER
   print('Hello World')
</code>```

I am also interested in any distinctions between purely random and the deterministic random that computers generally use. Assume the seed is not able to be known in the case of the deterministic random.

Naively it could be suggested that the code will exit, after all every number has some possibility and all of time for that possibility to be exercised. On the other hand it could be argued that there is the random chance it may not ever meet the exit condition-- the generator could generate 1 'randomly' until infinity.

(I suppose one would question the validity of the random number generator if it was a deterministic generator returning only 1's 'randomly' though)

答:
To answer the other part of your question (regarding the implementation of random) then I would say it depends entirely on the implementation.  Divide implementations into pseudo-random number generators and "true" random number generators.

One popular implementation of a pseudo-random number generator is a linear feedback shift register (LFSR).  These actually generate repeatable sequences of numbers and they are only random in the sense of fulfilling a random distribution.  There is, in fact, an entity called a "maximum length LFSR" that is guaranteed to cycle through all the values.  In that case, your code would certainly terminate.

"True" random number generators can't be implemented only in software.  They need some kind of fundamental "noise" source: typically a reverse-biased PN junction with an amplifier, or a radio tuned off station run into a sound card, where you sample the smallest bit.  Sometimes there's a source built into the operating system that tries to generate random bits using entropy such as disk I/O times, keyboard press times, etc.  In that case, you're talking about whether a truly (quantum) random physical process will ever generate a zero, and for that perhaps we need to consult a physicist.

Also realize that even a truly random implementation may not be truly random if there's a subtle flaw that causes it never to generate some subset of numbers.


答:
Resources & tools I use to keep up are listed below.  I probably spend 1-2 hours per day reading up on tech subjects, though not always the tech subjects I should be directing my attention to.

As far as the ratio of time spent reading at work to time spent coding, I'll spend time reading up on a subject if it is directly related to the work at hand (e.g., how to use that new framework properly).

I find I do two types of reading.  Deep reading on a specific subject that I'm using or will use in the future, or Wide reading where I will browse other tech areas that I'm not using but still find interesting.

Podcasts

Useful because of their portability. You can listen when you wouldn't typically be able to read (e.g., at the gym, cleaning house, cooking)

RSS Readers

Useful because they aggregate your blog feeds.  Use them to group together high value content.

I've found setting up "search" folders for particular technologies useful as these folders will cover all blogs subscribed to.

Safari Books Online

I go back and forth on this one because of the cost.  When I do use it, it is a great value but it takes effort to read all the books you add to your shelf.

Books (Dead Tree Format)

Useful for deep dives on a particular technology or for reference.

Scott Hanselman has a good video on dealing with your "personal data stream" - http://www.hanselman.com/blog/ItsNotWhatYouReadItsWhatYouIgnoreVideoOfScottHanselmansPersonalProductivityTips.aspx


答:
It may be easier to understand what's going on if you look at the chain of function calls that the second one devolves to (I'm using the operator defs here, which do match the gcc headers on my system):

```<code>cout << b << " " << ink(a) << " " << b;

operator<<(operator<<(cout.operator<<(b)," ").operator<<(ink(a)), " ").operator<<(b);
</code>```

Aside: This looks very odd because the numeric inserters are all methods of the object, while the character string inserters are all global functions, which makes the call order even more strange than it might be.

Now that you have the actual call chain, you can see how it would end up putting the 7 on the stack before the 'ink' call, but actually won't use that until well after, thus causing the non-intuitive outputs.

Title: Order of executions in C++ streams

Body:
It is obvious that first cout prints 7 7 but why the second one prints  8 8 7 ? Why not 7 8 8? How does such constructions work in c++?

int ink(int *x){
     *x += 1;
     return *x;
}
```

<pre class="lang-c prettyprint-override"><code>int main(){
    int *a;
    int b = 6;

    a = &b;

    cout << ++b << " " << b << endl;
    cout << b << " " << ink(a) << " " << b;

    return 0;
</code>```

}

Body:
It may be easier to understand what's going on if you look at the chain of function calls that the second one devolves to (I'm using the operator defs here, which do match the gcc headers on my system):

cout << b << " " << ink(a) << " " << b;

operator<<(operator<<(cout.operator<<(b)," ").operator<<(ink(a)), " ").operator<<(b);

Aside: This looks very odd because the numeric inserters are all methods of the object, while the character string inserters are all global functions, which makes the call order even more strange than it might be.

Now that you have the actual call chain, you can see how it would end up putting the 7 on the stack before the 'ink' call, but actually won't use that until well after, thus causing the non-intuitive outputs.


问:
What are the benefits vs costs of comment annotation in PHP?
I have just started working with symfony2 and have run across comment annotations.

Although comment annotation is not an inherent part of PHP, symfony2 adds support for this feature.

My understanding of commenting is that it should make the code more intelligible to the human.  The computer shouldn't care what is in comments.

What benefits come from doing this type of annotation versus just putting a command in the normal PHP code?

ie-

```<code>/**
 * @Route("/{id}")
 * @Method("GET")
 * @ParamConverter("post", class="SensioBlogBundle:Post")
 * @Template("SensioBlogBundle:Annot:post.html.twig", vars={"post"})
 * @Cache(smaxage="15")
 */
public function showAction(Post $post)
{
}
</code>```

答:
The costs can effectively be neglected as this is indeed translated to PHP code and then cached. So unless you change the code often it just runs the PHP code(which in theory might even be faster code than what you'd write from hand)

The reason for doing is that this is a nice and compact way of providing this information to the system, these 5 lines would require, written in PHP a few lines more and it nicely fit's next to the thing it is related to.

On the downside each abstraction brings cost and adds a source for new bugs (what if the parser has a bug or generates buggy code?)


答:
I think the easiest solution is the following:

First, calculate the center of the 4 points: center = (A + B + C + D)/4

Then calculate the vector A - center. Let this be v := (x,y)

Let v2 be the vector v rotated by 90 degrees: v2 := (-y, x)

Now the other points should be center - v, center + v2 and center - v2.

The advantage of this solution is that you don't have to use square roots at all.

Title: How to check if 4 points form a square?

Body: Assume I have 4 points (they are 2-dimension), which are different from each other, and I want to know whether they form a square. How to do it? (let the process be as simple as possible.)</p>


答: I have never found a better explanation of "how" or "why" to make time for this than Peter Norvig's "Teach Yourself Programming in 10 Years".  When I lose motivation for "making the time" -- as you pointed out, who doesn't?!? -- I just re-read his article and re-commit. :)  </p>


答:
Full stop is for ending sentences, but if a comment consists of just one sentence surrounded by code, then full stop is not necessary in my opinion. Sometimes I even don't capitalize the first letter. A detailed multiline comment, on the other hand, does need full punctuation.</p>

```<code>// This function returns an average of two integers. Note that it may
// return an irrelevant result if the sum of a and b exceeds the int
// boundaries.

int avg(int a, int b)   // make it static maybe?
{
    // A better algorithm is needed that never overflows
    return (a + b) / 2;
}
</code>```

Body:
Full stop is for ending sentences, but if a comment consists of just one sentence surrounded by code, then full stop is not necessary in my opinion. Sometimes I even don't capitalize the first letter. A detailed multiline comment, on the other hand, does need full punctuation.

// This function returns an average of two integers. Note that it may
// return an irrelevant result if the sum of a and b exceeds the int
// boundaries.

int avg(int a, int b)   // make it static maybe?
{
    // A better algorithm is needed that never overflows
    return (a + b) / 2;
}


问:
What kind of specific projects can I do to master bitwise operations in C++? Also is there a canonical book?
I don't use C++ or bitwise operations at my current job but I'm thinking of applying to companies where it is a requirement to be fluent with them (on their tests anyway).

So my question is: Can anyone suggest a project which will require gaining a fluency in bitwise operations to complete?

On a side note, is there a canonical book on optimization techniques using bitwise operations since that seems to be an important use of them?

答:
You'd hardly need a book to figure this out, only to know how numbers are represented in binary. Buy yourself a pad and pencil and draw some Truth Tables

As for a project, how about writing an algorithm that takes an image bitmap and draws/blits it transparently onto another image using masks. Allow the user to select the transparent colour.


答: There's no mystery to bitwise operations. Perhaps you're thinking of some of the crazy bit twiddling tricks that people have come up with over the years? For example, Stanford has a page with a long list of such tricks. Your best bet there is to just start with a list such as the one I linked and go through a number of them. Step through them in a debugger if it helps. Once you understand a handful of them, you'll get more comfortable thinking in those terms.</p>

Title: What kind of specific projects can I do to master bitwise operations in C++? Also is there a canonical book?

Body:
I don't use C++ or bitwise operations at my current job but I'm thinking of applying to companies where it is a requirement to be fluent with them (on their tests anyway).

So my question is: Can anyone suggest a project which will require gaining a fluency in bitwise operations to complete?

On a side note, is there a canonical book on optimization techniques using bitwise operations since that seems to be an important use of them?


答:
For those working as fulltime developers, what I am trying to understand is this - on most days, how much time in the office is spent actually grinding out code compared to learning/research. I could easily spend 2-4 hours daily getting on top of the best ways to go about doing things.

My company are very forward thinking and like to ensure we are developing against the latest technologies. They appreciate that as part of this they must give their developers time to get their heads around new features/APIs etc. For example, we recently switched to Richfaces 4 from Richfaces 3. A massive migration where we easily spent half our time just trying to understand the new landscape. If a company cannot commit to giving you some company time to keep on top of the latest developments then you could be in the wrong place.

Try getting your company to get a Safari Books license. It is a comprehensive resource of the best technical books out there. Including a series of rough cuts and work in progress. The web in general is a great resource too but the levels of ambient noise and mis-information is high.

Do most good developers who are employed full time invest significant
  hours outside of work sharpening their skills?

I also invest an hour or so each evening outside of work to keep up to date. Every now and then I will update my professional certifications too which does require extra commitment over weekends to achieve.

Again let your company know that you are doing this in your own time and see if they will pay for your exam fees or training. Or perhaps allow you to sit the exam on company time.


答:
Really? This isn't one of the answers yet?

Suggest to the boss that you've heard about newThing and that it could help the company, especially with hideousProblemWeJustHad. That's how I made my foray into unit testing. That's not super-cutting edge, but my school did a horrible job of teaching what it was all about and it was new to me. Part of the time of doing that was definitely researching how to do it right.

And while this is more or less out of your control, I often find myself learning new things just to do my job. I learned DO-178 and SQL because they were kind of mandatory for the task at hand. If you REALLY want to dive into new stuff, get a new job.

In short. Get paid to learn. Because there's an actual honest-to-god reason to use (some) of these new things. Because they're better. If they're better, the boss will want you to use them because it will help his bottom line. There's some overhead, sure. The learning process isn't instant and time is money, but if it isn't worth it, hey, maybe the new thing isn't all that much better. In that case, shitcan it.


问:
How to get familiar with "what happens underneath of Java"?
I did not study CS nor IT. I just became a developer, now working with Java. Actually, since I now work with a big company writing high-scalable web applications, I think I need to be better with details.

I have no understanding of what happens underneath of Java. Java Performance, Server-Side Java might be the buzz words?!! I am very poor with those more of low-level details but I do not know where to look honestly.

I started looking for some keywords in Amazon, ended up reading books like "pragmatic programmer", "clean code", "code complete" which IMO they are not what I am looking for.

Could you please give me some learning resources (books, articles, blog posts, online trainings) for this matter? I also read this post as well: Approaching Java/JVM internals
But I think I need a pre-step before jumping into the OpenJDK, right?!

答:
If you have a lot of time, learn C then read the textbook for a Computer Architecture class.

If that level of commitment is too big, read a book on Java performance tuning.  A good book will describe why a given parameter has a given effect, how objects are layed out in memory, how a generational garbage collector works, etc.


答:
Conceptualize & build your own projects.

Seriously. Everything thing I have learned has come from me coming up with some far-fetched idea then sitting down to try and figure it out. If you do this long enough, you will set yourself on a path of continual improvement.


答:
What you want to learn involves studying CS. You technically could learn about what the JVM is doing under the covers, but without some Compsci it will all be just a jumble.

The book I had in college for this topic was Programming Language Pragmatics, IIRC. It had a good overview of parsing, semantic analysis, and such but was still fairly gentle. The dragon book is also a classic on the subject, but will be less gentle in its approach.

It sounds to me, though, that you have reached the stage in your craft that you are looking into the realm of computer science, which is a big milestone. Go ahead, jump in, and enjoy the ride. :)

Title: How to get familiar with "what happens underneath of Java"?

Body:
I did not study CS nor IT. I just became a developer, now working with Java. Actually, since I now work with a big company writing high-scalable web applications, I think I need to be better with details.

I have no understanding of what happens underneath of Java. Java Performance, Server-Side Java might be the buzz words?!! I am very poor with those more of low-level details but I do not know where to look honestly.

I started looking for some keywords in Amazon, ended up reading books like "pragmatic programmer", "clean code", "code complete" which IMO they are not what I am looking for.

Could you please give me some learning resources (books, articles, blog posts, online trainings) for this matter? I also read this post as well: Approaching Java/JVM internals
But I think I need a pre-step before jumping into the OpenJDK, right?!


答: In addition to what has been said, I would add - "Have a plan".  I try to pick one or two technologies every 6 - 12 months, and set a goal of getting a deep understanding of these. Then I try to define actual tasks to get me there - say, read through a few online tutorials, pick a side project using that technology, start to follow new discussion sites (or subscribe to the new tags in StackOverflow), etc.  This doesn't require a ton of time, but consistency in moving forward a little each week.  (If you use a productivity system, such as GTD, your learning goals can be included in your normal project and goal planning, and reviewed regularly).</p>


问:
Software Manager who makes developers do Project Management
I'm a software developer working in an embedded systems company.
We have a Project Manager, who takes care of the overall project schedule (including electrical, quality, software and manufacturing) hence his software schedule is very brief.

We also have a Software Manager, who's my boss.
He makes me write and maintain the software schedule, design documents (high and low level design), SRS, change management, verification plans and reports, release management, reviews, and of course the software.

We only have one Test Engineer for the whole software team (10 members), and at any given time, there are a couple of projects going on.

I'm spending 80% of my time making these documents. My boss comes from a Process background, and believes what we need is better documentation to improve software:

He considers the design to be paramount, coding is "just writing the design down", it shouldn't take too long, and "all the code should be written before the hardware is ready".

Doesn't understand the difference between a Central & Distributed Version control, even after we told him its easier to collaborate with a distributed model.

Doesn't understand code, and wants to understand every bug and its proposed solution.

Believes verification should be done by developer, and validation by the Tester. Thing is though, our verification only checks if implementation is correct (we don't write unit tests, it's never considered in the schedule), and validation is black box testing, so the units tests are missing.

I'm really confused.

Am I responsible for maintaining all these documents? It makes me feel like I'm doing the Software Project Management, in essence. I'm ok with technical documentation, but I believe scheduling/planning should not be done by the developer.

I don't really like creating documents, I want to solve problems and write code. In my experience, creating design documents only helps to an extent, its never the solution to better or faster code.

I feel the boss doesn't really care about making better products, but only about being a good manager in the eyes of the management.

What can I do? This whole year I've done 3 months of actual coding, the rest just spent in making documents and waiting for bug reports from clients.

答:
To some degrees, I agree with your project manager. Software development goes well beyond coding features. :-)

Given your situation, I would go to him and explain that his requests are taking 80% of your time, and seek to understand why it is important for him that you spend this time maintaining documentation rather than developing (which goes beyond coding).

FYI, Atlassion, a software company, has a ratio of 13 developers for one QA person and most of the testing (planning and execution) is done by the developers. I learned this during one of their presentations at Agile 2012 and our teams I currently trying to emulate this practice.

However, I would also discuss with your project manager if he would be open to try out Scrum as a methodology to help move the whole team forward. Given your description, I don't think you are using Scrum.

Like you, I was extremely frustrated at maintaining plans that were constantly changing and a Scrum lightweight approach helped me overcome this frustration.

OwnerDisplayName: David Segonds


答:
You sound like a Software Engineer.

A Project Manager is more focused on the status of the overall project and allocating resources in an effective way to ensure that milestones are being met and in proper time.  They also remove roadblocks and help the project resources focus on their specific job functions.

Writing and maintaining design and technical documentation is an important part of being a software engineer and is appropriate for your role.  Too much of a good thing can be bad though (See Analysis Paraylsis ).

He considers the design to be paramount, coding is "just writing the design down"

If the project manager considers the design documents to be paramount then he expects the documents as a deliverable in the process.  It is not a wasted time on your part if he feels they are important enough to allocate 80% of your time to it.

it shouldn't take too long, and "all the code should be written before the hardware is ready".

This is wishful thinking and quite an antiquated Waterfall style view of how software development works.  It invariably is never that clean no matter how much design and preparation that you devote.  On that note however, you should have clear hardware specs and proper test environments and mock hardware simulations for your code to interact with but again, the real world is messy.

Project management is incredibly easy in a perfect world.  The world is not perfect however no matter how much you wish it to be so making real project management incredibly difficult.  This is why they are paid the big bucks.

(2) Doesn't understand the difference between a Central & Distributed Version control.

Why should he care?  How does it affect the milestones?  It doesn't.

3) Doesn't understand code, and wants to understand every bug and its proposed solution

His goal is for working software and yours should be too.  He does not need to understand the code but he does need to understand the issues that are preventing working software.  Once the two of you see eye to eye on this basic level then your mutual goal will help you work together more effectively.

(4) Believes verification should be done by developer, and validation by the Tester.

What is wrong with this sentiment?  Testers in the quality assurance role should be concerned with validating features and requirements.  Developers should make every effort to verify and test their work before it goes to testing.

I don't really like creating documents, I want to solve problems and write code.

If you would rather be a simple programmer then perhaps you should talk to your boss about this and see if there is a better role for you on the project.  Somebody needs to write and maintain the technical documentation, so perhaps one of the other developers can help you with some of these tasks so you aren't spending 80% of your time writing documentation.

In my experience, creating design documents only helps to an extent, its never the solution to better or faster code.

This is mostly true... but only if all ten developers are spending 80% of their time writing technical documentation that nobody will ever read.  This is an enormous management anti-pattern that I have lived in before.  If you find that you are doing most of the documentation for the team then it hardly seems fair that you are denied the right to perform more coding work.

The fact of the matter is that the best technical documentation is the code itself.

I feel the boss doesn't really care about making better products, but only about being a good manager in the eyes of the management

I feel that he does care because the product is his ward and if projects and features are not completed and clients aren't happy then upper management will not care for him very much.  The problem is that your perspective on the necessary quality improvements don't match with his, and upper management, and the clients perception of what they feel is important.

Try to understand what is truly important for the product, because while you can increase the efficiency of a process 3 fold, if you spend an entire week doing this then it is at the cost of another important feature that the client is demanding.

We all want to look good to the eyes of our superior.  There is nothing wrong with that, it is human nature to be self serving.  This is a fact of life.

Title: Software Manager who makes developers do Project Management

Body:
I'm a software developer working in an embedded systems company.
We have a Project Manager, who takes care of the overall project schedule (including electrical, quality, software and manufacturing) hence his software schedule is very brief.

We also have a Software Manager, who's my boss.
He makes me write and maintain the software schedule, design documents (high and low level design), SRS, change management, verification plans and reports, release management, reviews, and of course the software.

We only have one Test Engineer for the whole software team (10 members), and at any given time, there are a couple of projects going on.

I'm spending 80% of my time making these documents. My boss comes from a Process background, and believes what we need is better documentation to improve software:

He considers the design to be paramount, coding is "just writing the design down", it shouldn't take too long, and "all the code should be written before the hardware is ready".

Doesn't understand the difference between a Central & Distributed Version control, even after we told him its easier to collaborate with a distributed model.

Doesn't understand code, and wants to understand every bug and its proposed solution.

Believes verification should be done by developer, and validation by the Tester. Thing is though, our verification only checks if implementation is correct (we don't write unit tests, it's never considered in the schedule), and validation is black box testing, so the units tests are missing.

I'm really confused.

Am I responsible for maintaining all these documents? It makes me feel like I'm doing the Software Project Management, in essence. I'm ok with technical documentation, but I believe scheduling/planning should not be done by the developer.

I don't really like creating documents, I want to solve problems and write code. In my experience, creating design documents only helps to an extent, its never the solution to better or faster code.

I feel the boss doesn't really care about making better products, but only about being a good manager in the eyes of the management.

What can I do? This whole year I've done 3 months of actual coding, the rest just spent in making documents and waiting for bug reports from clients.


答:
There are a few issues that immediately come to mind with comment annotations (and, particularly, symfony2's format):

Developer Confusion The code you posted looks exactly like a DocBlock documentation comment. While the comments may be effectively interchangeable between the two meta-processors (each ignoring what they don't understand, or some using some other method of gracefully handling things), developers may or may not understand the purpose of a given comment, especially if they're not wholly familiar with one system or the other. Additionally, it opens the door to confusing annotations with documentation, which can lead to someone removing what they think is supposed to be documentation, but is actually "code".

Potential Meta-Processor Conflicts Because of the above, what happens if one or the other meta-processor decides to be more strict and not allow what it doesn't recognize? Now your processor breaks at every conceivable point. Requiring you to spend time cleaning up, and inevitably losing something of value in the process (including time, and either documentation or annotations). If it must be done in comments (see advantages), then I would have at least gone with a different indicator to distinguish it from the documentation standard (a good example is SASS/Compass comments vs standard CSS comments; CSS /**/ comments are sent through to the compiled CSS, while non-CSS comments // are eaten by the compiler; additionally, it makes it fairly easy to distinguish between the two, simply by looking at the first two characters).

Code/comment line-blurring In programming in general, code and comments are supposed to be separate. Code that's meant to be run shouldn't be in comments, usually for obvious reasons (because it doesn't run). You then start opening the door to doing other things inside comments, potentially pushing out the ability to actually comment, or having to jump through other hoops to distinguish between code-in-comment and actual comments (which will also increase compilation time/resources as the compiler has to go through more comments and determine whether they're meaningful, instead of just ignoring them all). Other alternatives I happened to see with a quick look on comments about Symfony's annotation, include C#'s style of wrapping angle brackets around annotations, Python's decorator style (basically what symfony already has, but not wrapped in comments), and probably just about any other style would be superior to doing it inside comments. (Or, to put it another way - It violates the "I don't need to look inside comments to find the source of bugs" rule.)

That said, doing something like this is not without its advantages.

Adding functionality that is not available natively in the language. First and foremost, this is probably the reason it's done this way by Symfony. PHP doesn't have decorators/annotations, and therefore, if you want that feature, you have to find a way to implement it. Even more, if you want it and don't want your users to be dependent on PHP extensions (because they can't always control that level of their environment), you have to find a way to do it internally that won't break the PHP compiler. Comments are the obvious choice.

Provide a clean way of adding various functionality to specific segments. Were I've seen annotations/decorators the most is Python, but you'll probably see it in a number of other languages, if you use them. For example, CherryPy uses it to expose functions as web page controllers (ie - a function with a specific decorator can be accessed by a browser, in the same way certain public functions in PHP controllers are accessed). They basically provide an "extension" capability to functions, or classes, offering utility features without cluttering the code inside the function.

Unfortunately, I don't know enough about Symfony to point out others with Symfony's format, but there's a lengthy discussion of the pros/cons of this in this Hacker News thread you might be interested in. You might also be interested in the request for change on the PHP site for native annotations.

Title: What are the benefits vs costs of comment annotation in PHP?

Body:
I have just started working with symfony2 and have run across comment annotations.

Although comment annotation is not an inherent part of PHP, symfony2 adds support for this feature.

My understanding of commenting is that it should make the code more intelligible to the human.  The computer shouldn't care what is in comments.

What benefits come from doing this type of annotation versus just putting a command in the normal PHP code?

ie-

```<code>/**
 * @Route("/{id}")
 * @Method("GET")
 * @ParamConverter("post", class="SensioBlogBundle:Post")
 * @Template("SensioBlogBundle:Annot:post.html.twig", vars={"post"})
 * @Cache(smaxage="15")
 */
public function showAction(Post $post)
{
}
</code>```


答:
Do you add periods (or, as the OP wrote, "full stops") in your code comments?

To keep it relevant, why?

For the same reason I add them when writing "normal" text - they are a part of the language in writing, and there shouldn't be anything special about them. I use them equally when writing one sentence (one line) comments as well as whole paragraphs.

Source code is not normal text, and therefore we use different rules for it. Simple ;-)


答:
Newsletters!

I currently write a newsletter called Pycoder's Weekly a weekly newsletter for python developers which covers the weekly happens in various topics within python which is very topical to a certain area you might want to keep up with.

That really wasn't intended to be a plug.

I think this medium serves itself very well to keeping up with things and is an excellent resource for many developers.

There are many for various languages and tools, have to trudge through tons of news and find interesting things can be time consuming and extremely distracting.

Body:
I was a freelance web developer until circa 2004 when I started going down the management route but have decided to try to get back into development again (specifically JavaScript and HTML5 web/mobile web apps) and I really get the impression to be truly good at these and similar fast moving technologies a constant amount of time is required to be set aside to invest in getting better at existing skills in addition to learning new skills.

I understand right now since I am getting back into things there is a pretty steep learning curve, but seeing how good many guys are out there - the only way I see of getting up there is putting in a serious amount of time.

For those working as fulltime developers, what I am trying to understand is this - on most days, how much time in the office is spent actually grinding out code compared to learning/research. I could easily spend 2-4 hours daily getting on top of the best ways to go about doing things.

Do most good developers who are employed full time invest significant hours outside of work sharpening their skills?

Or maybe I'm looking at all of this completely wrong?


答:
Some of the answers suggest a bottom up approach (learn CS or some close equivalent).

You could spend a year plus learning CS and still not have an answer to “what happens underneath of Java”?

Whilst I am of a CS background, I had similar questions about .NET.
These are the things I have done to bring my knowledge of .NET up to scratch.

Implement my own basic class.  Simple use case, implemented a LinkedList for IEnumerable<T>, Iterable<T>.

Compare my implementation with Microsoft's/Oracle.  You'll find a lot of things they take into consideration that you did not.

Read about the topic.  For e.g. if you're implementing your own Map / IDictionary<TKey, TValue>, what is the best bucket size?  Why should the bucket size be a prime number?  What's a good HashCode() fuction implementation?  When do you resize the bucket?

Performance, compare your implementation and the native implementation.  It will likely lead you down the route of bounds checking, Closable / IDisposable, garbage collection & its generations.

"Academic" papers, once you've exhausted the above, you can learn a lot more detail from academic papers.  E.g. dated Paper on IO in Windows & .NET, or Patterns of Parallel Programming.

There is bound to be some decent interview questions you've come across, try implementing an answer and look for the most efficient one.  They'll generally test your knowledge (depth and breadth) as a good measure of progress.

Implementing a collection is just an example.  Could easily be an algorithm (BinarySearch) or an IO library.

To address the absence of Computer Science, I've stuck "Computer Science Moudles" in google, loads of good hits

In no particular order, aim to cover java classes that touch on these topics,

Abstract Data Structures

Algorithms

Software Engineering (design patterns), interesting to see how they're used in a good open source project for e.g.

Human Computer Interaction

Operating System (think the java side of processor / memory / IO, threads / GC etc...)


答: You can also join the Adopt OpenJDK programme that's run by Java User Groups around the world to help people ease into the world of OpenJDK.  See http://adoptopenjdk.java.net for details.</p>


问:
Is static universally "evil" for unit testing and if so why does Resharper recommend it?
I have found that there are only 3 ways to unit test (mock/stub) dependencies that are static in C#.NET:

Moles

TypeMock

JustMock

Given that two of these are not free and one has not hit release 1.0, mocking static stuff is not too easy.

Does that make static methods and such "evil" (in the unit testing sense)?  And if so, why does resharper want me to make anything that can be static, static? (Assuming resharper is not also "evil".)

Clarification:
I am talking about the scenario when you want to unit test a method and that method calls a static method in a different unit/class.  By most definitions of unit testing, if you just let the method under test call the static method in the other unit/class then you are not unit testing, you are integration testing.  (Useful, but not a unit test.)

答: I see that after long time no one has yet stated a really simple fact. If resharper tells me that I can make a method static, it means a huge thing to me, I can hear his voice tell me: "hey, you, these pieces of logic are not current class's RESPONSIBILITY to handle, so it should stay out in some helper class or something".</p>


问:
How do web-developers do web-design when freelancing?
So I got my first job recently as junior web-developer.

My company creates small/medium sites for wide variety of customers: autobusiness companies, weddign agencies, some sauna websites, etcetc, hope you get my point. They don't do big serious stuff like bank systems or really big systems, it's mostly small/medium-sized websites for startups/medium sized business.
My main skills are PHP/MySQL, I also know HTML and a bit of CSS/JS/AJAX.
I know that good web-developer must know some backend language (like PHP/Ruby/Python) AND HTML+CSS+JS+AJAX+JQuery combo.

However, I was always wondering. In my company we have web-designer. In other serious organisations I often see the same stuff: web-developers who create business-logic and web-designers, who create design.
As far as I know, after designers paint design of website they give it to developers either in PSD or sliced way, and developers put it together with logic, but design is NOT created by developers. Such separation seems very good for full-time job, but I am concerned with question how do freelance web-developers do websites?
Do most of them just pay freelance designers to create design for them? Or do some people do both?

Reason why I ask - I plan to start some freelancing in my free time after I get good at web-development. But I don't want to create websites with great business-logic but poor design. Neither I want to let someone else create a design for me. I like web-development very much and I am doing quite good, I like design aswell, even though I am a bit lost how to study it and get better at it.
But I am scared that going in both directions won't let me become expert, it seems like two totally different jobs and getting really good in both seems very hard. But I really want to do both. What should I do? Thank you!

答:
You have to determine if you are good at web design.  If you are not, and it sounds like you may not be, then you will need to hire a separate designer for your freelance work.

You will want to keep this in mind when bidding.

Additionally, design can be learned, to a certain extent, and you should see what you can learn from the designers you hire or designers at work.   You don't have to create things in Photoshop either, you can make them straight in HTML if that works for you.

Good luck.


答: Yes, Because comments are in English, and proper English uses punctuation.</p>


问:
Questioning pythonic type checking
I've seen countless times the following approach suggested for "taking in a collection of objects and doing X if X is a Y and ignoring the object otherwise"

```<code>def quackAllDucks(ducks):
  for duck in ducks:
    try:
      duck.quack("QUACK")
    except AttributeError:
      #Not a duck, can't quack, don't worry about it
      pass
</code>```

The alternative implementation below always gets flak for the performance hit caused by type checking

```<code>def quackAllDucks(ducks):
  for duck in ducks:
    if hasattr(duck,"quack"):
      duck.quack("QUACK")
</code>```

However, it seems to me that in 99% of scenarios you would want to use the second solution because of the following:

If the user gets the parameters wrong then they will not be treated like a duck and there will be no indication.  A lot of time will be wasted debugging why there is no quacking going on until the user finally realizes his silly mistake.  The second solution would throw a stack trace as soon the user tried to quack.

If the user has any bugs in their quack() method which cause an AttributeError then those bugs will be silently swallowed.  Once again time will be wasted digging for the bug when the second solution would simply give a stack trace showing the immediate issue.

In fact, it seems to me that the only time you would ever want to use the first method is when:

The block of code in question is in an extremely performance critical section of your application.  Following the principal of "avoid premature optimization" you would only realize this of course, after you had implemented the safer approach and found it to be a bottleneck.

There are many types of quacking objects out there and you are only interested in quacking objects that quack with a very specific set of arguments (this seems to be a very rare case to me).

Given this, why is it that so many people prefer the first approach over the second approach?  What is it that I am missing?

Also, I realize there are other solutions (such as using abcs) but these are the two solutions I seem to see most often for the basic case.

答:
The reason you should use the first version is performance. Raising an exception is most often cheaper than calling a method or a function.

The first argument you present for using the second version is not quite valid, since using if hasattr(duck, 'quack'): also would silently prevent the call to duck.quack() and no exception would be raised.

Your second argument only applies because your implementation is not correct. You should instead do it like so:

```<code>def quackAllDucks(ducks):
  for duck in ducks:
    try:
      duck.quack
    except AttributeError:
      #Not a duck, can't quack, don't worry about it
      continue
    duck.quack("QUACK")
</code>```

Then any exception raised inside of duck.quack() would be propagated to the caller of quackAllDucks().

[EDIT]

delnan raised a good question in his comment below. It lead me to further investigate, and the recomended way now seems to be to use hasattr().

But the best solution is probably to design your program so that it doesn't depend on such tests. As Steve Oualline said, "If we don't write code like this, then we don't have to worry about such questions".

Title: Questioning pythonic type checking

Body:
The reason you should use the first version is performance. Raising an exception is most often cheaper than calling a method or a function.

The first argument you present for using the second version is not quite valid, since using if hasattr(duck, 'quack'): also would silently prevent the call to duck.quack() and no exception would be raised.

Your second argument only applies because your implementation is not correct. You should instead do it like so:

def quackAllDucks(ducks):
  for duck in ducks:
    try:
      duck.quack
    except AttributeError:
      #Not a duck, can't quack, don't worry about it
      continue
    duck.quack("QUACK")

Then any exception raised inside of duck.quack() would be propagated to the caller of quackAllDucks().

[EDIT]

delnan raised a good question in his comment below. It lead me to further investigate, and the recomended way now seems to be to use hasattr().

But the best solution is probably to design your program so that it doesn't depend on such tests. As Steve Oualline said, <a href="http://books.google.de/books?id=4miO-X83hmUC&pg=PA80&lpg=PA80&dq=%22Steve%20Oualline%22%20%20%22If%20we%20don%27t%20write%20code%20like%20this,%20then%20we%20don%27t%20have%20to%20worry%20about%20such%20questions%22&source=bl&ots=EBBFmQqn8G&sig=CQW9Tzym6zy5rzOKLTYfm0nIlLI&hl=de&sa=X&ei=SLu3UIGnA42P4gS2tYDQDw&ved=0CC0Q6AEwAA#v=onepage&q=%22Steve%20Oualline%22%20%20%22If%20we%20don%27t%20write%20code%20like%20this,%20then%20we%20don%27t%20have%20to%20worry%20about%20such%20questions%22&f=false" rel="nofollow noreferrer">"If we don't write code like this, then we don't have to worry about such questions".


答:
The most performant teams in my experience were those that faced the least amount of process necessary to do their work. At some point additional process starts taking away quality from the product. If QA starts to miss bugs because they are more concerned with getting paperwork out of the way, and DEV isn't coding features or fixing bugs because they are writing documentation then you have a problem. However, figuring out of if this is actually the case in your company is a highly localized question that only people on your team can answer (not us).

There is one thing that your boss is very wrong about, and that is the fact that you have so little QA and no unit tests. A bug created by adeveloper is by definition an oversight on their part. Expecting developers to always test their own features and having little testing aside from that is a process problem. QA can be replaced by automated testing depending on your domain to an extent, but if you have neither then you're probably letting bugs slip through (and that usually ends up costing more than finding them early).

Also, from a strict business perspective, hiring QA is cheaper than hiring developers. You will be able to cover more ground for the money spent if the teams have a good QA/DEV ratio.


答: The problem is there is no difference between the two.  duck.quack() calls __ getattr__ to look up the quack attribute then attempts to invoke what comes back.  hasattr makes the same __ getattr__ function call then returns false if it throws an exception.  So basically the second version is identical to the first version except you have a double look up of the quack attribute.</p>

Title: Questioning pythonic type checking

Body:
I've seen countless times the following approach suggested for "taking in a collection of objects and doing X if X is a Y and ignoring the object otherwise"

```<code>def quackAllDucks(ducks):
  for duck in ducks:
    try:
      duck.quack("QUACK")
    except AttributeError:
      #Not a duck, can't quack, don't worry about it
      pass
</code>```

The alternative implementation below always gets flak for the performance hit caused by type checking

```<code>def quackAllDucks(ducks):
  for duck in ducks:
    if hasattr(duck,"quack"):
      duck.quack("QUACK")
</code>```

However, it seems to me that in 99% of scenarios you would want to use the second solution because of the following:

If the user gets the parameters wrong then they will not be treated like a duck and there will be no indication.  A lot of time will be wasted debugging why there is no quacking going on until the user finally realizes his silly mistake.  The second solution would throw a stack trace as soon the user tried to quack.

If the user has any bugs in their quack() method which cause an AttributeError then those bugs will be silently swallowed.  Once again time will be wasted digging for the bug when the second solution would simply give a stack trace showing the immediate issue.

In fact, it seems to me that the only time you would ever want to use the first method is when:

The block of code in question is in an extremely performance critical section of your application.  Following the principal of "avoid premature optimization" you would only realize this of course, after you had implemented the safer approach and found it to be a bottleneck.

There are many types of quacking objects out there and you are only interested in quacking objects that quack with a very specific set of arguments (this seems to be a very rare case to me).

Given this, why is it that so many people prefer the first approach over the second approach?  What is it that I am missing?

Also, I realize there are other solutions (such as using abcs) but these are the two solutions I seem to see most often for the basic case.


答:
I've been practicing design and learning how to use digital design tools myself in my spare time. I haven't been doing it with the idea that my design skills will match my development skills (at least not in the short term), but just so that I can grow as a person. I wouldn't recommend taking on a design task yourself, either bring a full-time designer along to supplement your skills or look at some of the alternatives.

There are templates available for purchase from various websites.

You can also go to freelance sites and hire a subcontrator.

There are a lot of small "rent a suite" office buildings targetted toward freelancers. I was able to find a web designer to work with when I rented an office. (Even better we were able to work on projects together that neither of us could have handled individually).

Finally, there are sites like 99Designs that let you create a design project, set a price, wait for the results to come in and choose the best one (or let your client do the choosing).

I would argue that this approach should be used with many of the decisions regarding a small business. Yes you COULD manage your accounting yourself, or you can pay an accountant to do it for you. Remember the time you spend doing things that aren't part of your core skills end up costing more than the savings of paying someone else to do them.

Title: How do web-developers do web-design when freelancing?

Body:
So I got my first job recently as junior web-developer.

My company creates small/medium sites for wide variety of customers: autobusiness companies, weddign agencies, some sauna websites, etcetc, hope you get my point. They don't do big serious stuff like bank systems or really big systems, it's mostly small/medium-sized websites for startups/medium sized business.
My main skills are PHP/MySQL, I also know HTML and a bit of CSS/JS/AJAX.
I know that good web-developer must know some backend language (like PHP/Ruby/Python) AND HTML+CSS+JS+AJAX+JQuery combo.

However, I was always wondering. In my company we have web-designer. In other serious organisations I often see the same stuff: web-developers who create business-logic and web-designers, who create design.
As far as I know, after designers paint design of website they give it to developers either in PSD or sliced way, and developers put it together with logic, but design is NOT created by developers. Such separation seems very good for full-time job, but I am concerned with question how do freelance web-developers do websites?
Do most of them just pay freelance designers to create design for them? Or do some people do both?

Reason why I ask - I plan to start some freelancing in my free time after I get good at web-development. But I don't want to create websites with great business-logic but poor design. Neither I want to let someone else create a design for me. I like web-development very much and I am doing quite good, I like design aswell, even though I am a bit lost how to study it and get better at it.
But I am scared that going in both directions won't let me become expert, it seems like two totally different jobs and getting really good in both seems very hard. But I really want to do both. What should I do? Thank you!


问:
How to deal with well-meaning open-source contributors?
If a programmer contacts you and asks to contribute to your project, how do you handle it?

You don't know if this guy is any good. Perhaps he'll be more trouble than he's worth.

He might be trying to attach his name to a successful project just for the kudos.

He might be trying to take the project in a direction you don't really want, adding features you think aren't worth the extra complexity.

Or, he might be a very useful contributor. You just don't know.

How do you handle such requests from people you don't know (On GitHub, specifically, if that makes any difference)? What's the etiquette here?

答: Why not let this eager person send you a pull request? You'll have the opportunity to review and critique that person's code. This seems like the simplest solution.</p>


答: Accept and review changes from him on a provisional basis.  Give him write access to the source code repository when he's proven his worth.</p>

Title: How to deal with well-meaning open-source contributors?

Body:
If a programmer contacts you and asks to contribute to your project, how do you handle it?

You don't know if this guy is any good. Perhaps he'll be more trouble than he's worth.

He might be trying to attach his name to a successful project just for the kudos.

He might be trying to take the project in a direction you don't really want, adding features you think aren't worth the extra complexity.

Or, he might be a very useful contributor. You just don't know.

How do you handle such requests from people you don't know (On GitHub, specifically, if that makes any difference)? What's the etiquette here?


答:
The answer is simple, try to use the latest technologies at work, and if you can't, do side projects

But to save time you need to first know what to learn so your time is well spent.

This is what worked for me

Hacker news, but one needs to be careful, searching periodically for keywords works for me

GitHub - see the list of most starred and forked projects, this is almost always in sync with reality

Stackoverflow - see the most trending tags and questions

Google trends (but you need to know what to look for first)

Indeed job trends (this is how I learned about MongoDB for example)

Meetups (very good source)

Twitter - follow fellow hackers you respect, I often learned of new stuff that way

Coderwall, Geeklist and other hacker dedicated social networks help sometimes too

Conferences - most of them are now online recorded after the fact or live

Or, you can simply create a new technology yourself :)

Second part is how to learn it effectively so you use your time effectively

I found udacity, coursera, codeschool, codecademy, teamtreehouse, edx.org, udemy, net tuts+ and others to be great resources since their courses tend to keep up with latest technology

On the other hand you can end up in an information explosion and rant about it like I had before: http://tilomitra.com/the-crazy-world-of-code/


问:
Why was support for Windows XP dropped in PHP 5.5?
In the release notes for PHP 5.5.0 it's announced that Windows XP and Windows 2003 are not supported anymore:

Drop Windows XP and 2003 support. (Pierre)

Why is this? Many people in different companies develop applications under Windows XP.

So, can anyone tell me what is the sense of dropping Windows XP and 2003 support?

答:
Windows XP and Windows 2003 are very near their end of life, Microsoft has already announced that they will stop supporting both products on April 8, 2014.

PHP is an open source project supported mostly by volunteers, it wouldn't make sense to support every legacy system there is ad infinitum. Both systems are about a decade old, and while people may still use them, I see absolutely no reason for PHP to continue supporting them.

You always have the option of forking PHP 5.5 and adding support for either system if you want.


问:
What build tools do not depend on java (or Ruby)?
I'm wondering what generic build tools out there include their binary run-times and do not depend on another environment not shipped with them.

For example, ANT requires Java, Rake requires Ruby, etc..

would be great if talking about also target-platform-agnostic tools, where I'd just give whatever command for building, whatever command for testing, etc.. and can then define my artifacts in CI or so.

Would see something like that useful for building .NET projects (say, on both Windows .NET and  Mono), and Node JS projects especially. I do not want to install Java and / or Ruby if what I want is a .NET build or a Node JS build.

This is a bit of general awareness question not an exact problem I'm facing, that's why it's here not on StackOverflow.

Update:

To explain a bit more,  what I'm after is the build script that would run MSBuild for compiling for example ( in .NET, and then maybe several Node/NPM commands in Node, etc..), and then have the rest build/test steps, instead of setting these all in MSBuild (again, in .NET case, also, wondering if there is equivalent story in Node).

Update2:

My target is being able to have a developer on a vanilla machine to just clone the code without installing any dependencies except the platform the code targets be it .NET/Mono or Node (not even Java, Ruby, or Python) and still be able to build and run tests.

答: Since you specifically called out Node.js as a platform target, I assume that everyone has that installed on their machines.  In that case, have you looked at Grunt?  I don't have any real experience with it (I downloaded it, tried making a script, then realized that NPM does most of what I needed), but it appears to be a flexible build tool written on Node.  </p>


问:
How do you get your product owner more engaged on agile projects?
During iteration retrospectives on agile projects, one of the topics that comes up most often for us is that the product owner is (or product owners are) not available or engaged in the project at a day to day level.

It seems to be a common theme that customers are unwilling to "give up" the necessary amount of their product owner's time to the project, but instead have them answer questions via email, or during product demos only. This has the effect of increasing the length of the feedback cycle and making the project less effective.

Have you had to overcome this hurdle? How did you do it?

答:
If the product owner is too busy be available to the team, that means that they aren't convinced that such time isn't productive towards the success of the project, or that the product owner doesn't care about the success of the project.

Presuming the former, it's your job to show the product owner how responsive an agile team can be to suggestions made by the product owner.  If you can demo changes in the software that were in response to his comments and suggestions, he may come to understand why his involvement is in his best interest.

Above all, don't try to tell the product owner that this is what you need.  Agile development is about solving his problems, don't let him think for a minute agile means that he has to solve your problems.


答:
Dropping support for 10 year old systems means one can use more modern and efficient APIs and options.

One area (among others) is around the TCP/IP stack. Windows Vista introduced a  new stack and kept old APIs for compatibility. By using the new APIs PHP can get better preforming results in some areas. (Sample for that: https://github.com/php/php-src/commit/94994104a54a57ee3ff2a143a1f6c43850589378)

Another thing is that due to the way Windows works and due to the fact that people don't compile PHP themselves specifically for the platform there are a few runtime decisions depending on the windows version to enable or disable specific features. By dropping support for old systems the code can be made simpler to maintain.

Title: Why was support for Windows XP dropped in PHP 5.5?

Body:
In the release notes for PHP 5.5.0 it's announced that Windows XP and Windows 2003 are not supported anymore:

Drop Windows XP and 2003 support. (Pierre)

Why is this? Many people in different companies develop applications under Windows XP.

So, can anyone tell me what is the sense of dropping Windows XP and 2003 support?


问:
What's special about currying or partial application?
I've been reading articles on Functional programming everyday and been trying to apply some practices as much as possible. But I don't understand what is unique in currying or partial application.

Take this Groovy code as an example:

```<code>def mul = { a, b -> a * b }
def tripler1 = mul.curry(3)
def tripler2 = { mul(3, it) }
</code>```

I do not understand what is the difference between tripler1 and tripler2. Aren't they both the same? The 'currying' is supported in pure or partial functional languages like Groovy, Scala, Haskell etc. But I can do the same thing (left-curry, right-curry, n-curry or partial application) by simply creating another named or anonymous function or closure that will forward the parameters to the original function (like tripler2) in most languages (even C.)

Am I missing something here? There are places where I can use currying and partial application in my Grails application but I am hesitating to do so because I'm asking myself "How's that different?"

Please enlighten me.

EDIT:
Are you guys saying that partial application/currying is simply more efficient than creating/calling another function that forwards default parameters to original function?

答:
As @jk. alluded to, currying can help make code more general.

For example, suppose you had these three functions (in Haskell):

```<code>> let q a b = (2 + a) * b

> let r g = g 3

> let f a b = b (a 1)
</code>```

The function f here takes two functions as arguments, passes 1 to the first function and passes the result of the first call to the second function.

If we were to call f using q and r as the arguments, it'd effectively be doing:

```<code>> r (q 1)
</code>```

where q would be applied to 1 and return another function (as q is curried); this returned function would then be passed to r as its argument to be given an argument of 3. The result of this would be a value of 9.

Now, let's say we had two other functions:

```<code>> let s a = 3 * a

> let t a = 4 + a
</code>```

we could pass these to f as well and get a value of 7 or 15, depending on whether our arguments were s t or t s. Since these functions both return a value rather than a function, no partial application would take place in f s t or f t s.

If we had written f with q and r in mind we might have used a lambda (anonymous function) instead of partial application, e.g.:

```<code>> let f' a b = b (\x -> a 1 x)
</code>```

but this would have restricted the generality of f'. f can be called with arguments q and r or s and t, but f' can only be called with q and r -- f' s t and f' t s both result in an error.

MORE

If f' were called with a q'/r' pair where the q' took more than two arguments, the q' would still end up being partially applied in f'.

Alternatively, you could wrap q outside of f instead of inside, but that'd leave you with a nasty nested lambda:

```<code>f (\x -> (\y -> q x y)) r
</code>```

which is essentially what the curried q was in the first place!

Body:
As @jk. alluded to, currying can help make code more general.

For example, suppose you had these three functions (in Haskell):

> let q a b = (2 + a) * b

> let r g = g 3

> let f a b = b (a 1)

The function f here takes two functions as arguments, passes 1 to the first function and passes the result of the first call to the second function.

If we were to call f using q and r as the arguments, it'd effectively be doing:

> r (q 1)

where q would be applied to 1 and return another function (as q is curried); this returned function would then be passed to r as its argument to be given an argument of 3. The result of this would be a value of 9.

Now, let's say we had two other functions:

> let s a = 3 * a

> let t a = 4 + a

we could pass these to f as well and get a value of 7 or 15, depending on whether our arguments were s t or t s. Since these functions both return a value rather than a function, no partial application would take place in f s t or f t s.

If we had written f with q and r in mind we might have used a lambda (anonymous function) instead of partial application, e.g.:

> let f' a b = b (\x -> a 1 x)

but this would have restricted the generality of f'. f can be called with arguments q and r or s and t, but f' can only be called with q and r -- f' s t and f' t s both result in an error.

MORE

If f' were called with a q'/r' pair where the q' took more than two arguments, the q' would still end up being partially applied in f'.

Alternatively, you could wrap q outside of f instead of inside, but that'd leave you with a nasty nested lambda:

f (\x -> (\y -> q x y)) r

which is essentially what the curried q was in the first place!


答: I think all code is guaranteed to terminate, since eventually entropy will eliminate all energy differentials, making it impossible for logic circuits to change state.  However, one of the attributes of a truly random number generator is that it may never produce a particular number, just as it may produce infinitely-long runs of one particular number.  So the answer to your question is "yes, but not because it meets your exit criterion".

Title: Is code that terminates on a random condition guaranteed to terminate?

Body:
If I had a code which terminated based on if a random number generator returned a result (as follows), would it be 100% certain that the code would terminate if it was allowed to run forever.

```<code>while (random(MAX_NUMBER) != 0): // random returns a random number between 0 and MAX_NUMBER
   print('Hello World')
</code>```

I am also interested in any distinctions between purely random and the deterministic random that computers generally use. Assume the seed is not able to be known in the case of the deterministic random.

Naively it could be suggested that the code will exit, after all every number has some possibility and all of time for that possibility to be exercised. On the other hand it could be argued that there is the random chance it may not ever meet the exit condition-- the generator could generate 1 'randomly' until infinity.

(I suppose one would question the validity of the random number generator if it was a deterministic generator returning only 1's 'randomly' though)