问:
Saving Passwords To The Local Device
So In my app (iOS), you have to register in order to use the service (a food service).  But in order to change details about your account (username, password, and email), you have to reenter your password.  Except for if the user logged out, this is the only time you need your password to use the app.  So I was wondering, since the user basically never uses their password, and its likely they would forget it the one time they might need it, is it ok if I store their password to their local device (in NSUserDefaults)?

Since their password would only be on their local device, it doesn't seem like a security risk.  If the app was hacked, the only password they could get would be their own.

Further, I was planning on just storing it as a string (no encryption).  Would it make a difference if I hashed it or encrypted it before saving the password to their defaults?

Thanks in Advance.

答: Users tend to stick with 1 or 2 passwords.  If the app was hacked by another app, then having the user's password from your service might grant access to other more sensitive resources besides your food service.  A better method may be to store some sort of long term authentication token on the phone than the password itself.  That token could be tied to the user's account information on the server, thus allowing the user to enter their password just once while keeping his or her password secure.  </p>

Title: Saving Passwords To The Local Device


问:
Practices for navigating and changing "long" code files?
Many a times I have to deal with code files which are quite long - about 5 screen pages at the minimum. Almost always there is something towards the top/bottom that I need to refer when I'm at the bottom/top (respectively). It's a mammoth overhead to constantly scroll back-n-forth between the file parts.

It's a cognitive overload to just remember each and everything throughout the file and it's quite necessary to be able to refer to parts of the file.

Yes, the Outline view in some editors like Eclipse/NetBeans helps, but sometimes they will work well only for parts recognizable by that parser. Sometimes outline views don't show up e.g. when coding in CoffeeScript or JavaScript using closures/namespaced functions etc. The fallback is then just manual scroll overhead.

So as programmers what are some of the techniques/practices that can be employed to reduce this ridiculous overhead?

Yes, I can shorten the files, but specifically javascript libraries like Backbone.js etc. are all as one file since you really can't split them into multiple file due to lack of Java-like packages. So under the constraints of inability of splitting a file and the outline views not working, what are some of the techniques I can use to navigate through long source files? I work a lot on Eclipse/Netbeans and Aptana and sometimes Vi (but seldom in production environments). It'd be great to be able to split a window into two and see the same file on one side and code in the other. Not doable with Eclipse/NB/Aptana IMO. Vi, yes but can't use it all the time.

PS: As of now, I split the file among multiple editors e.g. Eclipse and Aptana. It'd be great to have it at one place, but is that the best that we can do? :)

UPDATE - Seems Eclipse has way for doing this and can be found here

答:
The most important thing to reduce this problem is to provide good abstractions for your methods. If you need to look at what Foo does everytime, then that is a good reason to refactor the code, to either rename the method, or break up the method into different ones. (Breaking up is useful when you have a complex control flow based on the input)

If you don't want to refactor, typically in visual studio I use goto definition and the back button on my mouse to navigate around to the various points. You might be able to use similar shortcuts in your IDE to avoid having to manually look around so much.

ContentLicense: CC BY-SA 3.0


答:
Here's the rules which allows keeping files of 10kloc in size with 100 classes in each file in c++ code:

Use emacs + esc-< + C-s for going to beginning of file and then searching a class by search words "class MyClass" and "::mymemberfunction". It requires remembering the name of the class or member function you want to find.

notepad has the same feature in C-f

other ides probably have ability to find text from single file which you have already open; going to beginning of file is more difficult to find...

Title: Practices for navigating and changing "long" code files?

Body:
Many a times I have to deal with code files which are quite long - about 5 screen pages at the minimum. Almost always there is something towards the top/bottom that I need to refer when I'm at the bottom/top (respectively). It's a mammoth overhead to constantly scroll back-n-forth between the file parts.

It's a cognitive overload to just remember each and everything throughout the file and it's quite necessary to be able to refer to parts of the file.

Yes, the Outline view in some editors like Eclipse/NetBeans helps, but sometimes they will work well only for parts recognizable by that parser. Sometimes outline views don't show up e.g. when coding in CoffeeScript or JavaScript using closures/namespaced functions etc. The fallback is then just manual scroll overhead.

So as programmers what are some of the techniques/practices that can be employed to reduce this ridiculous overhead?

Yes, I can shorten the files, but specifically javascript libraries like Backbone.js etc. are all as one file since you really can't split them into multiple file due to lack of Java-like packages. So under the constraints of inability of splitting a file and the outline views not working, what are some of the techniques I can use to navigate through long source files? I work a lot on Eclipse/Netbeans and Aptana and sometimes Vi (but seldom in production environments). It'd be great to be able to split a window into two and see the same file on one side and code in the other. Not doable with Eclipse/NB/Aptana IMO. Vi, yes but can't use it all the time.

PS: As of now, I split the file among multiple editors e.g. Eclipse and Aptana. It'd be great to have it at one place, but is that the best that we can do? :)

UPDATE - Seems Eclipse has way for doing this and can be found here


问:
Handling Indirection and keeping layers of method calls, objects, and even xml files straight
How do you keep everything straight as you trace deeply into a piece of software through multiple method calls, object constructors, object factories, and even spring wiring.  I find that 4 or 5 method calls are easy to keep in my head, but once you are going to 8 or 9 calls deep it gets hard to keep track of everything.  Are there strategies for keeping everything straight?

In particular, I might be looking for how to do task x, but then as I trace down (or up) I lose track of that goal, or I find multiple layers need changes, but then I lose track of which changes as I trace all the way down.  Or I have tentative plans that I find out are not valid but then during the tracing I forget that the plan is invalid and try to consider the same plan all over again killing time....

Is there software that might be able to help out?  grep and even eclipse can help me to do the actual tracing from a call to the definition but I'm more worried about keeping track of everything including the de-facto plan for what has to change (which might vary as you go down/up and realize the prior plan was poor).

In the past I have dealt with a few big methods that you trace and pretty much can figure out what is going on within a few calls.  But now there are dozens of really tiny methods, many just a single call to another method/constructor and it is hard to keep track of them all.

答:
I tend to have a sheet of paper (the reverse side before it goes in the recycler) partially held by my keyboard that I scribble notes on, and call stacks get scribbled down there too - in a shorthand form.

You could day that if you your call stacks go on for 10, 20 or even 30 method calls, then you've got one mess on your hands. You need to make the objects much clearer - so that you can skip pieces of the call stack as "obvious" and therefore unnecessary to remember. (eg, you don't really need to step into the assembly when you add 2 ints together, you trust it to work).


问:
What limitations does the JVM impose on tail-call optimization
Clojure does not perform tail call optimization on its own: when you have a tail recursive function and you want to have it optimized, you have to use the special form recur. Similarly, if you have two mutually recursive functions, you can optimize them only by using trampoline.

The Scala compiler is able to perform TCO for a recursive function, but not for two mutually recursive functions.

Whenever I have read about these limitations, they were always ascribed to some limitation intrinsic to the JVM model. I know pretty much nothing about compilers, but this puzzles me a bit. Let me take the example from Programming Scala. Here the function

```<code>def approximate(guess: Double): Double =
  if (isGoodEnough(guess)) guess
  else approximate(improve(guess))
</code>```

is translated into

```<code>0: aload_0
1: astore_3
2: aload_0
3: dload_1
4: invokevirtual #24; //Method isGoodEnough:(D)Z
7: ifeq
10: dload_1
11: dreturn
12: aload_0
13: dload_1
14: invokevirtual #27; //Method improve:(D)D
17: dstore_1
18: goto 2
</code>```

So, at the bytecode level, one just needs goto. In this case, in fact, the hard work is done by the compiler.

What facility of the underlying virtual machine would allow the compiler to handle TCO more easily?

As a side note, I would not expect actual machines to be much smarter than the JVM. Still, many languages that compile to native code, such as Haskell, do not seem to have issues with optimizing tail calls (well, Haskell can have sometimes due to laziness, but that is another issue).

答:
As a sidenote, I would not expect actual machines to be much smarter than the JVM.

It's not about being smarter, but about being different.  Until recently, the JVM was designed and optimized exclusively for a single language (Java, obviously), which has very strict memory and calling models.

Not only there wasn't any goto or pointers, there wasn't even any way to call a 'bare' function (one that wasn't a method defined within a class).

Conceptually, when targeting JVM, a compiler writer has to ask "how can I express this concept in Java terms?".  And obviously, there's no way to express TCO in Java.

Note that these aren't seen as failures of JVM, because they aren't needed for Java.  As soon as Java needed some feature like these, it is added to JVM.

It's only recently that the Java authorities started taking seriously JVM as a platform for non-Java languages, so it has already gained some support for features that have no Java equivalent.  The best known is dynamic typing, which is already in JVM but not in Java.


答:
I develop in Object Pascal/Delphi and once I came up with an idea (I called it Wident) for simplifying navigation in the long files. Basically it's about having a quick two-direction search of the identifiers at caret (I used Ctrl-Alt-[arrows]). You press for example Ctrl-Alt-Down, the tool detects the keyword at the caret pos and goes to the next mentioning of the keyword. Since after the jump your caret is placed at the same word only at different position, the next pressing will jump to the next reference (Ctrl-Alt is held so you just repeat pressing Down key). Although at this point you can be far away from your starting point, you can return to it easily. The caret is still at the name, so Ctrl-Alt-Up pressed twice will do the magic.

And this is just an example. Actually it's like quickly creating new dimensions in navigation while keeping full control of where you are. This works because the names of variables, functions, types and their references is what connects pieces of software semantically.

Although I use the tool developed for Delphi IDE, in other editors similar functionality can be implemented just by assigning new keys to the corresponding functions. For example, in notepad++ they are "Find (Volatile) Next" and "Find (Volatile) Previous".


问:
What direction should I consider the offset when searching strings in reverse?
I'm making an indexOfReverse utility function in my C++ program, and I have caught a bit of a snag. Implementing the offset and maxOffset in my indexOf was very intuitive to me.. These start from the beginning of the string (+offset), and go forth to the end of the string (or maxOffset if given).

While implementing offsets for the indexOfReverse, though, I was wondering what the most logical way to do this is? Should the offset be from the beginning of the string, or end of the string? Is there an established norm for this I am missing somewhere? I tried explaining it to my duck, but he just looked at me funny. I'm leaning towards thinking of it from the beginning, because of its ease-of-use being more valuable to me than its counter-intuitiveness.. considering the offset from the end just makes things harder to think about in my head.

I have looked at how it's done in a string library for C++, PHP, and Python, and what seems common in the description of each is finding the last of occurrence of a string where the offset is considered from the beginning, rather than doing true reverse-string searching... But I desire true reverse-string searching rather than last occurrence ofs. Is there a most logical way to consider this, though, so I can move on?

答:
Take a look at how it's done in the C++ standard library: string::rfind.  Better yet, just use that function instead of writing your own.

They take offsets from the beginning of the string.  Doing so makes it easier to use the result in, say, substr:

```<code>string str         = "I haven't done C++ in a while.";
size_t last_in     = str.rfind("in");
string last_phrase = str.substr(last_in); // "in a while."
</code>```

There's actually two decisions to make for an rfind function:

Should the result index be based on the beginning of the haystack?

```<code>I haven't done C++ in a while.
0123456789
</code>```

or the end of it?

```<code>I haven't done C++ in a while.
                     9876543210
</code>```

Should the result index be the beginning of the found result?

```<code>I haven't done C++ in a while.
                   ^
</code>```

or the end of it?

```<code>I haven't done C++ in a while.
                     ^
</code>```

If we answer "end" to either of these questions, we have to answer one more question: does "end" mean the last character?

```<code>in
 ^
</code>```

or the character after it?

```<code>in
  ^
</code>```

The latter is more consistent with the regime of beginning-based indexes.

Body:
Take a look at how it's done in the C++ standard library: string::rfind.  Better yet, just use that function instead of writing your own.

They take offsets from the beginning of the string.  Doing so makes it easier to use the result in, say, substr:

string str         = "I haven't done C++ in a while.";
size_t last_in     = str.rfind("in");
string last_phrase = str.substr(last_in); // "in a while."

There's actually two decisions to make for an rfind function:

Should the result index be based on the beginning of the haystack?

I haven't done C++ in a while.
0123456789

or the end of it?

I haven't done C++ in a while.
                     9876543210

Should the result index be the beginning of the found result?

I haven't done C++ in a while.
                   ^

or the end of it?

I haven't done C++ in a while.
                     ^

If we answer "end" to either of these questions, we have to answer one more question: does "end" mean the last character?

in
 ^

or the character after it?

in
  ^

The latter is more consistent with the regime of beginning-based indexes.


答:
Depending on the circumstances you could use the Keychain.

There are some advantages of using the keychain, and things like UICKeyChainStore and STKeychain make it pretty simple to implement.

Features to be aware of are:

Your other apps can access the same information if you choose to make it so.

Information persists after the app is removed, so it can be used by other apps or if the user reinstalls.

Title: Saving Passwords To The Local Device

Body:
So In my app (iOS), you have to register in order to use the service (a food service).  But in order to change details about your account (username, password, and email), you have to reenter your password.  Except for if the user logged out, this is the only time you need your password to use the app.  So I was wondering, since the user basically never uses their password, and its likely they would forget it the one time they might need it, is it ok if I store their password to their local device (in NSUserDefaults)?

Since their password would only be on their local device, it doesn't seem like a security risk.  If the app was hacked, the only password they could get would be their own.

Further, I was planning on just storing it as a string (no encryption).  Would it make a difference if I hashed it or encrypted it before saving the password to their defaults?

Thanks in Advance.


问:
What are the disadvantages of starting an opensource project if one is not an experienced programmer?
I have lots of ideas for products to be built. The problem is that I have less than a year of professional work experience and I am afraid of getting judged negatively in the future based on what I produce now. I have no clue if my code is any good.

I am not familiar with any of the coding patterns. All I know is to build products that work. I want to have a public profile in github for my future projects and I will try hard to make sure that it is well commented, is optimized and clean.

These are the things that I fear getting exposed publicly:

My code may not be highly optimized.

Wrong usage of certain libraries or functions which coincidentally get the job done.

Not knowing or following any coding pattern.

Lots of bugs/ not considering corner, edge cases

Fundamental lack of understanding and application of certain concepts such as thread safety, concurrency issues in multi-threaded programming, etc.

Should I go ahead and get started or continue to stick to building stuff locally and privately till I get more experience. I don't want the mistakes made here to haunt my career prospects in the long run.

答:
We find people with high knowledge in the Open Source field. That's true, and also intimidating for new comers. But they are also very good in providing help for good projects, even if the main developer does not reflect the actual requirements for the software to reach a high quality.

You already know yours limitations. That's not a bad start. That's a good start.

Get into the party and find your place there.

Good luck!


答:
For most string users, measuring the offset from the beginning of the string regardless of the method called would make the most sense.

Recognize that when a user wants to get the last occurrence of something, it does not imply that the user have a logical use of the "reversed string". If it were so, the user could have simply done a reverse first, and proceed with whatever operation desired. Rather, the user is more likely interested in splitting the string into three or more parts:

```<code>Mr. Thomas A. Anderson
<<<|------|>>>>>>>>>>>
</code>```

Namely, everything before, the matched substring, and everything after.

Because of this, there is a need to pass the string offsets obtained from one method into another method, between find and rfind. Having two definitions just complicates the matter.

A more nuanced approach would be to define an enumerator of matches, a.k.a. Regex. This enumerator allows navigating any number of matches. For each occurrence, the positions of the first character and last character can be queried.

Title: What direction should I consider the offset when searching strings in reverse?

Body:
I'm making an indexOfReverse utility function in my C++ program, and I have caught a bit of a snag. Implementing the offset and maxOffset in my indexOf was very intuitive to me.. These start from the beginning of the string (+offset), and go forth to the end of the string (or maxOffset if given).

While implementing offsets for the indexOfReverse, though, I was wondering what the most logical way to do this is? Should the offset be from the beginning of the string, or end of the string? Is there an established norm for this I am missing somewhere? I tried explaining it to my duck, but he just looked at me funny. I'm leaning towards thinking of it from the beginning, because of its ease-of-use being more valuable to me than its counter-intuitiveness.. considering the offset from the end just makes things harder to think about in my head.

I have looked at how it's done in a string library for C++, PHP, and Python, and what seems common in the description of each is finding the last of occurrence of a string where the offset is considered from the beginning, rather than doing true reverse-string searching... But I desire true reverse-string searching rather than last occurrence ofs. Is there a most logical way to consider this, though, so I can move on?

Body:
For most string users, measuring the offset from the beginning of the string regardless of the method called would make the most sense.

Recognize that when a user wants to get the last occurrence of something, it does not imply that the user have a logical use of the "reversed string". If it were so, the user could have simply done a reverse first, and proceed with whatever operation desired. Rather, the user is more likely interested in splitting the string into three or more parts:

Mr. Thomas A. Anderson
<<<|------|>>>>>>>>>>>

Namely, everything before, the matched substring, and everything after.

Because of this, there is a need to pass the string offsets obtained from one method into another method, between find and rfind. Having two definitions just complicates the matter.

A more nuanced approach would be to define an enumerator of matches, a.k.a. Regex. This enumerator allows navigating any number of matches. For each occurrence, the positions of the first character and last character can be queried.


问:
What is dependency of ASP.NET MVC on .NET Framework and how to use it with .NET 2.0?
When you download and install asp.net MVC, does it just add code to the .net framework class library? Or does it also modify the installed Visual Studio editions?

Another question: If it is just adding code to the .net framework class library, why can it not be installed on top of .net 2.0?

答:
To be clear, the ASP.NET MVC framework is built upon the ASP.NET framework, which in turn is built upon the .NET framework. So when you download and install ASP.NET MVC, it can both add code to the .NET Framework class library (it adds System.Web.Mvc) and can also modify the installed Visual Studio edition if one is installed. You could just install the class libraries and build ASP.NET MVC applications from scratch if you really wanted to without the aid of Visual Studio. If you look at the current MVC 3 installer packages you'll see there are two separate .exe's: one for the .NET class libraries, and the other for the Visual Studio tools.

ASP.NET MVC versions 1 & 2 target .NET 3.5. ASP.NET MVC 3 targets .NET 4.0. MVC v4 will target .NET 4.5 - it is because they build upon those specific framework versions that you cannot expect ASP.NET MVC to install and work with .NET 2.0 'out-of-the-box'.


答:
After 30 years of professional software development, I still create bugs. I still find patterns I don't know. I still learn from my colleagues, and encounter stuff I don't know every day.

Most experienced developers will judge you on how you respond to issues and criticism, whether you learn from your mistakes and improve your product to meet the users' or community's needs, whether you admit what you don't know and seek to improve.

One of the best skills for a developer is willingness to ask the dumb questions and to look a bit foolish at times in order to find good answers as quickly as possible.

Everyone who is experienced and very proficient was once where you are now. You will learn much faster if you put your work out there and work with other people.

There is no reason to wait. Make your project open.

Better yet, contribute to other open projects and learn from them.

Title: What are the disadvantages of starting an opensource project if one is not an experienced programmer?

Body:
I have lots of ideas for products to be built. The problem is that I have less than a year of professional work experience and I am afraid of getting judged negatively in the future based on what I produce now. I have no clue if my code is any good.

I am not familiar with any of the coding patterns. All I know is to build products that work. I want to have a public profile in github for my future projects and I will try hard to make sure that it is well commented, is optimized and clean.

These are the things that I fear getting exposed publicly:

My code may not be highly optimized.

Wrong usage of certain libraries or functions which coincidentally get the job done.

Not knowing or following any coding pattern.

Lots of bugs/ not considering corner, edge cases

Fundamental lack of understanding and application of certain concepts such as thread safety, concurrency issues in multi-threaded programming, etc.

Should I go ahead and get started or continue to stick to building stuff locally and privately till I get more experience. I don't want the mistakes made here to haunt my career prospects in the long run.


答:
I think you worry too much.

The OS community is more concerned about how useful a particular app is more than how well it is written.  If it's written poorly, the community will step in and help rectify the mistakes.  What's more interesting is how well the application solves problems that people are struggling with.  If the application / project provides an elegant solution to a vexing problem, then the quality of code becomes a moot point.

Put it out there, see what happens.  You won't know how good / how bad your code is until others look at it and start playing around with it.  ALL code has bugs.  What's more interesting is how quickly the author works on resolving those bugs.

Consider it a learning exercise.  You're not going to find out what you don't know until you stick your neck out a little and pick up some criticism.  Hopefully, most of the criticism can become constructive.  Given that you're asking about it in the first place, then I'm pretty comfortable saying you'll have at least average or better quality code.


问:
FizzBuzz - really?
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.

答:
Some thoughts:

I wouldn't hold it against someone if their program had some bugs but they clearly had the right idea. Debugging is part of programming.

I think it is sad that so many people are applying for jobs they don't know they can't do. Seems to me like a problem with the economy.

It is really easy to ask people bad questions, where the only "correct" answer is the one the interviewer would give.

Title: FizzBuzz - really?

ContentLicense: CC BY-SA 2.5


答:
```<code>When you download and install asp.net MVC, does it just add code to the .net framework class library?
</code>```

ASP.NET MVC is a framework that works on top of the ASP.NET Framework which is build on top of The .NET Framework. However, it provides ability to configure freely and have Open Source code.

```<code>why can it not be installed on top of .net 2.0?
</code>```

The earlier version of ASP.NET MVC framework Can be deployed on top of .NET Framework 2.0. Here is an article demonstrating it - Deploying ASP.NET MVC on ASP.NET 2.0.

Steps to follow are:

Developed on Visual Studio 2008

Targeted .NET 2.0 in Project

Properties Deployed the Application to a .NET 2.0 SP1 machine Copied

System.Core.dll local to the web apps /bin folder

You may also find it useful to follow this article to deploy your asp.net mvc app to .NET 2.0 - Deploying an ASP.NET MVC website on IIS 6 and .NET 2.0

Title: What is dependency of ASP.NET MVC on .NET Framework and how to use it with .NET 2.0?

Body:
When you download and install asp.net MVC, does it just add code to the .net framework class library? Or does it also modify the installed Visual Studio editions?

Another question: If it is just adding code to the .net framework class library, why can it not be installed on top of .net 2.0?

Body:
When you download and install asp.net MVC, does it just add code to the .net framework class library?

ASP.NET MVC is a framework that works on top of the ASP.NET Framework which is build on top of The .NET Framework. However, it provides ability to configure freely and have Open Source code.

why can it not be installed on top of .net 2.0?

The earlier version of ASP.NET MVC framework Can be deployed on top of .NET Framework 2.0. Here is an article demonstrating it - Deploying ASP.NET MVC on ASP.NET 2.0.

Steps to follow are:

Developed on Visual Studio 2008

Targeted .NET 2.0 in Project

Properties Deployed the Application to a .NET 2.0 SP1 machine Copied

System.Core.dll local to the web apps /bin folder

You may also find it useful to follow this article to deploy your asp.net mvc app to .NET 2.0 - Deploying an ASP.NET MVC website on IIS 6 and .NET 2.0


问:
Is it better to use multiple html pages or just change content on the same page using JavaScript?
Is it better to use multiple html pages and link them together with href or just change content on the same page using JavaScript? I am thinking of how to layout a page and I don't have a lot of content. It would probably be about three of for pages if I just used all html. If I toggled and swapped bits of html around using JavaScript, I could probably fit it all on one page, and it would be a bit "cooler", in that it's more of an application, dynamic, etc. But I'm just wondering what the best way to go here? Is it horrible to have to much JavaScript "squashed" to one document? How do you know where to draw the line when thinking about this?

答:
A good maintainable approach or practice to follow would be using master page layout. While having separate content pages that are linked through your master page.

Here is a reference how to set it up, if you use pure HTML and CSS - Using a Master Page to create a 2 column CSS layout.

If you are using Visual Studio then you may also find it useful to look at the followings:

Creating a Site-Wide Layout Using Master Pages (C#)

Tutorial 3: Master Pages and Site Navigation


答:
The downsides you need to consider if you go with the "all on one page, swapped using Javascript" approach:

Will people be able to bookmark or link to specific pages of information?

Will people be able to use their browser's back/forward buttons to navigate between pages on your site?

Will people with Javascript disabled (small but non-zero population) be able to use your site at all?

Will Google and other search engines be able to spider and index your content?

None of these problems are insurmountable, but they're all problems you won't have if you follow the traditional decades-old model of putting separate pieces of content on separate pages.

Title: Is it better to use multiple html pages or just change content on the same page using JavaScript?

Body: Is it better to use multiple html pages and link them together with href or just change content on the same page using JavaScript? I am thinking of how to layout a page and I don't have a lot of content. It would probably be about three of for pages if I just used all html. If I toggled and swapped bits of html around using JavaScript, I could probably fit it all on one page, and it would be a bit "cooler", in that it's more of an application, dynamic, etc. But I'm just wondering what the best way to go here? Is it horrible to have to much JavaScript "squashed" to one document? How do you know where to draw the line when thinking about this?


问:
What's the most important, useful or enlightening thing you learnt in the last 12 months?
A lot of people in the coding community talk about continuous improvement, deliberate practice and so-on - but when they talk about their current practices it's almost like they 'sprang fully formed from the loins of Zeus' because you don't hear about how their opinions changed over time or what they learnt recently.

Every now and then though I go to a talk, or read a book, or talk to someone and they open up a bit more and I find that I learn a lot from these insights.

So, if you had to pick one thing from the last 12 months that you learnt what would it be?

答:
My top three thanks for the last programming year would go to the following (in descending order of importance and gratefulness):

the functional programming paradigm for opening my mind to other, often more elegant and terse ways of expressing ideas and algorithms in code. I feel that my overall programming skill has improved much in a very short time, thanks to functional programming ideas.

(My personal thanks go to Tomáš Petříček for his excellent book Real-world functional programming.)

both dependency injection and unit testing have taught me that object composition is arguably the best way for creating complex (object-oriented) systems (and that class inheritance isn't nearly as important as I used to think). Both have taught me and made me think about how to best compose systems and how to write components that are easy to use, yet still flexible enough for reuse.

(If I had to mention a good teaching resource, I'd say Roy Osherove's Art of Unit Testing.)

All of these taken together have resulted in me writing code that generally has fewer bugs than before, because I'm now writing code that's far easier to understand and get wrong than what I previously put out.


问:
2 Dimensional Arrays in C++
I started learning arrays in C++ and came over a little side note in the book talking about 2D arrays in breif.

I tested it out and i was amazed that it could give the programmer the ability to store data or information and lay it out infront of him in a spread sheet format.

In a normal array to access elements i would simply do this:

```<code>int matrix[2] = { 1, 15};
</code>```

But in 2D arrays :The only way it tells me to actually acces elements is by using a loop:

```<code>int fly[2][2];
int i = 0;
int n=0;
for(i=0; i<2; i++){
    for (n=0; n<2; n++){
        fly[i][n] =0;
    }
}
for(i=0; i<2; i++){
    for (n =0; n<2; n++){
        cout << fly[i][n]<< endl;
    }
}
</code>```

I have tried accessing elements the old way:

```<code>int fly[2][2] = { 0};
</code>```

but i noticed that this changes all the elements to 0

So..

Can anyone explain when i try accessing this 2D array like this all the elements change.

Is there another way to access 2D array elements without using a loop.

Thank you all.

答:
In a normal array to access elements i would simply do this:

```<code>int matrix[2] = { 1, 15};
</code>```

You're declaring an array with that code. You're also assigning '1' to the int at index 0 and '15' to the int at index 1.

I have tried accessing elements the old way:

```<code>int fly[2][2] = { 0};
</code>```

but i noticed that this changes all the elements to 0

That code doesn't assign '0' to the int at coordinates 2, 2... it creates a 2x2 array and tries to initialize it with the array that you've provided. Since the array is smaller than the size of the array that you're assigning to, the rest of the elements are simply initialized to 0. If you'd used '{15}' instead, you'd get a '15' in the first position, and '0' everywhere else. Try this instead:

```<code>int fly[2][2] = {{1, 2}, {3, 4}};
</code>```

or even just:

```<code>int fly[2][2] = {1, 2, 3, 4};
</code>```

In those cases, enough values are provided for every element of fly. If you this, though:

```<code>int fly[2][2] = {1, 2, 3};
</code>```

you'll find that fly[1][1] is 0 because you didn't provide enough data.

Can anyone explain when i try accessing this 2D array like this all the elements change.

You can't really say that they "changed". You're only just creating the array, so other than the initialization you don't know what values are in the array. At any point after you create the array, you can access the array using the two subscripts:

```<code>int fly[2][2] = {{1, 2}, {3, 4}};
printf("%d %d %d %d\n", fly[0][0], fly[0][1], fly[1][0], fly[1][1]);   // prints '1 2 3 4'
</code>```

Title: 2 Dimensional Arrays in C++

Body:
In a normal array to access elements i would simply do this:

int matrix[2] = { 1, 15};

You're declaring an array with that code. You're also assigning '1' to the int at index 0 and '15' to the int at index 1.

I have tried accessing elements the old way:

int fly[2][2] = { 0};

but i noticed that this changes all the elements to 0

That code doesn't assign '0' to the int at coordinates 2, 2... it creates a 2x2 array and tries to initialize it with the array that you've provided. Since the array is smaller than the size of the array that you're assigning to, the rest of the elements are simply initialized to 0. If you'd used '{15}' instead, you'd get a '15' in the first position, and '0' everywhere else. Try this instead:

int fly[2][2] = {{1, 2}, {3, 4}};

or even just:

int fly[2][2] = {1, 2, 3, 4};

In those cases, enough values are provided for every element of fly. If you this, though:

int fly[2][2] = {1, 2, 3};

you'll find that fly[1][1] is 0 because you didn't provide enough data.

Can anyone explain when i try accessing this 2D array like this all the elements change.

You can't really say that they "changed". You're only just creating the array, so other than the initialization you don't know what values are in the array. At any point after you create the array, you can access the array using the two subscripts:

int fly[2][2] = {{1, 2}, {3, 4}};
printf("%d %d %d %d\n", fly[0][0], fly[0][1], fly[1][0], fly[1][1]);   // prints '1 2 3 4'


答:
int fly[2][2]={0} ; allocates and initialises an new array - it is not an accessor to an existing array. Study up in C++ Initialises and partial intialisation.

Question 2 : As far as acessing the array elements - you could use

```<code> cout << fly[0][0]<< endl;
 cout << fly[0][1]<< endl;
 cout << fly[1][0]<< endl;
 cout << fly[1][1]<< endl;
</code>```

This does not use a loop,  the quesiton clear but probably not the question you want answered. -  what part of using a loop do you have a problem with?

Title: 2 Dimensional Arrays in C++

Body:
I started learning arrays in C++ and came over a little side note in the book talking about 2D arrays in breif.

I tested it out and i was amazed that it could give the programmer the ability to store data or information and lay it out infront of him in a spread sheet format.

In a normal array to access elements i would simply do this:

```<code>int matrix[2] = { 1, 15};
</code>```

But in 2D arrays :The only way it tells me to actually acces elements is by using a loop:

```<code>int fly[2][2];
int i = 0;
int n=0;
for(i=0; i<2; i++){
    for (n=0; n<2; n++){
        fly[i][n] =0;
    }
}
for(i=0; i<2; i++){
    for (n =0; n<2; n++){
        cout << fly[i][n]<< endl;
    }
}
</code>```

I have tried accessing elements the old way:

```<code>int fly[2][2] = { 0};
</code>```

but i noticed that this changes all the elements to 0

So..

Can anyone explain when i try accessing this 2D array like this all the elements change.

Is there another way to access 2D array elements without using a loop.

Thank you all.

Body:
int fly[2][2]={0} ; allocates and initialises an new array - it is not an accessor to an existing array. Study up in C++ Initialises and partial intialisation.

Question 2 : As far as acessing the array elements - you could use

 cout << fly[0][0]<< endl;
 cout << fly[0][1]<< endl;
 cout << fly[1][0]<< endl;
 cout << fly[1][1]<< endl;

This does not use a loop,  the quesiton clear but probably not the question you want answered. -  what part of using a loop do you have a problem with?


答:
This is an implementation question, so it should therefore be posted on StackOverflow.com , not Programmers.StackExchange.com.

int fly[2][2] = { 0}; is declaring an array (hence why it has int at the front) and assigning it (to {0}).  It's been years since I've done any C++, but I'm somewhat surprised it actually compiles (I'll take your word for it), seeing as how you are assigning a one-dimensional array to a two-dimensional array.

Accessing the array (and outputting it to the screen) would be done by cout << fly[2][2].

Title: 2 Dimensional Arrays in C++


问:
How to utilize Xcode project & target to manage products?
At first, hopefully following terms project and product won't be confused.

Traditionally, we used to have a code base, which usually was a main project. For our products, we created one project for each product, and these projects surly depended on main project (code base). When product was released, we created release branch for archive and maintenance.

Now I'm developing iOS applications, and I noticed there were specific terms for Xcode, project and target, which were similar to project and product. At first look, it's more easier to share configuration between products, to simplify product releases by taking advantage of target and target dependencies. Compared with traditional way, on the other hand, it's more difficult to manage source code, to branch, etc, if number of products goes really large.

In practice, is anyone efficiently using this Xcode built-in structure to manage code and products?

I'm quite new at iOS & Xcode and looking for good advice, thanks.

答:
The targets within a single project file are usually strongly related. For example, if you have a product that collects data and which has several related components, DataCollector, DataCollectorAdministrator, and DataCollectorLibrary, those components might all be targets in the same project. Furthermore, you might also have targets in that project for things like unit tests and even documentation.

You probably wouldn't have a target for a mostly unrelated product, BaseballStatsGuru, in your DataCollector project. You'd use a different project file for that, because it's really a whole different product, even though it uses DataCollectorLib as one of it's components. Even though it's a different project, you still want BaseballStatsGuru to be rebuilt whenever DataCollectorLib changes, so it always uses the latest code. That's fine -- you can add the DataCollector project to the BaseballStatsGuru project as a dependency.

There's even a special type of target called 'Aggregate':

Aggregate takes this a step further: an aggregate target doesn't have a product of it's own -- it only exists so that it can be dependent on other build targets. When you build an aggregate target, it causes all the targets that it depends on to be built (if they're not already up to date). So, you could create a single uber-project that includes all your other projects as sub projects and depends on them. The target of that project would simply be an aggregate target that depends on the targets of all its sub projects. Using a system like this gives you the ability to build a whole series of products with a single command.

Note that this isn't exactly novel -- you can do the same thing with makefiles if you want to.

In practice, is anyone efficiently using this Xcode built-in structure
  to manage code and products?

Sure. Both the ability to have different targets and to create dependencies between targets are very important. I'm not sure how to characterize the level of "efficiency," but you can bet that having Xcode manage the dependencies is a lot easier and more reliable than trying to do it by hand.


问:
Effective Ways to Introduce Agile into the Workplace?
In your experience (anecdotal or otherwise), what are some effective ways to introduce Agile into a non-Agile organization or company? </p>

<p>UPDATED: Can anyone speak to cases where you tried to introduce Agile but you were "shot down"? Also, do you now have a retrospective understanding why you were "shot down"? </p>

答:
Before thinking about introducing agile development first explore which is the best fit for your organisation / project. If for example you are looking at scrum consider whether you'd use it strictly or if a more loose form of scrum, or even another method altogether might better fit. My answer then is on scrum as your agile method.

Scrum is great for projects that require innovation, where little is known and where experimentation is needed. It isn't the best fit for doing things like maintaining existing products or handling recurrent maintenance work. Fortunately though, scrum is a loose framework and you can use it the best way you can.

For maintenance work Kanban might be better for you or you might try just a few scrum elements for managing the sprint and doing things like daily standups. I call this "scrum-but", "yes we do scrum in our company but...". That's fine, don't feel bad about it.

For introducing scrum proper in your organisation you need involvement of the product owner and stake holder. If you're a small company, that guy might be one person, the boss, and in a larger one a product manager and the department head / boss. I would suggest two routes for introducing scrum:

1) you can start using scrum  in a slightly looser form for managing existing work queues immediately. But look into Kanban too.

2) start using scrum in a more strict form on some new project that will require innovation, early feedback and where much is unknown. You can suggest to the boss / product owner that scrum would be ideal for this new project.

But remember! this isn't just about code, the product owner has a crucial part and must understand and fulfill his/her role. That means for example not writing all the specs up front, rather starting with the minimum, rapidly iterating, getting feedback, learning and feeding that back in and so on. Try to work with a product manager who would be as keen to introduce scrum as you are but from the product owner side, and ideally he/she should be tough enough to fend off management requests and protect the sprint.

It'll take united effort from development and product management to introduce scrum.

On such a new project, try and get the new team moved to a separate room and use post-it notes to visualise work in the various states such as backlog, in progress etc. Don't get bogged down in electronic tools at this stage, keep things as simple as possible. Don't feel silly doing planning poker with cards when you start too, once your team is up to speed you probably won't use them just say the numbers.

In my experience it is easier to introduce scrum in a pure form first then ease up on it for more maintenance type work queues. It is harder the other way round.

My final comment is to beware thinking scrum is some development panacea, it isn't. Scrum is a useful and simple framework for product innovation but explore other methods combining as your business requires it and don't feel bad about it.

OwnerDisplayName: Troy DeMonbreun


问:
What's the most appropriate duration of the video tutorial?
It is now more and more popular to have video tutorials of the software or technology instead of writing long articles. As for me, it makes perfect sense, especially for such areas like "Getting Started" or "What's New".

What do you think is the most appropriate duration for such a videos? If you record the video tutorial yourself, would you just touch main points to keep it brief, or rather split it into a number of parts to keep the same level of details? And why?

I know this question isn't implied to have one and only answer. I'd like to hear the reasoning behind various opinions.

I have personally come across a video tutorial 45 minutes long today, and I got tired at around minute 10... So, my own impression is it's better to keep it from 5 to 10 minutes to gain visitor's attention fully.

Thanks!

答:
I think it's more important to focus on communicating a single topic than getting hung up on length (within reason). A lot of things can be done in 5-15 minutes - but don't shy away from something longer if the audience is prepared for it and it's required.

By about an hour the audience is going to be fatigued - so if you're going to be doing something that's maybe 45min+ then you should probably have a small change of pace in the middle - maybe an aside or something - to wake people up.

More than an hour and people will be getting uncomfortable so try not to go over that.


问:
Lisp Macros: A practical approach
On my way to learn Lisp I have discovered the all powerful and feared so called Macros, then after spending a hard time trying to understand them and their usefulness I said to myself, I FINALLY GOT IT.

I couldn't be more wrong, I was thinking that the only purpose of Macros was to define new control structures and that was all I needed to know until I start reading more and more on the subject and a whole new world has comes to me !

One can use Macros for new Domain Specific Language, Code Transformation and to avoid Boilerplate Code.

Hence, if a few examples at which the aforementioned usages of macros and others as well, with a concise and simple-to-understand explanation could be given it would be really nice.

答:
The canonical reference for LISP macros is
On Lisp: Advanced Techniques for Common Lisp, by Paul Graham (book version).  It is out of print, and everyone who owns a copy knows what it is worth.  You can
download it, but Paul says nine figures got lost somewhere in the ozone.

Let Over Lambda, by Doug Hoyte, is also good.

Title: Lisp Macros: A practical approach


问:
"Read" a file without using a file pointer
I was asked this question in an interview. I'm somehow supposed to "read" a file into my C program as input without using a file pointer (including "f" functions, e.g. fgets, fscanf etc.). I'm also not allowed to redirect it using the terminal, i.e. no system or exec calls. The program will not get the file during runtime.

I'd like to know how it'd be possible to do this.

答:
File pointers are not the only way to access files on POSIX systems (which, obviously Linux is).

As a matter of fact, the FILE struct exists to make it easier to work with files in a cross-platform manner (fopen() will work on both Linux, Mac OS X, any BSD and Windows) and to provide some facilities like transparent buffering (buffered I/O is way faster).

This is all usually good, unless it's counter-productive (you need the file to be synced for common access from many processes) or dangerous (buffered output might not be flushed when necessary and it might leave the file in a bad state if interrupted improperly). Now, I'm not an expert and these issues might be nonexistent, but there certainly are reasons to use the lower-level API provided by POSIX: the file descriptor mechanism, open(), read(), write(), close() and mmap().

These functions are the building blocks of the FILE* abstraction, under Linux, at least (you can test that by running a sample file I/O program with strace) and you can use them if you want direct access to a file.

This is probably the solution to the problem the interviewer was expecting. The reason he might want you to know this is if you were interviewed for a job in embedded systems; knowledge of the underlying system is essential in such a position.

I once met a Linux programming guru, who said to me that he thinks a person may claim he knows C when he can implement the whole standard library by himself on at least one platform without any significant difficulties. In certain domains, low-level knowledge is a must.


问:
How do I locate Uncalled Functions?
I am looking at some C/C++ code that appears to have functions that are defined, but never used. This is a pretty tedious process to trace through the code and verify. I've done some surveys and there are a number of tools that can do this type of analysis.

Can anyone share any experiences or tips on which tools and techniques are best or alternative methods of verifying this code is in fact not used?

答:
There are some tools out there which can find 'dead code' in your programs. you can read about them on Stack Overflow threads here and here.
a small summary:

use the gcc compiler flags -Wunused and -Wunreachable-code, and then use a tool like lcov to find the unused methods.

Title: How do I locate Uncalled Functions?


答:
Clojure could perform automatic optimisation of tail recursion into loops: it is certainly possible to do this on the JVM as Scala proves.

It was actually a design decision not to do this - you have to explicitly use the recur special form if you want this feature. See the mail thread Re: Why no tail call optimization on the Clojure google group.

On the current JVM, the only thing that is impossible to do is tail call optimisation between different functions (mutual recursion). This isn't particularly complex to implement (other languages like Scheme have had this feature from the beginning) but it would require changes to the JVM spec. For example, you'd have to change the rules about preserving the complete function call stack.

A future iteration of the JVM is likely to get this capability, though probably as an option so that backwards compatible behaviour for old code is maintained. Say, Features Preview at Geeknizer lists this for Java 9:

Adding tail calls and continuations...

Of course, future roadmaps are always subject to change.

As it turns out, it's not that big a deal anyway. In over 2 years of coding Clojure, I have never run into a situation where the lack of TCO was an issue. The main reasons for this are:

You can already get fast tail recursion for 99% of common cases with recur or a loop. The mutual tail recursion case is pretty rare in normal code

Even when you need mutual recursion, often the recursion depth is shallow enough that you can just do it on the stack anyway without TCO. TCO is just an "optimisation" after all....

In the very rare cases where you do need some form of non-stack-consuming mutual recursion there are plenty of other alternative that can achieve the same goal: lazy sequences, trampolines etc.

Title: What limitations does the JVM impose on tail-call optimization

Body:
Clojure does not perform tail call optimization on its own: when you have a tail recursive function and you want to have it optimized, you have to use the special form recur. Similarly, if you have two mutually recursive functions, you can optimize them only by using trampoline.

The Scala compiler is able to perform TCO for a recursive function, but not for two mutually recursive functions.

Whenever I have read about these limitations, they were always ascribed to some limitation intrinsic to the JVM model. I know pretty much nothing about compilers, but this puzzles me a bit. Let me take the example from Programming Scala. Here the function

```<code>def approximate(guess: Double): Double =
  if (isGoodEnough(guess)) guess
  else approximate(improve(guess))
</code>```

is translated into

```<code>0: aload_0
1: astore_3
2: aload_0
3: dload_1
4: invokevirtual #24; //Method isGoodEnough:(D)Z
7: ifeq
10: dload_1
11: dreturn
12: aload_0
13: dload_1
14: invokevirtual #27; //Method improve:(D)D
17: dstore_1
18: goto 2
</code>```

So, at the bytecode level, one just needs goto. In this case, in fact, the hard work is done by the compiler.

What facility of the underlying virtual machine would allow the compiler to handle TCO more easily?

As a side note, I would not expect actual machines to be much smarter than the JVM. Still, many languages that compile to native code, such as Haskell, do not seem to have issues with optimizing tail calls (well, Haskell can have sometimes due to laziness, but that is another issue).


答:
Some years ago, I was consultant in a very large company (nearly 20,000 employees) that was running many large enterprise software projects. I was on one of them. A quite critical one.

We faced many problems and the pressure was strongly pussed on us, the development team. Problems were just common to software industry, but the management had a more infrastructure oriented experience and very few software oriented experience. So everything was focused on us. I thought it would be a great idea to tell the management about Scrum.

I was faced with strong reluctance, so I dropped the idea for a while. But the problems continued to add up so with the sponsor of the team leader, we finally decided to make Scrum anyway, by ourselve.

Anyone, including me, had any experience with Scrum. So we discovered the framework by doing...

Today, Scrum is generalized to the whole enterprise through a program administered by a certified trainer. I do not know if our initiative was the trigger. That said, I know that it was a real revolution in quite rigid company.

I think to introduce something into an enterprise like that, you must respect the following principles:

It has to change is necessary. If there is no compelling reason that the change must be done, there is no reason why management teams in place to take risks.

We must focus on the problems of management and not to mention the problems of the developers, unless they are part of management concerns. In other words, you must come with a solution for them, not for you. Put yourself in the management's shoes. What are their concerns?

You should not propose to change the whole organization at once. You must propose a pilot project which you would take the responsibility. I advise you to give realistic goals, such as the significant increase in the visibility on what is going one in the project. It is, IMHO, the main contribution of Scrum to software management. It allows the human common sense to operate and thus move forward.

Finally, it is imperative to ensure that experienced people are in control of this introduction. Do not just read a book or two. You have to go to training and I would say it is rather necessary to use an experienced coach. Obviously, it can be done without, but it will be in pain :)

If you follow the principles and come with facts, it will works. About facts, you'll find many in the book Software in 30 Days: How Agile Managers Beat the Odds, Delight Their Customers, And Leave Competitors In the Dust. It's the latest book of Scrum's creators, Ken Schwaber and Jeff Sutherland.

In a blog post of Ken about the book you can read:

Jeff Sutherland and I have done it. We wrote a book together, our first joint writing since the initial publication of Scrum in 1995. What prompted us? The question that we frequently are asked:

How do we sell Scrum to our management?

I’ve always been puzzled by this question. Why would you have to sell more predictability, productivity, quality, value, risk control, satisfied customers, engaged employees, and less waste to anyone in management? However, I talked with Jeff and we figured that where there was smoke, there must be fire.

We spent the last half of 2011 writing the book. Any manager, from top to bottom, can easily pick up and read this book.

[...]

Title: Effective Ways to Introduce Agile into the Workplace?

Body:
In your experience (anecdotal or otherwise), what are some effective ways to introduce Agile into a non-Agile organization or company? </p>

<p>UPDATED: Can anyone speak to cases where you tried to introduce Agile but you were "shot down"? Also, do you now have a retrospective understanding why you were "shot down"? </p>


答: Trace? Why? Just comment them out and run through the compiler. It will quickly tell you if you commented out some function which was referenced somewhere else.</p>

Title: How do I locate Uncalled Functions?

Body:
I am looking at some C/C++ code that appears to have functions that are defined, but never used. This is a pretty tedious process to trace through the code and verify. I've done some surveys and there are a number of tools that can do this type of analysis.

Can anyone share any experiences or tips on which tools and techniques are best or alternative methods of verifying this code is in fact not used?


问:
I am a git user confused by mercurial's branching. How am I supposed to track small changes?
I've always used git before, but I want to contribute to python so now I have to learn mercurial and I find it very frustrating.

So, I've made a couple of small patches and I wanted to track them as commits in my local mercurial repository. Apparently there are 4 ways to handle branching in mercurial.
1 and 4 looked completely ridiculous to me, named branches seem to be heavyweight and I feel that I'm not supposed to use them for quick 1-commit fixes, so I used bookmarks.

Now, my patch gets rejected and I want to remove one of my bookmark-branches from my repository.
OK, in git I would just force-delete my branch and forget about it, so I delete my bookmark and now I have following problems:

TortoiseHG and hg log still show that commit and default branch has 2 heads. And if I understand correctly, you can't delete commits in hg without additional plugins.

Mercurial has not only hashes, but also revision numbers. As I've added a couple of my own commits, all commits pulled after that have different revision numbers from the main central
repo.

I do hg update after pulling to move my master bookmark to the latest commit automatically, but I couldn't find a way to do that in TortoiseHG.

What am I doing wrong? Is this normal and expected and should I just ignore these issues?
Or how am i supposed to work with my branches?

答:
Personally, for your scenario, I wouldn't bother even creating a branch, unless I was working on multiple changes, each of which would need to be accepted by the core developers.

Just clone their repository and work in it, then make a pull request.

If I were to use a branch then I'd rather use named branches. They were designed for this exact purpose, where bookmarks weren't. I don't see why you'd consider it heavy-weight.

Mercurial have a whole page on their wiki describing different ways of "Pruning Dead Branches". The "Using clone" option should satisfy your requirements.

To answer your more specific issues ...

TortoiseHG and hg log still show that commit and default branch has 2 heads. And if I understand correctly, you can't delete commits in hg without additional plugins.

This is a mistake I made with Mercurial when I was new to it. Do not be afraid of those additional plugins. Some of them are very powerful tools and often they later get pulled into the core product. That just how Mercurial works. If you need one to perform a specific task, get it and use it.

Revising history is considered a bad thing in the Mercurial world, so the vanilla product doesn't always have everything that a Git user thinks it should have, but there are plenty of plugins for those who want to use the application but have different priorities.

Mercurial has not only hashes, but also revision numbers. As I've added a couple of my own commits, all commits pulled after that have different revision numbers from the main central repo.

Do not worry about revision numbers. They are a matter of convenience, no more. The hash codes are the important identifiers that will pass from repo to repo. Revision numbers are inconsistent across repositiories. Check out Hg Init for a good explanation.

Revision numbers are just a handy and more memorable shortcut when working with a single repo.

I do hg update after pulling to move my master bookmark to the latest commit automatically, but I couldn't find a way to do that in TortoiseHG.

When using TortoiseHG, use the Workbench rather than the other tools. Everything (almost) is in there. Update is in the revision context menus. It's not always intuitive, but there is a good guide at the link above and as you get used to it, you end up clicking away with confident abandon.


答: Unless you're looking for trouble (ie; you know they should be called) why bother.  If they are genuinely uncalled, they will probably be removed by the linker, and in any case the wasted space is not significant.  On the other hand, if you remove them and later find they were needed (perhaps in some compiler configuration you were not aware of) you will have more work to do to recover them.  This is especially difficult if the removal and rediscovery are separated by a lot of time.</p>

Title: How do I locate Uncalled Functions?


答:
Even when Mercurial and Git are similar, they have different designs, maybe being the most important design difference is that in Mercurial modifying the history is not as flexible as in git (because it is kind of discouraged).

Short answer: it doesn't matter if you have a small amount of changes, you can still use a branch. If you are thinking about deleting that branch then use a bookmark so you can delete it later and strip the changes afterwards.

First, trying to shed a little light on some of the things you mention:

1 and 4 are considered branching is because every time you commit you are effectively creating an unnamed branch (if there is another commit by the same time at your source/blessed repo), which is technically a branch. In method 4 you are creating a new "head" while in method 1 you are not. Heads are supposed to be merged. I agree that method 1 is kind of silly, but some seem to like it... for small projects, I'd guess.

Regarding method 2, it is not that branches are heavy, it is that they are permanent. You cannot remove a branch unless you use something like the strip extension. Again, Mercurial's design philosophy doesn't go towards modifying the history (but it has gotten better at that).

Regarding revision numbers, they are just a local and more humanly readable reference for you to use all commands that have to do with revisions. If you like using hashes, you can still do. Revision numbers are just a shortcut and are disregarded by Mercurial for any internal operations between different repositories.

Now, to answer your other questions:

You can check what heads you have with hg heads, if you see 2+ heads in a single named branch, it is preferable that they are merged. That is probably where your bookmark is.

To get rid of a revision you've just made, you could do hg rollback, but I'm guessing this isn't the case.

To delete a bookmark just do hg bookmark --delete yourbookmark

You will be happy that it is easy to cut branches in the history. Look into the Rebase extension and the Strip operation.

Mercurial already comes bundled with several extensions, but they are not activated by default. Just go into any folder and right click anywhere to get the TortoiseHG context menu, go into Global Settings and then Extensions: activate the MQ extension and the Rebase extension. This does not damage compatibility between repositories whatsoever.

Now that you are here, you could either:

Strip where your bookmark began (this probably fixes your problem)

For easier visualization, maybe you could rebase your changes at the front and then strip them afterwards. I just mentioned rebase because it might be something useful for you some other time.

Also, in git you can have "private local branches" because you have to push them explicitly and you can delete them afterwards. In Mercurial you push all what you have, however, if you want to avoid this you can use the Phases feature and mark a set of revisions as secret. Secret revisions won't get pushed.

Finally, you are not doing anything wrong, just keep in mind that they are just different tools built with slightly different mindsets, which pretty much boil down to: modifying history (git) or not modifying history (hg). In Mercurial it is harder to shoot yourself in the foot modifying the history (specially with Phases) and that is why some like it better than git.

Title: I am a git user confused by mercurial's branching. How am I supposed to track small changes?

Body:
I've always used git before, but I want to contribute to python so now I have to learn mercurial and I find it very frustrating.

So, I've made a couple of small patches and I wanted to track them as commits in my local mercurial repository. Apparently there are 4 ways to handle branching in mercurial.
1 and 4 looked completely ridiculous to me, named branches seem to be heavyweight and I feel that I'm not supposed to use them for quick 1-commit fixes, so I used bookmarks.

Now, my patch gets rejected and I want to remove one of my bookmark-branches from my repository.
OK, in git I would just force-delete my branch and forget about it, so I delete my bookmark and now I have following problems:

TortoiseHG and hg log still show that commit and default branch has 2 heads. And if I understand correctly, you can't delete commits in hg without additional plugins.

Mercurial has not only hashes, but also revision numbers. As I've added a couple of my own commits, all commits pulled after that have different revision numbers from the main central
repo.

I do hg update after pulling to move my master bookmark to the latest commit automatically, but I couldn't find a way to do that in TortoiseHG.

What am I doing wrong? Is this normal and expected and should I just ignore these issues?
Or how am i supposed to work with my branches?


答:
If you are actively looking for unused code, use something Jake223 suggested.

But, if you just stumble upon some code that seems to be unused, you can just do a search for the method's name in your codebase. If it's a private method, your job is easy, search only the current class. If it's a public method, search everything. If it's a whole class, search for it's name in all your code.

No hit? Perfect. Delete the code and run tests. You do have tests, don't you? Than commit your changes to your document version system. You use one, don't you? That way if you discover, ever, that you need it back, you just revert a change.

Deleting code should be something you do every day. Maybe you refactor some code and delete the old one. Or find old, unused code and delete it. And even if you don't have backups, how hard it is to rewrite a function or two? And the second time you will certainly write them better than before.

Title: How do I locate Uncalled Functions?


答: My IDE of choice is Eclipse, and while it's clunky and a bit of a pain to set up at first, it's well worth the effort considering all of the tools I get. One such tool (and I've no idea what it's official name is) informs you about unused code, such as classes, functions, variables, etc. The IDE simply displays a yellow line underneath the declaration. I'm not 100% sure if this works with multi-file projects, but you could always give it a shot!</p>

Title: How do I locate Uncalled Functions?


答:
Apparently there are 4 ways to handle branching in mercurial. 1 and 4 looked completely ridiculous to me, named branches seem to be heavyweight

In Mercurial, you don't create branches. Every commit is effectively a branch, any commit can have multiple parents and multiple children. So those are the four different ways to organize the same entities.

You can give them different names, you don't have to, but it's a good idea. There is nothing heavyweight about named branches - it's just some extra metadata. I personally prefer named branches to anything else in any situation.

TortoiseHG and hg log still show that commit and default branch has 2 heads.

Which is exactly the reason to use named branches instead of dumping everything into default.

And if I understand correctly, you can't delete commits in hg without additional plugins.

You can't actually delete anything in Mercurial at all and you shouldn't. You can use hg strip but it isn't logged - you basicaly just cut off a part of your local repo. You can't push that, and if you pull from a repo that has the branch you stripped locally, it comes back.

Mercurial has not only hashes, but also revision numbers. As I've added a couple of my own commits, all commits pulled after that have different revision numbers from the main central repo.

Numbers don't mean anything. You can disregard them if they confuse you.

I do hg update after pulling to move my master bookmark to the latest commit automatically, but I couldn't find a way to do that in TortoiseHG.

I haven't used TortoiseHG but hg pull -u will do both pull and update.

I've always used git before, but I want to contribute to python so now I have to learn mercurial and I find it very frustrating.

That's ok, many Mercurial users feel the same about Git (including me).


问:
Getting non-programmers to understand the development process
When starting a project for a company that's not primarily a programming company, one of the expectations is that there's a finished product at the end free of all bugs and does everything needed right away. However, that's rarely the case.

What are some ways to manage expectations and explain to non-programmers how software development differs from other types of product development?

答:
The traditional way of stating it is the Project Management Triangle: the three competing criteria of scope, cost, and schedule; typically expressed as "cheap, fast, good -- pick two".

At the end of a design, development and deployment process, the expectation that a product is is relatively free of design flaws and operates with a specified functionality is perfectly reasonable. The same expectation is completely unreasonable with respect to a project, process, or profession.

What professional based on sciences, hard or soft, does not go through a process of exploration, forming inaccurate and imprecise conceptualizations, following less-than-optimal (or just plain wrong) tactics, discovering what works through trial and error, and repeating the process over and over again till either resources run out or a sufficient level of performance is attained?

No process is ever free of flaws, although it can asymptotically approach higher quality levels.

That is true of the medical profession where tactics often involve guesswork and protocols, and much of the activity is basically debugging a mostly wetware machine. It is true of civil engineering and architecture where applications of novel engineered materials have to be field validated and can fail abruptly after years of service despite strict adherence to standards.  It is true of the automotive field where age and changes in operating conditions commonly affect performance to the point of failure, through no fault of the engineering or repair services applied. Software development is not fundamentally different from these professions in such respects, it just has a greater part of its focus involved in contriving novel, purposeful machines.


问:
Experience of Python's “PEP-302 New Import Hooks”
I'm one of the developers of Ruby (CRuby). We are working on Ruby 2.0 release (planned to release 2012/Feb).

Python has "PEP302: New Import Hooks" (2003):

This PEP proposes to add a new set of import hooks that offer better customization of the Python import mechanism. Contrary to the current import hook, a new-style hook can be injected into the existing scheme, allowing for a finer grained control of how modules are found and how they are loaded.

We are considering introducing a feature similar to PEP302 into Ruby 2.0 (CRuby 2.0). I want to make a proposal which can persuade Matz. Currently, CRuby can load scripts from only file systems in a standard way.

If you have any experience or consideration about PEP 302, please share.

Example:

It's a great spec. No need to change it.

It is almost good, but it has this problem...

If I could go back to 2003, then I would change the spec to...

答:
PEP 302 allows you to hook into the Python import mechanism, meaning that you can import code from other sources like databases, zip files and so on.

In the Python implementation of imports there is a long history of complexity that will only soon be simplified by the introduction of a Python implementation of import.

I should advise thinking long and hard about the corner cases. Then you are likely to get a useful implementation.


答:
I'm the maintainer of Python's runpy module, and one of the maintainers of the current import system. While our import system is impressively flexible, I'd advise against adopting it wholesale without making a few tweaks - due to backwards compatibility concerns, there are bunch of things that are more awkward than they would otherwise need to be.

One thing that hurt with PEP 302 in Python is how long it took us to convert the core import system over to using it. For the better part of a decade, anyone doing anything complex with import hooks has been stuck implementing two pieces: one handling PEP 302 compliant loaders (such as zip imports), and a second handling the standard filesystem based import mechanism. It's only in the forthcoming 3.3 that handling PEP 302 loaders will also take care of handling modules imported through the standard filesystem import mechanism. Try not to repeat that mistake if you can possibly avoid it.

PEP 420 (implemented for Python 3.3) makes some additions to the protocol to allow importers to contribute portions to namespace packages. It also fixes a naming problem in the Finder API definition (effectively replacing the misnamed "find_module" with the more accurate "find_loader"). This should hopefully all be documented more clearly in the language spec by the time 3.3rc1 rolls around in a couple of weeks time.

Another notable problem is that the approach documented specifically in PEP 302 has way too much process global state. Don't follow us down that path - try to encapsulate the state in a more coherent object model so it's slightly easier to selectively import other modules (C extension modules are the bane of making any such encapsulation completely effective, but even some level of encapsulation can be helpful).

PEP 406 (http://www.python.org/dev/peps/pep-0406/) discusses a possible backwards compatible evolution of Python's approach with improved state encapsulation. If you have an encapsulated state model from the beginning though, then you can define your APIs accordingly and avoid having importers and loaders access global state at all (instead being passed a reference to the active engine).

Another missing piece in PEP 302 is the ability to ask an importer for an iterator over the modules provided by that importer (this is necessary for things like freeze utilities and automatic documentation utilities that extract docstrings). Since it's incredibly useful, you'd probably be better off standardising it from the get go: http://docs.python.org/dev/library/pkgutil#pkgutil.iter_modules (we'll probably finally elevate this to a formally specified API in Python 3.4)

And my last comment is that you should take a close look at the division of responsibility between the import system and the loader objects. In particular, consider splitting the "load_module" API into separate "init_module" and "exec_module" steps. That should allow you to minimise the degree to which loaders need to interact directly with the import state.

PEP 302 and importlib are a great starting point for a more flexible import system, but there are definitely mistakes we made that are worth avoiding.

Title: Experience of Python's “PEP-302 New Import Hooks”

Body:
I'm one of the developers of Ruby (CRuby). We are working on Ruby 2.0 release (planned to release 2012/Feb).

Python has "PEP302: New Import Hooks" (2003):

This PEP proposes to add a new set of import hooks that offer better customization of the Python import mechanism. Contrary to the current import hook, a new-style hook can be injected into the existing scheme, allowing for a finer grained control of how modules are found and how they are loaded.

We are considering introducing a feature similar to PEP302 into Ruby 2.0 (CRuby 2.0). I want to make a proposal which can persuade Matz. Currently, CRuby can load scripts from only file systems in a standard way.

If you have any experience or consideration about PEP 302, please share.

Example:

It's a great spec. No need to change it.

It is almost good, but it has this problem...

If I could go back to 2003, then I would change the spec to...


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答: A good algorithm is like a sharp knife - it does exactly what it is supposed to do with a minimum amount of applied effort. Using the wrong algorithm to solve a problem is trying to cut a steak with a screwdriver: you may eventually get a digestible result, but you will expend considerable more effort than necessary, and the result is unlikely to be aesthetically pleasing.

LastEditorDisplayName: Roger Pate


问:
JavaFX - the right way to use Properties with domain objects
JavaFX has provided a bunch of new Property objects, such as javafx.beans.property.DoubleProperty which allow you to define fields which can be automatically observed and synchronised.

In many JFX examples, the MVC model class has a number of these Property fields, which can then bind automatically to the view.

However, this seems to be encouraging us to put JFX properties into our Domain objects (if you assume that the Model class is going to be a domain object), which strikes me as a poor separation of concerns (i.e. putting GUI code in the Domain).

Has anyone seen this problem being solved in 'real life' and, if so, how was it done?

答:
I have been playing around with JavaFX 2.0, which I assume your question is about. Not real production code, just a personal project, but I ran into the same problem that you mention above. The entire model tends to become dependent from the 2D framework, and I don't like it.

What I did that I split every single class in the model in two, the real model class, which has the capabilities to load its contents from database, knows how it alters its state etc etc... and the representation class that decides the appearance on screen. The latter would contain all the Property classes.

You'll find the same design in any MVC framework, like Swing. it's just that here there's no escape from doing it.


问:
How does it matter if a character is 8 bit or 16 bit or 32 bit
Well, I am reading Programing Windows with MFC, and I came across Unicode and  ASCII code characters. I understood the point of using Unicode over ASCII, but what I do not get is how and why is it important to use 8bit/16bit/32bit character? What good does it do to the system? How does the processing of the operating system differ for different bits of character.

My question here is, what does it mean to a character when it is a x-bit character?

答: It relates to the amount of possible letters/numbers/symbols a character set can have.  An 8-Bit character can only have 256 possible characters.  Whereas a 16-bit can have 65,536.  A 32-bit character can have 4,294,967,296 possible characters.  A character set that large should be able to store every possible character in the world.  Whereas a 8-bit character set can only store enough characters for the English language.  8-bit character sets were the preferred standard in the early days of computing where memory was measured in bits and in some cases, KB.  But with computers with multi-core processors and gigs of RAM it is not such a concern anymore (except in some rare cases)</p>


答:
Unicode is logically a 21-bit code. As modern computers don’t conveniently work with such units, there are various solutions: use 32 bits (4 bytes), wasting a lot of bits, especially if your data is dominantly in English; use a special scheme that uses one or two 16-bit units per character; and use a variable number of 8-bit bytes per character. These are known as UTF-32, UTF-16, and UTF-8 transfer encodings.

Windows uses internally UTF-16, whereas UTF-8 dominates e.g. on the Web, so you often need to convert between them. This is nontrivial but usually made with suitable library routines, maybe implicitly, depending on programming environment. UTF-32 is rarely used.

Technically, UTF-16 is very simple for all characters that fit into the 16-bit subspace of Unicode, Basic Multilingual Plane (BMP)—quite possibly all characters you ever heard of. UTF-8 is more complex but has been design with Western emphasis: all Ascii characters are represented as single bytes in UTF-8, so any file that contains dominantly Ascii is of almost the same size in UTF-8 as in Ascii. This is opposite to UTF-16, which always uses two bytes per Ascii character.

Title: How does it matter if a character is 8 bit or 16 bit or 32 bit

Body:
Well, I am reading Programing Windows with MFC, and I came across Unicode and  ASCII code characters. I understood the point of using Unicode over ASCII, but what I do not get is how and why is it important to use 8bit/16bit/32bit character? What good does it do to the system? How does the processing of the operating system differ for different bits of character.

My question here is, what does it mean to a character when it is a x-bit character?


问:
Auto update for application hosted on multiple servers on cloud
I'm working on an application which will run on multiple Amazon EC2 instances. I wish to incorporate auto update feature for my application. The updater should update all the Ec2 instances. Also, there is a central server which governs the creation/termination of EC2 instances as per load. The central server creates a EC2 new instance from a pre-configured custom AMI (custom image which has our application pre-installed).

Also, once there is an update, the pre-configured AMI needs to be updated too else it would create new instances which are not updated.

Should the central server notify all the ec2 instances for an update and then the instances update themselves?Or should the application on Ec2 instance have a check for periodically updating themselves?
Also how should the Amazon custom AMI be updated? Should a new instance be created from it, updated and then a new AMI be re-created and then new images be created from this AMI?
What is the best way to incorporate an auto update feature for this architecture?

The central server is written in Java and the application running on the cloud is written in C++. Is there a good framework available that can be used for this architecture?

Please let me know on what I could be missing in the design and how it would help me to have a nice, extensible and fail safe auto update architecture.

Thanks

答: I believe that this is the case for configuration management tools such as puppet and Chef (there are more). With some of them you can also script the creation of the AMIs, if this is needed. After a fast read on your requests, you could start from one of the generic AMIs that suits your needs and incrementally script the rest of the infrastructure from there.</p>


问:
What limitations does the JVM impose on tail-call optimization
Clojure does not perform tail call optimization on its own: when you have a tail recursive function and you want to have it optimized, you have to use the special form recur. Similarly, if you have two mutually recursive functions, you can optimize them only by using trampoline.

The Scala compiler is able to perform TCO for a recursive function, but not for two mutually recursive functions.

Whenever I have read about these limitations, they were always ascribed to some limitation intrinsic to the JVM model. I know pretty much nothing about compilers, but this puzzles me a bit. Let me take the example from Programming Scala. Here the function

```<code>def approximate(guess: Double): Double =
  if (isGoodEnough(guess)) guess
  else approximate(improve(guess))
</code>```

is translated into

```<code>0: aload_0
1: astore_3
2: aload_0
3: dload_1
4: invokevirtual #24; //Method isGoodEnough:(D)Z
7: ifeq
10: dload_1
11: dreturn
12: aload_0
13: dload_1
14: invokevirtual #27; //Method improve:(D)D
17: dstore_1
18: goto 2
</code>```

So, at the bytecode level, one just needs goto. In this case, in fact, the hard work is done by the compiler.

What facility of the underlying virtual machine would allow the compiler to handle TCO more easily?

As a side note, I would not expect actual machines to be much smarter than the JVM. Still, many languages that compile to native code, such as Haskell, do not seem to have issues with optimizing tail calls (well, Haskell can have sometimes due to laziness, but that is another issue).

答:
So, at the bytecode level, one just needs goto. In this case, in fact,
  the hard work is done by the compiler.

Have you noticed that the method address starts with 0? That all methods ofsets start with 0? JVM doesn't allow one to jump outside a method.

I have no idea what would happen with a branch with offset outside the method was loaded by java -- maybe it would be caught by the bytecode verifier, maybe it would generate an exception, and maybe it would actually jump outside the method.

The problem, of course, is that you can't really guarantee where other methods of the same class will be, much less methods of other classes. I doubt JVM makes any guarantees about where it will load the methods, though I'd be happy to be corrected.


问:
Designing a 3-phase commit web service
We already have a fully operational web service which caters requests from multiple paltform devices.
Each device sends only one request at a time and immediately after a response for the request the device sends an applicative ACK, this ack message is like a regular request message, and it's all via http.

During a performance/load test we discovered that the following situation happens alot: regular requests gets processed ok but when the ack message is sent, it is thrown because the server can't handle too many requests.

We accept the case that the server throws requests because of overload, but we do not accept throwing ack messages.

So essentially we want the server to process 2 requests at a time for each device, is there anyway to do it in the current situation?

if not, what kind of changes do we need to do?

答:
I'm thinking you need something like Apache's KeepAlive (my site).  httpd will keep the connection open to the browser until a timeout is reached.  So that connection is effectively reserved for that browser session for a few seconds.

If your request + ACK are using two separate connections your server may hit its limit and reject or delay some requests.  Keeping the connection open a short time is also a performance benefit since there are less connections needed to open.

Title: Designing a 3-phase commit web service


答:
Joel Spolsky, co-founder of this site, actually has a wonderful and brief article on character sets titled The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).

I found it to be a good read, and it answers many questions about different character sets that you may have, as well as briefly going over the historical reasons for the whole character set mess anyway.

I'm not sure why you're being voted down; it's pretty useful stuff to know!


问:
Does mobile based (Android) development, benefit from Object Oriented Programming?
My development on Android is based on scientific programs and while I'm building these most of the code is in one or two long classes. When I come to deploy these programs I try to decouple everything and use classes and objects like I would on a Java desktop application.

However reading guide Designing for Performance | Android Developers about  Internal Getters/Setters it seems OO is not a good approach.

My question is what is best approach when designed Android applications, should I still use lots of classes with getters/setters and lots of object passing around. This seems counter intuitive thinking about the architecture of Android, but it also does not seem right to have lots of code in long classes.

I have looked at source codes from other projects and these seem to follow the OO approach.

My applications involve heavy image processing and time and performance is important.

I am more of a science researcher than a programmer so thanks in advance for any help.

答:
Write dumb code

"Often, the way to write fast code in Java applications is to write dumb code -- code that is straightforward, clean, and follows the most obvious object-oriented principles." -- Brian Goetz

Don't get me wrong - there is a chance that particular object design may have substantial performance impact in some particular case on specific execution path in some application on some device - why not, everything is possible given the variety of Android devices. Know what? there is even a chance of it having an opposite impact on some other device, why not.

If (if) that happens, if (if) you'll somehow get a clear, solid, tested and proven justification of specific performance impact - then (then), go ahead, implement whatever tricks necessary to reach required performance, no matter how perverse they may be (BTDTGTTS). Until then, though, drop any baseless assumptions that just may come to your mind.

Until then... Just. Drop. It.

Developers love to optimize code and with good reason. It is so satisfying and fun. But knowing when to optimize is far more important. Unfortunately, developers generally have horrible intuition about where the performance problems in an application will actually be... Most performance tuning reminds me of the old joke about the guy who's looking for his keys in the kitchen even though he lost them in the street, because the light's better in the kitchen... (Brian Goetz)


答:
Write in C++ and do it just like you would for any other platform.

Development for Android can be done in C++ (look for Native Development Kit (NDK)) and if you need raw performance, I would definitely suggest taking a look at it, but depends on which languages and libraries you know well.

The Dalvik virtual machine is far less optimized than the Oracle JVM or IBM HotSpot and even these well tuned JVMs generally need a lot more memory than corresponding program in C++. In fact, Java (or any other language targeting JVM) typically needs much more memory than equivalent C# or even Python or Ruby application. If you are going to do image processing, being memory efficient is an advantage.

You can also start coding in Java and rewrite the most critical bits in C++ when you find, by testing a prototype, which ones they are (see gnat's answer, it is good).

Title: Does mobile based (Android) development, benefit from Object Oriented Programming?

Body:
My development on Android is based on scientific programs and while I'm building these most of the code is in one or two long classes. When I come to deploy these programs I try to decouple everything and use classes and objects like I would on a Java desktop application.

However reading guide Designing for Performance | Android Developers about  Internal Getters/Setters it seems OO is not a good approach.

My question is what is best approach when designed Android applications, should I still use lots of classes with getters/setters and lots of object passing around. This seems counter intuitive thinking about the architecture of Android, but it also does not seem right to have lots of code in long classes.

I have looked at source codes from other projects and these seem to follow the OO approach.

My applications involve heavy image processing and time and performance is important.

I am more of a science researcher than a programmer so thanks in advance for any help.


答:
Next to ncoghlan I'm the other maintainer of Python's import system and the author of its current implementation, importlib (http://docs.python.org/dev/py3k/library/importlib.html). Everything Nick said I agree with, so I just want to add some extra info.

First, don't rely too heavily on PEP 302 directly but instead look at what importlib provides in terms of abstract base classes, etc. For backwards-compatibility things had to be be compatible with PEP 302, but I had to add some of my own APIs in order to finish fleshing out the support for true flexibility.

Another important point is that you are giving developers two pieces of flexibility. One is the ability to store code in a way other than just directly on the file system as individual files (I call this the storage back-end for imports), e.g. this is allowing code to live in a zip file, sqlite database, etc. The other support is in allowing control to pre- or post-process code in some way, e.g. Quixote (https://www.mems-exchange.org/software/quixote/) and its alternative use of string literals not assigned to a variable would be much easier to support.

While the latter is rarely needed, the former is where you have to worry about support. And this is where you end up practically redefining file system interaction APIs. Since some people need assets stored as files with their code, you need to provide a good way to read files, discover files, etc. We still need to implement the part of the API for discovering what data files are available, listing them, etc.

But then you also have the need for APIs which are code-specific. As Nick mentioned, you end up needing APIs on discovering what modules a package contains, etc. which are not file-specific. There is this odd duality of having APIs for dealing with modules where you have extracted away the concept of files, but then you end up needing to provide APIs to access file-like asset data. And as soon as you try to implement one in regards of the other to avoid duplication the waters get really murky (i.e. people end up relying on expected file path structuring, etc. without paying attention to the fact the path may not be a true path because it is for a zipfile containing code and not just a file). IOW you will end up having to implement two similar APIs, but you will be better off for it in the long run.

As Nick said, our solution is a good starting point, but it isn't how I would do it today if I was designing the API from scratch.