问:
What does it mean if a repo has one license and the files have other license statements?
I found a certain repository on GitHub that contains a LICENSE.txt file with an MIT license dated 2014, but in one of the source files, the top of the file contains an Apache 2.0 license dated 2013.

This specific instance isn't that important, it's just illustrating my question, but what sort of implications does this have for licensing? Does the license on individual files override the license placed on the whole project? Does the date on the license have any effect?

答:
You can indeed have more than one license in place, at the same time, and either give the user of the code some freedom to pick the license he likes best (see dual- or multi-licensing on Wikipedia), or require him to obey the terms of both licenses, as long as they do not contain contradicting requirements.

A popular model is to have one license for a "work as a whole" (containing many source files), and different licenses for individual source code files, as long as the license for the individual source file is more permissive than the license for the work as a whole. For example, the GPL is a license where the text explicitly mentions it applies to the "work as a whole". That is why the Linux kernel is under GPL, but some kernel modules contain files which are under MIT or a modified BSD license. So as long as you use or publish those files individually, and not as part of the Linux kernel, you only have to follow the terms of the MIT or BSD license.

In your specific case, I would expect the MIT license has to be applied to the "work as a whole", and the combined MIT & Apache 2.0 for the files which contain the Apache license. The latter one is - at least slightly - less permissive than the MIT license. For example, the Apache license requires you to mention changes to the original code. IANAL, but such a term does not seem to contradict the MIT license. For example, when you change the file with the Apache license embedded, I would expect you have to mention those changes. When you change a different file, I would expect you are not required to do so. There are more differences between the two like a patent clause in the Apache license which is not part of the MIT license. So what you will actually have to check is if your intended usage of the code confirms to both licenses. And if you are not sure, ask a lawyer.


问:
SVN shared modules / dependency management
I'm working with a small-ish team of developers. We're using Subversion for version control. Much of the software is for embedded systems.

We want to set up a reasonably convenient way to share internally-developed software/firmware modules among multiple projects. Desirable features include:

To be able to pull shared modules down inside whatever projects use them, and build them in place. (Makes for easy zipping / exporting.)

To have traceability into what projects uses a shared module, if possible. (i.e. To be able to answer the question, "Which projects use FancySharedWidget?".)

Questions

I'm thinking a reasonable repo setup / folder hierarchy with svn:externals (with explicit revision numbers) will meet #1 nicely. Right?

Can I meet requirement #2 with svn:externals?

a. Maybe with a post-commit hook, to track when external svn props are added or modified? Do any such scripts already exist?

Are there better tools approaches for the job? (Preferably in addition to combination with svn. I don't forsee convincing the company to move away from svn , though I'm personally interested in hearing what else is out there.)

4. Meta: does this post belong here, or on Stack Overflow?

答:
Externals can be used for what you are trying, but first you should check if you really need them. For our team, it is mostly sufficient to have our shared modules in a folder below named shared_libs, and let all using projects reference that folder by a relative path. However, one will need externals if you are going to have the libs/shared modules in different local folders below your project folder. That way, you can handle situations where you need

Project A to reference shared module L version/revision 1.0

Project B to reference shared module L version/revision 1.1

both at the same time in local your development environment. By using externals, you cannot just control to have different copies at different locations in your development environment, you get also fine grained control which revision, or branch, or tagged version of the lib/module you want to have placed there.

For us, however, it is mostly sufficient to have different versions of the same lib in our production environment only (we use some externals, but not for the majority of shared libs). For testing and deployment, most of our build scripts pull the compiled results into a test or deployment folder, without the help of SVN.

The drawback of using externals is that you have increased administrative effort - you might need to update explicitly to a newer version of a lib in each project which uses it. For editing and commiting changes your libraries source code directly in the external's checkout folder you will have to utilize the peg-revision mechanism of SVN (or maybe its exactly what you want to prohibit). And if your shared libs are dependent from other shared libs, maybe recursively, you have to make sure the relative paths of all those libs in your local file system are always similar to each other. You will have to validate if this what you need and/or what you want.

Concerning your second question: SVN is not really the right tool for tracking dependencies, the only reliable place where the dependencies are stored are your make files / project files / build scripts / linker files (whatever you use for your build process), so my first suggestion would be to scan those files by a script to collect dependency information. Nevertheless, if you are going to use SVN externals consequently for every shared module dependency, I am sure you can write a script which iterates over the projects in your repo(s) and collects which externals are added there. And I do not think you will need a hook for that, just utilize svn propget svn:externals for this, as shown here.

ContentLicense: CC BY-SA 3.0


问:
What is the "type" of data that pointers hold in the C language?
I know that pointers hold addresses. I know that pointers' types are "generally" known based on the "type" of data they point to. But, pointers are still variables and the addresses they hold must have a data "type". According to my info, the addresses are in hexadecimal format. But, I still do not know what "type" of data is this hexadecimal. (Note that I know what a hexadecimal is, but when you say 10CBA20, for example, is this string of characters? integers? what? When I want to access the address and manipulate it .. itself, I need to know its type. This is why I am asking.)

答:
You're overcomplicating things.

Addresses are just integers, period. Ideally they're the number of the referenced memory cell (in practice this gets more complicated because of segments, virtual memory etc.).

Hexadecimal syntax is a complete fiction that exists only for the convenience of programmers. 0x1A and 26 are exactly the same number of exactly the same type, and neither is what the computer uses - internally, the computer always uses 00011010 (a series of binary signals).

Whether or not a compiler allows you to treat pointers as numbers depends on the language definition - "systems programming" languages are traditionally more transparent about how things work under the hood, while "high-level" languages more often try to hide the bare metal from the programmer - but that changes nothing about the fact that pointers are numbers, and usually the most common type of number (the one with as many bits as your processor architecture).


问:
Do you have any team guidelines regarding exceptions?
My team recently inherited a project from a team where the amount of developers dropped so low they had to offload some work. One of the projects we inherited was a project littered with nested code, and awful exception handling (Exceptions were in effect handled as goto statements and thus used as a part of the normal program flow.).

All in all it was a hairy code ball someone had been coughing up for a few years.

Now we've been having a few team guidelines in place for quite some time, but all of the regards to the structures of objects, coding styles and what not. But we haven't covered exception handling.

So I'm wondering if you have any guidelines in your teams regarding exception handling, and if so how you enforce them?

答:
I think that exceptions should reamin Exceptions. I think its abusive and generates overhead when using exceptions as a workflow in your code. So, keep them verbose, and use only when something unexpected happened.

Note: tray to avoid the most common mistackes, like not passing the connection database to a function, or things like that. But rather use them when the primaryKey does not exists and you need it to do something.

ContentLicense: CC BY-SA 2.5


问:
Which pattern to use with a typical Web Form?
I am writing a simple ASP.NET Web Forms application. I want to improve the code by implementing any design pattern with which abstraction is achieved and increases manageability and understandability.

Which pattern is recommended? Please also provide links to sample applications.

答:
MVVM is possible in. NET 4.5 with model binding and the use of templated bound controls like FormView.

Here is the technique I use:

I design ViewModels for each UserControl and nested UserControl and then use a FormView that is always in EditMode, where I include the controls that bind to model properties using Binding expressions.

I set the SelectMethod and UpdateMethod of the FormView. The first returns the ViewModel and the 2nd calls TryUpdate() on it. On postbacks I always call the FormView's Update method in Preload or Load. In that way the ViewModel is always up-to-date from the view.

I run the logic inside the ViewModel and on PreRender I rebind the view to apply any changes. The key in this method is to inject the ViewModel into the view (UserControl) outside the view (ex. in Page level) and of course ensure that is serializable and cached in ViewState or any other place I choose.

Finally I disable the ViewState in all controls since they are ultimetaly "driven" by the cached stateful ViewModel and don't need their own state.

This technique never failed me so far and I only wish I could find a solution for command/button binding too, like WPF.


答:
On most architectures, the type of a pointer ceases to exist once they've been translated into machine code (except for perhaps "fat pointers").  Therefore, a pointer to an int would be indistinguishable from a pointer to a double, at least on its own.*

[*] Although, you can still make guesses based on the kinds of operations that you apply to it.

Title: What is the "type" of data that pointers hold in the C language?

Body: I know that pointers hold addresses. I know that pointers' types are "generally" known based on the "type" of data they point to. But, pointers are still variables and the addresses they hold must have a data "type". According to my info, the addresses are in hexadecimal format. But, I still do not know what "type" of data is this hexadecimal. (Note that I know what a hexadecimal is, but when you say 10CBA20, for example, is this string of characters? integers? what? When I want to access the address and manipulate it .. itself, I need to know its type. This is why I am asking.)


问:
Best practice to handle POST with array of objects if at least one object raise an Exception
I want to POST an array of objects and make an insertion in database concerning each of them.

What is the best practice if one object does not conform and raise an Exception? (cancel all transactions or just one and specify it when I return this list of objects?)

答:
Your post should be a single, self contained action that succeeds as a whole or fails as a whole. Therefore if one item contains an error you should reject the entire set.

You should also be checking these items if at all possible before even starting your database transaction so you have the chance to error out early.

Of course, if your database engine raises an exception (for example due to referential constraints), then you rollback the whole transaction.


问:
Is it possible to have currying and variadic function at the same time?
I am thinking about making currying and variadic functions both available in a dynamically-typed functional programming language, but I wonder if it is possible or not.

Here are some pseudocode:

```<code>sum = if @args.empty then 0 else @args.head + sum @args.tail
</code>```

which is supposedly to sum all its arguments. Then, if sum itself is treated a number, then the result is 0. for example,

```<code>sum + 1
</code>```

is equal to 1, assuming that + can only work on numbers. However, even sum == 0 is true, sum will still maintain its value and functional property no matter how many arguments are given (hence "partially applied" and "variadic" at the same time), for example, if I declare

```<code>g = sum 1 2 3
</code>```

then g is equal to 6, however, we can still further apply g. For example, g 4 5 == 15 is true. In this case, we cannot replace the object g by a literal 6, because although they yield the same value when treated as an integer, they contain different codes inside.

If this design is used in a real programming language, will it cause any confusion or ambiguity?

答:
How can varargs be implemented? We need some mechanism to signal the end of the argument list. This can either be

a special terminator value, or

the length of the vararg list passed as an extra parameter.

Both of these mechanisms can be used in the context of currying to implement varargs, but proper typing becomes a major issue. Let's assume that we are dealing with a function sum: ...int -> int, except that this function uses currying (so we actually have a type more like sum: int -> ... -> int -> int, except that we don't know the number of arguments).

Case: terminator value: Let end be the special terminator, and T be the type of sum. We now know that applied to end the function returns: sum: end -> int, and that applied to an int we get another sum-like function: sum: int -> T. Therefore T is the union of these types: T = (end -> int) | (int -> T). By substituting T, we get various possible types such as end -> int, int -> end -> int, int -> int -> end -> int, etc. However, most type systems do not accommodate such types.

Case: explicit length: The first argument to a vararg function is the number of varargs. So sum 0 : int, sum 1 : int -> int, sum 3 : int -> int -> int -> int etc. This is supported in some type systems and is an example of dependent typing. Actually, the number of arguments would be a type parameter and not a regular parameter – it would not make sense for the arity of the function to depend on a runtime value, s = ((sum (floor (rand 3))) 1) 2 is obviously ill-typed: this evaluates to either s = ((sum 0) 1) 2 = (0 1) 2, s = ((sum 1) 1) 2 = 1 2, or s = ((sum 2) 1) 2 = 3.

In practice, none of these techniques should be used since they are error-prone, and don't have a (meaningful) type in common type systems. Instead, just pass a list of values as one paramter: sum: [int] -> int.

Yes, it is possible for an object to appear as both a function and a value, e.g. in a type system with coercions. Let sum be a SumObj, which has two coercions:

coerce: SumObj -> int -> SumObj allows sum to be used as a function, and

coerce: SumObj -> int allows us to extract the result.

Technically, this is a variation of the terminator value case above, with T = SumObj, and coerce being a un-wrapper for the type. In many object-oriented languages, this is trivially implementable with operator overloading, e.g. C++:

#include <iostream>
using namespace std;

class sum {
  int value;
public:
  explicit sum() : sum(0) {}
  explicit sum(int x) : value(x) {}
  sum operator()(int x) const { return sum(value + x); }  // function call overload
  operator int() const { return value; } // integer cast overload
};

int main() {
  int zero = sum();
  cout << "zero sum as int: " << zero << '\n';
  int someSum = sum(1)(2)(4);
  cout << "some sum as int: " << someSum << '\n';
}
```


问:
How does a network load balancer work with session affinity?
I would like to know the low level details of how a network load balancer works with sticky session enabled.

Reason behind the question:

We have a legacy ASP.NET application that is both a front-end application and a REST service.

e.g.

https://somedomain.com/legacyapp/UI.aspx

https://somedomain.com/legacyapp/Service.aspx

No. 1 is a no-login page but stateful.
No. 2 is a service endpoint receiving an XML payload via HTTP POST

There are 2 instances of legacyapp behind the load balancer.

The load balancer has session affinity enabled. We noticed an unequal distribution of load. For each client there are lots of calls to the service endpoint (No. 2). We would want to leverage load balancing for No. 2. However, due to the session affinity being enabled, it's ignoring load balancing i.e. routing traffic to a single instance where a session was established initially.

答:
That's one of those "it depends" questions. I am going to mostly discuss web server balancing here.

Some do it by creating a hash of some pertinent information (client IP, target server IP and/or URL; map this to one of N backends).

Some do it by taking any un-allocated incoming session and send it to an arbitrary backend, then that backend sets a cookie of some sort (I'll call that an "affinity cookie"). If the cookie is set, the session is sent preferentially to that backend. If that backend is no longer alive, one of two things happen. Either it picks a new backend (and a new affinity cookie is set) or the session is terminated.


问:
NoSQL or MySQL?
I'm developing an app that requires to save data that is not consistent across all rows. These database entries represent different kind of sport activities. Let's take an example: In football the final result is an important field. However, in cycling there's no such field. So it wouldn't be a good idea to create a table that has a score column, would it? This kind of data would be easy to store in a NoSQL database.

All these have some things in common, though: date, time, duration and location, at least.

The app also has functionality that would greatly benefit from typical relational database. Users table, messages etc.

How should I implement a database for such an application? All data is relational in a way that connects everything to a specific user. However, not all data can be organized in a traditional row/column based database.

Should I use MySQL, and for these activities have a data field that contains the relevant data in JSON? What are my options?

Also keep in mind that the database might be holding millions of entries.

答:
It is no problem to have data "not consistent across all rows" in a relational database. This is precisely what relational databases are designed for! You create a table for the data which is common across all activities, and then you create separate tables for data specific for kind of activities. E.g. a football table with a score column, a cycling table with a distance column, both linked to the activities table with foreign keys.

So I'm skeptical that "not all data can be organized in a traditional row/column based database." You can always do that, unless you have very peculiar data. There are some cases where it might be inconvenient (eg. you have some complex application specific structured data which you never need to query or update - it might be easier to just serialize into a single field), but this depends on your particular use cases.

There is nothing in your question that indicates why a relational database wouldn't be fine.

Title: NoSQL or MySQL?


答:
The type of a pointer variable is .. pointer.

The operations you're formally allowed to do in C are to compare it (to other pointers, or the special NULL / zero value), to add or subtract integers, or to cast it to other pointers.

Once you accept undefined behaviour, you can look at what the value actually is. It will usually be a machine word, the same kind of thing as an integer, and can usually be losslessly cast to and from an integer type. (Quite a lot of Windows code does this by hiding pointers in DWORD or HANDLE typedefs).

There are some architectures where pointers are not simple because memory is not flat. DOS/8086 'near' and 'far'; PIC's different memory and code spaces.


问:
Why are regular expressions so morbidly attractive?
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

答:
Why are regular expressions so morbidly attractive?

They're not. They're actually ugly as hell. And incomprehensible.
They're an abomination that should be killed as soon as possible.

Now, this being said, I'm going back to debugging a little Perl app. Can't help it; unfortunatelly, they're still the best tool for the job sometimes.


问:
User authorization with microservices
Should microservices be responsible for handling their own authorization or you think it's better to have a separate authorization service that is shared across all or a subset (within the same business domain) of microservices?

To me the latter makes more sense as it makes it easier to apply changes, enforce policies; it is DRY etc. However it can easily get out of hand by all sorts of services dumping their rules into one place, and also concerned about the network overhead.

Any thoughts?

答:
I would use a central, unified authentication system and have separate permissions/stats for each microservice (sort of like how I can't yet upvote on this stack exchange site but I can in stack overflow while using the central stack exchange authentication system). One of my current projects will involve this approach in the near future, which will be nice; the previous development work involved creating a HIPPA compliant system, necessitating a second level of authorization/authentication, and it is a time consuming annoyance to daisy chain authorizations from legally separate but functionally inseparable components of the system. The debugging process involves a lot less joy than a simple oauth login or an api with appid and x-auth headers.

Which to use depends upon the specific requirements of a development roadmap, but I would choose the simpler approach where possible to avoid excessive overhead and development time/effort.

Title: User authorization with microservices


答:
A pointer is just that - a pointer. It's not something else. Don't try to think that it is something else.

In languages like C, C++, and Objective-C, data pointers have four kinds of possible values:

A pointer can be the address of an object.

A pointer can point just past the last element of an array.

A pointer can be a null pointer, which means it isn't pointing to anything.

A pointer can have an indeterminate value, in other words it is rubbish, and anything can happen (including bad things) if you try to use it.

There are also function pointers, which either identify a function, or are null function pointers, or have an indeterminate value.

Other pointers are "pointer to member" in C++. These are most definitely not memory addresses! Instead, they identify a member of any instance of a class. In Objective-C, you have selectors, which are something like "pointer to an instance method with a given method name and argument names". Like a member pointer, it identifies all methods of all classes as long as they look the same.

You can investigate how a specific compiler implements pointers, but that is an entirely different question.


问:
Member: Use unique IDs vs domain object
After a couple of useful answers on whether I should use domain object or a unique id as method/function parameter here Identifier vs domain object as a method parameter , I have a similar question re: members (the previous questions discussion didn't manage to cover this).
What are the pros and cons of using unique IDs as member vs object as member. I'm asking in reference to strongly typed languages, like Scala/C#/Java. Should I have
(1)

```<code>User( id: Int, CurrentlyReadingBooksId: List[Int])
Book( id: Int, LoanedToId: Int )
</code>```

or (2), preferred to (1) After going through: Should we define types for everything?

```<code>User( id: UserId, CurrentlyReadingBooksId: List[ BookId] )
Book( id: BookId, LoanedToId: UserId )
</code>```

or (3)

```<code>User( id: Int, CurrentlyReadingBooks: List[Book])
Book( id: Int, LoanedTo: User)
</code>```

While I cannot think of benefits to having the object (3), one benefits to having IDs (2) & (1) is that when I am creating the User object from DB, I don't have to create the Book object, which may in turn depend on the User object itself, creating an endless chain. Is there a generic solution to this problem for both RDBMS and No-SQL (if they are different)?

Based on some answers so far, rephrasing my question: (with use of IDs supposed to be in wrapped types)
1) Always use IDs?
2) Always use Objects?
3) Use IDs when there is a risk of recursion in serializing and deserializing, but use objects otherwise?
4) Anything else?

EDIT: If you answer that Objects should be used always or for some cases, please make sure to answer the biggest concern other answerers have posted => How to get data from DB

答:
Short and simple rule of thumb:

IDs are used in DTOs.

Object references are usually used in the Domain Logic/Business Logic and UI layer objects.

That's the common architecture in larger, enterprisey enough projects. You'll have mappers that translate to and fro these two kinds of objects.

Title: Member: Use unique IDs vs domain object


问:
Are "plus" and "minus" appropriate method names?
Java SE 8 comes with a new mechanism for dates, introducing LocalDate, LocalTime and LocalDateTime classes to represent instants of time. To manipulate such instants, a set of methods are given: LocalDate.plusDays(...), LocalDate.minusDays(...) and so on.

I've always thought that good practice was naming methods after verbs describing their purpose, as methods are, actually, operations to be executed, something that will perform an action. Just to mention, if you consider classes like StringBuilder, for instance, methods' names are append, insert, delete...

This is why to me it doesn't sound right naming a method plusDays instead of sumDays, minusDays instead of subtractDays. It's just me finding it very annoying? What do you think?

The only reason I can think of is that dates are immutable objects, so by calling plusDays you're not adding days to the original object but creating a new one with new properties, but that's very very subtle.

答:
The only reason I can think of is that dates are immutable objects, so by calling plusDays you're not adding days to the original object but creating a new one with new properties, but that's very vary subtle.

This is exactly the reason. Imagine you had some kind of api for manipulating ranges of dates for scheduling purposes. It might expose methods letting you make a statement like:

```<code>var workdaySchedule = initialSchedule.withoutWeekends();
</code>```

This reads very similarly to the English statement: "The workday schedule is the initial schedule without weekends". It doesn't imply changing the initial schedule, it implies the work schedule being a different, new thing.

Now instead imagine it was named:

```<code>var workdaySchedule = initialSchedule.removeWeekends();
</code>```

This is confusing. Is initial schedule being modified? It certainly sounds like it, because it sounds like we're removing weekends from it. But then why are we assigning it to a new variable? Although these two naming schemes are very similar, this one is much less clearly evocative of what's happening. This would be more appropriate if removeWeekends did change the initial schedule, and returned void- in which case withoutWeekends would be the confusing option.

This is essentially a declarative vs. imperative distinction. Are we declaring that the workdaySchedule is a particular thing, or are we carrying out a list of imperative instructions (like "remove") to make that particular thing? Usually, imperative naming makes more sense when you're mutating values, and declarative makes more sense with immutable values, as the above example demonstrates.

In your case, you have exactly the same thing. If I saw: tomorrow.plusDays, I wouldn't imagine that tomorrow was being mutated, whereas tomorrow.addDays, I'd think it might be. This is somewhat subtle- but not necessarily in a bad way. Without having to think about it too hard, this naming naturally sets your thinking along the right lines in terms of whether or not you're mutating. To make this distinction between these imperative and declaritive styles clearer: "add" (and "remove") are verbs, whereas "plus" (and "without") are prepositions.

Body:
The only reason I can think of is that dates are immutable objects, so by calling plusDays you're not adding days to the original object but creating a new one with new properties, but that's very vary subtle.

This is exactly the reason. Imagine you had some kind of api for manipulating ranges of dates for scheduling purposes. It might expose methods letting you make a statement like:

var workdaySchedule = initialSchedule.withoutWeekends();

This reads very similarly to the English statement: "The workday schedule is the initial schedule without weekends". It doesn't imply changing the initial schedule, it implies the work schedule being a different, new thing.

Now instead imagine it was named:

var workdaySchedule = initialSchedule.removeWeekends();

This is confusing. Is initial schedule being modified? It certainly sounds like it, because it sounds like we're removing weekends from it. But then why are we assigning it to a new variable? Although these two naming schemes are very similar, this one is much less clearly evocative of what's happening. This would be more appropriate if removeWeekends did change the initial schedule, and returned void- in which case withoutWeekends would be the confusing option.

This is essentially a declarative vs. imperative distinction. Are we declaring that the workdaySchedule is a particular thing, or are we carrying out a list of imperative instructions (like "remove") to make that particular thing? Usually, imperative naming makes more sense when you're mutating values, and declarative makes more sense with immutable values, as the above example demonstrates.

In your case, you have exactly the same thing. If I saw: tomorrow.plusDays, I wouldn't imagine that tomorrow was being mutated, whereas tomorrow.addDays, I'd think it might be. This is somewhat subtle- but not necessarily in a bad way. Without having to think about it too hard, this naming naturally sets your thinking along the right lines in terms of whether or not you're mutating. To make this distinction between these imperative and declaritive styles clearer: "add" (and "remove") are verbs, whereas "plus" (and "without") are prepositions.


问:
What would you consider best practice workflow tools for web application (PHP) development?
I'm really hoping somebody with more experience can edit the question as per my examples of answers:

using version control

test driven development

debugging code (xdebug for php)

use of UML diagrams

use of OOP for maintainable, reusable code

use of frameworks (like Zend Framework for php) for rapid application development

Anything else or an elaboration of what I mentioned above?

Basically, I'm in the middle of forming a team of developers (I'm a developer myself) and I'd like some advice on how professional programmers/designers etc should work together and what standards/paradigms they should use.

Also, if anybody has any books or links on the subject I'd welcome that!

I did find this which I guess satisfies what I'm looking for, or at least part thereof:

http://www.ibm.com/developerworks/websphere/library/techarticles/0306_perks/perks2.html

答:
When dealing with collaborative work you need:

• using version control: i think that Git or Subversion will work out quite smooth

• test driven development: I'm starting to learn this is a must,but dont take it to extremes

• debugging code (xdebug for php): xdebug is my choice

• use of UML diagrams: This helps when everyones has a working knowledge on OO Programming and DesignPatterns, nevertheless it's always a good practice

• use of OOP for maintainable, reusable code: And FLEXIBILITY, i think this is the key aspect of OOP.

• use of frameworks (like Zend Framework for php) for rapid application development: My Advise is SYMFONY, the first php framework (aint a toolkit). It has a very big commnunity, lots of documentation, and its entirely implemented on php. I've been working with it for a year and it totally binds with OOP

• you may also need a system to track bugs, feature requests, etc. like: Mantis or Track . This sistems are quite easy and straightforward. They also let you bind your subversion and related your commits to certain features or bugs people post.

Finally, it's always important if your going to be leading a dev-team to make small meeting periodically so everyone knows the status of the system at a certain point and maybe that way you'll be capable of planning or see how things are working.

In my company i have to send an email every day telling what i've been working on and if there where any complications.

Best of luck!


问:
Why exactly is Git's pull and push approach better than Clearcase's locking and hijacking approach?
I'm trying to convince colleagues about using Git, and somehow it's hard to explain the advantage of doing a pull before a push, because just before pushing, some other developer has pushed his changes to the server and by the time I pull his changes and merge it, some other developer would've pushed his changes and I'm supposed to merge those too before I can push my changes. Loop infinitely.

In Clearcase, you can lock a file you're working on, so that nobody else can modify it. If they want to modify it, they have to 'hijack' it on their local machine and later merge it. Somehow, this seems to be a safer (but annoying) way of working with the files.

So how exactly is Git's approach an advantage?

答:
In one case the person who locks first wins.  In the other case the person who is ready to push first wins.  Most of the time, the person you want to have precedence is the one who is ready to push.  If I have a week left on my new feature, and you are done fixing a bug for today's release, you should have priority on checking in.

This leads to a lot of walking around getting other people to release their non-urgent locks so you can check in your urgent change.  Some people like this because it "forces a conversation," but it really doesn't.  Those annoying people who make significant changes without communicating properly can still make those changes on hijacked copies and wait for those files to get unlocked.  Mostly you end up annoying people for the same end result:  whoever is ready to check in first does so, and forces people who check in later to merge.


问:
Θ(1) algorithm that removes one element from a linkedlist
I have to find a Θ(1) solution to the following problem:

You're given a singly linked list and a reference to one of the elements in the list. You can be certain that this is not the last element in the list. Find an Θ(1) algorithm that removes this element from the linkedlist.

Image that I have to remove 99 from the next list. I was thinking of replacing the value 99 with a pointer to the next element and thus just skipping this element whenever you loop over it, but I don't think that's a very neat way to do this.

Any ideas on how to solve this problem?

答:
Simple:

Set the value of that node to the value of the next node.

Remove the next node from the linked list.

In Python code (as it is closest to executable pseudocode easily translated to your poison of choice):

```<code>def remove_node(node):
    node.value = node.next.value
    node.next = node.next.next
</code>```

It's a common coding puzzle. Note that the description clearly states that [y]ou can be certain that this is not the last element in the list, thus guaranteeing that there is a next node to nick the value from.

Body:
Simple:

Set the value of that node to the value of the next node.

Remove the next node from the linked list.

In Python code (as it is closest to executable pseudocode easily translated to your poison of choice):

def remove_node(node):
    node.value = node.next.value
    node.next = node.next.next

It's a common coding puzzle. Note that the description clearly states that [y]ou can be certain that this is not the last element in the list, thus guaranteeing that there is a next node to nick the value from.


答:
Pick your choice - do you prefer always getting a warning when there might be a potential conflict in the near future since two people are going to edit the same file (Clearcase)? Or do you prefer to get a warning when the VCS detects there is an actual conflict since the two people edited the same source code lines, or lines very near to each other (Git)?

The first model produces some false positives from time to time, which can be annoying. At a first glance, the second model seems to have a higher risk to introduce bugs. That is because when a merge is formally successful and you get no warning, there is a certain risk of having a "semantic" conflict, only revealed by tests. However, to my experience, in reality the latter is neglectable - I cannot remember ever to have encountered such a situation in the last 10 years. Moreover, the first model has indeed the same risk, since just because you get a warning about a simultaneous edit beforehand does not automatically ensure the two developers will inspect their merge results afterwards more carefully.

Title: Why exactly is Git's pull and push approach better than Clearcase's locking and hijacking approach?

Body:
I'm trying to convince colleagues about using Git, and somehow it's hard to explain the advantage of doing a pull before a push, because just before pushing, some other developer has pushed his changes to the server and by the time I pull his changes and merge it, some other developer would've pushed his changes and I'm supposed to merge those too before I can push my changes. Loop infinitely.

In Clearcase, you can lock a file you're working on, so that nobody else can modify it. If they want to modify it, they have to 'hijack' it on their local machine and later merge it. Somehow, this seems to be a safer (but annoying) way of working with the files.

So how exactly is Git's approach an advantage?


问:
Find a line that is closest to scattered points
I came across the below interview question on Glassdoor:

A scatter graph of points on a page, draw a horizontal line  across the page such the the perpendicular y distance to the line from all points in aggregate is minimized. Describe an algorithm for placing this line optimally

My approach:

I think we can compute the mean of y-distances and place the line there.

However, I am not sure if this is correct or if there is a better approach to solving this problem.

答:
The method you use to calculate the line depends on the cost function you minimize.  You can use the mean y-value which sets the sum of the distances (measured as positive when a point is above the line and negative when the point is below the line) to zero.

You could use a 'minimum sum of the squares of the distances' cost function, which would provide a different answer.

Both those are straight-forward to calculate.  You could use a 'minimum sum of the absolute distances'; that is trickier to compute, and in general yields a different answer from the other two methods.

You can also devise your own cost function to minimize.  Have fun!

For your purposes, I think the mean is a sensible choice.


问:
Virtual method returning a unique collection - how to ensure and hint?
I have a virtual method that returns a collection of items that must be unique. I want to make sure that it will be obvious when overriding the method. What is the best way to do this?

Here is an example, where "Two" is being returned twice erroneously.

```<code>public abstract class Base
{
    public abstract IEnumerable<string> GetUniqueNames();
}

public class Derived : Base
{
    public override IEnumerable<string> GetUniqueNames()
    {
        return new List<string> { "One", "Two" };
    }
}

public class Subderived : Derived
{
    public override IEnumerable<string> GetUniqueNames()
    {
        return base.GetUniqueNames().Concat(new List<string> { "Two", "Three" });
    }
}
</code>```

I am thinking of returning something like UniqueValueCollection that would throw an exception when a duplicate is attempted to be added. This way other developers will get a hint from name and a descriptive error if they still try to misuse it. Is this a good idea?

PS: I don't need to access the elements by key - it's just an enumerable collection, although UniqueValueCollection<> might use Dictionary<>/HashSet<> behind the scenes.

PPS: maybe a HasSet<> behind an interface? It would be great if it was ordered though.

答:
The designer of a virtual method will have occasion to worry about an implementer overlooking (or forgetting, as we self-implementers are prone to do) intended details of operation.

Here the intention is a virtual method that returns a container of unique items, possibly strings.  The fear is that when implemented, duplicates may occur in the return.

Adopting an expressive naming convention is part of the strategy.  A "unique value collection" is a set in mathematics. Of course "set" by itself can be used (as a verb) to indicate returning object members, often accompanied by "get" methods for object members.  Many times "SetOf..." or similar phrasing will be chosen to avoid the ambiguity or obscurity of reading "GetSet..." (which might well suggest a polymorphic method).

Beyond merely good names for methods, the designer has some opportunity to impose an interface on the returned value.  Here the IEnumerable interface was initially shown, and later the ISet interface was realized to be a better (more restrictive) choice.


问:
GIT approach to starting a new project?
I am currently a one man development team. My boss and I use Visual Studio Online for planning out our sprints and maintaining our backlog. Where I always get stuck is how to set up the initial repository for a new project. That leads me to ask the following questions about the best practices.

What is the best way to set up the initial repository? Should it be done on the GIT server first and then on the local machine or vice versa?

Should the initial master branch be just the skeleton structure for the project and then I create my branch to do development or should I work within master until the project is ready for release?

What is the best way to use tags?

With multiple branches is it best to work within one folder and just checkout the appropriate branch or is it better to have a different folder for each branch?

Thanks for the help!

Mike

答:
What is the best way to set up the initial repository? Should it be done on the GIT server first and then on the local machine or vice versa?

Typically this is done by adding a remote after you have created the project and initial project files on your machine.

Should the initial master branch be just the skeleton structure for the project and then I create my branch to do development or should I work within master until the project is ready for release?

The beauty of Git is that it is extremely powerful, but also very flexible allowing you to use a workflow that works best for you and your team (I understand, you're a lone developer).  A common approach to the master branch is for it to be the clean build, while you have dev and test branches off master.  There is no hard and fast rule here whatsoever.

What is the best way to use tags?

What do you mean, "best way"?  Assuming you mean when to use tags, they really shine when you'd like to have a documentable "checkpoint" in the repository.  Usually this is through versioning (tag for v1.0.0, another tag for v1.0.1, a separate tag for v2.3.1, etc. etc. etc.).

With multiple branches is it best to work within one folder and just checkout the appropriate branch or is it better to have a different folder for each branch?

I think you're confusing what branching is in Git.  Don't concern yourself with the file system folder structure, that shouldn't come into play with branching directly at all.  Git handles all of the semantics of the branches and commits, and what the working directory looks like for particular branches/commits.  So definitely do not use folders to handle any functionality with branching in Git.

Title: GIT approach to starting a new project?


问:
What is the "type" of data that pointers hold in the C language?
I know that pointers hold addresses. I know that pointers' types are "generally" known based on the "type" of data they point to. But, pointers are still variables and the addresses they hold must have a data "type". According to my info, the addresses are in hexadecimal format. But, I still do not know what "type" of data is this hexadecimal. (Note that I know what a hexadecimal is, but when you say 10CBA20, for example, is this string of characters? integers? what? When I want to access the address and manipulate it .. itself, I need to know its type. This is why I am asking.)

答:
A pointer is a bit pattern addressing (uniquely identifying for the purpose of reading or writing) a word of storage in RAM. For historical and conventional reasons the unit of update is eight bits, known in English as a "byte" or in French, rather more logically, as an Octet. This is ubiquitous but not inherent; other sizes have existed.

If I remember correctly there was one computer that used a 29bit word; not only is this not a power of two, it's even prime. I thought this was SILLIAC but the pertinent Wikipedia article doesn't support this. CAN BUS uses 29 bit addresses but by convention network addresses are not referred to as pointers even when they are functionally identical.

People keep asserting that pointers are integers. This is neither intrinsic nor essential, but if we interpret the bit patterns as integers the useful quality of ordinality emerges, enabling very direct (and therefore efficient on small hardware) implementation of constructs like "string" and "array". The notion of contiguous memory depends on ordinal adjacency, and relative positioning is possible; integer comparison and arithmetic operations can be meaningfully applied. For this reason there is nearly always strong correlation between the word size for storage addressing and the ALU (the thing that does integer math).

Sometimes the two don't correspond. In early PCs the address bus was 24 bits wide.


答:
On the contrary. People are parrotting the regex are evil meme way too often IMO. It's obvious that preg_match is overused in php, but it's less obvious that it's oftentimes sensible to do so (in PHP).

I would go so far and conjecture that it's yet another microoptimization in php land to use the string functions. There are many and many useful, and they are usually the better choice. But you shouldn't shun preg_match in favour of multiple strpos and if chains. Because in practice it turns out, libpcre is often faster than PHP can execute a loop looking for string alternatives e.g.

As a recent example made me realize, testing if a string is all-lowercase:

```<code> if ($string == strtolower($string))
</code>```

Is more readble than:

```<code> if (!preg_match("/[A-Z]/", $string))
</code>```

And you would assume the first must be faster, since it's all-PHP. But in reality the regex only looks over the string once, and can abort the negated condition as soon as it finds an uppercase letter. The strtolower() approach however looks over the string twice. First strtolower() makes a string duplicate by iterating over each letter, comparing and uppercasing it. Then the == iterates over the original and the copy again, comparing them once more.

So that's not an obvious case. And to be objective the first one is often faster, since you normally just compare short strings. But it's imperative to not go blindly by the assumption that PHP string functions are always advisable over regular expressions.

(I'm tempted to add another rant about @bobince's fun answer regarding xhtml-regexes, and how it's recently often linked in a very unhelpful manner. And the more objective answers below go ignored.)

Title: Why are regular expressions so morbidly attractive?

Body:
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

Body:
On the contrary. People are parrotting the regex are evil meme way too often IMO. It's obvious that preg_match is overused in php, but it's less obvious that it's oftentimes sensible to do so (in PHP).

I would go so far and conjecture that it's yet another microoptimization in php land to use the string functions. There are many and many useful, and they are usually the better choice. But you shouldn't shun preg_match in favour of multiple strpos and if chains. Because in practice it turns out, libpcre is often faster than PHP can execute a loop looking for string alternatives e.g.

As a recent example made me realize, testing if a string is all-lowercase:

 if ($string == strtolower($string))

Is more readble than:

 if (!preg_match("/[A-Z]/", $string))

And you would assume the first must be faster, since it's all-PHP. But in reality the regex only looks over the string once, and can abort the negated condition as soon as it finds an uppercase letter. The strtolower() approach however looks over the string twice. First strtolower() makes a string duplicate by iterating over each letter, comparing and uppercasing it. Then the == iterates over the original and the copy again, comparing them once more.

So that's not an obvious case. And to be objective the first one is often faster, since you normally just compare short strings. But it's imperative to not go blindly by the assumption that PHP string functions are always advisable over regular expressions.

(I'm tempted to add another rant about @bobince's fun answer regarding xhtml-regexes, and how it's recently often linked in a very unhelpful manner. And the more objective answers below go ignored.)


答:
This is probably an artifact of Java using .Method for all methods, both those that modify the object and those that don't.

Imagine a language which also has a object=>method syntax, which would give method a copy of the object to work on. Now in such a language, startDate=>plusDays(5) is clearly unambiguous. It takes the original date, and creates a new date which is 5 days later.

On an unrelated note, sumDays doesn't make sense here. LocalDate is a time point, not a time duration. You can sum any number of durations (and the result is another duration), and you can add a time point and a duration (result is another time point), but you cannot sum time points.

Title: Are "plus" and "minus" appropriate method names?

Body:
Java SE 8 comes with a new mechanism for dates, introducing LocalDate, LocalTime and LocalDateTime classes to represent instants of time. To manipulate such instants, a set of methods are given: LocalDate.plusDays(...), LocalDate.minusDays(...) and so on.

I've always thought that good practice was naming methods after verbs describing their purpose, as methods are, actually, operations to be executed, something that will perform an action. Just to mention, if you consider classes like StringBuilder, for instance, methods' names are append, insert, delete...

This is why to me it doesn't sound right naming a method plusDays instead of sumDays, minusDays instead of subtractDays. It's just me finding it very annoying? What do you think?

The only reason I can think of is that dates are immutable objects, so by calling plusDays you're not adding days to the original object but creating a new one with new properties, but that's very very subtle.


答:
In .NET the naming is different although the result is exactly same. Instead of:

```<code>tomorrow = LocalDateTime.plusDays(1);
</code>```

there is:

```<code>tomorrow = DateTime.Now.AddDays(1);
</code>```

This only means that differences between understanding of "plus" and "add" ended up as matter of personal opinion. Cheer up, you're not alone, at least you can choose the language which appeals to you better : )

Body:
In .NET the naming is different although the result is exactly same. Instead of:

tomorrow = LocalDateTime.plusDays(1);

there is:

tomorrow = DateTime.Now.AddDays(1);

This only means that differences between understanding of "plus" and "add" ended up as matter of personal opinion. Cheer up, you're not alone, at least you can choose the language which appeals to you better : )


答:
What is the best way to set up the initial repository? Should it be done on the GIT server first and then on the local machine or vice versa?

Either way is fine.  You can git init locally from the top level directory of your code to create the git repository locally (you will now see a .git/ directory) and then when you have also created the remote repository on the git server you can, locally, do git remote add ... and then git push - or - you can create the repository first on the remote git server and then do git clone ... locally.  The latter is probably the simpler in terms of steps.

Should the initial master branch be just the skeleton structure for the project and then I create my branch to do development or should I work within master until the project is ready for release?

Yes initially be on master.  Use branches to isolate pieces of work until you are satisfied with them and want to merge them into master.

What is the best way to use tags?

Mainly for version control and for features/epics/bugs/tasks that span multiple tickets.

With multiple branches is it best to work within one folder and just checkout the appropriate branch or is it better to have a different folder for each branch?

Forget the folders, you deal with branches through git, not by interacting with the file system.  The local copy of the files is present on your file system, everything else - all branches, etc. is under the .git/ directory and you should never have to look at it (it likely won't make much sense if you do anyway).

Title: GIT approach to starting a new project?

Body:
I am currently a one man development team. My boss and I use Visual Studio Online for planning out our sprints and maintaining our backlog. Where I always get stuck is how to set up the initial repository for a new project. That leads me to ask the following questions about the best practices.

What is the best way to set up the initial repository? Should it be done on the GIT server first and then on the local machine or vice versa?

Should the initial master branch be just the skeleton structure for the project and then I create my branch to do development or should I work within master until the project is ready for release?

What is the best way to use tags?

With multiple branches is it best to work within one folder and just checkout the appropriate branch or is it better to have a different folder for each branch?

Thanks for the help!

Mike


问:
CGI Scripts and Python / Ruby
I am new to web programming. Now unfortunately, I was a kid during the advent of the world wide web and didn't have access either. So now when I am just starting out, it feels like there's a myriad of concepts to learn and understand.

For example, I just read about CGI scripts. Now, usually when I see people talk about web application programming these days, they're using some framework for Ruby or Python or even PHP.

How do these programming languages and CGI scripts written in C(?) relate?

Are these frameworks somehow converting code written in Ruby or Python into CGI or are they doing something else entirely? It feels like there's too much to know to even understand how the simplest dynamic website works.

Also, do I need to learn HTTP in depth before I even begin learning to build Web apps?

答:
For example, I just read about CGI scripts. Now, usually when I see people talk about web application programming these days, they're using some framework for Ruby or Python or even PHP.

CGI is considered by most to be an outdated technology these days for anything but the simplest applications, some of your reference material may be outdated.

How do these programming languages and CGI scripts written in C(?) relate?

OK, let's say that we had some perl code as a CGI script:

```<code>#!/usr/bin/perl

print "Content-type: text/html\n\n";

print "Hello, world!\n";
</code>```

When there is an HTTP Request sent to the server for this file (eg: http://www.someserver.com/cgi-bin/hello.pl) the server will first execute this code and send the standard output as a response. This is the reason that we have to include the "Content-type: text/html\n\n" in the response as the HTTP header.

Web Frameworks however are a rather different beast. In their most basic description they are simply a blanket term for any tool-set that provides functionality associated with common web development activities.

In practice however they almost all function in a similar way and provide similar tooling.
From Wikipedia:

many frameworks provide libraries for database access, templating frameworks and session management

Let's compare the previous CGI code to this python code written using a Web Framework called Flask:

```<code>from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
</code>```

To avoid as much of the Python specific syntax as possible let us reduce this code to:

```<code>import Flask
app = Flask()

@app.route('/')
def hello_world():
    return 'Hello World!'

app.run()
</code>```

It is important to remember that this code will not actually run it's only shortened for clarity.

The first line imports our application framework.
The next defines a variable app that will reference our application

The def hello_world(): block defines a function that returns the string Hello World!

The @app.route('/') says to run this function when the URL route / is requested. Or, for clarity, when you point your browser at http://www.someserver.com/

app.run() then starts a new web server on the machine that serves the routes of our application.

These two pieces of code (CGI perl and Flask python) functionally do the same thing but achieve it in a very different way. You can see for example in the Flask application we didn't need the "Content-type: text/html\n\n" line. This is because the framework takes care of these things for us in the internal web server.

I would recommend following a good tutorial for a python web framework like Flask as a good starting point for understanding what a web framework is and how it works. For example, this one: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

Also, do I need to learn HTTP in depth before I even begin learning to build Web apps?

Not in great depth, a basic understanding of GET/POST and status codes will be all you need to start learning most web frameworks. That said knowledge is always good, you can fill in your understanding as you progress but don't focus entirely on completely understanding the inter-workings of every sub-component as that in our field is quite frankly an unobtainable goal.

I hope this helped.

Title: CGI Scripts and Python / Ruby

Body:
For example, I just read about CGI scripts. Now, usually when I see people talk about web application programming these days, they're using some framework for Ruby or Python or even PHP.

CGI is considered by most to be an outdated technology these days for anything but the simplest applications, some of your reference material may be outdated.

How do these programming languages and CGI scripts written in C(?) relate?

OK, let's say that we had some perl code as a CGI script:

#!/usr/bin/perl

print "Content-type: text/html\n\n";

print "Hello, world!\n";

When there is an HTTP Request sent to the server for this file (eg: http://www.someserver.com/cgi-bin/hello.pl) the server will first execute this code and send the standard output as a response. This is the reason that we have to include the "Content-type: text/html\n\n" in the response as the HTTP header.

Web Frameworks however are a rather different beast. In their most basic description they are simply a blanket term for any tool-set that provides functionality associated with common web development activities.

In practice however they almost all function in a similar way and provide similar tooling.
From Wikipedia:

many frameworks provide libraries for database access, templating frameworks and session management

Let's compare the previous CGI code to this python code written using a Web Framework called Flask:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

To avoid as much of the Python specific syntax as possible let us reduce this code to:

import Flask
app = Flask()

@app.route('/')
def hello_world():
    return 'Hello World!'

app.run()

It is important to remember that this code will not actually run it's only shortened for clarity.

The first line imports our application framework.
The next defines a variable app that will reference our application

The def hello_world(): block defines a function that returns the string Hello World!

The @app.route('/') says to run this function when the URL route / is requested. Or, for clarity, when you point your browser at http://www.someserver.com/

app.run() then starts a new web server on the machine that serves the routes of our application.

These two pieces of code (CGI perl and Flask python) functionally do the same thing but achieve it in a very different way. You can see for example in the Flask application we didn't need the "Content-type: text/html\n\n" line. This is because the framework takes care of these things for us in the internal web server.

I would recommend following a good tutorial for a python web framework like Flask as a good starting point for understanding what a web framework is and how it works. For example, this one: http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

Also, do I need to learn HTTP in depth before I even begin learning to build Web apps?

Not in great depth, a basic understanding of GET/POST and status codes will be all you need to start learning most web frameworks. That said knowledge is always good, you can fill in your understanding as you progress but don't focus entirely on completely understanding the inter-workings of every sub-component as that in our field is quite frankly an unobtainable goal.

I hope this helped.


答:
Basically every modern computer is a bit-pushing machine.  Usually it pushes bits around in clusters of data, called bytes, words, dwords or qwords.

A byte consists of 8 bits, a word 2 bytes (or 16 bits), a dword 2 words (or 32 bits) and a qword 2 dwords (or 64 bits).  These are not the only way to arrange bits.  128 bit and 256 bit manipulation also occurs, often in SIMD instructions.

Assembly instructions operate on registers and memory addresses usually operate in one of the above forms.

ALU (arithmetic logic units) operate on such bundles of bits as if they represented integers (usually Two's Complement format), and FPUs as if they where floating point values (usually IEEE 754-style float and double).  Other parts will act as if they are bundled data of some format, characters, table entries, CPU instructions, or addresses.

On a typical 64 bit computer, bundles of 8 bytes (64 bits) are addresses.  We display these addresses conventionally as in a hex format (like 0xabcd1234cdef5678), but that is just an easy way for humans to read the bit patterns.  Each byte (8 bits) is written as two hex characters (equivalently each hex character -- 0 to F -- represents 4 bits).

What is actually going on (for some level of actually) is that there are bits, usually stored in a register or stored in adjacent locations in a memory bank, and we are just trying to describe them to another human.

Following a pointer consists of asking the memory controller to give us some data at that location.  You'd typically ask the memory controller for a certain number of bytes at a certain location (well, implicitly a range of locations, usually contiguous), and it is delivered through various mechanisms I won't get into.

The code usually specifies a destination for the data to be fetched to -- a register, another memory address, etc -- and usually it is a bad idea to load floating point data into a register expecting an integer, or vice versa.

The type of the data in C/C++ is something that the compiler keeps track of, and it changes what code is generated.  Usually there is nothing intrinsic in the data that makes it actually of any one type.  Just a collection of bits (arranged into bytes) that are manipulated in a integer-like way (or a float-like way, or an address-like way) by the code.

There are exceptions to this.  There are architectures where certain things are a different kind of bits.  The most common example is protected execution pages -- while instructions telling the CPU what do do are bits, at run time the (memory) pages containing code to execute are marked specially, cannot be modified, and you cannot execute pages that are not marked as execution pages.

There are also read only data (sometimes stored in ROM that cannot physically be written to!), alignment issues (some processors cannot load doubles from memory unless they are aligned in particular ways, or SIMD instructions that require certain alignment), and myriads of other architecture quirks.

Even the above level of detail is a lie.  Computers aren't "really" pushing around bits, they are really pushing around voltages and current.  These voltages and current sometimes don't do what they are "supposed" to do at the abstraction level of bits.  The chips are designed to detect most such errors and correct them without the higher level abstraction having to be aware of it.

Even that is a lie.

Each level of abstraction hides the one below, and lets you think about solving problems without having to keep in mind Feynman diagrams in order to print out "Hello World".

So at a sufficient level of honesty, computers push bits, and those bits are given meaning by how they are used.


答:
First, since we only care about the y-distance and will be drawing a horizontal line, we only need to think about the y-coordinates of the points and the y-coordinate that defines the line. The distance between a point and our line will be the absolute difference between the y-coordinate of the point and the y-coordinate that defines the line.

So, rephrasing the problem, we have a set of numbers, y_1 to y_n, and need a number, z, that minimizes the aggregate of the absolute differences between z and the points y_1 to y_n. Instead of minimizing the aggregate, we can just minimize the sum and get the correct result (aggregate = sum / number_of_points).

It turns out that it is the median that does this, not the mean.

https://math.stackexchange.com/questions/113270/the-median-minimizes-the-sum-of-absolute-deviations

For intuition, have points at y-coordinates 10, 10, 10 and 110. The median is 10, aggregate distance is (0+0+0+100)/4=25. The mean is 140/4=35, aggregate distance is (25+25+25+75)/4=37,5. In fact moving the line any distance, d, away from y-coordinate 10 towards 100 increased the distance to 3 points (with d) while only decreasing the distance to 1 point (with d) and hence increasing the aggregate.

(If we would take squares of distances then the mean would be the correct answer)

Title: Find a line that is closest to scattered points

Body:
I came across the below interview question on Glassdoor:

A scatter graph of points on a page, draw a horizontal line  across the page such the the perpendicular y distance to the line from all points in aggregate is minimized. Describe an algorithm for placing this line optimally

My approach:

I think we can compute the mean of y-distances and place the line there.

However, I am not sure if this is correct or if there is a better approach to solving this problem.


答:
As Jonathan points out there are are a number of different cost functions you can minimize but from the perpendicular y distance to the line from all points in aggregate is minimized i'd assume we were looking for the 'minimum sum of the absolute distance'.

This isn't too bad to calculate if you happen to know that this is the same as the median, proof (I suspect this makes it a poor question for a general development position, and one more suited for data science)

to find the median one could sort the points by co-ord then take either the middle point from the list or average the two middle points.


问:
How many applications should you provide to cover all sort of mobile phones
At the moment we have:

Iphone

Android

J2me touch

J2me non-touch

J2me touch for Blackberry

J2me non-touch for Blackberry

We were thinking of making another

J2me non-touch for crappy devices (because the regular non-touch is just to heavy)

The question is, can you think of any other versions of our application that we should provide to target 'ALL' mobile phones

答: Symbian. Nokia still has the biggest market share worldwide for all mobile phones</p>


答:
First of all, Git is a decentralized VCS (as opposed to ClearCase, which is very centralized: see "What are the basic clearcase concepts every developer should know?")

That means, there is no central server to keep track of a "locked" file.

Secondly, you generally don't just pull, but you pull --rebase with autostash in order to replay your local (not yet pushed) modification on top of whatever concurrent modifications were published (pushed).

This is the natural workflow to allow concurrent collaboration.

Note that ClearCase allows for concurrent modifications as well, at least in snapshot views (but you cannot easily tell which hijacked file was modified).

Finally, there isn't much going for the old (1985) ClearCase model (See "ClearCase advantages/disadvantages"). Using it in 2015 is an anachronism, as it doesn't scale well with large number of files, unless you are using dynamic views, and even then, any merge is dreadfully slow.

If you have to go on using an IBM tool, consider at least RTC (Rational Team Concert). It does have a locking mechanism.


答:
You have changes to commit, but they are based on an old version. That's no good. In any source control system, you can rebase your changes so that they are now based on the current version. That's not automatic, it is work, there might be conflicts, but it's all unavoidable. So far, everything's the same.

But because the process of rebasing and retesting your change took time, by the time you are done you might again have changes based on an old version. Usually this is just bad luck (you rebased your code to include Joe's changes, and just then Jim had to check in his last month's work). With a bigger team, and people sometimes working  on the same files, this can be a problem.

With git, your choices are: Either be quick, or ask other developers not to commit anything until you are done. With other systems, you can lock files, so other developers cannot commit, which is really the same, except you don't walk to their desk, and they cannot say no. There isn't really much difference in practice, assuming you are not locking files and then keep them locked for ages. I'd always do a first rebase without telling anyone, to avoid bothering everyone else too much.


问:
Is there a way to make the default way a class is accessed a field within the class?
I'm trying to write a wrapper for the following bit of scala code:

```<code>val vertBuffer: FloatBuffer = createFloatBuffer(vertex_positions.length)
vertBuffer.put(vertex_positions)
vertBuffer.flip()
</code>```

However, the class will be used almost exclusively in things like this:

```<code>val vboId = glGenBuffers()
glBindBuffer(GL_ARRAY_BUFFER, vboId)
glBufferData(GL_ARRAY_BUFFER, vertBuffer, GL_STATIC_DRAW)
</code>```

I'm looking for a way to avoid having to type something similar to

```<code>vertBufferWrapper.getWrapped
</code>```

and be able to write just

```<code>vertBufferWrapper
</code>```

Thank you for your time.

答:
Don't store it in a wrapped class in the first place.  Just create a transformation function from the data structure you have to the one you need:

```<code>def createFlippedBuffer(vertex_positions: Positions) : FloatBuffer = {
  val vertBuffer: FloatBuffer = createFloatBuffer(vertex_positions.length)
  vertBuffer.put(vertex_positions)
  vertBuffer.flip()
  vertBuffer
}
</code>```

It's not clear if you had other reasons to choose a wrapper in the first place, but another option is the pimp my library feature, which allows you to add methods to existing classes without explicitly using a wrapper.

Body:
Don't store it in a wrapped class in the first place.  Just create a transformation function from the data structure you have to the one you need:

def createFlippedBuffer(vertex_positions: Positions) : FloatBuffer = {
  val vertBuffer: FloatBuffer = createFloatBuffer(vertex_positions.length)
  vertBuffer.put(vertex_positions)
  vertBuffer.flip()
  vertBuffer
}

It's not clear if you had other reasons to choose a wrapper in the first place, but another option is the pimp my library feature, which allows you to add methods to existing classes without explicitly using a wrapper.


答:
An important thing to understand about C and C++ is what types actually are.  All they really do is indicate to the compiler how to interpret a set of bits/bytes.  Lets start with the following code:

```<code>int var = -1337;
</code>```

Depending on architecture, an integer is usually given 32 bits of space to store that value.  That means that the space in memory where var is stored will look something like "11111111 11111111 11111010 11000111" or in hex "0xFFFFFAC7".  That's it.  That is all that is stored at that location.  All types do is tell the compiler how to interpret that information.  Pointers are no different.  If I do something like this:

```<code>int* var_ptr = &var;   //the ampersand is telling C "get the address where var's value is located"
</code>```

Then the compiler will get the location of var, and then store that address in the same way the first code snippet saves the value -1337.  There is no difference in how they are stored, just in how they are used.  It doesn't even matter that I made var_ptr a pointer to an int.  If you wanted to, you could do.

```<code>unsigned int var2 = *(unsigned int*)var_ptr;
</code>```

This will copy the above hex value of var (0xFFFFFAC7) into the location that stores var2's value.  If we were to then use var2, we'd find that the value would be 4294965959.  The bytes in var2 are the same as var, but the numerical value differs.  The compiler interpreted them differently because we told it that those bits represent an unsigned long.  You could do the same for the pointer value too.

```<code>unsigned int var3 = (unsigned int)var_ptr;
</code>```

You'd end up interpreting the value that represents the address of var as an unsigned int in this example.

Hopefully this clarifies things for you and gives you a better insight as to how C works.  Please note that you SHOULD NOT do any of the crazy stuff I did in the below two lines in actual production code.  That was just for demonstration.

Body:
An important thing to understand about C and C++ is what types actually are.  All they really do is indicate to the compiler how to interpret a set of bits/bytes.  Lets start with the following code:

int var = -1337;

Depending on architecture, an integer is usually given 32 bits of space to store that value.  That means that the space in memory where var is stored will look something like "11111111 11111111 11111010 11000111" or in hex "0xFFFFFAC7".  That's it.  That is all that is stored at that location.  All types do is tell the compiler how to interpret that information.  Pointers are no different.  If I do something like this:

int* var_ptr = &var;   //the ampersand is telling C "get the address where var's value is located"

Then the compiler will get the location of var, and then store that address in the same way the first code snippet saves the value -1337.  There is no difference in how they are stored, just in how they are used.  It doesn't even matter that I made var_ptr a pointer to an int.  If you wanted to, you could do.

unsigned int var2 = *(unsigned int*)var_ptr;

This will copy the above hex value of var (0xFFFFFAC7) into the location that stores var2's value.  If we were to then use var2, we'd find that the value would be 4294965959.  The bytes in var2 are the same as var, but the numerical value differs.  The compiler interpreted them differently because we told it that those bits represent an unsigned long.  You could do the same for the pointer value too.

unsigned int var3 = (unsigned int)var_ptr;

You'd end up interpreting the value that represents the address of var as an unsigned int in this example.

Hopefully this clarifies things for you and gives you a better insight as to how C works.  Please note that you SHOULD NOT do any of the crazy stuff I did in the below two lines in actual production code.  That was just for demonstration.


问:
Dealing with date fields across browsers
I'm building a web application with multiple forms which all require date fields, and these fields need to be supported across IE, Chrome, and the like.

Our application currently packages the output of the forms as a JSON object which we feed into GsonBuilder to convert them into a java object for persistence.

Our GsonBuilder object currently accepts a format of 'yyyy-MM-dd'. In Chrome, our forms seem to be utilizing HTML5, which include a date picker in the date fields, and the browser seemingly does some magic and GsonBuilder accepts the date with no issues. In IE, however, there is no date picker and the users need to hand-bomb a date, which has to be in the exact specified format for GsonBuilder to accept the field.

So today I've been trying to work out what a good solution to this problem would be, and there are almost so many possibilities that it seems hard to identify the proper one to use.

So far I've considered using the jquery mask plugin to enforce the proper format in IE, however I don't know how this would work in Chrome as the date fields include a date picker which already enforce format.

I've also considered propagating a specific server error back up to the front-end when a user enters an incorrect format in IE. This seems like a bad solution because it would cause guessing games for the user.

Surely, at some point I need to enforce data integrity in IE, but I am not sure what the best way of doing this is. Is there a common pattern that people use to deal with this issue?

答:
I tried to use a few poly-fills, which seems like a good solution, however was having difficulty finding one which produced the desired effect (might have been an error on my part).

Instead, we ended up using Bootstrap 3 Datepicker which seems to work just fine across browsers.


答:
Symbian / Android / IPhone

That's it ... this gives you a very (very!!) large majority coverage. Disregard the rest ... you cannot please everybody, and it will probably be not worth the cost either (always think of the cost/benefits).

Title: How many applications should you provide to cover all sort of mobile phones

Body:
At the moment we have:

Iphone

Android

J2me touch

J2me non-touch

J2me touch for Blackberry

J2me non-touch for Blackberry

We were thinking of making another

J2me non-touch for crappy devices (because the regular non-touch is just to heavy)

The question is, can you think of any other versions of our application that we should provide to target 'ALL' mobile phones


问:
A practical use of "yield" keyword in C#
After almost 4 years of experience, I haven't seen a code where yield keyword is used. Can somebody show me a practical usage (along explanation) of this keyword, and if so, aren't there other ways easier to fullfill what it can do?

答:
Some time ago I had a practical example, let's assume you have a situation like this:

```<code>List<Button> buttons = new List<Button>();
void AddButtons()
{
   for ( int i = 0; i <= 10; i++ ) {
      var button = new Button();
      buttons.Add(button);
      button.Click += (sender, e) =>
          MessageBox.Show(String.Format("You clicked button number {0}", ???));
   }
}
</code>```

The button object does not know his own position in the collection. The same limitation applies for Dictionary<T> or other collections types.

Here is my solution using yield keyword:

```<code>interface IHasId { int Id { get; set; } }

class IndexerList<T>: List<T>, IEnumerable<T> where T: IHasId
{
   List<T> elements = new List<T>();
   new public void Clear() { elements.Clear(); }
   new public void Add(T element) { elements.Add(element); }
   new public int Count { get { return elements.Count; } }
   new public IEnumerator<T> GetEnumerator()
   {
      foreach ( T c in elements )
         yield return c;
   }

   new public T this[int index]
   {
      get
      {
         foreach ( T c in elements ) {
            if ( (int)c.Id == index )
               return c;
         }
         return default(T);
      }
   }
}
</code>```

And that's how I use it:

```<code>class ButtonWithId: Button, IHasId
{
   public int Id { get; private set; }
   public ButtonWithId(int id) { this.Id = id; }
}

IndexerList<ButtonWithId> buttons = new IndexerList<ButtonWithId>();
void AddButtons()
{
   for ( int i = 10; i <= 20; i++ ) {
      var button = new ButtonWithId(i);
      buttons.Add(button);
      button.Click += (sender, e) =>
         MessageBox.Show(String.Format("You clicked button number {0}", ( (ButtonWithId)sender ).Id));
   }
}
</code>```

I don't have to make a for loop over my collection in order to find the index. My Button has an ID and this is also used as index in IndexerList<T>, so you avoid any redundant ID's or indexes - that's what I like! The index/Id can be an arbitrary number.

Body:
Some time ago I had a practical example, let's assume you have a situation like this:

List<Button> buttons = new List<Button>();
void AddButtons()
{
   for ( int i = 0; i <= 10; i++ ) {
      var button = new Button();
      buttons.Add(button);
      button.Click += (sender, e) =>
          MessageBox.Show(String.Format("You clicked button number {0}", ???));
   }
}

The button object does not know his own position in the collection. The same limitation applies for Dictionary<T> or other collections types.

Here is my solution using yield keyword:

interface IHasId { int Id { get; set; } }

class IndexerList<T>: List<T>, IEnumerable<T> where T: IHasId
{
   List<T> elements = new List<T>();
   new public void Clear() { elements.Clear(); }
   new public void Add(T element) { elements.Add(element); }
   new public int Count { get { return elements.Count; } }
   new public IEnumerator<T> GetEnumerator()
   {
      foreach ( T c in elements )
         yield return c;
   }

   new public T this[int index]
   {
      get
      {
         foreach ( T c in elements ) {
            if ( (int)c.Id == index )
               return c;
         }
         return default(T);
      }
   }
}

And that's how I use it:

class ButtonWithId: Button, IHasId
{
   public int Id { get; private set; }
   public ButtonWithId(int id) { this.Id = id; }
}

IndexerList<ButtonWithId> buttons = new IndexerList<ButtonWithId>();
void AddButtons()
{
   for ( int i = 10; i <= 20; i++ ) {
      var button = new ButtonWithId(i);
      buttons.Add(button);
      button.Click += (sender, e) =>
         MessageBox.Show(String.Format("You clicked button number {0}", ( (ButtonWithId)sender ).Id));
   }
}

I don't have to make a for loop over my collection in order to find the index. My Button has an ID and this is also used as index in IndexerList<T>, so you avoid any redundant ID's or indexes - that's what I like! The index/Id can be an arbitrary number.


问:
Best-matching comparative values using all items in array
I have two arrays of objects (items) in the exact same format.  Each item represents a wager, and each array represents one of two outcomes for that wager (ex: Team A vs Team B).  Both arrays look like this to start with:

```<code>  {
    "_id": "55762b3de624f37d80d09b34",
    "value": 803,
    "owner": 923
  },
  {
    "_id": "55762b3dc73fad717a7173ed",
    "value": 1457,
    "owner": 897
  },
  ...
</code>```

These arrays differ in length.  Let's say array A has 1200 items and array B has 800 items with each item's value ranging from 4 to 5,000.  In production each array will likely range from 1000-200,000 entries, so keep efficiency in mind.  The goal is to take all the items in array B (lost wagers) and add them to array A (won wagers) so that the value of items in B are distributed evenly by sum of values grouped by user in A.  So if you bet three items, you would get those items back plus any number of items from array B.

First I run through array A (winners) and handle the user grouping and summing.  Array A is now Object A and looks like this:

```<code>  '997': // User ID
   { bet: 15090, // Summed value of all items wagered in the below array
     items: // Original item IDs from their wager
      [ '55762b3dd82338e9683eea9b',
        '55762b3dccd4800148eec868',
        '55762b3de495cbcd594ecc17',
        '55762b3daad995d207c506f0',
        '55762b3d2154c4c0e273fe94' ] },
  '998':
   { bet: 5196,
     items: [ '55762b3da1e658e5cb37ede6', '55762b3d1fca60c0cdd21a2e' ] },
   ...
</code>```

Then take the total value of each array and figure out the multiplier to use for each "bet" value (aka: calculate the odds).  Using the same randomly generated data this works out to be:

```<code>A Total Value: 2,439,112 (entire value of items bet on Team A)
B Total Value: 1,608,947 (entire value of items lost on Team B)
0.6596445755668456 value from B for each A
</code>```

So, for instance, user 997's total bet of 15,090 would need to gain ~9,954 of value from array B.  When the items from array B are used, they are removed and the _id field is added to the "items" array.  Since the values are associated with individual items and not a divisible currency, they cannot be split in order to make perfect change.  The values don't have to match up exactly, but should be relatively close.  For example, if a user bets 100 and should gain 65.9, they can get items within the 62-68 range if needed.  This also means that users who bet very little may end up getting nothing in return depending on the odds, since there is a minimum bet of 4.  Ex: If you bet 4, your winnings would be 2.63, but the lowest item value to distribute is 4.

What type of algorithm would be most appropriate for this kind of task?  It sounds like something straight out of a textbook, but I have no idea where to start my search.

All this data will eventually be in mongodb, so mongo-specific functions are welcomed as well!

答:
Hmm I guess the obvious one is to:

```<code>sort B desc
sort A asc

loop through A
    loop through B
        if Value(B) <= RemainingValue(A)
           add B to A
           break if RemainingValue(A) == 0 OR you run out of B
    Next B
Next A
</code>```

but this is not quick

Body:
Hmm I guess the obvious one is to:

sort B desc
sort A asc

loop through A
    loop through B
        if Value(B) <= RemainingValue(A)
           add B to A
           break if RemainingValue(A) == 0 OR you run out of B
    Next B
Next A

but this is not quick


问:
Python replace function for classes? Like namedtuple _replace?
Does the Python standard library offer anything similar to the custom replace function below? I can put this in my own *utils module, but I'd rather use a standard library implementation. Also, this example would better be served by a namedtuple, which already has _replace, but I need the same function for other classes in my project.</p>

```<code>from copy import copy

class cab(object):
    a = None
    b = None

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return "cab(a=%s, b=%s)" % (self.a, self.b)

# Does not modify source. Creates a copy with the specified modified fields.
def replace(source, **kwargs):
    result = copy(source)
    for key in kwargs:
        setattr(result, key, kwargs[key])
    return result

v1 = cab(3,4)
v2 = replace(v1, a=100)
v3 = replace(v1, b=100)
</code>```

答:
namedtuple has such a method because it itself is immutable. Other immutable types in the standard library have one too, like datetime.datetime for example.

It is not a common pattern to use with mutable objects. So no, there is no built-in version for custom types for this. Custom classes invariably require custom handling anyway.

Note that your utility is a function, and not a method either. You'd usually make it a method on custom classes:

```<code>class cab(object):
    a = None
    b = None

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return "cab(a=%s, b=%s)" % (self.a, self.b)

    def replace(self, **kw):
        return type(self)(kw.get('a', self.a), kw.get('b', self.b))
</code>```

Body:
namedtuple has such a method because it itself is immutable. Other immutable types in the standard library have one too, like datetime.datetime for example.

It is not a common pattern to use with mutable objects. So no, there is no built-in version for custom types for this. Custom classes invariably require custom handling anyway.

Note that your utility is a function, and not a method either. You'd usually make it a method on custom classes:

class cab(object):
    a = None
    b = None

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __repr__(self):
        return "cab(a=%s, b=%s)" % (self.a, self.b)

    def replace(self, **kw):
        return type(self)(kw.get('a', self.a), kw.get('b', self.b))


问:
Using an LGPL licensed library that may or may not include GPL licensed code from an MIT licensed library
I have read Interfacing with GPL applications from MIT licensed code - is a dual-license unavoidable? (now deleted) on Stack Overflow, but it doesn't appear to fully answer my question.

I maintain a library which is licensed under the MIT License. In my MIT licensed library, I dynamically link (Python ctypes to be specific) against another library which is licensed under the GNU Lesser General Public License 2.1 (LibRaw). This would be fine by itself, however, LibRaw is sometimes statically linked against a sort of "plugin" called the LibRaw Demosaic Pack which is licensed under GNU General Public License 2+ or GNU General Public License 3 depending on the version. I have no way of checking if LibRaw has been linked against these libraries. (LibRaw is just installed on the end users computer and when they download our library and use it it links against it, I am not redistributing or building LibRaw.)

Does linking against the LGPL library from my MIT library when the LGPL library has been linked against GPL code mean that I'm illegally using GPL code in my MIT Library?

If it is so, is there some way around this short of sub-licensing parts of my code under the GPL, or dual-licensing (which is just confusing for the end user)? Or can I still link against the LGPL library under the terms of the LGPL even though it then links against GPLed code?

答:
The question becomes really simple if you are releasing as free and open source and everything using your code is also free and open source: everything will be fine as long as your code is using a compatible license. If your code is proprietary or is used in proprietary software, it becomes a bit more complicated. The main question is whether or not you or others are using your MIT licensed code in a proprietary manner.

You can link to code covered by the GPL even in proprietary systems as long as the license is compatible. The MIT license is generally compatible with the GPL, but I recommend asking FSF directly as these multi-license situations can be tricky.

ContentLicense: CC BY-SA 4.0


问:
What's the best way to return an array as a response in a RESTful API?
Assume we have resources like this,

```<code>book:
    type: object
    properties:
        author: {type: string}
        isbn: {type: string}
        title: {type: string}

books:
    type: array
    items: book
</code>```

So, when someone makes a GET on the books resource, we would be returning the following

```<code>[{"author": "Dan Brown", "isbn": "123456", "title": "Digital Fortress"},
 {"author": "JK Rowling", "isbn": "234567", "title": "Harry Potter and the Chamber of Secrets"}]
</code>```

I heard from someone at work that the recommended REST practice is to always return responses as JSON objects, which would mean that our schema for books would look like this,

```<code>books:
    type: object
    properties:
        list:
            type: array
            items: book
</code>```

So, now, response would look like this,

```<code>{
    "list": [{"author": "Dan Brown", "isbn": "123456", "title": "Digital Fortress"},
             {"author": "JK Rowling", "isbn": "234567", "title": "Harry Potter and the Chamber of Secrets"}]
}
</code>```

Which of these is the best REST practice?

答:
The reason you make your response JSON compliant is that JSON is a defacto standard; any language with a JSON parser can trivially parse it, and if you're using JavaScript, you don't even need a parser since JavaScript understands it natively.

In other words, make it JSON compliant, and you won't have to write your own parser.  Further, there will be no surprises when the next developer writes software that consumes the service.

REST doesn't have anything to do with your JSON schema.  Either schema is acceptable, from a REST perspective.


问:
How to handle 50% of worse than average sprints?
My understanding of Scrum is that I determine the work my team can take on in the next sprint by averaging the number of completed points for the past several sprints.

This is an average, so if history repeats itself, this sprint it is 50% likely that we are taking on too few story points, and 50% likely that we are taking on too many story points.

In the case we have taken on too many story points we could:

Fail to complete the sprint. This means we will fail to meet our sprint commitment half the time.

Work extra to catch up. The problem is that this ratchets only one way. We will accomplish the sprint, and the number of story points completed will reflect that. Since we always finish, over time, our average will trend upward to the point where we are always accomplishing a large number of story points and staying late.

Is my understanding of average velocity and sprint commitments correct?

If so, what should we do for the 50% of sprints where we are behind average?

If not, what have I gotten wrong?

答:
First, your velocity is from your previous sprint, or sometimes from an average of a few recent Sprints (Yesterday's Weather), and not an average of all past sprints. Of course, if you have no historical data from your team or company, you need to come up with a reasonable value for your first sprint. On your second sprint, you take in the completed story points into the sprint. If you were to graph it, you may see variations over the first few sprints. That is to be expected as you normalize your teamwork and estimation process, along with gaining a better understand of the project (technology, domain).

That isn't to say that you don't adjust. For example, if you have a week that is a holiday week, be sure to account for the holiday where the business is closed. If you know that team members are taking a vacation, plan for fewer people working. Of course, unplanned events do happen as well, but you can explain those in a Sprint Retrospective and you can decide how that influences the number of story points that you bring into the next sprint.

As far as what to do, "fail to complete the sprint" is different than "we didn't complete all of the stories". To me, a failure of a sprint means that you didn't produce a potentially shippable product at the end - none of your stories are complete, you don't have a build, you can't demonstrate any added value to stakeholders.

Whatever you do, you shouldn't work late or excessive over time. This is called the sustainable pace (Agile Alliance, Scrum Alliance).

The indicators that there may be issues is if:

Your team is not working a sustainable pace. You need to work overtime to complete the story points planned for a sprint. Make your sprints smaller to complete on-time without the added pressure.

Your velocity doesn't normalize over time. No one is expecting velocity to never change, but if you notice spikes or swings, deal with those in your Sprint Retrospectives. Figure out what's causing them and address the root causes.