问:
Is this a good game plan to become a fluent Java developer?
I am an efficient person, and I am trying to find the best method of becoming a great Java developer. Here's what I'm thinking:

First, learn syntax and Object Oriented concepts. Practice it, and read it as fluently as a spoken langauge. Program very small, all-in-one class programs (30-50 lines) to practice basic concepts, and finish most of the codingbat pratice problems.

Learn the fundamental libraries: java.util, java.lang, and java.io. Master these, and the concepts that apply to them. Write some small programs with simple class structure, and solve a bunch of problems on codeabbey with the newly taught concepts.

Become familiarized with many of the other Java libraries by writing a program based around the concepts that are convered in it. Ex: I could make a simply painting application w/ java.awt. Each program may take a couple days to complete, and will have class structures that will become slightly more complex over time.

Start making medium sized projects and study source code of highly successful java projects. These projects might take a week or two, and will mostly be clones of simple applications and utilities. Do this until I am very comfortable with Java and the standard libraries.

Start to take on progressively bigger projects. Look for big open source projects to gain experience in, and look for small time jobs (that progressively get bigger) in Java development. Maybe get certification, and take some test to verify Java programming abilities.

I would love some criticism on my plan, and if some of the more experienced programmers could tell me what they would do if they were to learn programming all over again. I am currently on the tail-end of step 2, and am highly motivated. Thanks!

答:
That sounds like a great plan. Unfortunately, as they say in in the military "No plan survives contact with the enemy."

Learning any complex subject can rarely be handled in a such a simple linear fashion. The fundamental libraries are huge, and as a beginner you simply won't have the context need to understand large sections of them. Heck, I've been programming for 25 years and large sections of them are completely opaque to me.

In my experience learning programming requires lots of loops and recursion:

I hear about some cool new tool that might be useful in a small
project I'm working on. I read the documentation. I have no idea
what it's talking about.

I Google and Wikipedia some of they key words. I'm still lost. I skim any related

books I haven on hand. I get an inkling of the general gist of the tool. I decide
it's too complex and sophisticated for my current needs, so I move on.

After several weeks of working on my project I get a dim recollection that something
I'm trying to do was available in that cool tool I didn't understand. I re-read the
documentation. I understand parts of it now! The rest is still opaque.

I try writing a few small sample programs using the cool tool. I can't get any of
them to work. I go back to my project.

A after few days more of general reading and struggling with my project, a light bulb
goes off and I understand why my sample programs didn't work. I go back to my
sample programs and get them all working.

I modify my project to use the cool new tool. It works ... mostly.

I re-read the documentation for the cool new tool and I see now that it is a
model of clarity and could not be written any more simply or precisely.


答:
Like Charles, I have about 25 years' commercial experience. The thing I find easier to learn a language is to just use it. Think of a project that you are interested in and just start working on it. You'll learn the language and associated libraries as you go. Because it is a project you have interest in, you'll stay motivated when things get difficult. Because it is a stand-alone project, it has a completion to look forward to. Keep the project small enough to be do-able

Learning a language is (relatively) easy. "Getting" a language takes time (Python was a big jump from C#). Learning all the associated libraries tends to be hard. You can't learn them all, so target the project so you pick up the things you're after.

I started a project a couple of months ago. The aim was to learn Swift, Mac development and Cocao. My previous project was Objective-C and OpenGL.

ContentLicense: CC BY-SA 3.0

Title: Is this a good game plan to become a fluent Java developer?

Body:
I am an efficient person, and I am trying to find the best method of becoming a great Java developer. Here's what I'm thinking:

First, learn syntax and Object Oriented concepts. Practice it, and read it as fluently as a spoken langauge. Program very small, all-in-one class programs (30-50 lines) to practice basic concepts, and finish most of the codingbat pratice problems.

Learn the fundamental libraries: java.util, java.lang, and java.io. Master these, and the concepts that apply to them. Write some small programs with simple class structure, and solve a bunch of problems on codeabbey with the newly taught concepts.

Become familiarized with many of the other Java libraries by writing a program based around the concepts that are convered in it. Ex: I could make a simply painting application w/ java.awt. Each program may take a couple days to complete, and will have class structures that will become slightly more complex over time.

Start making medium sized projects and study source code of highly successful java projects. These projects might take a week or two, and will mostly be clones of simple applications and utilities. Do this until I am very comfortable with Java and the standard libraries.

Start to take on progressively bigger projects. Look for big open source projects to gain experience in, and look for small time jobs (that progressively get bigger) in Java development. Maybe get certification, and take some test to verify Java programming abilities.

I would love some criticism on my plan, and if some of the more experienced programmers could tell me what they would do if they were to learn programming all over again. I am currently on the tail-end of step 2, and am highly motivated. Thanks!


问:
Can someone else copyright my wordpress plugin if I don't own any copyright for it?
Assuming I have a plugin hosted on wordpress.org, can someone else just take my plugin and copyright it?

Can they take the name of my plugin and copyright or trademark it (assuming I do not have it copyrighted or trademarked)?

Can they take my code, extensively add to it and build off it creating a new plugin but using my code as a base without my permission?

What if they copyrighted it before I got a chance to?

What if they file for a provisional patent on my work? Can they do that?

答:
Copyright, trademark, and patents are three very different things with very different laws concerning each. You seem to be confused on the basics of these matters you should do some research; here is a document explaining some of the US copyright system.

In general:

Copyright protects a specific expressions of an idea.

Patents protect inventions; generally physical.

Abstract patents are generally invalid, see Alice v Bank

Trademark protects business names, logos, etc.

Copyright attaches when the work is fixated, i.e. when you write it down, record it as a file on a storage device, etc. You don't need to register a copyright to own it; you need to register your copyright if you want to sue someone and be eligible for statutory damages. Actual damages can be awarded even without registration (n.b. I Am Not A Lawyer (IANAL.))

can someone else just take my plugin and copyright it?

Legally no, could they register it anyway, possibly.

can someone trademark the name of my plugin

I don't know much about trademark law, if they are using the mark then probably; i.e. they happen to have a similar product already that uses the name. The test, if i recall correctly, is about market confusion, i.e. could someone confuse your product for mine. Also, trademarks have to go through a 'comment' period where interested parties can object to your mark.

What if they file for a provisional patent on my work? Can they do that?

Legally no, since software patents are abstract and are rarely valid, but invalid patents are granted all the time. Most software patents wouldn't hold up in court but the cost of litigation allows invalid patents to be wielded as a threat, again IANAL!


问:
What kind of copyright laws should I be aware of when creating software?
I'm trying to build a winform so I can play a web based game and have some other little utilities on the side. I do not plan on ever selling this or even distributing it to more than a handful of people.
My question is, Would I be infringing on any copyright laws if I use images from the game in my client?
I just want to be safe on the off chance the company does see it, I don't want to get sued.

Edit: I took a screenshot from the game and cropped out the icons for each skill that I will use as a link to skill guides, calculators, etc.
Also, I should note that I live in America and the company is based in the UK. I don't know if that affects anything or not.

答:
Copyright concerns/protects (source)

Reproduction of the work

Derivatives of the work

Distribution/publication of the work

Public performances of the work

Public displays of the work

But there is fair use! There is a 4 pronged test if the use is fair, your use might be fair, your edit implies to me that it might!


答:
You establish ownership by asserting copyright.

I can easily do this for a $1000 fee. Or you could do it yourself by inserting a comment:

```<code>// Copyright Your Name Here , 24/04/2015, all rights reserved
</code>```

at the top of your source code.

Title: Can someone else copyright my wordpress plugin if I don't own any copyright for it?

Body:
Assuming I have a plugin hosted on wordpress.org, can someone else just take my plugin and copyright it?

Can they take the name of my plugin and copyright or trademark it (assuming I do not have it copyrighted or trademarked)?

Can they take my code, extensively add to it and build off it creating a new plugin but using my code as a base without my permission?

What if they copyrighted it before I got a chance to?

What if they file for a provisional patent on my work? Can they do that?

Body:
You establish ownership by asserting copyright.

I can easily do this for a $1000 fee. Or you could do it yourself by inserting a comment:

// Copyright Your Name Here , 24/04/2015, all rights reserved

at the top of your source code.


问:
How to count sort comparison
When it is said that this sort has M number of comparisons what does it mean?

As an example:

```<code>procedure bubbleSort( A : list of sortable items )
   n = length(A)
   repeat
     swapped = false
     for i = 1 to n-1 inclusive do
       if A[i-1] > A[i] then
         swap( A[i-1], A[i] )
         swapped = true
       end if
     end for
   until not swapped
end procedure
</code>```

Has

```<code>for i = 1 to n-1
</code>```

or

```<code>for(int i = 0 ; i < n-1; i++)
</code>```

is this comparison (i < n-1) taken into account?

Or in merge sort, beside the main comparison:

```<code>        if (v[first1]<v[first2])
</code>```

at the end of a used function it is written:

```<code>    while (first1 <= last1)
        temp[index++] = v[first1++];
    while (first2 <= last2)
        temp[index++] = v[first2++];
    for (index = first; index <= last; index++)
        v[index] = temp[index];
</code>```

Are these comparisons are taken into account?

答:
When you find a statement like "M number of comparisons" about sorting algorithms in literature, the author typically means the number of comparisons between the sorted elements, not the comparisons of something like loop indexes. So if you are asked this in a university assignment, I would guess that this is the number which is meant (but to make that clear, if you give an answer, why not add a note describing exactly what you counted).

In fact, this assumes that the predominant operations in a sorting algorithm are comparisons and "swaps", and that there are not more loop iterations than comparisons between the sorted elements. When you assume the latter, for calculating Big-O it is irrelevant if you count the "loop index comparisons" or not.

Furthermore, note that a term like "exact number of comparisons" instead of "O(number of comparisons)" makes only sense for a specific implementation of an algorithm, not "for an algorithm" in general. So when you try to compare the number of comparisons of your implementation of bubble sort to a different implementation from a different author, you have to make sure you do not compare apples and oranges. That is why comparisons in terms of "Big-O" makes more sense when comparing algorithms on a theoretical level.

However, from a more practical point of view, counting the exact "number of comparisons" (or swaps) will indeed make sense when it comes to speed comparisons of specific sorting implementations on real-world data.

Title: How to count sort comparison


问:
How to use DDD to solve a common address situation?
This is a simple example to show a situation that I find hard to solve with DDD.

Consider this:
- A property (e.g. a house) has an Address.
- An address can be complete or partial (country only; country and state; country, state and city).
- When a end-user is searching for properties, I need to display a list of all countries.
- When a country is selected, I need to retrieve all related states.
- When a state is selected, I need to retrieve all related cities.

This can be easily done using a data driven approach (querying against a relational model), but when I try to model this, thinking in Domain Driven Design, I'm failing.

I have this obvious constraints:

A city can't exist without a estate.

A estate can't exist without a country.

Conclusion - country is the aggregate root to enforce this constraints.

I'm supposing that address is another aggregate root. But address can only refer to an aggregate root, so how can I refer a partial address? Do I need to think in another root?
When I need to query for city, I need to bring the whole country aggregate root?
And what if I need to search for all cities available for a given string? I need to query for all countries and than transverse through relations?

In this situation, the most obvious solution for me is to have and aggregate root for city, state, country and address. But this is an anemic model.
But to avoid an anemic model, it looks like the only way to solve is having different models. One to insert new cities (using the country aggregate) and others to retrieve and associate those entities. But this smells bad.

I'ts very hard to find a sample that cover a situation like this.
Can someone give me some directions? I'ts fine to recommend a book, but I would love some direct insights.

I read a lot about DDD and I know most of the terms (aggregate, entities, services, associations, value-objects).

答:
Object-oriented modeling, especially in context of DDD is all about behavior. You are talking about anemic model, but I'm having hard time figuring out what behavior would country/state/city have. Mostly, they are just holders of data.

There is also a conflict in your narrative. You are saying the user can get a country or state and based on this, get the data on lower hierarchy. You cannot do this if country and state don't have identity to be identified with, meaning they have to be entities.

In your case, I wouldn't mind creating each of those as an entity. You could also create a composite key for each. For example city key would be composed of {country_id, state_id, city_id}. You can also enforce this by only allowing to "add" new state through country and new city through state. They could create the "containing" part of the key while leaving the child ID to database engine.


问:
Does it really need to convert decimal,string, etc to binary?
I'm very new to programming. Just read some articles about algorithm for converting a decimal or string to binary. But,according to what I know, computers hold these data in binary form. So why don't we just read raw binary in the memory? Isn't it much easier and faster?
If possible, how to do that in C or Assembly?

I just need the binary form of input number, for example: check if a positive number is a power of two or not. My idea is: if N=2^k (N and k are positive integers) then binary form of N is 100...0 (k times of 0).

答:
We do work with binary representations of numbers internally, but ultimately people want to use a computer program, and there the format isn't usable. So we do need to have code for converting string representations of things into binary, but only for new data entered by the user.

People are extremely bad at remembering information-dense representations - that's why we invented the alphabet in the first place. So if the user enters a price or age, they come into the program as a sequence of characters. To do any arithmetic on them, the computer has to convert them to numbers, which on virtually all digital computer means creating the bit pattern corresponding to that number.

Far more often the inverse problem arises: the program has stored a value as a number, but the user would like to see the human-readable digit sequence. This means the computer has to format the number back into the input syntax (or remember the original representation).

It is true that the entire software business would become easier if people could learn to understand binary representations, but that isn't in the cards until we invent some serious neuroprogramming trickery, so for the time being we are stuck with converting numbers back and forth all the time.


答:
Yes, it's true.  Both strings and decimals, as well as all other types, are represented in binary.

However, the problem lies in the significance of the binary.  You cannot simply read a string as a decimal, or at least you shouldn't if you were looking to get the decimal representation of that decimal.

Take for example this string in ASCII:  "1.5"

In binary, this is represented by an array of bytes of size 4 or greater.

```<code>1  .  5  \0
31 2E 35 00
</code>```

If this were to be interpretted as a double, the value would be:

```<code>4.07659398311e-315
</code>```

What does this have to do with the number 1.5?  They share the same binary message, but since binary is only as good as its interpretation, this double is meaningless.  This interpretation is complicated further when you consider that some systems prefer to save decimal information in big-endian or little-endian formats, meaning you're also dependent on the system you're working on.

In order to convert this into a double, you'd have to parse this binary as it was intended.  As it turns out, the equivalent conversion of 1.5 in hexadecimal is 0x3FF8000000000000.

If you prefer precision, then you generally tend to retain only the string form in your program.  Similarly, if you need to use this value in calculations, you keep the float or double form.  So what happens if you need both?  You keep both in your program, using whichever form is best suited for precision or calculation.  Long past are the days when keeping both in memory might be an issue (save for few exceptions where speed is critical, such as in the case of drivers).

If you wanted to determine whether or not a string representation of a number is a power of 2, the calculation to do so would be more complicated than the simple act of converting it first to a number.  Once it is a number, determining whether or not it is a power of two is trivial, with any binary string containing exactly one 1 (in the case of decimal, you should check also for binary strings containing exactly one 0 for negative decimal values).

Title: Does it really need to convert decimal,string, etc to binary?

Body:
I'm very new to programming. Just read some articles about algorithm for converting a decimal or string to binary. But,according to what I know, computers hold these data in binary form. So why don't we just read raw binary in the memory? Isn't it much easier and faster?
If possible, how to do that in C or Assembly?

I just need the binary form of input number, for example: check if a positive number is a power of two or not. My idea is: if N=2^k (N and k are positive integers) then binary form of N is 100...0 (k times of 0).

Body:
Yes, it's true.  Both strings and decimals, as well as all other types, are represented in binary.

However, the problem lies in the significance of the binary.  You cannot simply read a string as a decimal, or at least you shouldn't if you were looking to get the decimal representation of that decimal.

Take for example this string in ASCII:  "1.5"

In binary, this is represented by an array of bytes of size 4 or greater.

1  .  5  \0
31 2E 35 00

If this were to be interpretted as a double, the value would be:

4.07659398311e-315

What does this have to do with the number 1.5?  They share the same binary message, but since binary is only as good as its interpretation, this double is meaningless.  This interpretation is complicated further when you consider that some systems prefer to save decimal information in big-endian or little-endian formats, meaning you're also dependent on the system you're working on.

In order to convert this into a double, you'd have to parse this binary as it was intended.  As it turns out, the equivalent conversion of 1.5 in hexadecimal is 0x3FF8000000000000.

If you prefer precision, then you generally tend to retain only the string form in your program.  Similarly, if you need to use this value in calculations, you keep the float or double form.  So what happens if you need both?  You keep both in your program, using whichever form is best suited for precision or calculation.  Long past are the days when keeping both in memory might be an issue (save for few exceptions where speed is critical, such as in the case of drivers).

If you wanted to determine whether or not a string representation of a number is a power of 2, the calculation to do so would be more complicated than the simple act of converting it first to a number.  Once it is a number, determining whether or not it is a power of two is trivial, with any binary string containing exactly one 1 (in the case of decimal, you should check also for binary strings containing exactly one 0 for negative decimal values).


问:
how integer type can handle text stream (getchar()) in C?
While going through C programming by Ritchie and kernighan, I came across the following code.

```<code>#include<stdio.h>
int main() {
    int t;
    t = getchar();
    while ((t=getchar()) != EOF) {
            putchar(t);
    }
    return 0;
}
</code>```

I am not able to understand how can a integer type variable c , be used to handle buffered text stream,

delimited by newline or ctrl-D,

When I tried for ,
printf("%d",getchar());

it's giving me ASCII value of only first character, but here t seems to be manipulating the whole buffer until I press enter,

and when I press ctrl-D in between line it just copies the previous buffer content.

does it mean ctrl-D is a delimiter as well as `EOF'?
Can someone please explain me the logic behind it?

答:
Usually, the operating system handles the buffered text stream.  It does this for a variety of reasons, mostly for performance, but also to support features like inline editing.

Your program is sleeping until you either press enter or ctrl-D.  At that point, the entire line is passed to your programs input stream.  Then each getchar call will retrieve only one character from that stream at a time and return it in t.  As long as there is input available, getchar will immediately return with the first character of that data.

So the next question is what happens when the string runs out.  Assuming you haven't indicated end of file with ctrl-D, getchar will then block while waiting for user input, and your program again sleeps while the operating system gets back to work.

So, t isn't manipulating the whole line, the operating system is, and t hasn't yet been assigned at this point, because getchar hasn't returned yet.


问:
Conceptual mismatch between DDD Application Services and REST API
I'm trying to design an application that has a complex business domain and a requirement to support a REST API (not strictly REST, but resource-oriented). I have some trouble coming up with a way to expose domain model in a resource-oriented manner.

In DDD, clients of a domain model need to go through procedural 'Application Services' layer to access any business functionality, implemented by Entities and Domain Services.
For example there's an application service with two methods to update a User entity:

```<code>userService.ChangeName(name);
userService.ChangeEmail(email);
</code>```

The API of this Application Service exposes commands (verbs, procedures), not state.

But if we also need to provide a RESTful API for the same application, then there is a User resource model, that looks like this:

```<code>{
name:"name",
email:"email@mail.com"
}
</code>```

The resource-oriented API exposes state, not commands. This raises the following concerns:

each update operation against a REST API can map to one or more Application Service procedure call, depending on what properties are being updated on the resource model

each update operation looks like atomic to REST API client, but it is not implemented like that. Each Application Service call is designed as a separate transaction. Updating one field on a resource model could change validation rules for other fields. So we need to validate all resource model fields together to ensure that all potential Application Service calls are valid before we start making them. Validating a set of commands at once is much less trivial that doing one at a time. How do we do that on a client that doesn't even know individual commands exist?

calling Application Service methods in different order might have a different effect, while REST API makes it look like there's no difference (within one resource)

I could come up with more similar issues, but basically they all are caused by the same thing. After each call to an Application Service, state of the system changes. Rules of what is valid change, the set of actions an entity can perform next change. A resource-oriented API tries to makes it all look like an atomic operation. But the complexity of crossing this gap must go somewhere, and it seems huge.

In addition, if the UI is more command-oriented, which often is the case, then we'll have to map between commands and resources on the client side and then back on the API side.

Questions:

Should all this complexity just be handled by a (thick) REST-to-AppService mapping layer?

Or am I missing something in my understanding of DDD/REST?

Could REST simply be not practical for exposing functionality of domain models over a certain (fairly low) degree of complexity?

答:
I've had the same problem and "solved" it by modelling REST resources differently, e.g.:

```<code>/users/1  (contains basic user attributes)
/users/1/email
/users/1/activation
/users/1/address
</code>```

So I've basically split the larger, complex resource into several smaller ones. Each of these contain somewhat cohesive group of attributes of the original resource which is expected to be processed together.

Each operation on these resources is atomic, even though it may be implemented using several service methods - at least in Spring/Java EE it's not a problem to create larger transaction from several methods which were originally intended to have their own transaction (using REQUIRED transaction propagation). You often still need to do extra validation for this special resource, but it's still quite manageable since the attributes are (supposed to be) cohesive.

This is also good for HATEOAS approach, because your more fine-grained resources convey more information on what you can do with them (instead of having this logic on both client and server because it can't be easily represented in resources).

It's not perfect of course - if UIs is not modelled with these resources in mind (especially data-oriented UIs), it can create some problems - e.g. UI presents big form of all attributes of given resources (and its subresources) and allows you to edit them all and save them at once - this creates illusion of atomicity even though client must call several resource operations (which are themselves atomic but the whole sequence is not atomic).

Also, this split of resources is sometimes not easy or obvious. I do this mainly on resources with complex behaviors/life cycles to manage its complexity.

Body:
I've had the same problem and "solved" it by modelling REST resources differently, e.g.:

/users/1  (contains basic user attributes)
/users/1/email
/users/1/activation
/users/1/address

So I've basically split the larger, complex resource into several smaller ones. Each of these contain somewhat cohesive group of attributes of the original resource which is expected to be processed together.

Each operation on these resources is atomic, even though it may be implemented using several service methods - at least in Spring/Java EE it's not a problem to create larger transaction from several methods which were originally intended to have their own transaction (using REQUIRED transaction propagation). You often still need to do extra validation for this special resource, but it's still quite manageable since the attributes are (supposed to be) cohesive.

This is also good for HATEOAS approach, because your more fine-grained resources convey more information on what you can do with them (instead of having this logic on both client and server because it can't be easily represented in resources).

It's not perfect of course - if UIs is not modelled with these resources in mind (especially data-oriented UIs), it can create some problems - e.g. UI presents big form of all attributes of given resources (and its subresources) and allows you to edit them all and save them at once - this creates illusion of atomicity even though client must call several resource operations (which are themselves atomic but the whole sequence is not atomic).

Also, this split of resources is sometimes not easy or obvious. I do this mainly on resources with complex behaviors/life cycles to manage its complexity.


答:
I will answer your question.

So why don't we just read raw binary in the memory?

But we are reading raw binary - calculations, netowrking, it is all binary-based representation. I will go a step further and say that computers ultimately use only binary representation.

Isn't it much easier and faster? If possible, how to do that in C or Assembly?

Let's consider it.

Assume that we have a two buttons keyboard with 0 and 1, how the code for reading will looks like? (pseudocode, warning!):

```<code>function readNumber() {
  int number;
  while(someStopCondition()) {
    number = (number << 1) | readClick()
  }
  return number;
}
</code>```

Is is a correct idea what you want to achive? You have to consider multiple types of numbers, like decimals too. How to user will input an 2.1?

01000000000001100110011001100110

Yes, this is 2.1. The point is computers are for humans, so they should solve problems for us without making it more complex.

Body:
I will answer your question.

So why don't we just read raw binary in the memory?

But we are reading raw binary - calculations, netowrking, it is all binary-based representation. I will go a step further and say that computers ultimately use only binary representation.

Isn't it much easier and faster? If possible, how to do that in C or Assembly?

Let's consider it.

Assume that we have a two buttons keyboard with 0 and 1, how the code for reading will looks like? (pseudocode, warning!):

function readNumber() {
  int number;
  while(someStopCondition()) {
    number = (number << 1) | readClick()
  }
  return number;
}

Is is a correct idea what you want to achive? You have to consider multiple types of numbers, like decimals too. How to user will input an 2.1?

01000000000001100110011001100110

Yes, this is 2.1. The point is computers are for humans, so they should solve problems for us without making it more complex.


问:
Writing a parser on top of an XML-based AST: am i doing it right?
I have a sort of AST defined in XML that i'm trying to parse and evaluate. The XML tree contains the tokens and all the information i need. However, i'm finding it difficult to do it "properly". Here's what i have:

```<code>    <node type="operation">
        <value name="OP">AND</value>
        <value name="A">
            <node type="comparison">
                <value name="OP">EQ</value>
                <value name="A">1</value>
                <value name="B">1</value>
            </node>
        </value>
        <value name="B">
            <node type="comparison">
                <value name="OP">EQ</value>
                <value name="A">2</value>
                <value name="B">2</value>
            </node>
        </value>
    </node>

    def getNode() {
        switch (xmlNode[type]) {
            case 'operation':
                new OperationNode(xmlNode[value.OP], getNode(xmlNode[value.A]), getNode(xmlNode[value.B]))

            case 'comparison':
                new ComparisonNode(xmlNode[value.OP], xmlNode[value.A], xmlNode[value.B])
        }
    }

    nodes = getNode(xmlTree)
    nodes.evaluate()
</code>```

That's pseudo-code, but you can get an idea of what i'm doing. Basically, i recursively go into every node element of the XML, discover what it is based on my switch-case, and then create the proper object in my domain, so i can later evaluate all the nodes together.

But i have a few questions:

How can i get rid of the switch? Seems very dirty to me, but i can't think of a better solution

How can i evaluate all nodes elegantly? Right now, all nodes inherit from a base Node class, which has an eval() method, which by polymorphism, i endup having all the different behaviors between conditions and operations.

Is there a more efficient way of traversing this XML?

答:
Depending on your implementation language, there may be dynamic mappings or code generators to map XML to your object graph.

If you don't want to go that route, I'd suggest using an event based parser rather than creating the XML document, then creating your AST from the events instead using recursive descent. So when you see the start of the value element you call a function which returns a ValueNode and let the call stack manage the stack. (this assumes the call stack is large enough for your deepest nested expression, which is probably true in practice but does open up a failure mode if someone wants to create a nasty XML document).

If you do go down the hand-coded parsing route, you won't get away from switching on the element tag name. You might hide it using a map of tag name to function to call, but if your implementation language supports switch on strings then that's unlikely to improve readability much.


问:
How do I design a Javascript Object to not use any public properties?
I have been playing with the Object creation outlined by Douglas Crockford in his new talk "The Better Parts"

```<code>function constructor(spec){
    var that = otherConstructor(spec),
        member,
        method = function(){
           // spec, member, method all available without using this
        };

     that.method = method;
     return that
}
</code>```

In the code I'm working on I have a member value that I'd like to set in my object and my first instinct was to make that member public and simply change that value. When I asked Crockford the best way to do that (getter/setter vs that.property) he replied:

I covered that. You don't need public properties at all. Design at a higher level.

So I'm left wondering, what would be the higher level design?

If this is a simplified version of my object

```<code>animator = function(){
    var that = {},
        playbackSpeed;

    return that;
}
</code>```

and my goal is to mutate playbackSpeed. My inclination is to add a public method setPlaybackSpeed. Is this what he means?

答:
When you create an object with the new keyword, you have access to the this object which represents the "public" view of the object. Inside the scope of the function you also can create local variables which are then in the "private" scope. When you assign a function to a field of this and implement that function in the same scope, it can access any of your private variables. Here is an example:

```<code>function Animator (specs) {

    // private variable
    var playbackSpeed = specs.playbackSpeed;

    // public method
    this.setPlaybackSpeed = function(speed) {
         // can access playbackSpeed because it is in the surrounding scope
         playbackSpeed = speed;
    }

}

var animator = new Animator( { playbackSpeed: 3.0 } );
</code>```

Body:
When you create an object with the new keyword, you have access to the this object which represents the "public" view of the object. Inside the scope of the function you also can create local variables which are then in the "private" scope. When you assign a function to a field of this and implement that function in the same scope, it can access any of your private variables. Here is an example:

function Animator (specs) {

    // private variable
    var playbackSpeed = specs.playbackSpeed;

    // public method
    this.setPlaybackSpeed = function(speed) {
         // can access playbackSpeed because it is in the surrounding scope
         playbackSpeed = speed;
    }

}

var animator = new Animator( { playbackSpeed: 3.0 } );


问:
How to handle "circular dependency" in dependency injection
The title says "Circular Dependency", but it is not the correct wording, because to me the design seems solid.

However, consider the following scenario, where the blue parts are given from external partner, and orange is my own implementation. Also assume there is more then one ConcreteMain, but I want to use a specific one. (In reality, each class has some more dependencies, but I tried to simplify it here)

I would like to instanciate all of this with Depency Injection (Unity), but I obviously get a StackOverflowException on the following code, because Runner tries to instantiate ConcreteMain, and ConcreteMain needs a Runner.

```<code>IUnityContainer ioc = new UnityContainer();
ioc.RegisterType<IMain, ConcreteMain>()
   .RegisterType<IMainCallback, Runner>();
var runner = ioc.Resolve<Runner>();
</code>```

How can I avouid this? Is there any way to structure this so that I can use it with DI? The scenario I'm doing now is setting everything up manually, but that puts a hard dependency on ConcreteMain in the class which instantiates it. This is what i'm trying to avoid (with Unity registrations in configuration).

All source code below (very simplified example!);

```<code>public class Program
{
    public static void Main(string[] args)
    {
        IUnityContainer ioc = new UnityContainer();
        ioc.RegisterType<IMain, ConcreteMain>()
           .RegisterType<IMainCallback, Runner>();
        var runner = ioc.Resolve<Runner>();

        Console.WriteLine("invoking runner...");
        runner.DoSomethingAwesome();

        Console.ReadLine();
    }
}

public class Runner : IMainCallback
{
    private readonly IMain mainServer;

    public Runner(IMain mainServer)
    {
        this.mainServer = mainServer;
    }

    public void DoSomethingAwesome()
    {
        Console.WriteLine("trying to do something awesome");
        mainServer.DoSomething();
    }

    public void SomethingIsDone(object something)
    {
        Console.WriteLine("hey look, something is finally done.");
    }
}

public interface IMain
{
    void DoSomething();
}

public interface IMainCallback
{
    void SomethingIsDone(object something);
}

public abstract class AbstractMain : IMain
{
    protected readonly IMainCallback callback;

    protected AbstractMain(IMainCallback callback)
    {
        this.callback = callback;
    }

    public abstract void DoSomething();
}

public class ConcreteMain : AbstractMain
{
    public ConcreteMain(IMainCallback callback) : base(callback){}

    public override void DoSomething()
    {
        Console.WriteLine("starting to do something...");
        var task = Task.Factory.StartNew(() =>{ Thread.Sleep(5000);/*very long running task*/ });
        task.ContinueWith(t => callback.SomethingIsDone(true));
    }
}
</code>```

答: Some IOC containers (for example Spring or Weld) can solve this issue using dynamically-generated proxies. Proxies are injected on both ends and the real object is only instantiated when the proxy is first used. That way, circular dependencies aren't an issue unless the two objects call methods on each other in their constructors (which is easy to avoid).</p>


问:
Is there a approximate string comparison function which is odd like mathematical functions are odd?
I say odd like a mathematical function, a mathematical function is odd if

```<code>f(-x) = -f(x)
</code>```

I understand that comparing two strings may seem to have little to do with this, because the arguments cannot be negative, but I mean that the functions value should be the negative of it's value with swapped arguments, i.e.,

```<code>distance(str2, str1) = -distance(str1, str2);
</code>```

答:
You could do this with any string distance function.

For example, consider the following distance function:

```<code>distance(a, b)
{
    return calc(a, b);
}
</code>```

If you make the order of the arguments significant, then you can invert the sign of the result as needed:

```<code>distance(a, b)
{
    var first = getFirstAlphabetically({a, b});

    var isNegative = (a != first);
    var sign = isNegative ? -1 : 1;

    return calc(a, b) * sign;
}
</code>```

Keep in mind this is just pseudocode.

Body:
You could do this with any string distance function.

For example, consider the following distance function:

distance(a, b)
{
    return calc(a, b);
}

If you make the order of the arguments significant, then you can invert the sign of the result as needed:

distance(a, b)
{
    var first = getFirstAlphabetically({a, b});

    var isNegative = (a != first);
    var sign = isNegative ? -1 : 1;

    return calc(a, b) * sign;
}

Keep in mind this is just pseudocode.


问:
What do you do when you have to work on a project using a language that you hate?
I've recently been assigned to work on a project written in PHP. I can't change that, and have no intention of really trying.

However, this can't be an uncommon scenario. How do you motivate yourself to work on the project when the code you're looking at and producing constantly makes you want to cry?

EDIT:

It should be noted that this is pretty much the only on-campus job doing anything software related available at the moment, so "just change jobs" isn't really an option :(

答:
You design the programming language that you would like to use, then write a compiler that outputs the language you don't like to use.

At least, that's what these guys did:

haXe targets PHP, Flash, JavaScript, C++ and Neko; maybe JVM in the future

Wasabi targets VBscript, JavaScript, PHP4, PHP5 and .NET

Scriptol targets PHP and C++

CoffeeScript targets JavaScript

ContentLicense: CC BY-SA 2.5


问:
Alternatives to #if when polymorphism doesn't seem possible
There are couple of places where #if seems to give you abilities that polymorphism doesn't:

Conditionally specifying base class

When a section contains code that is not recognised by a compiler on another platform

e.g. some new operator only supported on one platform

I was thinking about splitting into 3 partial classes so each platform includes the 2 it requires, but that seems worse to me.

Example 1

Changing base class, depending on condition

```<code>public class FullBase
{
    public void Register()
    {
        Console.Write("I am full featured so will use the :-) operator");
        int a = 1 :-) 2
    }
}
public class MobileBase
{
    public void Register()
    {
        Console.Write("My compiler does not know what the :-) operator is");
    }
}
#if MOBILE
    public class MyClass : MobileBase
#else
    public class MyClass : FullBase
#endif
{
    //...
}
</code>```

Example 2

Here, I have a class to hide the IDisposable pattern boilerplate.  If I moved to DI, I think it would introduce DI boilerplate in the many derived classes.

```<code>public class Disposable : IDisposable
{
    //...

    private void RunChecks()
    {
        #if !MOBILE
          //Use reflection to walk the OBJECT tree looking for potential issues
        #endif
    }
}

public class A: Disposable
{
    //...
    protected override void DisposeManagedResources()
    {

    }

}
// Also Class B, C, D, E.....
</code>```

答:
Conditional compilation effectively creates multiple versions of the code base. That's exactly the purpose of version control branches.

The other alternative is put whatever code needs to vary in its own assembly/dll. Different dlls can contain different implementations of the same class (assuming the public fields are the same).

Both alternatives have the advantage of not cluttering the code with every alternate implementation simultaneously and presenting only the code you're working with as a coherent whole.


问:
How should a senior programmer monitor another senior programmer?
I'm working with a new senior programmer who has almost the same amount of experience as me. He his own project to work on -- but I have to make sure he does not mess things up.

Now, how can I monitor him since he's not junior?

Do I examine his code? Cons of this are that I am not as deep into project as himself so it's time consuming for me (have my own project besides this).

Do I only do QA from the perspective of another senior?

Any advise here is appreciated. I was recently in the same situation where I relied that another senior will handle all tickets properly, and then it took me 3 weeks to fix his oversights. So I do not want to be in the same situation again.

答:
Start doing code reviews. Whenever he has some feature finished, go through all the changes together and discuss them. Do the same thing for all your code, discuss your code with him too.

That way you can both make sure the other doesn't mess up, you both know what the other is doing, you can decide on a common style together, you can learn from each other, and you'll probably find bugs and improvements that would have taken much more time to fix if they had been found by users later on.

A good code review is not necessary directed from a senior developer to a junior developer: peer reviews are good too. Everyone makes mistakes, and everyone has something to learn whether you are on your first day of your first job or on your final work day before retirement.

Code reviews are collaborative, not instructive: they are not college lectures and are not like grading homework. They are focused on working together to achieve a common goal: good code. Keep an open mind and be receptive to constructive criticism.


问:
How do you decide your side projects
At any given time, I usually have a bunch of ideas for weekend/side projects that I can work on. The ideas can be generally be categorized into these:

Self Learning: Learning a new language/ technology/ framework

Work related: Learning/Doing something that would help you at work

Money: Projects that (you think) can make some money

Fun/Utility projects

These are just the rough categories that I can think of and there can be more/other ways of classification.

My question is based on your experience what should drive the decision of what kind of project to work on. What parameters apart from the type of project should impact this decision (time, effort, money...)

答:
I've commited to the Shuffle app on Android, this is for my own usage, but it was also a learning experiences as I got to use the Android SDK for something larger than myself.

I started an online booking system because the idea had nagged me for quite some time that hairdressers used paper books to book their customers. This was quite a learning experience as well, since it was the first I started with money making focus. It was my first experience with marketing and sales on my own. This in turn created a lot of knowledge that I find very usefull as I work.

Lastly I made a project to collect errors that occur in JavaScript functions on websites to help developers see errors that occur when their users use the site. This was born out of the need of having such a system, as I was creating JavaScript heavy sites myself for the booking system.

In general Learning and Utility are the ones that follow in nearly all the projects I have on the side. However the one that gives the most value back to me is the Shuffle project, as it is being used quite a lot.

If you want a side project that helps you continue commiting to it, I'd recommend getting a  project that you write for others. Something someone else wants to use, as well as you.

Title: How do you decide your side projects


问:
How to monitor a long-running program programmatically
What I've currently got can be summed up with this pseudo code:

```<code>public static void Main(string[] args)
{
    var listOfObjects = Database.GetObjectsToUploadToOnlineService();
    Parallel.ForEach(Upload)
}

private static void Upload(MyUploadObject obj)
{
    //Build object (takes a few milliseconds)
    //Format to JSON (takes a few more milliseconds)
    //Upload (can take up to a max of 10 minutes)
    //Wait for a response (can take up to a max of 10 minutes)
    //Save response to our database (takes a few milliseconds)
}
</code>```

This program is just set up on our server as a scheduled task. We own the program and can do what we want with it. My question stems from a blog about making automated monitoring checks (I don't have a link handy).

So that got me to think: How in the world can I modify my program so that I can fire up another "monitoring" program? Or should this change from being a console program to to say a WPF program that is hidden?

Overall, I would prefer to be able to just run a program on my computer that checks on the progress of the program through the network, so I don't have to RDP into the server to check on its status (but it wouldn't be the end of the world).

Overall, I suppose I would like to see a window that says something like: Process x of y so far, the following items are being processed. List the items in, like, a table and have them say like "Uploading" or "Waiting for response". Maybe if I get crazy I could also how a queue of failed items (but that would just be extra).

My mind keeps leaning towards an event, but I can't figure out how I would run a program that can subscribe and unsubscribe to a running program. Is this even possible?

答:
What you need is a way to communicate between your programs that does not tie them to each other. There are a number of ways to do this, you could have the task write to a file and have to monitor read from the file, make the task available via WCF so the monitor can 'poll' for changes, use the network...

To avoid reinventing the wheel, have a look at the log4net logging targets If I were to implement something like this I would probably use log4net and log to UDP or Telnet and have the monitor on the other end connect to it. log4net takes care of everything for you, including not throwing exceptions when there is no monitor active.


答:
From your comments I see you have a client/server database available, and you uploader already has a connection and write access? Then it would probably be easiest to add a "monitoring" or "status" table to the database and let your uploader report its progress there (log each "interesting" step there, probably the 5 steps you listed above).

To view the status, create a second program with GUI, which connects to the database and displays the status (for example, by polling in intervals of 1 minute). You can run that program on your local desktop, assumed it is possible to connect to the database from there.

Of course, when writing to a status table interfers with your database transactions, you might use a separate connection. You can also utilize a message queue mechanism like MSQM for it, but that might be an oversized solution for your simple case.

Title: How to monitor a long-running program programmatically

Body:
What I've currently got can be summed up with this pseudo code:

```<code>public static void Main(string[] args)
{
    var listOfObjects = Database.GetObjectsToUploadToOnlineService();
    Parallel.ForEach(Upload)
}

private static void Upload(MyUploadObject obj)
{
    //Build object (takes a few milliseconds)
    //Format to JSON (takes a few more milliseconds)
    //Upload (can take up to a max of 10 minutes)
    //Wait for a response (can take up to a max of 10 minutes)
    //Save response to our database (takes a few milliseconds)
}
</code>```

This program is just set up on our server as a scheduled task. We own the program and can do what we want with it. My question stems from a blog about making automated monitoring checks (I don't have a link handy).

So that got me to think: How in the world can I modify my program so that I can fire up another "monitoring" program? Or should this change from being a console program to to say a WPF program that is hidden?

Overall, I would prefer to be able to just run a program on my computer that checks on the progress of the program through the network, so I don't have to RDP into the server to check on its status (but it wouldn't be the end of the world).

Overall, I suppose I would like to see a window that says something like: Process x of y so far, the following items are being processed. List the items in, like, a table and have them say like "Uploading" or "Waiting for response". Maybe if I get crazy I could also how a queue of failed items (but that would just be extra).

My mind keeps leaning towards an event, but I can't figure out how I would run a program that can subscribe and unsubscribe to a running program. Is this even possible?


答:
Just to build on @JDT's answer, a common way to do this is writing messages to a message queue.  Whenever something important happens in your application it would write a message and send it to the message queue.  Typically the format of the message is XML or similar.  It's the queue writer.

The monitoring application reads (queue reader) the queue and picks the messages and processes them by saving them and analyzing the message versus prior messages or conditions.  If a condition is met, the monitoring application will raise an alert signifying a potential problem.

This decouples your application from monitoring itself as it is just firing away messages.  It's up to the monitoring application to determine when based on the current messages that something good or bad has happened.  Queue's are used because they offer a good means to store the messages without loss.

You want to centralized messaging if there are multiple instances of your application running.  If there is only 1 instance, then using other stores like the windows event log or a file can be sufficient.


问:
Automatic builders/chain setters for Java?
Consider that code:

```<code>FancyClass c = new FancyClass();
s.setParameter(value);
s.setParameter2(value2);
//a lot of parameters
</code>```

It is really naive, so we can use a builder pattern:

```<code>FancyClass c = new FancyClassBuilder().setParameter(value).setParameter2(value2).build()
</code>```

It is okay, but what if we have to use a lot of setters during a program?

```<code>s.setParameter(value)
s.setParameter1(value)
s.setParameter2(value)
s.setParameter3(value)
//more and more...
</code>```

It will be more efficient and less boilerplated:

```<code>s.setParameter(value).setParameter1(value).setParameter2(value)
 .setParameter3(value)
</code>```

Looks more okay and it allows programmer not do this action: (i hate it):

```<code>s.setParamter()
// a lot of doing smth
s.setParameter2()
</code>```

even there is no neccessary to put this setters away (because it is a some legacy issue, somebody just tap the enter twice and someone type in a other code...

What if...

```<code>@SetterChain
class MyFancyClass {
  public void setParameter(Parameter p) {}
  public Parameter getParameter(Parameter p) {}
  public void setParameter2(Parameter p) {}
  public Parameter getParameter2(Parameter p) {}
}

//somewhere else...

MyFancyClass s = new MyFancyClass()

//a long time ago

s.set().parameter(value).parameter2(value); //and more and more...
</code>```

Cool stuff or no? Is this solution would significally increase a code quality or not and its a wreck and why?

答:
It wouldn't prevent people from having:

```<code>s.set().parameter1(value);

// yadda yadda yadda

s.set().parameter2(anotherValue);
</code>```

Which is what you frowned upon in the first place, so I'd say it wouldn't increase code quality by itself.

Builder pattern - that you mention - does enforce passing all values in one place (or deferring construction of the object unless they're all in), but that's also accomplishable by having a constructor that expects every single value to be passed straight away, plus immutability - so, all getters and no setters.

Fluent builders are sort of syntax sugar for that, equivalent to named parameters like: Link

If you mean automatical generators for builder classes, rather than entity classes with chainable setters, then yes they do exist, eg. https://github.com/mkarneim/pojobuilder

Personally I don't see much point in using them, given that IntelliJ Idea or Android Studio is capable of automatically generating a builder class in a matter of seconds.

Body:
It wouldn't prevent people from having:

s.set().parameter1(value);

// yadda yadda yadda

s.set().parameter2(anotherValue);

Which is what you frowned upon in the first place, so I'd say it wouldn't increase code quality by itself.

Builder pattern - that you mention - does enforce passing all values in one place (or deferring construction of the object unless they're all in), but that's also accomplishable by having a constructor that expects every single value to be passed straight away, plus immutability - so, all getters and no setters.

Fluent builders are sort of syntax sugar for that, equivalent to named parameters like: Link

If you mean automatical generators for builder classes, rather than entity classes with chainable setters, then yes they do exist, eg. https://github.com/mkarneim/pojobuilder

Personally I don't see much point in using them, given that IntelliJ Idea or Android Studio is capable of automatically generating a builder class in a matter of seconds.

ContentLicense: CC BY-SA 4.0


答:
The Builder pattern addresses a particular problem that arises - those constructors with a dozen (or more!) arguments. Yes, there's often another problem lurking with such objects, but the Builder makes it so that one doesn't need too many constructors to handle all the different variations on how the object can be constructed.

A fluent style setter (where the setter returns this), doesn't have this issue. Other than some stylistic annoyances to it, I don't see a problem that needs to be solved.

Having a compile time annotation, while neat, cool, and powerful adds a significant amount of complexity to the build of the project and makes it difficult for someone (or something) reading the code to reason about it. Sure, you can annotate it and have the compiler do its magic... but there is often something before the compiler (aside fro the coder) who needs to deal with the code.

The "something" reading the code is a real concern here. The IDE doesn't know about the method set(). Nor does it know what it returns, nor all of the methods that it has.  This would make the IDE's view of the class a mass of red "this does not exist" markers.

The set() approach is also far from standard (and doesn't actually solve a real problem) and makes it harder for a new coder to come to the code base and understand it. It adds unnecessary complexity to the build process and can make the IDE unhappy.

While all of this may be cool and clever (yes, I think annotations are cool and clever and have a love / hate relationship with them myself), I don't think that this is a good path to follow.

Title: Automatic builders/chain setters for Java?

Body:
Consider that code:

```<code>FancyClass c = new FancyClass();
s.setParameter(value);
s.setParameter2(value2);
//a lot of parameters
</code>```

It is really naive, so we can use a builder pattern:

```<code>FancyClass c = new FancyClassBuilder().setParameter(value).setParameter2(value2).build()
</code>```

It is okay, but what if we have to use a lot of setters during a program?

```<code>s.setParameter(value)
s.setParameter1(value)
s.setParameter2(value)
s.setParameter3(value)
//more and more...
</code>```

It will be more efficient and less boilerplated:

```<code>s.setParameter(value).setParameter1(value).setParameter2(value)
 .setParameter3(value)
</code>```

Looks more okay and it allows programmer not do this action: (i hate it):

```<code>s.setParamter()
// a lot of doing smth
s.setParameter2()
</code>```

even there is no neccessary to put this setters away (because it is a some legacy issue, somebody just tap the enter twice and someone type in a other code...

What if...

```<code>@SetterChain
class MyFancyClass {
  public void setParameter(Parameter p) {}
  public Parameter getParameter(Parameter p) {}
  public void setParameter2(Parameter p) {}
  public Parameter getParameter2(Parameter p) {}
}

//somewhere else...

MyFancyClass s = new MyFancyClass()

//a long time ago

s.set().parameter(value).parameter2(value); //and more and more...
</code>```

Cool stuff or no? Is this solution would significally increase a code quality or not and its a wreck and why?


问:
Multi platform password storage with retrieval for applications with authorization?
I'm working on a development tool that requires knowing one or more api passwords for a user to operate. Currently it works on Mac, and uses keychain to store the credentials for later re-use.

Are there any similar password store options that are cross-platform and have the following properties?

Store the credentials securely

Ability to authorize applications to access the credentials repeatedly without re-authenticating?

Credentials are accessible via an API (provided the user has authorized one-time or indefinite access)?

(Nice-to-have) Ability to authorize applications for a specific time period (i.e. a week or a month), after which the user is required to re-authorize the application.

(Nice-to-have) Support for multi-factor authentication during authorization

Keychain works great in this sense, since it allows me to let them be responsible for the security of the credentials, and allows the credentials to be used by other applications (provided a structured credential key) with authorization that can be one-time or indefinite.

I've attempted to the scour the web (probably poorly), but I'm having trouble with the fact I only get password managers, which are geared towards a user requesting the credentials, rather than an application, or I get instructions for how to properly store using bcrypt, which is great for verifying passwords, but not if I need to retreive it later. For instance, I have a proof of concept for storing the credentials in LastPass, but it requires enter a master password each time the credentials are requested unless I store the master password somewhere accessible, which kind of defeats the purpose of the password manager in the first place.

答:
In a nutshell, you are writing a program that reads information from a protected secure storage facility (so it can call external APIs).  The secure storage facility itself has it's own authentication (username/password and possibly multi-factor authentication).

And the key is that this authentication to the secure storage facility you want to persist somehow, so that the program doesn't bug the user for it repeatedly over time, presumably across program restarts (maybe even operating system restarts).

So you want two storage facilities!

The first protected secure storage facility stores all the external API credentials.  The second protected secure storage facility stores ONE THING -- credentials to the first storage facility.

At this point, you want help on building the second storage facility.  The entire problem is reduced to one question: "How do I store one set of credentials"?

SSH solves this with ssh-agent (here) "ssh-agent allows the user to connect multiple times without having to repeatedly type the passphrase".  You start ssh-agent near the beginning of user login, and it sticks around until you logout or shutdown.

But that doesn't help you across logins.  Linux solves this with keychain (here) "Keychain will allow you to reuse an ssh-agent between logins, and optionally prompt for passphrases each time the user logs in"; (here) "re-use ssh-agent and/or gpg-agent between logins".

You mentioned your Mac OS uses keychain, which I assume is the same thing.

For Windows the question seems to be answered here (here) "Is there an equivalent of the OS X Keychain, used to store user passwords, in Windows?"


问:
Learning to Program in Assembly - Useful Resources
Following on from a previous thread, it has got me interested in learning a little about Assembly programming.  Not so much for wanting to program useful apps in, just to get a feel for low level programming to better understand what is happening.

Can anybody recommend any books or online resources for beginners?

Thanks.

答: Basically, in the sense of assembly programming, you need to know the underlying architecture first, then the correspondent language, for example, with the PIC micro-controllers, you can use the compiler which the provided and the language. I use this site for referencing to PIC micro-controller tutorials.


问:
What is the purpose of separating routes into individual modules with Node.js and Express?
My app uses Node.js and Express 4 and has the following code in the app.js file located in the root directory:

```<code>var express = require('express');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

app.use('/', index);
app.use('/users', users);
</code>```

The routes folder in the root directory contains an index.js file with the following code:

```<code>var express = require('express');
var router = express.Router();

router.get('/', function (req, res, next) {
    res.render('index');
});

module.exports = router;
</code>```

The routes folder also contains a users.js file with the following code:

```<code>var express = require('express');
var router = express.Router();

router.get('/', function (req, res, next) {
    res.render('users');
});

module.exports = router;
</code>```

I'm new to Express and Node.js. It's my understanding that this structure causes browser requests to domainName.com to run the index.js file, while requests to domainName.com/users will run the users.js file, resulting in different views being rendered in the browser.

What is the purpose of organizing the code this way? (i.e. why is app.use() in app.js used to isolate each router.get(path, callback) into it's own respective module?)

Is the commonly-accepted practice to organize routes differently for a single page app versus a website consisting of mostly static text, such as a blog? If so, how?

答:
When you only have two routes, it makes no sense to separate them in this way. However, when you consider a real application with many routes, it begins to make more sense.

/routes/user.js

```<code>var express = require('express');
var router = express.Router();
var User = require('../models/user');

router.get('/', function (req, res, next) {
    res.render('users');
});

router.param('userid', function (req, res, next, userid) {
    req.user = User.findById(userid);
    req.userid = userid;
});

router.get('/:userid', function (req, res, next) {
    req.user.exec(function (err, user) {
        if (err) { return next(err); }
        res.render('user', {user: user});
    });
});

router.put('/:userid', function (req, res, next) {
    User.findByIdAndUpdate(req.userid, req.body, function (err) {
        if (err) { return next(err); }
        res.render('user-updated');
    });
});

router.delete('/:userid', function (req, res, next) {
    User.findByIdAndDelete(req.userid, function (err) {
        if (err) { return next(err); }
        res.render('user-deleted');
    });
});

module.exports = router;
</code>```

Having all of that in app.js will get out of hand very quickly, even more so once you have more models than just user.

Also note that this isn't the only way to organize your routes/models/views nor is it the "best" way for all cases. You'll have you decide for yourself what will work best in each application.

Note, the code in the sample is of course all just sample code that probably won't work. My model methods were based off of mongoose model methods.

Body:
When you only have two routes, it makes no sense to separate them in this way. However, when you consider a real application with many routes, it begins to make more sense.

/routes/user.js

var express = require('express');
var router = express.Router();
var User = require('../models/user');

router.get('/', function (req, res, next) {
    res.render('users');
});

router.param('userid', function (req, res, next, userid) {
    req.user = User.findById(userid);
    req.userid = userid;
});

router.get('/:userid', function (req, res, next) {
    req.user.exec(function (err, user) {
        if (err) { return next(err); }
        res.render('user', {user: user});
    });
});

router.put('/:userid', function (req, res, next) {
    User.findByIdAndUpdate(req.userid, req.body, function (err) {
        if (err) { return next(err); }
        res.render('user-updated');
    });
});

router.delete('/:userid', function (req, res, next) {
    User.findByIdAndDelete(req.userid, function (err) {
        if (err) { return next(err); }
        res.render('user-deleted');
    });
});

module.exports = router;

Having all of that in app.js will get out of hand very quickly, even more so once you have more models than just user.

Also note that this isn't the only way to organize your routes/models/views nor is it the "best" way for all cases. You'll have you decide for yourself what will work best in each application.

Note, the code in the sample is of course all just sample code that probably won't work. My model methods were based off of mongoose model methods.


答:
It is only my belief, but trust and transparency in feedback should be at first place for any co-workers. It doesn't mean that you have to just let him/her into work without monitoring progress. First of all:

pair programming, but it takes a lot of time, although its worth doing, especially you will feel secure that you have a good and competent collegaue (or not). Worth doing in first phase of getting know each other.

code review, but it should be both-side code review - show him your code and let him ask you about it, not just monitoring his progress (he might have other techniques in writing code, but it might be useful as yours).

just talking, openess and trust in telling what is going wrong (nobody wants to say "i have some issues" for stranger) will help you too.

These are mine thoughts, i rely on them and it never get me into wrong path.

Title: How should a senior programmer monitor another senior programmer?

Body:
I'm working with a new senior programmer who has almost the same amount of experience as me. He his own project to work on -- but I have to make sure he does not mess things up.

Now, how can I monitor him since he's not junior?

Do I examine his code? Cons of this are that I am not as deep into project as himself so it's time consuming for me (have my own project besides this).

Do I only do QA from the perspective of another senior?

Any advise here is appreciated. I was recently in the same situation where I relied that another senior will handle all tickets properly, and then it took me 3 weeks to fix his oversights. So I do not want to be in the same situation again.


答:
Yes, there is a lot of them!  This is just the theory of even and odd part of functions adapted to this context.

Take any function h defined on pair of strings and set ĥ(a,b) = h(b,a). Then the odd and even part of h are respectively h- = (h - ĥ)/2 and h+ = (h + ĥ)/2.

Now, if you take any function h defined on pair of strings, then its odd part h- suits your requirements. Furthermore you obtain every interesting function this way, because if h is odd then it is its own odd part h = h-.

It might also be fun to remark, as @MetaFight did, that given any odd function u which only takes the values 1, 0 and -1, then the multiplication by u turns an odd function into an an even function and conversely!

Title: Is there a approximate string comparison function which is odd like mathematical functions are odd?

Body:
I say odd like a mathematical function, a mathematical function is odd if

```<code>f(-x) = -f(x)
</code>```

I understand that comparing two strings may seem to have little to do with this, because the arguments cannot be negative, but I mean that the functions value should be the negative of it's value with swapped arguments, i.e.,

```<code>distance(str2, str1) = -distance(str1, str2);
</code>```


问:
Which mathematical properties apply to XOR Swap algorithm (and similar bitwise operator algorithms)?
Assume you have two variables a and b, and you need to swap them, and for whatever reason, making a temporary variable for storage is not an option. This is the algorithm in pseudocode

```<code>a ← a XOR b
b ← a XOR b
a ← a XOR b
</code>```

Based on examples I can see that this does work.

But, why does it work?

More specifically, how was this derived? Was it a mere coincidence that XOR such and such values does this? This question applies to all bitwise operators.

I understand perfectly what they do, and how they work, and various algorithms that take advantage of them. But, are there mathematical properties of these bitwise operators that these algorithms are derived from? What are those mathematical properties? And which of them apply to the specific example of an XOR swap?

答:
But, why does it work?

Since XOR works bitwise, it is enough to assume that a and b are just one bit long. In this case, XOR is just the same thing as the addition modulo 2. Now if a[0] and b[0] denote the value of a and b before the calculation and a[1] and b[1] their value after, we have (modulo 2):

```<code> a[1] = b[0] + 2*a[0] = b[0]
 b[1] = a[0] + 2*b[0] = a[0]
</code>```

If you are in a pedantic mood, you can pack all this in a little sentence: we are computing in a vector space of characteristic two and XOR is just the addition of vectors.

Body:
But, why does it work?

Since XOR works bitwise, it is enough to assume that a and b are just one bit long. In this case, XOR is just the same thing as the addition modulo 2. Now if a[0] and b[0] denote the value of a and b before the calculation and a[1] and b[1] their value after, we have (modulo 2):

 a[1] = b[0] + 2*a[0] = b[0]
 b[1] = a[0] + 2*b[0] = a[0]

If you are in a pedantic mood, you can pack all this in a little sentence: we are computing in a vector space of characteristic two and XOR is just the addition of vectors.


问:
Partial or full changelog for release
When releasing a new version of a program is it better to include the full changelog since the beginning of the project or just the part since the last release?

I know that the release notes would get get really long if I include the full changelog, but if I don't, a user looking for the full changelog would need to look at each and every release.

答:
When releasing a new version of a program is it better to include the full changelog since the beginning of the project or just the part since the last release?

Neither.

Only provide the relevant, bigger changes that an end user is going to care about.

No one cares about the fact that you refactored class Foo so that it can be re-used a bit more easily in certain circumstances.

What they care about are the things they can see or think they can see.  Did you change the UI?  Or some of the workflow?  Or put in performance updates?

Don't bore the end user with minutia.  Provide only the relevant details within the release notes.  If they really want to find all the minutia, advertise it through your CVS / bug-tracking system.

Title: Partial or full changelog for release


答:
Pick up your resume, and start looking for a different job. PHP is a powerful language, however its syntax is shitty and non consistent. At the same time start home project in the language you do want to work in, and if you can join an open source project.

good luck.

Title: What do you do when you have to work on a project using a language that you hate?

Body:
I've recently been assigned to work on a project written in PHP. I can't change that, and have no intention of really trying.

However, this can't be an uncommon scenario. How do you motivate yourself to work on the project when the code you're looking at and producing constantly makes you want to cry?

EDIT:

It should be noted that this is pretty much the only on-campus job doing anything software related available at the moment, so "just change jobs" isn't really an option :(


问:
Structuring Procedural vs OO code
I have spent the vast majority of my programming career using Java and very OO based C++. I am really interested in learning to think more procedurally, so I have been starting to do some practice using a more restricted subset of C++ (basically C) and trying to keep my code very procedural.

My question lies in the area of how to structure a program. In Java, I am constantly thinking of objects... so when I create a class I am thinking of:

What is this object representing?

What can this object do?

What do others need to be able to do to it?

What do I expose, what do I hide?

Etc

In the case of procedural code, how does this sort of thing work? Lets say wanted a struct to represent a Car. I would create a header to define it in... but where do functions go that should operate on a car type? Would you also define all Car related functions in the same file line you would a Java class? Am I totally thinking about this the wrong way, in that there should not be any Car related functions since the emphasis should not be on the Car object but on the functions themselves? IS the idea of a member function totally thrown out the window?

The bottom line is my brain has been wired to think about Objects, Encapsulation, Polymorphism, etc.. and I cant seem to wrap my head around anything else. How can I practice?

Any advice is appreciated!

答:
To be honest, this seems a bit like going backward and programming with one hand behind your back, but if by "structured", you mean, like how people created programs before Object Orientation in procedural languages, then it's about how you start thinking about the problem.  In your fourth paragraph, you are essentially still thinking in an Object Oriented way.  The way people wrote in languages like C, Pascal and BASIC back in the day was to start with the code not the data.  An analogy would be that a computer program was like a recipe; a series of steps to follow.

So you wouldn't say "Let's say you wanted a struct to represent a Car".  You'd say "I want to transport myself to the grocery store".  You'd only start thinking about objects like "Car" when you got to the step that required it.

To use a more concrete example: Suppose you wanted to send a bunch of letters to addresses in a file.  Thinking in OO, you'd probably first start thinking about things like address objects.  But with old structured languages, you'd probably first think about the steps:

Open file

Read a address

Format address information

Print address

Go to 2

You'd devolve each of those into steps, like

4:

Print name

Print house number

Print street

Print city

Print state

Print zip code

To make all this easier, you'd almost certainly put the address data into some sort of struct to keep it together, but that would be driven by the steps you were taking.  You wouldn't start with that.

The thing is: this gets really hard to manage once you get to programs of any significant size.  This is why nearly everyone thinks in objects these days unless they are writing a quick little script.

Title: Structuring Procedural vs OO code


问:
Should I omit database and server communication (after initial response)?
I have a project that I'm working on where a user uploads a big file which gets parsed by the backend, and then returns the data back in a friendlier format. Now I'm wondering whether I actually need a database to store it, or should I just send all the data back to the user in JSON and let JavaScript to show the data properly on button presses?

I'd like to add a database and have all project organised MVC, but I feel like storing the data and then extracting it to serve it to the user and querying it at each button press is unnecessary and would slow down the communication.

I am aware that using the no-database method would mean other users can't access the data that the user who uploads the file can see, but that's not a big issue. Any other issues that I should consider?

答:
It mostly depends on the size of the data you return and whether the user is expected to use all the data at once.

For instance, if it's a list containing hundreds of thousands of complex entries:

The response served as a single JSON will be rather large, and:

It is unlikely that the user will actually need to see all the data at once.

Instead, the user will prefer accessing the data either with paginated table or a table limited by criteria or based on a search, or in a form of a report which can eventually be configured on the fly. In those cases, there would be not one huge JSON response, but multiple JSON requests, serving a tiny part of the overall data which was collected or generated.

On the other hand, it may be that there is no much to return and that the user will expect to see everything at once. In this case, multiple JSON requests are not really useful, and may even cause perceived slowness.

If this is an important project, make sure you work with qualified interaction designers who can advise you according to the actual situation.

Example

Take an example of an application which let photographers submit a JPEG image and shows them the EXIF data. You determined, together with your users, that there are two sets of EXIF information: one set contains the data the users absolutely need: such as focal length or ISO—the ordinary photographers' stuff they manipulate on daily basis; another set contains the data that might eventually be useful: interoperability index, bits per pixel—technical stuff many photographers will ignore during their whole career.

Let's assume you did a prototype which returns all EXIF data at once, and it appears that it is too slow. Indeed, some photographs contain a lot of data which may be problematic to return in a single JSON response.

So you decide to return the first set immediately and put a button "See more" which loads the remaining EXIF information. The second prototype appears a failure as well: users who actually need the remaining information find your application very unresponsive: they click on "See more" expecting the data to pop out immediately, and instead find themselves watching an animated "loading" GIF for a second.

What's next? An alternative would be to:

Flush the essential EXIF data immediately with a "See more" button,

Once the page is loaded, do another JSON request which loads the remaining data without the user noticing something is happening in the background. Once the data is loaded, either "See more" can be replaced by the actual result, or may act as before, just without the 1 second delay.


答:
The way I see it, to go from proper object-oriented programming to a procedural style, you need to:

remove behavior from your objects; make them just containers of data (data structures)

implement behavior in separate classes (services); they will take the data structures as arguments and perform some action according to application use cases

use the same criteria of design quality you would use in OOP (cohesion, coupling, etc), only apply them to services

As others pointed out, this is probably a regression from OOP, especially for large projects. Could be a valid approach for simple scenarios.

Title: Structuring Procedural vs OO code

Body:
I have spent the vast majority of my programming career using Java and very OO based C++. I am really interested in learning to think more procedurally, so I have been starting to do some practice using a more restricted subset of C++ (basically C) and trying to keep my code very procedural.

My question lies in the area of how to structure a program. In Java, I am constantly thinking of objects... so when I create a class I am thinking of:

What is this object representing?

What can this object do?

What do others need to be able to do to it?

What do I expose, what do I hide?

Etc

In the case of procedural code, how does this sort of thing work? Lets say wanted a struct to represent a Car. I would create a header to define it in... but where do functions go that should operate on a car type? Would you also define all Car related functions in the same file line you would a Java class? Am I totally thinking about this the wrong way, in that there should not be any Car related functions since the emphasis should not be on the Car object but on the functions themselves? IS the idea of a member function totally thrown out the window?

The bottom line is my brain has been wired to think about Objects, Encapsulation, Polymorphism, etc.. and I cant seem to wrap my head around anything else. How can I practice?

Any advice is appreciated!


问:
Do named arguments replace the builder pattern?
When using a language that supports named and optional arguments, does the builder pattern no longer have a practical use?

Builder:

new Builder(requiredA, requiredB).setOptionalA("optional").Build();
```
<p><strong>Optional/named arguments:</strong></p>
<pre class="lang-cs prettyprint-override"><code>new Object(requiredA, requiredB, optionalA: "optional");
</code>```

答:
Builders are most useful when your object needs a lot of arguments/dependencies to be useful, or you want to allow many different ways of constructing the object.

Off the top of my head, I can imagine someone might want to "build" objects in a 3D game like this:

// Just ignore the fact that this hypothetical god class is coupled to everything ever
new ObjectBuilder(x, y, z).importBlenderMesh("./meshes/foo")
                          .syncWithOtherPlayers(serverIP)
                          .compileShaders("./shaders/foo.vert", "./shaders/foo.frag")
                          .makeDestructibleRigidBody(health, weight)
                          ...
```
<p>I would argue this example is more readable with the builder methods I made up just now than it would be with optional parameters:</p>
<pre class="lang-cs prettyprint-override"><code>new Object(x, y, z, meshType: MESH.BLENDER,
                    meshPath: "./meshes/foo",
                    serverToSyncWith: serverIP,
                    vertexShader: "./shaders/foo.vert",
                    physicsType: PHYSICS_ENGINE.RIGID_DESTRUCTIBLE,
                    health: health,
                    weight: weight)
                    ...
</code>```

In particular, the information implied by the builder method names has to get replaced by yet more parameters, and it's much easier to forget about one parameter in a group of closely related parameters. In fact, the fragment shader is missing, but you wouldn't notice that unless you knew to look for it.

Of course, if your object only takes one to five arguments to construct, there's no need to get the builder pattern involved, whether or not you have named/optional parameters.

Body:
Builders are most useful when your object needs a lot of arguments/dependencies to be useful, or you want to allow many different ways of constructing the object.

Off the top of my head, I can imagine someone might want to "build" objects in a 3D game like this:

// Just ignore the fact that this hypothetical god class is coupled to everything ever
new ObjectBuilder(x, y, z).importBlenderMesh("./meshes/foo")
                          .syncWithOtherPlayers(serverIP)
                          .compileShaders("./shaders/foo.vert", "./shaders/foo.frag")
                          .makeDestructibleRigidBody(health, weight)
                          ...

I would argue this example is more readable with the builder methods I made up just now than it would be with optional parameters:

new Object(x, y, z, meshType: MESH.BLENDER,
                    meshPath: "./meshes/foo",
                    serverToSyncWith: serverIP,
                    vertexShader: "./shaders/foo.vert",
                    physicsType: PHYSICS_ENGINE.RIGID_DESTRUCTIBLE,
                    health: health,
                    weight: weight)
                    ...

In particular, the information implied by the builder method names has to get replaced by yet more parameters, and it's much easier to forget about one parameter in a group of closely related parameters. In fact, the fragment shader is missing, but you wouldn't notice that unless you knew to look for it.

Of course, if your object only takes one to five arguments to construct, there's no need to get the builder pattern involved, whether or not you have named/optional parameters.


答:
The way we used to do sort-of OOP back in the days of C was by declaring a struct and then declaring functions that accept such a struct as their first parameter.  Then sometimes the need for polymorphism would kick in, so we would have our struct contain not only data fields, but also pointers to functions.  It is quite pointless, really, doing by hand what C++ would do for us with far fewer lines of code, more safely, more elegantly, and in a way that everyone who knows C++ understands, instead of each shop rolling their own.

If you really want to abandon OOP in favour of structured programming, you have to move away from objects, and start thinking in terms of modules, but you will soon see that you will naturally and inevitably gravitate towards OOP, and there is nothing wrong with that, because OOP is a very convenient way of thinking about programming, and I would even dare say a necessity in order to build complex systems.

Before C++ we used to write modules which exposed functions, and quite often these modules were managers which contained some plurality of entities, so they would expose some sort of 'handle' to let you indicate which entity you were referring to, as for example the case is with operating system "file handles" of old, which you may have heard of.  That was already OOP, even though it was not called by that name yet.  In the beginning the handle usually was an int and it was used by the module as an index into some internal array of structs, but at some point someone figured that since the user code is not supposed to try and interpret the handle in any way, the handle could just as easily be an actual pointer to the internal struct; nobody would notice, and nobody should mind.

So, in order to do anything a) useful and b) large-scale you have to think OOP, but if you don't use an OOP language then your implementation will be behind some monolithic flat interface, and you will still have to do an awful lot of mindless manual work in order to achieve certain things like inheritance and polymorphism, (which you will need if you try to do anything of non-trivial complexity,) and which will be provided for you if you use an OOP language.

Title: Structuring Procedural vs OO code


答:
A lot of procedural code is very OOP-like.  Basically, instead of object.function(params), you do function(object, params).  You can group your files accordingly.

However, what a lot of long-time OOP programmers don't realize is how limiting it is that a function must belong to one and only one class, and that all such functions must be grouped into one file accordingly.  Procedural-style allows for many other kinds of groupings that often fit better under certain circumstances:

Combinations of two objects, like all functions dealing with both engines and transmissions.

Collections of objects, like all functions dealing with lists of cars.

All implementations of an interface.  For example, the implementations of steer() for different kinds of vehicles could all be grouped into one file.

Functions that convert from one kind of data structure to another.  For example, functions that take a collection of parts and return a car.

Basically, all those times you couldn't really figure out which class is the best fit for something, in procedural that's not really an issue.  Don't get me wrong, the way OOP groups functions is successful because it's a very reasonable default.  That doesn't make it the best grouping under all circumstances, though.

Title: Structuring Procedural vs OO code


问:
What is calendar time and execution time in terms of reliability testing?
What is calendar time and execution time in terms of reliability testing?

My book is talking about the Musa Okumoto model and says that it uses calendar time and execution time. However googling and looking into the index is not helping. I see no precedence in the chapter that it is being discussed. It says it uses execution time for determining inter-failure rates (which I know what that is) and calendar time to determine if the reliability (I know this as well) they need is achieved.

答:
I don't know about "in terms of reliability testing", but the meanings of those to terms is as follows:

Calendar time - How long whatever you are testing took in actual time.  In other words, if you start a stopwatch when you start a program and check it when the program is done, you are measuring calendar time.  This is equivalent to the "real" time reported by the Unix time utility.

Execution time - How much CPU time was used.  If there are many things running on the machine at the same time, this could obviously be much less than calendar time.  Also, if the program is sitting suspended while it waits for IO, the execution time might be low while calendar time might be high.

In general, users care most about calendar time as they are sitting around waiting for the program to be done.  On the other hand, execution time is going to show how much of a load the program is putting on the machine.


问:
Explanation of two of Lehman's Laws of Software Evolution
I have a hard time understanding #3 and #8 of Lehman's Laws of Software Evolution.

The laws are:

(1974) "Self Regulation" — E-type system evolution processes are self-regulating with the distribution of product and process measures close to normal

and

(1996) "Feedback System" (first stated 1974, formalised as law 1996) — E-type evolution processes constitute multi-level, multi-loop, multi-agent feedback systems and must be treated as such to achieve significant improvement over any reasonable base

The rest of the laws are clear to me.

Could someone explain these two laws?

答:
Law:

(1974) "Self Regulation" — E-type system evolution processes are self-regulating with the distribution of product and process measures close to normal

In other words 'an E-type systems growth inevitably slows as it grows older'.

Source:

http://www.governmentciomagazine.com/2013/04/implications-lehman%E2%80%99s-laws-it-priorities-wake-sequester