答: I suggest to study the xUnit Framework along with the implementation. It's a mature product with clean architecture and extremely tidy source code. Also it comes with a full pack of unit tests, so you can achieve several goals at once: deeply learning a unit testing framework, looking at the examples of applied design patterns, and seeing how to write tests for them.</p>

Title: C# Open Source software that is useful for learning Design Patterns

Body:
In college I took a class in Expert Systems.  The language the book taught (CLIPS) was esoteric - Expert Systems: Principles and Programming, Fourth Edition.  I remember having a tough time with it.  So, after almost failing the class, I needed to create the most awesome Expert System for my final presentation.  I chose to create an expert system that would calculate risk analysis for a person's retirement portfolio.  In short, the system would provide the services normally performed by one's financial adviser. In other words, based on personality, age, state of the macro economy, and other factors, should one's portfolio be conservative, moderate, or aggressive?

In the appendix of the book (or on the CD-ROM), there was this in-depth example program for something unrelated to my presentation.  Over my break, I read and re-read every line of that program until I understood it to the letter.  Even though it was unrelated, I learned more than I ever could by reading all of the chapters.  My presentation turned out to be pretty damn good and I received praises from my professor and classmates.

So, the moral of the story is..., by understanding other people's code, you can gain greater insight into a language/paradigm than by reading canonical examples.  Still, to this day, I am having trouble with everyday design patterns such as the Factory Pattern.  I would like to know if anyone could recommend open source software that would help me understand the Gang of Four design patterns, at the very least.  I have read the books, but I'm having trouble writing code for the concepts in the real world.  Perhaps, by studying code used in today's real world applications, it might just "click".

I realize a piece of software may only implement one kind of design pattern.  But, if the pattern is an implementation you think is good for learning, and you know what pattern to look for within the source, I'm hoping you can tell me about it.

For example, the System.Linq.Expressions namespace has a good example of the Visitor Pattern.  The client calls Expression.Accept(new ExpressionVisitor()), which calls ExpressionVisitor (VisitExtension), which calls back to Expression (VisitChildren), which then calls Expression (Accept) again - wooah, kinda convoluted.  The point to note here is that VisitChildren is a virtual method.  Both Expression and those classes derived from Expression can implement the VisitChildren method any way they want.  This means that one type of Expression can run code that is completely different from another type of derived Expression, even though the ExpressionVisitor class is the same in the Accept method.  (As a side note Expression.Accept is also virtual).  In the end, the code provides a real world example that you won't get in any book because it's kinda confusing.

To summarize, If you know of any open source software that uses a design pattern implementation you were impressed by, please list it here.  I'm sure it will help many others besides just me.

```<code>public class VisitorPatternTest
{

    public void Main()
    {
        Expression normalExpr = new Expression();
        normalExpr.Accept(new ExpressionVisitor());
        Expression binExpr = new BinaryExpression();
        binExpr.Accept(new ExpressionVisitor());
    }
}

public class Expression
{
    protected internal virtual Expression Accept(ExpressionVisitor visitor)
    {
        return visitor.VisitExtension(this);
    }

    protected internal virtual Expression VisitChildren(ExpressionVisitor visitor)
    {
        if (!this.CanReduce)
        {
            throw Error.MustBeReducible();
        }
        return visitor.Visit(this.ReduceAndCheck());
    }

    public virtual Expression Visit(Expression node)
    {
        if (node != null)
        {
            return node.Accept(this);
        }
        return null;
    }

    public Expression ReduceAndCheck()
    {
        if (!this.CanReduce)
        {
            throw Error.MustBeReducible();
        }
        Expression expression = this.Reduce();
        if ((expression == null) || (expression == this))
        {
            throw Error.MustReduceToDifferent();
        }
        if (!TypeUtils.AreReferenceAssignable(this.Type, expression.Type))
        {
            throw Error.ReducedNotCompatible();
        }
        return expression;
    }

}

public class BinaryExpression : Expression
{
    protected internal override Expression Accept(ExpressionVisitor visitor)
    {
        return visitor.VisitBinary(this);
    }

    protected internal override Expression VisitChildren(ExpressionVisitor visitor)
    {
        return CreateDummyExpression();
    }

    protected internal Expression CreateDummyExpression()
    {
        Expression dummy = new Expression();
        return dummy;
    }
}

public class ExpressionVisitor
{
    public virtual Expression Visit(Expression node)
    {
        if (node != null)
        {
            return node.Accept(this);
        }
        return null;
    }

    protected internal virtual Expression VisitExtension(Expression node)
    {
        return node.VisitChildren(this);
    }

    protected internal virtual Expression VisitBinary(BinaryExpression node)
    {
        return ValidateBinary(node, node.Update(this.Visit(node.Left), this.VisitAndConvert<LambdaExpression>(node.Conversion, "VisitBinary"), this.Visit(node.Right)));
    }
}
</code>```


问:
How can I get my progress reviewed as a solo junior developer
I am currently working for a 2 person company, as the solo primary developer. My boss gets the clients, mocks up some png design templates and hands them over to me.

This system has been working fine and i'm really enjoying it.

The types of projects I work on are for small - medium sized businesses and they usually want a CMS system. Developed from scratch i'll build a customised backend for the client to add/edit/remove categories, tags, products etc and then output them to the front end according to the design template handed to me. As time has gone on, the projects have increased in complexity, with shopping cart / ordering features and other common e-commerce type features.

Again, this system has been working fine and i'm really enjoying it.

My issue is my personal development as a programmer. I spend a lot of my spare time reading programming blogs, checking through stackexchange, reading suggested programming books (currently on 'The Pragmatic Programmer', really good so far), doing brain exercises (lumosity.com and khanacademy math problems), doing lots of physical exercise and other personal development type activities.

I can't help but feel though, that I'm missing out on feedback, critique. My boss is great and never holds back on praise in regards to my work, but he unfortunately is either to busy to check my code, or to be honest, I don't think it's one of his specialties and so can't provide feedback.

I want to know what i'm doing wrong and what i'm doing right. Should I be putting that much logic in the controller, am I modulating my code enough etc.

So what I have done is developed a little 'Family Budgeting' app and tried to do it as cleanly and effectively as I currently know how.

What i'm wanting to know is, is there somewhere I can submit this app, and have some seasoned developers provide feedback. It's not just a subsection of my code like 'codereview.stackexchange' appears to require, it's my entire workflow that I want critiqued.

I know this is a lot to ask, and I expect the main advice given will be to look for a job within a team, which is certainly something I will look into later down the track, but for now I want to persist with my current employment situation, but just don't want to develop too many bad habits.

Let me know if I can provide any further information to help clarify, or if this isn't the right place for this type of question I apologise in advance. Didn't want to use reddit as I felt this community fosters more well thought out responses.

答:
Continue to read books, blogs and Stack Overflow Q&A. If you want to improve yourself in a more social way, why not engage work on an open source project? I don't mean create your own project, but work on an existing one.

As you are the only developer in this company, I imagine that it would be possible that someday, you will hire somebody else. Tell yourself that this day, the guy will have to read your code. Do you already write some documentation about your tool? Keeping in mind your work can be read by other people is a good thing for solo developers and help you to make better code.

ContentLicense: CC BY-SA 3.0


问:
Why would one bother marking up properly and semantically?

Note that I (try) to mark up as semantically as possible because I like they way it looks and feels, but not because I'm aware of any other stunning advantages. The point of my question is to be able to educate others

Well, I've seen a lot of articles and tutorials which often state "Let's mark this up in the most semantic possible way".

But a strange thought came to me, why?

Why would one need (or want) to bother with the specific elements which convey the correct semantic meaning? Specifically, I'm referring to the new HTML5 elements, such as <time>, <output>, or <address>. Especially, if the page "works" (it renders nicely in all browsers).

Why would I want to use elements like <time> or <address>, where nothing at all (or at the worst case, a generic ) works just as nicely?

I'm asking this because I'm seeing a multitude of (very popular) websites (this one included) which does not follow these so-called best practices.

答:
Because it can be useful or needed for crawlers and web services (AKA computers communicating with computers). If you write:

```<code><span class="time">Sep 16 at 2:17</span>
</code>```

...the web crawler will not necessary understand it as a date, an a time stuff. Or it will be much more difficult to locate it as a date information.

If you use:

```<code> <time datetime="2012-02-11 16:24:02">feb 11 2012 at 16:24:02</time>
</code>```

...it will be much more easier for any crawler to find and analyse the stuff.

When I say crawlers, I don't mean search engines necessarily :)

Body:
Because it can be useful or needed for crawlers and web services (AKA computers communicating with computers). If you write:

<span class="time">Sep 16 at 2:17</span>

...the web crawler will not necessary understand it as a date, an a time stuff. Or it will be much more difficult to locate it as a date information.

If you use:

 <time datetime="2012-02-11 16:24:02">feb 11 2012 at 16:24:02</time>

...it will be much more easier for any crawler to find and analyse the stuff.

When I say crawlers, I don't mean search engines necessarily :)


问:
Belkin device runs Linux, how can I create my own custom firmware for it?
The Belkin N300 F9K1002 firmware is located here. It does not appear to be encrypted. How can I upload my own custom Linux firmware to this device. How would I go about hacking it?</p>

答: On most other routers I have used, there's an admin console somewhere that has an "Update Firmware" link.  You click that, it opens a file browser window, you point it at the location of your firmware file and it takes care of everything.  You'll have to dissect the factory firmware package to see how it's structured, but it shouldn't be too hard to figure out how to add or replace stuff.</p>


问:
Having two sets of infrequently changing data or converting on the fly
I am currently working on a small project in which I work with some "static data", which is  extracted from one source. The data might change from time to time (up to once a week).
I don't need all of the information the data includes in my project so to allow easier and a more logical access to it I wrote some small tool that converts the extracted data into my desired format.

The conversion is mostly dropping data I don't need, and splitting some strings into arrays. No intensive calculations or anything. But, I drop more than 50% of the original data because their is no need for it.

Now since it is static data would it make more sense to just store that converted data and do all further operations from this data or would it make more sense to convert from the raw data on the fly?

Since the project is in JavaScript speed of course is important, but if converting on the fly has significant advantages it might make more sense to go with that approach.

It is static data from a computer game that defines several units and other objects within the game. They are stored in JSON therefore I can easily use them in JavaScript. But I don't need a lot of the information, just some parts of it to build a kind of "encyclopedia", now since the data is already present in JSON I was wondering if I should just use it or convert it before usage.

答: I would write a Data Conversion Process that Runs on a timer. (Once a Day or once a week.) Once the data it conversion is Complete, generate a JSON file from it drop it on you Web server, overwriting your previous JSON file .


答:
It sounds like you are leaning towards better performance, then you would rather store the data and make sure that you only update the stored version if any changes were made. Of course this approach can pose it's own challenges such as version control and keeping the data in sync if so desired.

If data integrity is of absolute importance you should rather convert on-the-fly and compromise a bit on performance.

Sit down and think what your application is supposed to do and what is more important to the people that will be using the software. Speed or data integrity?

Title: Having two sets of infrequently changing data or converting on the fly

Body:
I am currently working on a small project in which I work with some "static data", which is  extracted from one source. The data might change from time to time (up to once a week).
I don't need all of the information the data includes in my project so to allow easier and a more logical access to it I wrote some small tool that converts the extracted data into my desired format.

The conversion is mostly dropping data I don't need, and splitting some strings into arrays. No intensive calculations or anything. But, I drop more than 50% of the original data because their is no need for it.

Now since it is static data would it make more sense to just store that converted data and do all further operations from this data or would it make more sense to convert from the raw data on the fly?

Since the project is in JavaScript speed of course is important, but if converting on the fly has significant advantages it might make more sense to go with that approach.

It is static data from a computer game that defines several units and other objects within the game. They are stored in JSON therefore I can easily use them in JavaScript. But I don't need a lot of the information, just some parts of it to build a kind of "encyclopedia", now since the data is already present in JSON I was wondering if I should just use it or convert it before usage.


问:
Software Architecture - From design to sucessful implementation
As the subject goes; once a software architect puts down the high level design and approach to a software that is to be developed from scratch, how does the team ensure that it is implemented successfully? To my mind the following things will need to be done

Proper understanding of requirements

Setting down coding practices and guidelines

Regular code reviews to ensure the guidelines are being adhered to

Revisiting the requirements phase and making necessary changes to design based on client inputs if there are any changes to requirements

Proper documentation of what is being done in code

Proper documentation of requirements and changes to them

Last but not the least, implementing the design via object oriented code where appropriate

Did I miss anything?

Would love to hear any mistakes that you have learned from in your project experiences. What went wrong, what could have been done better.

Thanks for taking the time..

答:
From your list: "Implement the design via object oriented code" Absolutely no. You implement the design with the best tool that can be used for that specific problem. It that means using a functional programming language so be it. Otherwise OO is a hammer for the screws of your project.

Additional

Involve the user (very important). In fact, all stakeholders.

Release early, Release often.

A branching strategy

Unit test, Integration test, any kind of testing


问:
How should I get my code ready for OpenSourcing it and putting it on GitHub?
In a few weeks, my project is going to be finished and I want to start getting my code ready for other people to use it.

I am going to be posting everything to GitHub so people can tweak it and hopefully make it better.

I guess what I'm asking is, what would be the best way to make sure my code is sufficiently documented and worded right for other people to use?

I know you should always comment everything and I'm going to be putting in the @params feature for every method, but are there any other tips in general?

答:
Make sure there is a README.txt file in the root of the repository that points people to instructions on how to build it. The instructions could be in that file, or they could be in a separate file or wiki page.

Ideally, make it so that you can completely build and test the code with a single command. Don't require a bunch of manual steps.

Make sure you have tests for the code. This provides a convenient place for other developers to see how your code is used, plus it provides a safety net for people who modify your code. Knowing I can edit your code and then run a suite to see if I broke something is invaluable.

Follow common coding standards, or publish the ones you use.

If your code uses OO, make sure at least all public methods and attributes have sufficient documentation

Make sure it's clear what license your code uses. Typically this means to include a LICENSE.txt file, or follow whatever mechanism your specific license requires. Also, make a conscious choice about the license. Don't just use GPL because that's all you know. Likewise, don't just use BSD or MIT or Apache if that's all you're familiar with... spend an hour researching those so you at least understand the fundamental difference between GPL and non-GPL licenses.

Remove all sensitive information from the code, such as hard-coded usernames, passwords, email addresses, ip addresses, API keys, etc. (thanks to Hakan Deryal for the suggestion)


问:
What role does .ini play?
I am working with a MFC application for the first time and I have lots of doubts the biggest at the moment is What is .ini file and why is it there? What exactly is the role it plays? Can some tell me the required?

Edit : What if I make an application and do not have .ini file, what do I loose on?

答:
Old and recent softwares use INI files, like OpenOffice.org and Mercurial.
The problem of the INI format is simple : there is no standard. Some implementations allow advanced features (key references, Unicode support, etc), others not.

If you want a Properties file with "sections" (like "[foo]"), INI is a good choice.
It has the same role as Properties, CFG, CONFIG, XML, PO, etc.

Title: What role does .ini play?


答:
Documentation in source file is always good, but you should publish additional documentation  on a website. Explain its goal, how it works, your future plans, try to make contribution easy (otherwise... nobody will help you) and put some tutorials.

Trying to work on a project with source code documentation only is always frustrating.

Title: How should I get my code ready for OpenSourcing it and putting it on GitHub?

Body:
In a few weeks, my project is going to be finished and I want to start getting my code ready for other people to use it.

I am going to be posting everything to GitHub so people can tweak it and hopefully make it better.

I guess what I'm asking is, what would be the best way to make sure my code is sufficiently documented and worded right for other people to use?

I know you should always comment everything and I'm going to be putting in the @params feature for every method, but are there any other tips in general?


问:
If immutable objects are good, why do people keep creating mutable objects?
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.

答:
Programming languages are designed for execution by computers. All important building blocks of computers - CPU's, RAM, cache, disks - are mutable. When they aren't (BIOS), they're really immutable and you can't create new immutable objects either.

Hence, any programming language built on top of immutable objects suffers from a representation gap in its implementation. And for early languages such as C, that was a big stumbling block.


答:
I guess what I'm asking is, what would be the best way to make sure my code is sufficiently documented and worded right for other people to use?

As open source, the most important comments of all are the copyright and license agreement comment. Rather than a big long comment at the start of every file, you might want to use a short and sweet one that briefly specifies copyright and refers the reader to license.txt in the root directory.

I know you should always comment everything and I'm going to be putting in the @params feature for every method, but are there any other tips in general?

Comment everything? No. Comment that code which truly does need commentary. Comment sparingly. As a potential user of a chunk of code, which of the following two versions of a class definition would you prefer to see?

Version A:

```<code>class Foo {
private:
   SomeType some_name; //!< State machine state

public:
   ...

   /**
    * Get the some_name data member.
    * @return Value of the some_name data member.
    */
   SomeType get_some_name () const { return some_name; }

   ...
};
</code>```

Version B:

```<code>/**
 * A big long comment that describes the class. This class header comment is very
 * important, but also is the most overlooked. The class is not self-documenting.
 * Why is that class here? Your comments inside the class will say what individual parts
 * do, but not what the class as a whole does. For a class, the whole is, or should be,
 * greater than the parts. Do not forget to write this very important comment.
 */
class Foo {
private:

   /**
    * A big long comment that describes the variable. Just because the variable is
    * private doesn't mean you don't have to describe it. You might have getters and
    * setters for the variable, for example.
    */
   SomeType some_name;

public:
   ...

   // Getters and setters
   ...

   // Getter for some_name. Note that there is no setter.
   SomeType get_some_name () const { return some_name; }

   ...
</code>```

};

In version A I've documented everything -- except the class itself. A class in general is not self-documenting. The comments that are present in version A are absolutely useless, or even worse than useless. That's the key problem with the "comment everything" attitude. That little terse comment on the private data member communicates nothing, and the doxygen comments on the getter has negative value.  The getter get_some_name() doesn't really need a comment. What it does and what it returns is patently obvious from the code. That there is no setter -- you have to infer that because it's not there.

In version B I've documented that which needs commenting. The getter doesn't have a doxygen comment, but it does have a comment mentioning that there is no setter.

Make your comments count, and beware that comments oftentimes are not maintained to reflect changes to the code.

Body:
I guess what I'm asking is, what would be the best way to make sure my code is sufficiently documented and worded right for other people to use?

As open source, the most important comments of all are the copyright and license agreement comment. Rather than a big long comment at the start of every file, you might want to use a short and sweet one that briefly specifies copyright and refers the reader to license.txt in the root directory.

I know you should always comment everything and I'm going to be putting in the @params feature for every method, but are there any other tips in general?

Comment everything? No. Comment that code which truly does need commentary. Comment sparingly. As a potential user of a chunk of code, which of the following two versions of a class definition would you prefer to see?

Version A:

class Foo {
private:
   SomeType some_name; //!< State machine state

public:
   ...

   /**
    * Get the some_name data member.
    * @return Value of the some_name data member.
    */
   SomeType get_some_name () const { return some_name; }

   ...
};

Version B:

/**
 * A big long comment that describes the class. This class header comment is very
 * important, but also is the most overlooked. The class is not self-documenting.
 * Why is that class here? Your comments inside the class will say what individual parts
 * do, but not what the class as a whole does. For a class, the whole is, or should be,
 * greater than the parts. Do not forget to write this very important comment.
 */
class Foo {
private:

   /**
    * A big long comment that describes the variable. Just because the variable is
    * private doesn't mean you don't have to describe it. You might have getters and
    * setters for the variable, for example.
    */
   SomeType some_name;

public:
   ...

   // Getters and setters
   ...

   // Getter for some_name. Note that there is no setter.
   SomeType get_some_name () const { return some_name; }

   ...

};

In version A I've documented everything -- except the class itself. A class in general is not self-documenting. The comments that are present in version A are absolutely useless, or even worse than useless. That's the key problem with the "comment everything" attitude. That little terse comment on the private data member communicates nothing, and the doxygen comments on the getter has negative value.  The getter get_some_name() doesn't really need a comment. What it does and what it returns is patently obvious from the code. That there is no setter -- you have to infer that because it's not there.

In version B I've documented that which needs commenting. The getter doesn't have a doxygen comment, but it does have a comment mentioning that there is no setter.

Make your comments count, and beware that comments oftentimes are not maintained to reflect changes to the code.


答:
Determining if a project was implemented successfully is pretty easy - does it meet the business requirements and are the support costs low?

Everything else (OOP, testing, documentation, guideline adherence, etc) are means to those ends.

They're mighty important and incredibly useful means to the ends, but that doesn't make them the solution.  As an architect you can follow all the rules and still fail spectacularly if you lose focus.

I was going to add this as a 2nd answer, but I guess not.

2 way communication is probably the most important tool an architect has.  An isolated software architect who issues edicts but doesn't solicit and listen to feedback from the team (& from the business) is going to be ignored.

Title: Software Architecture - From design to sucessful implementation

Body:
As the subject goes; once a software architect puts down the high level design and approach to a software that is to be developed from scratch, how does the team ensure that it is implemented successfully? To my mind the following things will need to be done

Proper understanding of requirements

Setting down coding practices and guidelines

Regular code reviews to ensure the guidelines are being adhered to

Revisiting the requirements phase and making necessary changes to design based on client inputs if there are any changes to requirements

Proper documentation of what is being done in code

Proper documentation of requirements and changes to them

Last but not the least, implementing the design via object oriented code where appropriate

Did I miss anything?

Would love to hear any mistakes that you have learned from in your project experiences. What went wrong, what could have been done better.

Thanks for taking the time..


问:
Multiple attribution in Python, JS, ...?
I accidentally discovered this a=b=c=d=e=f=2 in python(2.7)(and JavaScript a few minutes later) interpreter .

Is this a feature or just the way the interpreter works, if is a feature how it is called ?

Do other languages have this feature ?

答:
It is a feature of the language, the = statement evaluates the statement to its right and assigns that value to the variable on the left.

In Python a statement like a, b = 1,2 is also legal.  That is called multiple assignment. See Python Docs I don't know of a special term for the a=b=2 structure though.  It is just multiple assignments on the same line.


答:
This type of feature is typically known as "multiple assignment." Many languages have this type of feature.

This type of feature is typically known as "chained assignment." Languages that consider assignment to be expressions have this type of feature.

Multiple assignment typically means something else, e.g. Python:

```<code>a, b, c, d, e, f = [2, 2, 2, 2, 2, 2]
</code>```

This type of syntax structure can be referred to as multiple assignment. In the context of Python, this is also known as unpacking.

The astute programmer might note that this is related to multiple return values:

```<code>def f(): return [1, 2, 3]
a, b, c = f()
</code>```

There are a large number of languages that support chained assignment or multiple assignment in different ways.

C, C++, Java, and C# support the syntax you provided. VB does not support chained assignment (since assignment is a statement and not an expression like in the C family). Go supports multiple assignment similarly to Python, e.g. a swap:

```<code>a, b = b, a
</code>```

I believe Lua supports multiple assignment and multiple return values. It can be done in a Lisp but there's usually a better way to go about it.

Basically, most languages support either of these features in some way.

Title: Multiple attribution in Python, JS, ...?

Body:
I accidentally discovered this a=b=c=d=e=f=2 in python(2.7)(and JavaScript a few minutes later) interpreter .

Is this a feature or just the way the interpreter works, if is a feature how it is called ?

Do other languages have this feature ?

Body:
This type of feature is typically known as "multiple assignment." Many languages have this type of feature.

This type of feature is typically known as "chained assignment." Languages that consider assignment to be expressions have this type of feature.

Multiple assignment typically means something else, e.g. Python:

a, b, c, d, e, f = [2, 2, 2, 2, 2, 2]

This type of syntax structure can be referred to as multiple assignment. In the context of Python, this is also known as unpacking.

The astute programmer might note that this is related to multiple return values:

def f(): return [1, 2, 3]
a, b, c = f()

There are a large number of languages that support chained assignment or multiple assignment in different ways.

C, C++, Java, and C# support the syntax you provided. VB does not support chained assignment (since assignment is a statement and not an expression like in the C family). Go supports multiple assignment similarly to Python, e.g. a swap:

a, b = b, a

I believe Lua supports multiple assignment and multiple return values. It can be done in a Lisp but there's usually a better way to go about it.

Basically, most languages support either of these features in some way.


问:
Build/deployment tools for a small (1) development effort
What build or deployment tools are available for a 1 person development effort, in the .NET space, that are capable of producing project outputs?

I'm not looking necessarily looking for a CI server (though I can't think of anything else that does what I'm looking for) but I am looking for it to:

produce and publish documentation from xml comments

produce and publish the project (web and/or clickonce app)

handle basic versioning (automatic build number incrementing)

work from a sln file

be easy to setup (< 8-16 hrs for someone who knows little to nothing about the tool(s))

do this at the push of a button (after configuration obviously)

Things I don't need:

source control integration : I can point it to a sln if need be. Not a huge deal.

unit testing : I run test suite before commits

static analysis : again, I also run these before commits

I know that msbuild is capable of most or all of this, and I do have my msbuild book(s) with me, but I'm still very new to it and I don't have the time at the moment to learn it well enough to do what I want.

答:
While waiting for answers, I got looking around and stumbled upon MSBuild Explorer and think that, in combination with the MSBuild Extension Pack, the 'favorites' feature might be what I'm looking for.

I'm not going to mark this as the answer yet, because I have to try it out to see if it can do what I'm looking for. Feedback is appreciated if anyone else has used this before.

ContentLicense: CC BY-SA 2.5


问:
How to write a very basic compiler
Advanced compilers like gcc compile code into machine readable files according to the language in which the code has been written (e.g. C, C++, etc). In fact, they interpret the meaning of the code according to library and functions of the corresponding languages. Correct me if I'm wrong.

I wish to better understand compilers by writing a very basic compiler (probably in C) to compile a static file (e.g. Hello World in a text file). I tried some tutorials and books, but all of them are for practical cases. They deal with compiling dynamic code with meanings connected with the corresponding language.

How can I write a basic compiler to convert a static text into a machine readable file?

The next step will be introducing variables into the compiler; imagine that we want to write a compiler which compile only some functions of a language.

Introducing practical tutorials and resources is highly appreciated :-)

答:
If you really want to write machine readable code only and not targeted to a virtual machine, then you will have to read Intel manuals and understand

a. Linking and Loading Executable code

b. COFF and PE formats(for windows), alternatively understand ELF
format(for Linux)

c. Understand .COM file formats(easier than PE)

d. Understand assemblers

e. Understand compilers and code generation engine in compilers.

Much harder done than said. I suggest you to read Compilers and Interpreters in C++ as a starting point(By Ronald Mak). Alternatively, "lets build a compiler" by Crenshaw is OK.

If you don't want to do that, you could as well write your own VM and write a code generator targeted to that VM.

Another starting point:
http://gnuu.org/2009/09/18/writing-your-own-toy-compiler/

Great Book By Kenneth Louden:
http://www.amazon.com/Compiler-Construction-Principles-Kenneth-Louden/dp/0534939724

Tips: Learn Flex and Bison FIRST. Then go on to build your own compiler / VM.

Good Luck!

ContentLicense: CC BY-SA 4.0

Title: How to write a very basic compiler


问:
WINAPI beginner guidance question
I'm learning to develop windows applications using WINAPI and plain C.

Now I got a bit confused with all those handles and would like to ask if you guys could teach me some good practices to structure and handle controls and windows.

Here's where I get confused:

Using the IDs declared in the resources for each object, we can get their handles using GetDlgItem(). Now what if we don't know their parent, which is needed by this function.

One example: We have the main window created at launch. Then we register two new window classes and create a window for each new class and we create a message function for each too.
Now if inside one of the children windows I create a button and inside the other child window I create a text label. Now when we click the button inside of child window A the label in child window B shall be modified to whatever.

The WM_COMMAND for the button is interpreted inside the message loop for child window A. Now what would be the best and more elegant way to access the text label inside the child window B?

I am in the process of learning the WINAPI and just want to learn it right from the start instead of producing Hacked code that someday becomes unreadable and to later have to adapt to a new way of programing.

Is there really no one able to give me some advice?

答:
First thing to have in mind when writing programs for Windows using the Plain Old Win32 API is that every control on screen is a WINDOW on its own. Which means each have their own "HANDLES" and the like. I think you're using an easy way out by creating controls on a DialogBox using Win32 RES editor(which is fine for a beginner). But when you go into more advanced programming on Win32, I would suggest you use CreateWindow() function.

To answer your question you could just get the handle of the control like so: GetDlgItem(HWND hParent,int nIDDLGITEM) function, and SetWindowText() over it. Make sure that the Static label has SS_LEFT property.

Title: WINAPI beginner guidance question


问:
What is the best policy for allowing clients to change email?
We are developing a web application with a fairly standard registration process which requires a client/user to verify their email address before they are allowed to use the site.  The site also allows users to change their email address after verification (with a re-type email field, as well).

What are the pros and cons of having the user re-verify their email.  Is this even needed?

EDIT:

Summary of answers and comments below:

"Over-verification" annoys people, so don't use it unless critical

Consider a "re-type email" field to prevent typos, but users can still copy/paste, rendering it moot.

Beware of overwriting known good data with potentially good data

Send email to old for notification; to new for verification

Don't assume that the user still has access to the old email

Identify impact of incorrect email if account is compromised

答:
Why not provide whatever verification of the email there in the form?

Ultimately, the question you need to answer is "why are we verifying an email address" before you can answer whether or not re-verfication is required.

If the idea is to really enforce an opt-in mentality, then a re-verification may be appropriate.

If the idea is to make sure they didn't mistype something, providing a 2nd field to re-enter the new email address against for verification may be sufficient.

And then you should consider how the user will view a re-verification.  Without knowing the domain of your site, I would be annoyed at having to do so.  But I'll acknowledge there could be a domain or a use case to where I as the user would want you to re-verify my email address.


答:
if you are going to allow your users to change an email address you need to verify the new email address and send a notification to the old email address. The verification of the new email is more optional, but since you verified the original address not validating the new is an inconsistency, that can turn known good information into potentially useless information. The email sent to the old address is for security reasons in case the account was compromised, so the user can be notified and take action to recover the account if necessary.

You could also require the user to click verification links sent to both emails in the case of an email change and lock the account until both are verified or your customer service is contacted. Doing something like this really hurts user friendliness and should only be used if your application is something that if compromised can cause significant monetary losses or physical danger.

Title: What is the best policy for allowing clients to change email?

Body:
We are developing a web application with a fairly standard registration process which requires a client/user to verify their email address before they are allowed to use the site.  The site also allows users to change their email address after verification (with a re-type email field, as well).

What are the pros and cons of having the user re-verify their email.  Is this even needed?

EDIT:

Summary of answers and comments below:

"Over-verification" annoys people, so don't use it unless critical

Consider a "re-type email" field to prevent typos, but users can still copy/paste, rendering it moot.

Beware of overwriting known good data with potentially good data

Send email to old for notification; to new for verification

Don't assume that the user still has access to the old email

Identify impact of incorrect email if account is compromised


答: I'd actually start off with writing a compiler for Brainfuck. It's a fairly obtuse language to program in but it only has 8 instructions to implement. It's about as simple as you can possibly get and there are equivalent C instructions out there for the commands involved if you find the syntax off-putting.</p>

Title: How to write a very basic compiler

Body:
Advanced compilers like gcc compile code into machine readable files according to the language in which the code has been written (e.g. C, C++, etc). In fact, they interpret the meaning of the code according to library and functions of the corresponding languages. Correct me if I'm wrong.

I wish to better understand compilers by writing a very basic compiler (probably in C) to compile a static file (e.g. Hello World in a text file). I tried some tutorials and books, but all of them are for practical cases. They deal with compiling dynamic code with meanings connected with the corresponding language.

How can I write a basic compiler to convert a static text into a machine readable file?

The next step will be introducing variables into the compiler; imagine that we want to write a compiler which compile only some functions of a language.

Introducing practical tutorials and resources is highly appreciated :-)


答:
DIY approach for simple compiler could look like this (at least that's how my uni project looked like):

Define Grammar of the language. Context-free.

If your grammar isn't LL(1) yet, do it now. Note, that some rules that looked ok in    plain CF grammar may turn out ugly. Perhaps your language is too complex...

Write Lexer which cuts stream of text into tokens (words, numbers, literals).

Write top-down recursive descent parser for your grammar, which accepts or rejects input.

Add syntax tree generation into your parser.

Write machine code generator from the syntax tree.

Profit & Beer, alternatively you can start thinking how to do smarter parser or generate better code.

There should be plenty of literature describing each step in detail.

Title: How to write a very basic compiler


答:
Intro

A typical compiler does the following steps:

Parsing: the source text is converted to an abstract syntax tree (AST).

Resolution of references to other modules (C postpones this step till linking).

Semantic validation: weeding out syntactically correct statements that make no sense, e.g. unreachable code or duplicate declarations.

Equivalent transformations and high-level optimization: the AST is transformed to represent a more efficient computation with the same semantics. This includes e.g. early calculation of common subexpressions and constant expressions, eliminating excessive local assignments (see also SSA), etc.

Code generation: the AST is transformed into linear low-level code, with jumps, register allocation and the like. Some function calls can be inlined at this stage, some loops unrolled, etc.

Peephole optimization: the low-level code is scanned for simple local inefficiencies which are eliminated.

Most modern compilers (for instance, gcc and clang) repeat the last two steps once more. They use an intermediate low-level but platform-independent language for initial code generation. Then that language is converted into platform-specific code (x86, ARM, etc) doing roughly the same thing in a platform-optimized way. This includes e.g. the use of vector instructions when possible, instruction reordering to increase branch prediction efficiency, and so on.

After that, object code is ready for linking. Most native-code compilers know how to call a linker to produce an executable, but it's not a compilation step per se. In languages like Java and C# linking may be totally dynamic, done by the VM at load time.

Remember the basics

Make it work

Make it beautiful

Make it efficient

This classic sequence applies to all software development, but bears repetition.

Concentrate on the first step of the sequence. Create the simplest thing that could possibly work.

Read the books!

Read the Dragon Book by Aho and Ullman. This is classic and is still quite applicable today.

Modern Compiler Design is also praised.

If this stuff is too hard for you right now, read some intros on parsing first; usually parsing libraries include intros and examples.

Make sure you're comfortable working with graphs, especially trees. These things is the stuff programs are made of on the logical level.

Define your language well

Use whatever notation you want, but make sure you have a complete and consistent description of your language. This includes both syntax and semantics.

It's high time to write snippets of code in your new language as test cases for the future compiler.

Use your favorite language

It's totally OK to write a compiler in Python or Ruby or whatever language is easy for you. Use simple algorithms you understand well. The first version does not have to be fast, or efficient, or feature-complete. It only needs to be correct enough and easy to modify.

It's also OK to write different stages of a compiler in different languages, if needed.

Prepare to write a lot of tests

Your entire language should be covered by test cases; effectively it will be defined by them. Get well-acquainted with your preferred testing framework. Write tests from day one. Concentrate on 'positive' tests that accept correct code, as opposed to detection of incorrect code.

Run all the tests regularly. Fix broken tests before proceeding. It would be a shame to end up with an ill-defined language that cannot accept valid code.

Create a good parser

Parser generators are many. Pick whatever you want. You may also write your own parser from scratch, but it only worth it if syntax of your language is dead simple.

The parser should detect and report syntax errors. Write a lot of test cases, both positive and negative; reuse the code you wrote while defining the language.

Output of your parser is an abstract syntax tree.

If your language has modules, the output of the parser may be the simplest representation of 'object code' you generate. There are plenty of simple ways to dump a tree to a file and to quickly load it back.

Create a semantic validator

Most probably your language allows for syntactically correct constructions that may make no sense in certain contexts. An example is a duplicate declaration of the same variable or passing a parameter of a wrong type. The validator will detect such errors looking at the tree.

The validator will also resolve references to other modules written in your language, load these other modules and use in the validation process. For instance, this step will make sure that the number of parameters passed to a function from another module is correct.

Again, write and run a lot of test cases. Trivial cases are as indispensable at troubleshooting as smart and complex.

Generate code

Use the simplest techniques you know. Often it's OK to directly translate a language construct (like an if statement) to a lightly-parametrized code template, not unlike an HTML template.

Again, ignore efficiency and concentrate on correctness.

Target a platform-independent low-level VM

I suppose that you ignore low-level stuff unless you're keenly interested in hardware-specific details. These details are gory and complex.

Your options:

LLVM: allows for efficient machine code generation, usually for x86 and ARM.

CLR: targets .NET, multiplatform; has a good JIT.

JVM: targets Java world, quite multiplatform, has a good JIT.

Ignore optimization

Optimization is hard. Almost always optimization is premature.
Generate inefficient but correct code. Implement the whole language before you try to optimize the resulting code.

Of course, trivial optimizations are OK to introduce. But avoid any cunning, hairy stuff before your compiler is stable.

So what?

If all this stuff is not too intimidating for you, please proceed! For a simple language, each of the steps may be simpler than you might think.

Seeing a 'Hello world' from a program that your compiler created might be worth the effort.

Title: How to write a very basic compiler


问:
Copy-and-Pasted Test Code: How Bad is This?
My current job is mostly writing GUI test code for various applications that we work on. However, I find that I tend to copy and paste a lot of code within tests. The reason for this is that the areas I'm testing tend to be similar enough to need repetition but not quite similar enough to encapsulate code into methods or objects. I find that when I try to use classes or methods more extensively, tests become more cumbersome to maintain and sometimes outright difficult to write in the first place.

Instead, I usually copy a big chunk of test code from one section and paste it to another, and make any minor changes I need. I don't use more structured ways of coding, such as using more OO-principles or functions.

Do other coders feel this way when writing test code? Obviously I want to follow DRY and YAGNI principles, but I find that test code (automated test code for GUI testing anyway) can make these principles tough to follow. Or do I just need more coding practice and a better overall system of doing things?

EDIT: The tool I'm using is SilkTest, which is in a proprietary language called 4Test. As well, these tests are mostly for Windows desktop applications, but I also have tested web apps using this setup as well.

答:
Should people try and limit repitition when they can - yes.  But the payoff depends on the situation.  This could go back to the 'best practice' debate.  But the question is what is best for you in this situation.  There are exceptions to every rule.

A couple things I would ask are:
1) How likely is it that this functionality being tested in the UAT will change?  If it is unlikely it will change, then there is less chance that you will have to update each of your sets of code.  2) If there is a change in UAT, will it always impact each set of the copied code or might it only impact one or two sets? If it might be isolated and only require a change to one set, it might help to have the things separated.  3) How complex will the initial method be if you try and have it handle all scenarios?  Are you adding a lot of nested if/else/loops?  If you start over-doing all the branching, you may end up with code that is hard to comprehend.  Would it be easier to make the update in each of the copied text than it would be to revisit all the branching logic?

If you are stuck copy/paste/alter I would think you would want to add comments such as 'This is copied in method xyz'.  That way you will be reminded to update all the pasted versions of the code.  Or (coming from another SilkTest user) could you add a separate inc file that would focus just on this repeated code.  That way you have all the variations in one place and could easily see the different methods that would require updating.


答:
If you're looking for something simple, you might consider hudson.  I haven't used it with .Net, but it's pretty useful if you just want to have a series of build jobs that only need to run a set of shell commands.  It can be a bit simplistic if you get to the point where you have multiple packages with complex dependencies, but it sounds like it might be useful for the size of project you're doing.

EDIT:  It turns out that there's an MSBuild plugin as well

Title: Build/deployment tools for a small (1) development effort

Body:
What build or deployment tools are available for a 1 person development effort, in the .NET space, that are capable of producing project outputs?

I'm not looking necessarily looking for a CI server (though I can't think of anything else that does what I'm looking for) but I am looking for it to:

produce and publish documentation from xml comments

produce and publish the project (web and/or clickonce app)

handle basic versioning (automatic build number incrementing)

work from a sln file

be easy to setup (< 8-16 hrs for someone who knows little to nothing about the tool(s))

do this at the push of a button (after configuration obviously)

Things I don't need:

source control integration : I can point it to a sln if need be. Not a huge deal.

unit testing : I run test suite before commits

static analysis : again, I also run these before commits

I know that msbuild is capable of most or all of this, and I do have my msbuild book(s) with me, but I'm still very new to it and I don't have the time at the moment to learn it well enough to do what I want.


答:
Jack Crenshaw's Let's Build a Compiler, while unfinished, is an eminently readable introduction and tutorial.

Nicklaus Wirth's Compiler Construction is a very good textbook on the basics of simple compiler construction.  He focuses on top-down recursive descent, which, let's face it, is a LOT easier than lex/yacc or flex/bison.  The original PASCAL compiler that his group wrote was done this way.

Other people have mentioned the various Dragon books.

Title: How to write a very basic compiler


答:
In many languages, the = operator returns the value that was assigned.

The line a=b=c=d=e=f=2 is the same as a = (b = ( c = (d = (e = (f = 2)))))

f=2 returns the value of 2.

Thus, this then reduces to a = (b = ( c = (d = (e = 2)))) and so on.

This is known as chained assignment


问:
Learning Arlgorithms particularly graph algorithms (java)
I have a hard time learning algorithms (Particularly graphing algorithms).

Do you know of any good free resources that make some of the more harrowing algorithm concepts such NP-Complete, Traveling salesman, and other algorithms, A* heuristics, particularly graphing algorithms, simpler to learn?

答: http://www.nrbook.com/a/bookcpdf.php is really, really good. I've seen their books in C++, and FORTRAN, which are also very good. It has got a mixture of theory and practical code examples.</p>


答: You might find Mastering Algorithms with Perl helpful.  The beauty of this book is that it is very hands on.  There is code that goes with most of the sections.  If you learn better by doing, then this might be a good book for you.

Title: Learning Arlgorithms particularly graph algorithms (java)

Body:
I have a hard time learning algorithms (Particularly graphing algorithms).

Do you know of any good free resources that make some of the more harrowing algorithm concepts such NP-Complete, Traveling salesman, and other algorithms, A* heuristics, particularly graphing algorithms, simpler to learn?


答:
What books, websites, etc. have you looked at?

The Algorithm Design Manual is known for being a clear explanation of all these topics.  I recommend it highly.


问:
OS choice for functional developing
I'm mainly a .NET developer so I normaly use Windows/VisualStudio (that means: I'm spoiled) but I'm enjoying Haskell and other (mostly functional) languagues in my spare time.

Now for Haskell the windows-support is ok (you can get the Haskell-Platform) but latley I tried to get a basic Clojure/Scheme environment set up and it's just a pain on windows.

So I'm thinking about trying out another OS for better tooling and languague support.
Of course that leaves me with MacOS or some Linux distribution.

I never used MacOS before and of course Linux would be cheaper (free) and I don't think I can parallel-boot MacOS on your normal PC-Hardware (can you?).
PLUS: I don't have a clue about the tools you can use on those (to me) forign OSs.

To make it short: I want to explore more Haskell, Clojure, Scala, Scheme and of course need at least good tooling for JavaScript/HTML5/Css.
Support for .NET/Mono/F# would be great but for this I will still have my Win7 boot.

So I like to know:
 - what is your prefered OS, Distribution (is Ubuntu viable?)
 - what Editor/IDE are you using

Thank you for your help!

PS: I'm not sure if this is the right place for this question but I surely hope so - if not please let me know where I should move this to (StackOverflow don't seem to be the right place IMHO)

答:
Rather than picking an OS, let me come at this from the IDE angle. If you're interested in Scheme, I would encourage you to try out DrRacket, which emerged from the Scheme jungle a few years back. The IDE runs well on Windows, OS X, and Linux.

Now, you just have to pick the right OS to run all of your other functional languages.

Title: OS choice for functional developing


问:
What do you look at first: the code or the design?
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?

答:
The functional purpose of application

The functional scope and flow of the application an his linking with other system of the customer.

After I see the code of the most critical module/point of application: seeing the code, I can
to verify the goodness of the design.

Example:

You have to work in the application management of a web-app about financial reporting.

I ask and read the documentation about of the purpose: what data have to be reported? Who use this application?

What are the linked systems? There's any deadline for receive or sending data to anybody? If this system is down what other application are damages or stopped, what other department are damaged?

After I read the code about the message, the start and end application (for probable lock in db), the master process of creation of data what have to be reported etc etc (for example, in storage of gas the master process is about the computation of gas stock in storage area of the customers with supply and injection; the secondary process is the billing aabout this data previous calculated)


问:
How to maintain same code fragments on multiple projects
I am an indie developer working on multiple Android projects. I am having problem with maintaining same functionality on different projects. For example, three of my apps use the same 2 classes; since they are different projects, when I need to make a change in those classes, I need to make it three times. Is there a simple solution to this kind of common problem?</p>

答:
Version control. Git. Git Submodules.

Put your projects under version control, using a dvcs like git or mercurial etc. Put the shared code in a submodule in git. Use the submodule in the projects that need it. When you update the submodule, can pull the changes to other projects with a single command.


答:
If you were using JGraph, you should give a try to JGraphT which is designed for algorithms. One of its features is visualization using the JGraph library.

It's still developing, but in pretty stable state. I analyzed the complexity of JGrapT algorithms some time ago. Some of them aren't the quickest, but if you're going to implement them on your own and need to display your graph, then it might be the best choice.

I really liked using its api, when I quickly had to write an app that was working on graph and displaying it later.

Reference, here is a Hello World! example.


问:
How to convince a non-technical client that their application spec needs to be simplified?
Often times I am faced with the situation where a new client comes to me with an application that has literally 100s of unnecessary features and it is quite clear that things need to be drastically simplified for the project to have any chance of succeeding. How do you convince the client to take a more Minimum Viable Product (MVP) approach and simplify?

edit:

So the current top answer is to provide the client with a time/cost estimate for the huge application. I'm not too fond of this answer because it doesn't address the real problem with this situation. And that is - it's a bad practice to spec out a massive application and then try and build it from the get go. I feel much more comfortable initially building a small, simple MVP foundation. And then adding small features to that foundation one by one. So how do I convince the client to approach building software in this way?

答: I'd first try and explain to then that their requirements are not realistic, and present them with a set of counter requirements. Explain that this will solve their problem more simply, and faster, thus with less costs  and risks. Do not try and make this into a technical discussion, the client does not care about that. The client does care about getting a good product in time, solving their business case. If the client does not budge, either accept the contract and do the work, or reject and explain the client why you cannot take respnsibilty for the project in this form.</p>


答: By estimating how much money/time it will cost to do those hundreds of features with high quality. Very, very few clients will put their money where their mouth is.</p>

Title: How to convince a non-technical client that their application spec needs to be simplified?

Body:
Often times I am faced with the situation where a new client comes to me with an application that has literally 100s of unnecessary features and it is quite clear that things need to be drastically simplified for the project to have any chance of succeeding. How do you convince the client to take a more Minimum Viable Product (MVP) approach and simplify?

edit:

So the current top answer is to provide the client with a time/cost estimate for the huge application. I'm not too fond of this answer because it doesn't address the real problem with this situation. And that is - it's a bad practice to spec out a massive application and then try and build it from the get go. I feel much more comfortable initially building a small, simple MVP foundation. And then adding small features to that foundation one by one. So how do I convince the client to approach building software in this way?


答:
Separate the shared code off into a library, and include the library in the projects.

As an Android developer, you're presumably using Java. Consider using a dependency management tool like Maven or Ivy.

A side effect is that this will help maintain separation of concerns by enforcing modularity. The cost is that it may take some work to separate; the benefit is better future maintainability. Also, if you ever decide to, you can release the library separately (either commercially or as open source) from your applications.

Title: How to maintain same code fragments on multiple projects

Body: I am an indie developer working on multiple Android projects. I am having problem with maintaining same functionality on different projects. For example, three of my apps use the same 2 classes; since they are different projects, when I need to make a change in those classes, I need to make it three times. Is there a simple solution to this kind of common problem?</p>


答:
Two words: User Stories.

I've learned that the fastest way to help a client Get A Clue® is to have them talk me through a user story for each and every feature or page they want. Several things happen, including:

They have to think about what the hell the page/feature is actually supposed to do.

As you ask for more and more detail ("and then? ... and then? ...") they begin to understand that the whole thing isn't going to come into being by having Magic Space Monkeys™ fly in and do it over the weekend.

They become true partners in the creation process. Which means that they will understand why changing their mind about something that is already 80% complete will cause a) schedule delay, and b) cost increase.

Seriously. User Stories by owners  is one of the best tools I know for bringing at least some sanity to the process.


答:
While discussing the cost and time-to-production aspect, ask for a ranking of the requirements ("must have", "should have", and "nice to have") so that the minimum viable product set of features that are essential are "must have" in version 1, then put the remainder of the requirements into sets of backlogs that could be accomplished as sprints subsequent to the first version.  Hopefully the non-essential "nice to have" ones will go to the back of the pack and by the time you get to those sprints new ones that are more essential (from actual experience with the product) will have floated to the top.

The client should appreciate that you are considering the cost of their business and the importance of getting product quickly and you're not directly dismissing their "nice to have" by putting them in the backlog.

Edit to respond to OP edit:
To convince the client why it's a good idea to release early a minimum viable product explain that until the product is used by real users it's difficult to know whether it will be successful (especially in terms of usability). If the customer is hesitant to put out an early product to their whole user base, recommend doing a "limited beta" where it is available only to a targeted subset of their customers. Tell them the flip-side of this approach is a long, costly development cycle with a late determination that the product is unusable. 37 Signals has produced a couple of good references about this: Getting Real and Rework.  The Getting Real is available on the web for free.


问:
Is php|architect any good?
Kind of a hard topic to search for, as architect turns up a lot about software architects instead.

After 8 months of PHP self-study, I finally stumbled across the php|architect site. The length of time it took me to find it makes me suspicious of its quality.

3 related questions:

do professional PHP coders read/care about php|architect?

is it a good source for PHP beginners?

assuming yes to either of the above, how far back in the archives to articles remain relevant? (ex: does stuff written about PHP4 still matter?)

答: I have been into PHP development for over 5 years now & I really find the articles very relevant & helpful. It's clearly not aimed at PHP beginners but at the intermediate/expert programmer. </p>

Title: Is php|architect any good?


答: Similar to what the other folks have suggested, but slightly different, I'd suggest that everything the customer may be valid, but they have to PRIORITIZE.  Which item needs to be done first.  Which item needs to be done second.  Most importantly, if you run out of time, which items will it hurt the least not to have.  Prioritize each item from 1 to 732 (or whatever) and complete them in that order.</p>


答: Verifying an e-mail address by making a user enter it twice is a stupid idea (as a result, it is also a much copied idea). The user can verify what they entered the first time by reading. Requiring a password to be entered twice does make sense, since the user can't read what they typed (a the typical password edit control masks the actual text).


问:
Object Oriented Programming Language performance ranking
After reading this post about ideal programming language learning sequence, I am wondering what would have been the answers if the question was performance -instead of learning- oriented ?

Since there are many programming languages I chose to ask the question for OOL to be the least subjective. But any thought or comparison about no-OOL are appreciated :D

If we omit the programming effort, time and costs. What is your ranking of the most powerful object oriented languages ?

答:
There's an interesting slide in this Scale at Facebook presentation that shows relative performance of a few languages compared to C++.

C++ (1)

Java (2)

C# (3)

Erlang (6)

Python (21)

Perl (38)

PHP (+-40)

Ruby (+-70)


问:
Resolving equivalence relations
I am writing a function to label the connected component in an image
(I know there are several libraries outside, I just wanted to play with the algorithm).

To do this I label the connected regions with different labels and create an equivalence table that contain information on the labels belonging to the same connected component.

As an example if my equivalence table (vector of vector) looks something like:

```<code>1:    1,3
2:    2,3
3:    1,2,3
4:    4
</code>```

It means that in the image there are 2 different regions, one made of elements that are labelled 1,2,3 and an other made of elements labelled 4.

What is an easy and efficient way to resolve the equivalences and end up with something that looks like:

```<code>1: 1,2,3
2: 4
</code>```

that I can use to "merge" the different connected regions belonging to the same connected component?

Thanks a lot for the help!

答:
You probably want a disjoint set datastructure.  This yields near-constant amortized performance per operation, and can be made very efficient for the kind of task you describe.

Briefly, each equivalence class is stored as an "inverted tree":  each node has a parent link, but no child links.  A "query" follows the parent links until they reach the root (which can be marked by having itself as a parent).  Note that every node in the same tree will yield the same root, which is the "exemplar" representing that equivalence class.

Nodes typically start out as their own equivalence class (that is, they are initialized as a tree consisting of just the root).  To merge two equivalence classes, find the root of each, and make one the parent of the other.

By adding two simple optimizations (always "collapse" query paths to point directly to the root, and always choose the root of the deeper tree as merge parent), you gain "near-constant" amortized worst case performance for your operations.

Title: Resolving equivalence relations


问:
Is there a known algorithm for scheduling tournament matchups?
Just wondering if there is a tournament scheduling algorithm already out there that I could use or even adapt slightly.

Here are my requirements:

A variable number of opponents belonging to a variable number of teams/clubs each must be paired with an opponent

Two opponents cannot be from the same club

If there are an odd number of players, 1 of them randomly is selected to get a bye

Any algorithms related to this sort of requirement set would be appreciated.

EDIT: I only need to run this a maximum of one time, creating matchups for the first 'round' of the tournament.

答:
From my brief time on Wikipedia twenty seconds ago it looks like you'll need to decide on an elimination strategy first.  See Wikipedia:

Swiss-System

Single-elimination_tournament

Double-elimination_tournament

The single-elimination article described seeding techniques (the algorithm you're looking for) pretty generically and it looked helpful, although not quite an algorithm.

OwnerDisplayName: barfoon

OwnerDisplayName: Cpfohl


答: As I can see you want to find maximum matching in graph. In fact nodes are players, they connected to each other if they aren't in same club, now you should find maximum number of edges which are doesn't have same vertex. See Edmonds Maximum matching algorithm.</p>

Title: Is there a known algorithm for scheduling tournament matchups?

Body:
Just wondering if there is a tournament scheduling algorithm already out there that I could use or even adapt slightly.

Here are my requirements:

A variable number of opponents belonging to a variable number of teams/clubs each must be paired with an opponent

Two opponents cannot be from the same club

If there are an odd number of players, 1 of them randomly is selected to get a bye

Any algorithms related to this sort of requirement set would be appreciated.

EDIT: I only need to run this a maximum of one time, creating matchups for the first 'round' of the tournament.

OwnerDisplayName: Saeed


答:
Making this up as I go, it seems like an initial matching algorithm is quite simple:

```<code>While two or more clubs have at least one member not paired
    select the two clubs with the most unpaired members
    select a random unpaired member from each club
    pair those members
</code>```

If one person is left, it will be a random person, with one exception.  If one club has more members than all of the opposing players put together, then the leftovers will always be from that club.  Realistically, that's a super-rare situation, and picking a buy from any other club would leave even more people leftover.

Body:
Making this up as I go, it seems like an initial matching algorithm is quite simple:

While two or more clubs have at least one member not paired
    select the two clubs with the most unpaired members
    select a random unpaired member from each club
    pair those members

If one person is left, it will be a random person, with one exception.  If one club has more members than all of the opposing players put together, then the leftovers will always be from that club.  Realistically, that's a super-rare situation, and picking a buy from any other club would leave even more people leftover.

OwnerDisplayName: Mooing Duck


问:
Avoiding "double" subscriptions
I am working on a website that requires a bit of marketing; let me explain.

This website is offering a single, say, iTunes 50$ voucher to a lucky winner.

To be entered in the draw, you need to invite (and has to join) at least one friend to the website. Pretty straightforward.

Now, of course it would be easy for anyone to just create a fake account and invite that account so, I was thinking of some other way to somehow find out of possible cheating.

I was thinking of an IP check on the newly subscribed (invited) user, and if there is the same IP logged in the last 24 hours, and if that's the case, investigate more about it.

But I was thinking that maybe there is a more clever way around this issue. Has anyone ever though about this? What other solutions did you try?

Thanks in advance.

答:
I have seen solutions checking IP addresses before. This generally works because most people don't know or cannot be bothered using proxies. However users from universities, corporates, Internet cafes etc where many people share the same public IP will be adversely affected. Too many false positives.

Cookies are used in some solutions too. However sophisticated cheaters can usually get around that. False negatives if cheaters know how.

I myself use mobile authentication where users need to enter a code sent to their mobile phone. This prevents the vast majority of cheats, though requires some more infrastructural work.

You can also consider requiring users to log in with Facebook etc, which would largely increase the efforts required to cheat.

And after all, displaying a highly visible banner on the entry page stating that if double entry is found all entries from the user will be voided may deter some potential cheaters.

Title: Avoiding "double" subscriptions


问:
Removing occurrences of characters in a string
I am reading this book, Programming Interviews Exposed by John Mongan et. al and in chapter 6 they are discussing removing all instances of characters in a src string using a removal string, e.g. removeChars(string str, string remove).

They suggest to having a boolean lookup array with all values initially set to false, then loop through each character in remove setting the corresponding value in the lookup array to true. (note: this could also be a hash if the possible character set where huge like Unicode-16 or something like that or if str and remove are both relatively small... < 100 characters I suppose).  You then iterate through the str with a source and destination index, copying each character only if its corresponding value in the lookup array is false...

I understand their explanation, but I don't understand their code. They have

```<code>for(src = 0; src < len; ++src){
   flags[r[src]] == true;
}
</code>```

which turns the flag value at the remove string indexed at src to true...

so if you start out with PLEASE HELP as your str and LEA as your remove you will be setting in your flag table at 0,1,2... t|t|t but after that you will get an out of bounds exception because r doesn't have have anything greater than 2 in it. Even using their example you get an out of bounds exception. Is their code example unworkable?

Entire Function:

```<code>string removeChars( string str, string remove ){
   char[] s = str.toCharArray();
   char[] r = remove.toCharArray();
   bool[] flags = new bool[128]; // assumes ASCII!
   int len = s.Length;
   int src, dst;
   // Set flags for characters to be removed
   for( src = 0; src < len; ++src ){
      flags[r[src]] = true;
    }

   src = 0;
   dst = 0;
   // Now loop through all the characters,
   // copying only if they aren’t flagged
   while( src < len ){
       if( !flags[ (int)s[src] ] ){
       s[dst++] = s[src];
   }
   ++src;
   }
   return new string( s, 0, dst );
}
</code>```

r comes from the remove string.  So in my example the remove string has only a size of 3 while my str string has a size of 11.  len is equal to the length of the str string, which would be 11.  How can I loop through the r string since it is only size 3?  I haven't compiled the code so I can loop through it, but just looking at it I know it won't work.  I am thinking they wanted to loop through the r string... in other words they got the length of the wrong string here.

Am I right? Can someone explain this to me?

答:
There's not a lot of code here to work with and it's unlikely everyone has a copy of this book, so this is a guess! It would help if you would post more code.

Using your PLEASE HELP & LEA example, I'd wager the flags array is a lookup table indexed by the ASCII value of a character, and at the end would look like:

```<code>flags['A'] -> true
flags['B'] -> false
...
flags['E'] -> true
...
flags['L'] -> true
... (everything else would be false)
</code>```

Then when doing the removed copy the routine would see that

```<code>flags['P'] -> false, so copy it
flags['L'] -> true, so don't copy
flags['E'] -> true, so don't copy
etc
</code>```

'P' is the ASCII value of character P.

Body:
There's not a lot of code here to work with and it's unlikely everyone has a copy of this book, so this is a guess! It would help if you would post more code.

Using your PLEASE HELP & LEA example, I'd wager the flags array is a lookup table indexed by the ASCII value of a character, and at the end would look like:

flags['A'] -> true
flags['B'] -> false
...
flags['E'] -> true
...
flags['L'] -> true
... (everything else would be false)

Then when doing the removed copy the routine would see that

flags['P'] -> false, so copy it
flags['L'] -> true, so don't copy
flags['E'] -> true, so don't copy
etc

'P' is the ASCII value of character P.


答:
This is an idealized solution, and may take some effort to get working.

The DRY principle states that there should be a single authoritative source of truth. This dictates the use of a single source repository for all program logic, with no duplication; files organized to promote sharing and reuse of documents.

The pragmatic requirements of communication in a distributed, multi-team environment suggests that there should be multiple independent repositories, one for each project or collaboration.

I would approach this problem by submitting to the inevitable: you will need to take both approaches concurrently, and we will use scripting & automation to smooth over the fact that the approaches are contradictory.

:-)

The one unified repository will be your single authoritative source. The build process for each project will copy all the files used by that project (and only those files) into an intermediate location, then build from that intermediate location. (Unison or some similar tool can be used to move deltas instead of whole files).

These intermediate locations can be used as local working copies for the set of secondary, derived, or downstream repositories. Post-commit hook scripts on the authoritative repository will update all of the intermediate locations, and, for each in turn, check if it has changed, and make the same commit to the corresponding secondary repository if a change is detected.

This way, the multiple secondary repositories are kept in sync with the single authoritative source repository, and the build process ensures that the secondary repositories contain all of the (possibly shared) documents and other files that are needed for the build to succeed. Finally, and most importantly, the development and build process ensures that files are edited in one place and one place only, and that all copies are kept consistent and up to date.


答:
Short Answer: I would listen to my customer and find the middle way approach with them.

I would suggest to listen to the customer and depending on their budget and timing, split the project into phases (release, release2, etc.).

Then you may continue estimation of each phase of deliverable, budget, and prioritization of required features that application should deliver.

Thus, defining scope of work and deliverables is the way to go :)


答:
You Can't

There is absolutely no way to do this.

Look at the amount if Spam being pushed around the internet today. Simply put, the people trying to stop spammers are facing an easier task than you. The Anti-Spammers a looking for Robots pretending to be different people. You are looking for people pretending to be different people. The anti-spammers are loosing, you have no chance.

You also run the risk of people creating multiple fake accounts each recommending another fake account. So all you need is one jerk (who knows what they are doing) to create 100's of fake accounts making 100's of fake recommendations.

If there is a realistic chance this promotion would generate a large amount of junk accounts in your system, I would cancel it.

Also See: How can I prevent users from creating multiple accounts on a web site?

Title: Avoiding "double" subscriptions

Body:
I am working on a website that requires a bit of marketing; let me explain.

This website is offering a single, say, iTunes 50$ voucher to a lucky winner.

To be entered in the draw, you need to invite (and has to join) at least one friend to the website. Pretty straightforward.

Now, of course it would be easy for anyone to just create a fake account and invite that account so, I was thinking of some other way to somehow find out of possible cheating.

I was thinking of an IP check on the newly subscribed (invited) user, and if there is the same IP logged in the last 24 hours, and if that's the case, investigate more about it.

But I was thinking that maybe there is a more clever way around this issue. Has anyone ever though about this? What other solutions did you try?

Thanks in advance.


问:
Linking application build number to svn revision
I am looking for a strategy to version an application with the following requirements.

My requirements are given an exe with version number (major.minor.build-number)

1) I want to map the version to a svn source revision that made the exe

2) With the source and exe I should be able to attach and debug in vs2010 with no issue.

3) Once I check-out the source code for the exe I should be able to build the exe again with the version number without having to make any changes to a file.

答:
Side note:

While building app from not-modified WC (and, probably, from not-sparse checkout) is human task, you can move task of supporting link to SVN

Alternatives

Use tags and after creating release (X.Y.Z from revision NNN) in trunk or any branch copy this WC (or repo-tree) to tag X.Y.Z. Later you can always return back to any release by checkout corresponding tag

Use custom SVN properties (svn help propset, 1-st type: versioned property) on any always-must-have solution file for storing version-string and change this property (and commit only this change) after release by next commit. In order to find needed revision in this case you have to inspect log of signal-file, find needed revision, checkout "found" or "found-1" revision

PS: Mention of VS means that you can use SubWCRev for getting global repository-wide data on build-stage


问:
Jump into Android or learn Java basics first?
I am quite proficient in C and know some C++, but never touched Java. Recently I got an idea for an app which I think has potential, and I want to develop it.

I am planning to go Android first, cause it doesn't require a mac/iPhone.

So my question is: can I go straight to learning Android development, picking up the Java syntax as I go along and need it (after all I don't think it's much different from C/C++), or should I take a couple of weeks to learn the basics of Java first and then start with Android development?

答:
Answering to a rather old thread, but just had to, since none of the answers or comments highlighted what I believe is a very important point i.e. "learning Object Oriented Programming (OOP)". Especially so, in the light of what OP wrote:-

... quite proficient in C and know some C++, but never touched Java...

That might indicate, that OP's Object Oriented Programming (and potentially Design) skills might need some propping up. At least, it did so in my case, and I'd have made a very similar statement.

I'd suggest learning what is called "Core Java", and becoming proficient and then, the switch to Android programming would seem much easier. The benefit of that approach is that Java forces OOP, in following ways --

Clean (as in Puritan sense)

Easy to grasp (as in simplicity)

The only way (instead of having non-OOP alternative)

Also, "Core Java" can be learned pretty quickly for someone already fairly familiar with C/C++.


答:
No one else mentioned the double-edged sword yet, so I'll add my 2 cents. If you have multiple projects and they all share some reusable code, according to good programming practices/principles (DRY for example), you should place the code in one global place and structure it in such a way so that it can be shared by all your projects without any modifications. In other words, define interfaces to be generic and common enough to suit everyone.

There are few options for doing this:
1) Create a base project that others depend on. This project can create a binary distribution that other projects consume.
2) Pull an open-source model within your organization. Have common code be its own code branch and have other projects pull in code same way you would take source code from any OSS online.

Now here's where the sword comes in...

Placing code into a common place that other projects/people depend on can become rather expensive. Let's say you have a piece of code and 4 other projects depend on it. One of your customers that uses project A finds a bug and you have to make a fix. You rush the fix out and that customer is happy. But you just modified some code that 3 other projects depend on. Did you retest all of those to make sure no edge conditions were introduced?

Common code must also be crafted much more carefully and module interfaces must be much better designed because that code must accommodate not one but 4 clients and each of those might just use this code with ever so slight of a difference.

If your projects are on different release cycles, you need to be even more careful about managing the common code. You can't simply make changes in the common code because project B needs new functionality, if you are 3 days away from cutting the final image for project C.

I'm not saying common library isn't the right solution. I'm a strong supporter of DRY and I've created and supported common code before and continue to do so. Just wanted to put it out there that simply making code common will have it's own expenses.

If you are the only one reusing this code, this isn't as bad. If you have a team of engineers and they start using the common code, expenses shoot up even more. If others are involved, expect placing code into a common library to take 3 times as much time as it would takes to get it to a point where you think it is "complete". You will need to a) make the library more robust to protect against all kinds of edge conditions and invalid usage, b) provide documentation so others can use the library and c) help other people debug when they use the library in a way that you haven't anticipated and your documentation didn't cover their specific use case.

Few suggestions I can offer:

Having common code covered by automated unit tests can go a long way and give you some piece of mind that when you make a change, you didn't just break some other project.

I would only place very stable functionality into common code. If you wrote a class last year to do timer management and you haven't changed it in 9 months and now you have 3 other projects that need timers, then sure that's a good candidate.  But if you just wrote something last week, well... you don't have that many options (and I hate copy/pasting code probably more than the next guy) but I'd think twice about making it common.

If piece of code is trivial but you've used it in several places, maybe it's better to bite the bullet, leave DRY alone and let multiple copies live.

Sometimes it pays to not simply put common code into a common location and have everyone reference it. But rather treat common code as its own releasable with versions, release dates and everything. This way project C can says, "I use common library v1.3" and if project D needs new functionality, you leave v1.3 alone, release v1.4 and project C doesn't get affected.  Keep in mind, it is MUCH, MUCH more expensive to treat common code as its own product rather than simply having it checked into a common location.


问:
is it safe to use jQuery and MooTools together?
I just need to know is it safe to use jQuery and MooTools Together in one web framework?

I am not trying create application using both of them, but I am in a situation where I need to modify mootool based application framework, so I am used to jquery, I don't want to waste my time learning mootools and I think jquery is better than the mootools in many contexts like number of applications, plugins etc.

so questions are

is it safe to use mootools and jquery in one framework?

will there be cross browser issues?

how robust the application will be when using both?

答:
Yes, you can use them in one web application.

MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer. It allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API.

While, jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

Thus, if you may use them both. The choice of framework depends on the development style you’re after. If you’d like to quickly get something off the ground, jQuery is the way to go. If you want to “write Javascript” and extend its power, either MooTools or Prototype would be a better choice.


问:
Why is semantic markup given more weight for search engines?
This question follows directly from the part of an  answer of this question - Why would one bother marking up properly and semantically? .

I would like to understand why SEO techniques gives more weight to semantically correct mark up?

答:
why SEO techniques gives more weight to semantically correct mark up ?

Your question is actually addressed in a reference to - Semantic HTML:

In 2010, Google specified three forms of structured metadata that their systems will use to find structured semantic content within webpages. Such information, when related to reviews, people profiles, business listings, and events will be used by Google to enhance the 'snippet', or short piece of quoted text that is shown when the page appears in search listings. Google specifies that that data may be given using microdata, microformats or RDFa. Microdata is specified inside itemtype and itemprop attributes added to existing HTML elements; microformat keywords are added inside class attributes as discussed above; and RDFa relies on rel, typeof and property attributes added to existing elements.


问:
Make audible Ding! sound, or growl notification, when `rake test` finishes!
I lose a ton of productivity by getting distracted while waiting for my tests to run.

Usually, I'll start to look at something while they're loading --- and 15-20 minutes later I realize my tests are long done, and I've spent 10 minutes reading online.

Make a small change... rerun tests ... another 10-15 minutes wasted!

How can I make my computer make some kind of alert (Sound or growl notification) when my tests finish, so I can snap back to what I was doing??

答:
While I haven't tried this, a quick Google search brought up growlnotify, which will send growl notifications from the command line.

From there, it's just something like this:

```<code>$ rake test ; growlnotify "done"
</code>```

Your syntax may vary.

Body:
While I haven't tried this, a quick Google search brought up growlnotify, which will send growl notifications from the command line.

From there, it's just something like this:

$ rake test ; growlnotify "done"

Your syntax may vary.


答:
I would like to understand why SEO techniques gives more weight to semantically correct mark up ?

Because (certain) search engines pay attention to semantic markup when fulfilling search requests.

SEO is a set of techniques that try to make your website rank higher than others in people's search results.  This is done by exploiting knowledge of how various search engines rank the raw search results.  If (say) Google takes semantic markup into account, then an SEO optimizer might add semantic markup to improve the relevance of a site or page.

A more salient question would be to ask why search engines like Google bother to pay any attention to semantic markup if people are exploiting it for SEO purposes.  Presumably there is enough useful / good semantic markup around to make it worthwhile ... and to counter the misleading / bad stuff that shonky SEO outfits might create.

Title: Why is semantic markup given more weight for search engines?

Body:
This question follows directly from the part of an  answer of this question - Why would one bother marking up properly and semantically? .

I would like to understand why SEO techniques gives more weight to semantically correct mark up?


答:
You can use them both together as they both have no conflict modes, but you shouldn't. While there are some major differences in coding philosophy between the two, there is also a lot of overlapping functionality. Pick one and use it.

If you're thinking of using both because of one or two plugins, do some more searching. Most plugins in one will have been ported across to the other. If you can't find something that works, you should invest the time to learn JavaScript better so that you can port it yourself. It simply isn't worth it in terms of page weight to include both frameworks.

To learn more about the differences between the two frameworks, check out jQuery vs MooTools.

To specifically answer your questions:

Yes, theoretically if you use the noconflict modes for each framework, there shouldn't be any conflicts. But no, it's not recommended to use them together because of duplicated functionality and the enormous page size.

There are always cross-browser issues with any JavaScript framework, especially because new browser versions are constantly being released. MooTools and jQuery both do an excellent job of staying on top of the browser issues, but that doesn't mean either of them solves every problem you might run into. However, I don't know of any browser issues that would result as an incompatibility between the two frameworks.

Your application would be less robust. You would have more points of failure, a larger page size, and debugging would be more difficult. Maintenance would be harder and you would have to have programmers experienced in both frameworks. A JavaScript framework isn't like a patch that you can put on a leaky roof, where more patches would allow less water inside. You're trying to mix slate and cedar shingles. Both work fine on their own, but they don't make much sense used together.

Title: is it safe to use jQuery and MooTools together?

Body:
I just need to know is it safe to use jQuery and MooTools Together in one web framework?

I am not trying create application using both of them, but I am in a situation where I need to modify mootool based application framework, so I am used to jquery, I don't want to waste my time learning mootools and I think jquery is better than the mootools in many contexts like number of applications, plugins etc.

so questions are

is it safe to use mootools and jquery in one framework?

will there be cross browser issues?

how robust the application will be when using both?