答:
Is there a reason why, or a case when reading only the javadoc is the best thing to do?

While you're entirely correct that the JavaDoc may be out of date or bad, it does tend to be in a better format for reading wholesale than code in an IDE. And more importantly, it's in natural language. That is important for two cases:

People not used to reading code. University students for example, are likely more often be better served by reading natural language descriptions of functions than trying to understand code that they're in the process of learning.

People who do not use English (or languages that use phonetic alphabets at least) as their primary language. Since JavaDoc can work with characters that identifiers can't, it can provide better descriptions of what is going on to those users. JavaDoc in particular seems to even have some ability to localize the documentation for you.

That said, I'm a fairly strong believer in readable code. For experienced developers, I expect reading the code to be a better approach almost all of the time if that option is available.


问:
Why was Python's popularity so sudden?
Python first appeared in 1991, but it was somewhat unknown until 2004, if the TIOBE rankings quantify anything meaningful.

What happened?  What caused the interest in this 13 year old language to go through the roof? Is there a reason that Python wasn't considered a real competitor to Perl in its first decade of existence? Is there a reason that Python didn't continue in relative obscurity for another ten years?

I personally think that Python is a very nice language, and I'm glad that I'm not the only one. But it doesn't have corporate backing or a killer feature that would explain a sudden rise to relevance.

Does anyone know the story?

答:
Google

Google started using Python heavily and reinvesting in development of the language.

But it doesn't have corporate backing or a killer feature that would explain a sudden rise to relevance.

Google is the corporate backing. As for features Python is an OOP interpreted cross platform fast1 language. What's not to like? It's another excellent tool in the toolbox.

1. Fast to develop, not fast to execute. Writing a general purpose script in Python is much faster then say Java or C, disregarding the fact that those language would execute faster.

ContentLicense: CC BY-SA 3.0

Title: Why was Python's popularity so sudden?


问:
How does a user program access a device?
In Linux, from http://www.mulix.org/lectures/intro_to_linux_device_drivers/intro_linux_device_drivers.pdf

user programs talk with device drivers through device files

But if I understand correctly,

if the device driver is inside the OS kernel, a user program accesses the device, by making system calls to request the OS kernel to act on its behalf. How do the device file and system calls work together then, since they both help the user program to access the device? (Does the device file act both as an id to the device and also as the interface to the device driver?)

If the device driver is outside the OS kernel, does the user program only use the device file to access the device, without system calls?

Thanks.

答:
A file handle is an abstraction, even for a regular text file.  When the user performs a read system call, a lot happens inside the kernel.  To the user, it looks like you're reading consecutive bytes from a disk, but those bytes might be on separate disks on separate computers, or in various levels of memory cache.  The kernel has to find the best place to retrieve those bytes and return them to the user space.

There's nothing particularly special about bytes on a disk.  If your device is a mouse, the read system call inside the kernel might query the hardware to get the current position of the axes, and the state of the buttons.  Thus, the "file" the user reads contains a struct with that information, repeated over and over.  It allows the user to use the same system calls.  They only need to learn the struct format, which is usually provided in a header file.


问:
Using subroutines to return values?
I'm currently learning FORTRAN (I am familiar with MatLab) and I am very confused about the point of subroutines. Why would anyone use them as opposed to functions. Also, how is it that they can return values when called in the main programs? For example:

```<code>PROGRAM SUBDEM
    REAL A,B,C,SUM,SUMSQ
    CALL INPUT( + A,B,C)
    CALL CALC(A,B,C,SUM,SUMSQ)
    CALL OUTPUT(SUM,SUMSQ)
END

SUBROUTINE INPUT(X, Y, Z)
    REAL X,Y,Z
    PRINT *,'ENTER THREE NUMBERS => '
    READ *,X,Y,Z
    RETURN
 END

SUBROUTINE CALC(A,B,C, SUM,SUMSQ)
    REAL A,B,C,SUM,SUMSQ
    SUM = A + B + C
    SUMSQ = SUM **2
    RETURN
END

SUBROUTINE OUTPUT(SUM,SUMSQ)
    REAL SUM, SUMSQ
    PRINT *,'The sum of the numbers you entered are: ',SUM
    PRINT *,'And the square of the sum is:',SUMSQ
    RETURN
END
</code>```

My question is essentially, how do I know what each subroutine is returning?
Thank you.

答:
In Fortran, a subroutine "returns" everything you pass to it.  You can think of it almost like a C Macro.  In this:

```<code> SUBROUTINE CALC(A,B,C, SUM,SUMSQ)
</code>```

The subroutine "returns" A, B, C, SUM, and SUMSQ.  (Really, it just modifies the values passed to it in-place.)

In contrast, FUNCTION works like a C function, creating locals and returning a single value, which is what people used to more modern languages typically expect.

Title: Using subroutines to return values?

Body:
In Fortran, a subroutine "returns" everything you pass to it.  You can think of it almost like a C Macro.  In this:

 SUBROUTINE CALC(A,B,C, SUM,SUMSQ)

The subroutine "returns" A, B, C, SUM, and SUMSQ.  (Really, it just modifies the values passed to it in-place.)

In contrast, FUNCTION works like a C function, creating locals and returning a single value, which is what people used to more modern languages typically expect.


问:
Who should be allowed to add stories to the product backlog?
What is the best practice for that prevents the backlog from becoming a mess, but also maintaining developer productivity

Who should we allow to add stories to the product backlog? And how do you make sure these stories meet certain requirements?

For example I find a few small css bugs during the development of Feature X. Should I then as a developer be allowed to add a story describing the bugs to the bottom of the backlog? Or should I discuss it with the product owner?

Having all ideas/bugs go through the product owner sounds like possible bottleneck.

答:
We usually do it like this:
Product manager adds stories with descriptions to the product backlog. Our scrum master (who is also team lead) reviews those stories and requests additional feedback for stories that are not defined clearly enough. During the planning week, the team breaks down each of the stories to tasks. If bugs are raised, our team lead places them on backlog, with priority assigned too each of them.</p>


问:
Dynamic model based on JSON received from web service
I am creating a MVC web application which receives some data from a web service in JSON format. I get the different content type structures and data items related to that structure. Using that JSON I want to allow users to create new items in specific content type or edit item.

Now the problem is that I do not know the structure of item, there may be n number of structures. I want to create a ViewModel dynamically on runtime for this purpose.

Is it possible or there should be any other approach?

答:
JSON.NET has a nice approach for this. It provides different ways to deal with this issue. See Serializing and Deserializing JSON.

There are method resulting in a type called JObject which has methods allowing you to traverse the resulting model.


问:
How useful are IT headhunters/recruiters when looking for a new job?
Since they exist for several fields with varying degrees of usefulness, I'm curious as to the reputation of headhunters/recruiters that focus solely on IT professionals (e.g. programmers, software engineers, CIOs, etc) when it comes to finding a new job.

Are they actually useful or is it fairly hit or miss? Does the old adage of only working with a limited number apply or can you safely give you resume/CV to several of them?

答:
I think I agree most of the posted answers so far. My experience is that recruiters are all, of course, looking for the easy money. But they vary greatly in quality and attention to details. Some of the better ones make an effort to match you to a good fit opportunity, but the ones that come out of a cracker jack box just don't care (as someone said before, they're just matching up keywords).

However, some may work for agencies that have relationships with companies and can get you opportunities you could never get from the classifieds, online sites, etc. In these cases, if they know you, they can be the human conduit that gets you in the door. They have spent time building contacts with managers and HR departments and can capitalize on that.

So use them. They're most certainly going to use you.

ContentLicense: CC BY-SA 2.5


问:
Difference between the actors in the existing (non-automated) and the new (automated) system
I guess two main use-case diagrams in building an automated system (Software) from a non-automated system are:

Analysis of the existing system by a use-case diagram.

Mapping the current use-cases and requirements to the software use-case diagram.

How then the meaning of the actors differ in these two diagrams?

For example I want to implement a software for a non-automated library. Is the librarian an actor of the existing system or maybe part of the system itself?   Does the librarian turns to an actor when I draw the use-case diagram of the software system?

I myself guess when I want to analyze the existing system, I should look it as a library with its all staff and services, then the only actor is member!? But when I want to build a software for it, I should suppose the software as the system and everyone who works with it as an actor. Are they correct assumptions to find the actors of the existing and new system?

答:
When looking at a system that is going to be (partially) automated, what is considered part of the system (old or new) and who the actors are depends on the scope of the automation project.

To take your library example and a project to automate the lending administration.

In the non-automated system, the librarian (who records when a book has been borrowed and returned and collects any late-return fees when the book is returned) is part of the system.

If the automated system just covers the activities that the librarian did before, then the librarian is suddenly completely out-of-scope for the software system. He is neither part of the system, nor an actor.

On the other hand, if the automated system also tracks where each book is located (but without the means to physically move books), then the librarian would become an actor who notifies the system that a book has been moved from the collection-bin to the correct place on the shelf.

If the automation project were to digitize the index-card system of the library, then there might not even be a distinction between the librarian using the system or a member. Both would belong to the same class of actor: User.


问:
Using Database licensed under Creative Commons Attribution v3
I have access to a database which data is released under Creative Commons Attribution v3.0

I understand that using this database/data requires me to give credits on information origin in different ways.

I wish to migrate this database to a different engine, and in the future use other data sources (for wish i don't know the license) to complement this data.

Can I do this as long as i keep crediting the original source of some information bits?

答:
The Creative Commons Attribution license is a "open" license. It gives you the right to use and modify the data in any way you see fit, as long as you give proper attribution to the source of the data.

Migrating the data to a different database engine would be fine.

For the other data sources, you need to check on a case-by-case basis if their license allows the way you want to use the data.


问:
Naming Active-Low Outputs
I'm writing some software for an embedded system. I am trying to think of clear names for my single pin output functions.

Normally, when I'm working with active-high outputs (ON = 1, OFF = 0), I am happy to call these functions "setX" and "resetX", where X is a more descriptive name for the output that I'm working with. However, some of my outputs are active-low (ON = 0, OFF = 1), and it seems bizarre to make my "setX" make the output 0.

Is there a standard naming convention for (re)setting values that are on when they're 0?

答: Your software is an abstraction over the hardware.  Whether a particular signal is active low or not is a detail you are supposed to abstract away.  You should choose names to reflect that.  set and reset probably feel odd because they aren't abstract enough.  Try other verbs, such as as enable/disable, activate/deactivate, or select/deselect for a chip select pin.  If the pin has another specific purpose, use appropriate terms for that, such as transmit/receive, sleep/wake, forward/reverse, etc.

Title: Naming Active-Low Outputs


答:
Google was the reason. Only a handful of languages are mandated at Google: C++, Java, Python, Javascript, PHP?

Corporate backing is very important to a language's success. Examples:

C++: AT&T Bell Labs

Java: Sun

C#: Microsoft

Python: Google

Title: Why was Python's popularity so sudden?

Body:
Python first appeared in 1991, but it was somewhat unknown until 2004, if the TIOBE rankings quantify anything meaningful.

What happened?  What caused the interest in this 13 year old language to go through the roof? Is there a reason that Python wasn't considered a real competitor to Perl in its first decade of existence? Is there a reason that Python didn't continue in relative obscurity for another ten years?

I personally think that Python is a very nice language, and I'm glad that I'm not the only one. But it doesn't have corporate backing or a killer feature that would explain a sudden rise to relevance.

Does anyone know the story?


问:
Is self referencing tables a good idea for geographical data?
I am creating a design for different Geographical types where each type is just a little "place holder" in over all heirarchy.

One example is

Zip code Belongs to Territory Belongs to District

Other would be

Zip code belongs to State belongs to Some Region

We have two schools of thought one is that:

```<code>  1  create different tables like Zipcode, Territory, Regions etc
</code>```

other is that just create one table which is called Geographical
  Entity and then everything is just a type so you can assign a Type Id
  to each geographical entity and self reference the table

Now, if I go by design #1 then I don't have to worry about any non traditional decision. I can create one class in OO space and then map to each table. Also, imposing business level rules such as Territory can do such and such things but Distrtict can not. And also things like a Territory can belong to District but District can not belong to Territory are all contained in design itself.

However, If I go to Design #2. It is extensible such that if we have a new Geographical type called "XYZ" then we do not need to add a new table for that. We can simply add  a new type into Geography type and it would be addressed.

I find Design #2 extensible but unnecessarily complex. Am I right thinking it that way? Or that's the way to go?

答:
Yes is can be, but beware of the following:

Recursive queries (For example, in Sql Server, common table expression (CTE)

Recursion in code (self referencing objects)

Both of these can be tricky to understand, implement, and support.

For your queries, it will not be a simple

Select * from Table

type of query.  Also, most likely the object model in code will have self referencing objects that will require a root and tree/node structure to support.

However, I can say this model is appropriate.  In a past project we implemented a self referencing geographic model to good success.  As a precaution when we interviewed candidates we had a recursion code question to ensure they could handle the code and model as not everyone is familiar with this type of data structure.


问:
How to earn team members respect as team lead
If you were hired into a new company as a team lead (say a team of 10) one of the important things to do is to earn the respect of the members of the team. In the early days the new team lead may know nothing of the team culture, code base and business domain: in other words, is a complete neophyte. </p>

<p>How does one go about this? What are the do's and don'ts? </p>

答:
Here are some actionable things that worked for me:

1) Do very casual & relaxed one-on-one meetings with everyone in the team (something like lunch, or just drop by their cubicle, go for a walk around the building, etc).  Listen more, talk less, ask questions.  Find out their strengths, desires, character traits, and "soft spots".

2) Ask for their help.  Everyone likes to feel helpful and knowledgeable in front of their team lead.

3) Empower your people by asking their opinions, complementing frequently but for good reason.

4) Explain your decisions. Don't give the company line w/o in a way of a non-commital talk like C-execs do.  Be straightforward.

5) Once in a role, ACTIVELY and EVERY DAY remove obstacles from your teammates

6) Address non-performers right-away.  If something is bothering them, find a way to fix it.  If they're just lazy/angry/stupid - get rid of them through your mgmt.

7) And lastly, PREPARE your people ahead of time for changes that are about to hit the team, their work, their requirements, etc.  They need to work in a predictable environment.


问:
Serving a file from a private directory
I have a PDF that needs to be accessible for multiple unrelated areas across a website. I don't want to reveal anything about where the file is downloaded from and I want to only upload the file once.

Is it possible to serve a file stored in the private space, as opposed to storing it in a public directory. If so, can someone point me in the correct direction or give an example?

答:
Yes. Keywords are: file streaming with php.

It is something like this:

```<code>echo file_get_contents('secretfolder/the_file.pdf');
</code>```

Do a search or have a look at:
https://stackoverflow.com/questions/6914912/streaming-a-large-file-using-php

Title: Serving a file from a private directory

Body:
Yes. Keywords are: file streaming with php.

It is something like this:

echo file_get_contents('secretfolder/the_file.pdf');

Do a search or have a look at:
https://stackoverflow.com/questions/6914912/streaming-a-large-file-using-php


问:
When, if ever, should I draw the use-case diagram of the existing system?
When I want to design a software I usually think about the use-cases of my software, but I have heard some sort of analyzing the existing (non-automated) system is required.

To be specific, is analyzing the existing system through a use-case diagram a prerequisite to find the use-cases of a software system (automated system)? or we can directly start from the use cases of the intended software? If it depends on the project, which projects require that step and which don't.

If that is not a prerequisite, is there any other diagram which can help us in drawing the use-case diagram of the new system?  I know some analysis of the existing system is required but I would like to know is there some standard diagrams or steps for such analysis?

答:
Doing use-cases for an existing manual system is difficult because use-cases require a "system". Where are the boundaries of the "system" in the manual system? If you want your work to be relevant to your planned automated system then you should choose the part being automated as the "system". In which case, both the manual and automated systems should have pretty much the same use-cases and diagrams. Thus, there's not much point in doing use-cases for the manual system.

However, if you are automating an existing manual process then you might need to capture the manual work flow in some fashion so you know what the software has to replace. So that could be why some people recommend using use-cases for describing the manual process. Whether that is the most efficient way to capture that information is debatable. It might be the best approach if the people currently using the manual system will only be available for a short time at the beginning of the project so you need to capture as much info from them as possible at that time OR if you are flowing the process onto yet another company to actually build.

I would start with doing use-cases for the system being built and then fill out the details by figuring out what the manual system does. That would be the most efficient approach and will likely be sufficient for most projects.


问:
One Script file or Multiple Script Files
I have a moderately long(for me at least) bash script file that that maintains a list of LAN users and the bandwidth each one uses. It is 199 lines with 11 functions and is already calling 3 different files. At most it calls 3 functions at least 1 every 5 minutes.

Should I separate each function into its own file, or is this still small enough to run in 1 file?

答:
This is a very common question for any programming language, and the answer is surprisingly simple.

Do what makes sense and makes the program better.

Here are qualities that make a program/script better in no particular order:

Ease of understanding

Ease of maintenance

Ease of extension

Ability to be tested and debugged

Portability

Performance

If separating the code into multiple files increases any of these metrics without sacrificing the others, then you should do it.  If it does not, then you should avoid it.

It is sometimes difficult to determine if these metrics are being positively affected.  Furthermore many of these qualities can be subjective.  To get a better perspective on your code I would encourage you to submit the code for review by your peers and senior developers in said area.  Code review is one of the best tools programmers have to hone their ability to discern the above qualities.


问:
Why shouldn't I use the repository pattern with Entity Framework?
During a job interview, I was asked to explain why the repository pattern isn't a good pattern to work with ORMs like Entity Framework. Why is this the case?</p>

答:
We have had problems with duplicate but different Entity Framework DbContext instances when a IoC container that new() up repositories per type (for example a UserRepository and a GroupRepository instance that each call their own IDbSet from DBContext), can sometimes cause multiple contexts per request (in an MVC/web context).

Most of the time it still works, but when you add a service layer on top of that and those services assume objects created with one context will correctly be attached as child collections to a new object in another context, it sometimes fails and sometimes doesn't depending on the speed of the commits.

OwnerDisplayName: StringBuilder


问:
Is it necessary to apply to anywhere other than to add a file as LICENSE.txt for open source or free software licensing?
I am going to continue a game engine project I didn't engage in for a long time.I amatourly writed some core libraries using OpenGL with C++. Because I am not that into programming in general, I am asking this silly question about software licensing. If I want to license my program ,for example, with zlib, is it enough just to include the formal manifesto(full text of the license) in source code itself or add it as a seperate text file on root folder and put on github? If no, should I additionally apply to any formal foundation etc.?

Edit : I have tried to make the question as clear as possible. If the question is still not clear or any grammatical mistake exists, warn me.

答:
I am not a lawyer. You should get one, if you are concerned about possible legal issues.

You have to include a copyright notice (a ‘manifesto’, if you will) to each file that contains your work.

That ‘manifesto’ shall consist of:

A line Copyright © <years> <owner>.

Where <years> are years when this very file was created and substantially modified; you’ve said that you did not work on the project for a long time, so it might look like 2008, 2015 for example; do not use range (2008–2015) unless the file was modified every year.

<owner> is who holds exclusive rights on this very file. The authors are owners if they did not transfer rights to someone else. An employee typically transfer his copyright on the work his paid for to an employer by terms of contract or (in many countries) by the law. So if you was working on the project during your work hours, you would better check that your employer does not claim copyright on it.

Either ⓐ the full text of a license in the case of short permissive licenses, e. g.: BSD licenses (2 clause, 3 clause), X11, Expat, zlib licenses; or ⓑ something that refers to the full text: Apache License v2 (see under APPENDIX), GNU licenses (see under ‘How to apply...’ in the GNU GPL) and other long and well-written free/libre licenses; also WTFPL :-), which is a sort of parody on complicated copyright licenses.

When ⓑ you have to put the full legal text of a license in the file COPYING or LICENSE in the root of code repository usually; when ⓐ this in optional and does not make any sense from a legal point of view, but often considered a good habit since it helps to detect the license automatically, especially when a code hosting service does not have, like GitHub, a field for license in project properties.

You probably would also want to mention copyright terms briefly in README file.

I also have to note with regret, that many amateur free software developers neglects these legal technicalities, please do not take them as an example.


答:
The standard way to apply a license to a software is to put the full license text in a file called LICENSE or COPYING included with the source code and then put a short notice in a comment at the top of each source file (naming the copyright date, holder, license and saying where to find the full text of the license).

GPLv3 requires that if the program does terminal interaction, it also has to output a short notice like this when it starts in an interactive mode:

  Copyright (C) <year>  <name of author>

This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.

  This is free software, and you are welcome to redistribute it

  under certain conditions; type 'show c' for details.

If the license you want to apply doesn't have specific instructions (e.g. zlib) OSI suggests to follow the Apache License / GPLv3 instructions.

According to Github a LICENSE file in the root of the repository is enough (see Where does the license live on my repository? and I already have a project with a license file, do I need to do anything?).

Further details:

Applying the Apache License, Version 2.0

To apply the ALv2 to a new software distribution, include one copy of the license text by copying the file:

http://www.apache.org/licenses/LICENSE-2.0.txt

into a file called LICENSE in the top directory of your distribution.

[...]

Each original source document (code and documentation, but excluding the
  LICENSE and NOTICE files) SHOULD include a short license header
  at the top.

How to Apply GPL v3 Terms to Your New Programs

I want to use the Mozilla Public License for software that I have written. What do I have to do?

To apply the Mozilla Public License to software that you have
    written, add the header from Exhibit A of the license to each source
    code file in your project. Sample headers for various commenting
    styles are available here.
    You may also add additional accurate notices of copyright ownership, such as the name of the copyright holder, but this is not necessary.

This answer is for reference purposes only and it is not intended as nor does it constitute legal advice.
The author is not an attorney and makes absolutely no claim to have any knowledge about legal matters beyond that of an informed layman.

Title: Is it necessary to apply to anywhere other than to add a file as LICENSE.txt for open source or free software licensing?

Body:
I am going to continue a game engine project I didn't engage in for a long time.I amatourly writed some core libraries using OpenGL with C++. Because I am not that into programming in general, I am asking this silly question about software licensing. If I want to license my program ,for example, with zlib, is it enough just to include the formal manifesto(full text of the license) in source code itself or add it as a seperate text file on root folder and put on github? If no, should I additionally apply to any formal foundation etc.?

Edit : I have tried to make the question as clear as possible. If the question is still not clear or any grammatical mistake exists, warn me.


问:
Using Fonts in your Applications
When writing applications for software, specifically mobile devices, will there be a problem with using any specific type of fonts (copyright/patent issues)?

If so, how can we avoid this possible problems?

Will it then make a difference if the app was a paid version or a free version?

答:
Fonts are the font SOFTWARE (the actual .ttf or .otf file)

Just like Microsoft Office, only tiny.

Taking a font file and putting/embedding it in software, hardware, on a server, using it with @font face all requires a license fee

Taking the letterforms produced by a font like a .bmp or .jpg or any static picture of text is covered under the general EULA for $30 online at fonts.com, myfonts.com, linotype.com

When shipping the font in your app or serving it up on a server that's where you need an offline license that can cost thousands

Title: Using Fonts in your Applications


问:
Why doesn't Java have optimization for tail-recursion at all?
From what I have read: The reason is because it is not easy to determine which method will actually be called as we have inheritance.

However, why doesn't Java at least have tail-recursion optimization for static methods and enforce proper way to call static methods with the compiler?

Why doesn't Java have any support at all for tail-recursion?

I am not sure if there is any difficulty here at all.

Regarding the suggested duplicate, as explained by Jörg W Mittag1:

The other question asks about TCO, this one about TRE. TRE is much simpler than TCO.

Also, the other question asks about what limitations the JVM imposes on language implementations that wish to compile to the JVM, this question asks about Java, which is the one language that is not restricted by the JVM, since the JVM spec can be changed by the same people who design Java.

And lastly, there isn't even a restriction in the JVM about TRE, because the JVM does have intra-method GOTO, which is all that's needed for TRE

1Formatting added to call out points made.

答:
Unless a language has a special syntax for making a tail call (recursive or otherwise) and a compiler will squawk when a tail call is requested but cannot be generated, "optional" tail-call or tail-recursion optimization will yield situations where a piece of code may require less than 100 bytes of stack on one machine, but more than 100,000,000 bytes of stack on another.  Such a different should be considered qualitative rather than merely quantitative.

It's expected that machines may have differing stack sizes, and thus it's always possible for code to work on one machine but blow the stack on another.  Generally, however, code which will work on one machine even when the stack is artificially constricted will likely work on all machines with "normal" stack sizes.  If, however, a method which recurses 1,000,000 deep is tail-call optimized on one machine but not another, execution on the former machine will likely work even it its stack is unusually small, and fail on the latter even if its stack is unusually large.


答:
I once worked on a system that modeled similar data. Not geographical, but hierarchical, where the hierarchy was not necessarily well-defined and entities might "skip" layers: A -> B -> C was just as valid as A -> C.

Using separate tables is great when you can guarantee the data will match the structure, and in fact must match the structure. However, that appears not to be the case here.

Things to keep in mind:

Querying an entire hierarchy from leaf to root cannot be easily done. SQL Server has CTEs and Oracle has hierarchical queries, but the data is not in a consistent state the way an ORM layer would expect: you have arbitrarily many records of arbitrary types not defined by the table itself but by one of its fields. In other words, the type of a record is defined by the record itself, not the table in which it resides.

Other areas of an application require extra care. It is not as simple as grabbing the "state" or "postal code" field and linking it to a UI element, you have to look at a code/value pair to determine what the data represents. Extra logic is required to put data from the database in the proper place for your model and view.

Joins become almost impossible to do correctly in all cases which would not be true for the strongly-typed separate table solution.

Given the information in your question I would do it this way, but keep in mind it introduces complexity that must be considered and managed.

Title: Is self referencing tables a good idea for geographical data?

Body:
I am creating a design for different Geographical types where each type is just a little "place holder" in over all heirarchy.

One example is

Zip code Belongs to Territory Belongs to District

Other would be

Zip code belongs to State belongs to Some Region

We have two schools of thought one is that:

```<code>  1  create different tables like Zipcode, Territory, Regions etc
</code>```

other is that just create one table which is called Geographical
  Entity and then everything is just a type so you can assign a Type Id
  to each geographical entity and self reference the table

Now, if I go by design #1 then I don't have to worry about any non traditional decision. I can create one class in OO space and then map to each table. Also, imposing business level rules such as Territory can do such and such things but Distrtict can not. And also things like a Territory can belong to District but District can not belong to Territory are all contained in design itself.

However, If I go to Design #2. It is extensible such that if we have a new Geographical type called "XYZ" then we do not need to add a new table for that. We can simply add  a new type into Geography type and it would be addressed.

I find Design #2 extensible but unnecessarily complex. Am I right thinking it that way? Or that's the way to go?


问:
Should methods perform checks that they accomplished the task they were built for? or should they just throw an exception?
What are some pro's and con's of validating your performed the task intended?

```<code>public static bool UploadFile(string filename)
{
    // 1. upload the file
    // 2. check to see if the file now exist on the server and return status
}
</code>```

vs.

```<code>public static void UploadFile(string filename)
{
    // 1. upload the file and hope it's on the server now, or check with another method to see if the file exist on the server
}
</code>```

答:
Your example is flawed.

When uploading a file to the server, if something wrong happens, such as a timeout, or a server-side error, this would result in an exception. If this doesn't result in an exception, the underlying methods you are using which didn't threw one are a problem, and you should switch to a library which does things correctly.

For instance, if the HTTP library you use doesn't throw anything when receiving HTTP 500 from the server, the library sucks. Use a better one.

This also means that both of your pieces of code are wrong.

In the first case, you don't check if the file exists. It exists, obviously, because you just uploaded the file and the server returned an HTTP 201 which was processed by the underlying HTTP library as a success response. If it doesn't exist, you shouldn't reach the second point of your method, because an exception should have been thrown.

In the second case, you don't hope that something works. You know that it works.

So:

```<code>public static void UploadFile(string filename)
{
    // 1. Upload the file.
    // 2. The file is uploaded. It's there, on the server.
}
</code>```

Body:
Your example is flawed.

When uploading a file to the server, if something wrong happens, such as a timeout, or a server-side error, this would result in an exception. If this doesn't result in an exception, the underlying methods you are using which didn't threw one are a problem, and you should switch to a library which does things correctly.

For instance, if the HTTP library you use doesn't throw anything when receiving HTTP 500 from the server, the library sucks. Use a better one.

This also means that both of your pieces of code are wrong.

In the first case, you don't check if the file exists. It exists, obviously, because you just uploaded the file and the server returned an HTTP 201 which was processed by the underlying HTTP library as a success response. If it doesn't exist, you shouldn't reach the second point of your method, because an exception should have been thrown.

In the second case, you don't hope that something works. You know that it works.

So:

public static void UploadFile(string filename)
{
    // 1. Upload the file.
    // 2. The file is uploaded. It's there, on the server.
}


问:
Real life scenario of why we would use loops
I am going to school to become a programmer, and I am doing some homework and I have a question. It wants me to give an example of why we would use loops in the real world. And I was thinking about smart phones, I have an app on here that tells me the temperature outside, and if the temperature changes, it would tell me. Is that an acceptable answer to this question?</p>

答:
Loops are what make computers interesting machines.  Without loops, computers would just be really sophisticated adding machines, and not much else.

The very first computing course I took in high school, we didn't even have a computer... We just had this adding machine that was the size of a suitcase and weighed about 100 pounds.  It did what you might expect an adding machine to do: basic arithmetic.  And that's all it did.

Until the day I discovered you could write a loop.

I told the machine to multiply 2 by itself, and to repeat that operation in a loop.  The machine suddenly came alive, printing ever increasing numbers on a ribbon of paper.  Ka-chunk, ka-chunk, ka-chunk.  After about 30 loops, it suddenly stopped.  The machine had overflowed.

I was hooked.

Almost everything substantial that happens in a computer happens in a loop.  Your temperature example could poll some sensor somewhere every 10 seconds to see if the temperature has changed.  That's a loop.  A report that writes line items on an invoice is a loop: one iteration per line item.  The screen you're looking at runs in two loops: one for the horizontal pixels, and one for the vertical ones, refreshing the screen roughly 60 times per second.

In the real world, almost everything is cyclical, and therefore runs in a loop.  The vibration of atoms, the rotation of the engine in your car (or the tires), eating food one spoonful at a time, etc.


答: How about the simple act of taking a walk?  You know how to move your left leg.  You know how to move your right leg.  Now do that repeatedly (via a loop) until you arrive at your destination.</p>

Title: Real life scenario of why we would use loops

Body: I am going to school to become a programmer, and I am doing some homework and I have a question. It wants me to give an example of why we would use loops in the real world. And I was thinking about smart phones, I have an app on here that tells me the temperature outside, and if the temperature changes, it would tell me. Is that an acceptable answer to this question?</p>


问:
Thinking about a language for build definitions
I want to write a little tool that parses build definitions and converts them to a ninja.build file. It should not abstract compilation like CMake or Meson, but be similar to make in that you manually write the commands for a build step.

I have built an almost working solution in Python, but there are some stepping stones that I could not easily solve yet and the design is not ideal. My main goal is to have modular build definitions and be able to modify these definitions from another project for its requirements. Imagine

use platform
use platform.compiler as compiler

# Another user created build definition file.
use foolib

build_dir : join(project_path, 'build')
foolib.build_dir : build_dir  # Here we change the build_dir of the library
foolib.defines : array(foolib.defines, 'FOOLIB_LEGACY_API')  # And here we add another define

sources : wildcard('source/*.cpp')
objects : transform(sources, 'source', join(build_dir, 'obj'), platform.objsuffix)
executable : join(build_dir, platform.exename('main'))
includes : array(localpath('include'), foolib.includes)
defines : array(foolib.defines, 'BUFSIZE=512')
flags : compiler.includes(includes) compiler.defines(defines)

# Automatically deduces to issue a command for each source/object pair
target sources -> objects
    compiler.cpp quote(input) flags compiler.compile_only compiler.out(output)

target array(objects, foolib.library) -> executable
    compiler.cpp quote(input) flags compiler.out(executable)
```

<p><code>foolib</code> would look pretty similar, outputting a library file from source files to its <code>build_dir</code>.</p>

<p>I use lazy variable expansion at all times to allow things like changing the build directory of an imported project or update macro definitions used while compiling the dependency.</p>

<p>The problem I have with lazy evaluation is with self-references, and it also adds a lot of overhead. However, doing immediate evaluation on assignment will not allow this late configuration change.</p>

<p>Another aspect is that I want to be able to specify options on the command-line that will have effect on the modules configuration. For instance, let's say I want to build my program in debug mode.</p>

```if debug == 'true'
    executable : join(build_dir, platform.exename('main-dbg'))
    flags : flags compiler.debug
    defines : array(defines, 'DEBUG')
```

If foolib uses the same conditional to update its compilation flags and defines, it will be built in debug mode as well. Although in this special case, it would be desirable, there might be a case where I want to be specific to make it set only for my program but not for foolib module.

Do you have ideas for improvements, a different or better design?

答: It's probably a good idea to read through https://wiki.debian.org/UpstreamGuide#Your_Build_System (other Linux distros will probably have something similar). Respecting environment variables (e.g. CFLAGS) is important (see the SCons and waf discussion for the problems created by not doing this).</p>


答:
From the way your question is phrased, it sounds like you're generically asking if you should verify something executed correctly. The answer is yes.

If it's something simple like a system call, then you would return the runtime's exit code
For example:

Runtime.exitValue()

This is assuming whatever you executed itself returns a proper error.  If I run a Bash script from Linux and it returns 2, your Java code needs to know what that means and what to do.

In Java the big things to catch are Exceptions (and NOT just catching them as generic exceptions).  ArithmeticException (dividing by 0), ArrayOutOfBounds (accessing part of an array that isn't defined), NullPointer, etc.  Whenever you run into unexpected or risky behavior, it's always safer to catch yourself.

The extent to which you verify as you go varies on your development environment.

Title: Should methods perform checks that they accomplished the task they were built for? or should they just throw an exception?

Body:
What are some pro's and con's of validating your performed the task intended?

```<code>public static bool UploadFile(string filename)
{
    // 1. upload the file
    // 2. check to see if the file now exist on the server and return status
}
</code>```

vs.

```<code>public static void UploadFile(string filename)
{
    // 1. upload the file and hope it's on the server now, or check with another method to see if the file exist on the server
}
</code>```


答:
It seems to me that this would be a more clear example:

```<code>for student in students:
    grade_exam_of(student)
</code>```

It loops, the body of each loop is identical, and it is in a domain well understood by your instructor.

Body:
It seems to me that this would be a more clear example:

for student in students:
    grade_exam_of(student)

It loops, the body of each loop is identical, and it is in a domain well understood by your instructor.


问:
What open source library licenses can I use in closed-source?
I like to create a closed-source program and sell it.  I would like to make use of various open source libraries to make it easier to write this program.

So how I will choose the libraries that I could use. Which licenses for libraries could I use? I only will use the library - I will not edit the libraries.

Which licenses allowed me to use it for closed-source program?

答:
Most permissive licenses would be suitable for your purpose, because a permissive license allows to combine the work with another and release it under any license you want. But keep in mind that some conditions might apply, like giving credit to the original authors. So make sure to read the license properly before considering it for use in your project. The most widely-used software licenses of this kind are the MIT license and the BSD license family.

When you don't intend to modify the library, you can also use libraries licensed under the LGPL. This version of the GPL has an exception which allows dynamic linking (but not static linking!) with a program under any other license.


问:
What is the IDE for Visual basic?
So weird to ask and I am sorry for the this question. What is the IDE for Visual basic? I searched throughout the internet but I didnt find the nice information about visual basic and its IDE. </p>

答:
You can use any version of Visual Studio (I.E Express, Professional, Ultimate) to write Visual Basic code. When you create a new project in Visual Studio, select Other Languages and then Visual Basic.

If you don't have the Professional or Ultimate versions of Visual Studio, the Express versions of Visual Studio are free and offer most of the functionality of the other versions.

Also, there is no one IDE for Visual Basic, but Visual Studio is the most popular IDE for that language. What I'm saying is, you could write VB code in Notepad and then compile it with a Terminal window.

Title: What is the IDE for Visual basic?


答:
It sounds like you're talking about classic Visual Basic (not VB.net), right?. There was no separate IDE, the program was called "Visual Basic". </p>

<p>See the Visual Basic Wikipedia page for a screenshot of the VB6 IDE </p>

Title: What is the IDE for Visual basic?

Body: So weird to ask and I am sorry for the this question. What is the IDE for Visual basic? I searched throughout the internet but I didnt find the nice information about visual basic and its IDE. </p>

Body:
It sounds like you're talking about classic Visual Basic (not VB.net), right?. There was no separate IDE, the program was called "Visual Basic".

See the Visual Basic Wikipedia page for a screenshot of the VB6 IDE


问:
Is prototypal inheritance inherently slower?
I see Javascript 6 will add traditional class based inheritance, and one argument I hear is that classes are inherently much faster than prototypes because they can be optimized away by the compiler when doing (JIT) compilation to native code or to bytecode. That sort of makes sense to my mind, but I'm not nearly an advanced enough programmer to really understand this stuff.

The argument I always saw for prototypal inheritance (PI) was that it conserves memory, which is mostly a completely moot point these days. Personally, I like PI and always felt it "makes sense" in a dynamic language; like it is a luxury you can just as well afford if you already settled for the performance limitations of an interpreted dynamic language.

In C++, classes makes sense because of the limitations that comes with the C++ philosophy that everything takes a back seat to maximum possibility for performance.

Of course you can have PI in C++ and there is a well known design pattern for that, but I'm talking about built-in inheritance in a dynamic language.

If one was looking at the fastest possible implementation of prototypal inheritance in a fictional dynamic language, what would necessarily be the drawbacks with regards to performance vis-à-vis traditional classes?

What if you add the feature to the fictional language that you can specify that some objects are "final" and their prototype chain cannot be changed at runtime? (Coexisting with traditional PI) Also add optional static typing or type hinting if that helps the prototypal language.

Since this might be considered a bit of a vague question, I'm adding:

I guess I'm looking for the thoughts on the subject from people who are more clever and more interested in language theory and/or compiler/interpreter writing than me. Hope that is still an ok question.

This is not about Javascript 6 at all, I just brought it up because Javascript is the most successful prototypal language and it is interesting that they are adding native classes even though Javascript seemed to be doing fine without them (both popularity wise and having some jaw-dropping benchmark improvements in the last few years). I'm also not saying that I believe or think that Javascript is slow.

Really, I'm more interested in learning more about programming languages, possibly with the goal of some day constructing my own dynamic language.

答:
In C++, classes makes sense because of the limitations that comes with the C++ philosophy that everything takes a back seat to maximum possibility for performance.

You have two false premises inherent in this statement.  The first is that classes are a C++ thing.  They aren't; the concept is as old as OOP itself, dating back to Simula, the first object-oriented language, and nearly every OO language since then has had classes, including dynamic ones such as Python.  It's the prototypal model that is the aberration.

The second is that classes are used because of performance.  While that's certainly one benefit, it's hardly the reason for using them.  The real reasons for using classes are that they're a natural way to model many important types of programming problems, and that they mesh quite well with static typing as a way to help enforce correctness and head off entire classes of problems (no pun intended) at compile time.

And yes, classes are inherently faster at runtime than prototypal inheritance, for one simple reason: any information that can be calculated at compile time does not have to be calculated at runtime.  Classes provide the compiler with certain invariants that it can know ahead of time will not be violated, which allows it to create simpler runtime code that does not need to check for those things.

Depending on how the class is implemented, there can be a second major advantage: if the objects are implemented as contiguous records with fields, then member access becomes a dereference of a pointer at a constant offset from the beginning of the object's memory location, which will be dozens or even hundreds of times faster than looking members up in a hash table or other map, which is how you have to do it at runtime if the object's layout is not known to the compiler.

So yes, classes are inherently faster, which is why modern JavaScript JITs try to turn objects into classes whenever possible.  But this is just a side benefit; the real advantage comes from them being inherently safer and more useful as a tool to reason and prove things about the behavior of your code.


问:
How do you balance between "do it right" and "do it ASAP" in your daily work?
I find myself pondering over this question from time to time, again and again. I want to do things the right way: to write clean, understandable and correct code that is easy to maintain. However, what I end up doing is writing patch upon a patch; just because there is no time, clients are waiting, a bug should be fixed overnight, the company is losing money on this problem, a manager is pressing hard etc., etc.

I know perfectly well that in the long term I am wasting more time on these patches, but as this time spans months of work, nobody cares. Also, as one of my managers used to say: "we don't know if there will be a long term if we don't fix it now."

I am sure I am not the only one entrapped in these endless real/ideal choice cycles. So how do you, my fellow programmers, cope with this?

UPDATE:
Thank you all for this interesting discussion.
It is sad that so many people have to choose daily between a quantity and a quality of their code. Still, surprisingly many, people think it is possible to win this battle, so thank you all for this encouragement.

答:
Software is weird stuff and the software development process is weirder.

Unlike most things in real life, but like most things to do with computers

Faster is more reliable

This goes against every intuition that you life so far has taught you, highly tuned cars break down more often than standard ones, quickly built houses fall apart more quickly, homework done in the back of the school bus does not get high marks.

But slow methodical procedures don't produce better software. Guys who spend weeks churning out requirements documents, and days on class diagrams before writing code do not produce better software. The guy who gets the basic requirement, clarifies a few issues, scribbles a class diagram on the whiteboard and gets his team coding will nearly always produce more reliable and better software, and, do so in days rather than months.


问:
saving connectivity information in a nodes/edges network
I want to implement the A* algorithm. I have a network with Nodes and Edges, both are classes.

Now, I am unsure how to approach the connectivity information. Should a node know which edges depart from it? Should an edge know which two nodes it connects?

I thought both answers were true, but then there are circular dependencies, i.e. when copying a node, it copies all the edges it has, which, in turn, copy all the nodes they connect, and so on.

Maybe it is better to save all connectivity problems in the Network class? But then I have to explicitly create them and have to update them manually if I delete or add nodes/edges.

What is a good way to approach this?

答:
Graphs

The dependencies of a graph are:

```<code> graph  <- {vertices, edges}
 edge   <- {u, v}   // u and v are vertices
 vertex <- {Label}
</code>```

The Label of a vertex may be implicit in from the implementation's data structure, e.g. it's index within an array. Vertices are dependent on labels independently of edges because a single vertex is still a graph [or a tree, or a network] in its own right.

Business Logic

In an implementation, the vertex label might used to retrieve a record. What is stored in the record is a matter of business logic, not a property of graphs. Therefore the choice of storing edges at the vertex is subject to engineering analysis. But all graph operations can be implemented without doing so.

As more detailed information is stored at the vertices, the less general the implementation becomes. Storing edges at the node is essentially caching and comes with all the issues normally associated with any other cache process, e.g. routers and switches spend a lot of their energy implementing business logic to cope with storing edges at nodes.

Tradeoffs

The more mathematical the implementation, the easier it is to reason about. The more business like, the higher the ceiling for ultimate performance is in theory. However, theoretical ceilings on performance are based on getting the business logic right and that's harder than getting the mathematics right.

Body:
Graphs

The dependencies of a graph are:

 graph  <- {vertices, edges}
 edge   <- {u, v}   // u and v are vertices
 vertex <- {Label}

The Label of a vertex may be implicit in from the implementation's data structure, e.g. it's index within an array. Vertices are dependent on labels independently of edges because a single vertex is still a graph [or a tree, or a network] in its own right.

Business Logic

In an implementation, the vertex label might used to retrieve a record. What is stored in the record is a matter of business logic, not a property of graphs. Therefore the choice of storing edges at the vertex is subject to engineering analysis. But all graph operations can be implemented without doing so.

As more detailed information is stored at the vertices, the less general the implementation becomes. Storing edges at the node is essentially caching and comes with all the issues normally associated with any other cache process, e.g. routers and switches spend a lot of their energy implementing business logic to cope with storing edges at nodes.

Tradeoffs

The more mathematical the implementation, the easier it is to reason about. The more business like, the higher the ceiling for ultimate performance is in theory. However, theoretical ceilings on performance are based on getting the business logic right and that's harder than getting the mathematics right.


问:
Send heavy computation jobs from web server to another process and wait for response
I know it is a common practice to send cpu-bounded heavy tasks to background processes, in order to free a web server to serve other requests.

But - what if the request must know the result of that computation? Is there a known pattern, where the web server waits for a background process to finish its job, before it responds? I couldn't find any example of this use case.

In my case, for instance, I want to send an HTTP post request's body to Spark Streaming process that runs separately from the server, wait for the result and then respond to the request. (Server and Spark Streaming communicate through Kafka)

Many thanks

答:
The web server is expected to give HTTP replies (to the web clients, i.e. browser) fairly quickly. A user would be unhappy if a web page loads in more than a second or two.

However, you could use AJAX and websocket technologies (with HTML5 and Javascript) in your web page. Then your web page could query asynchronously or periodically the web server (which would query your other process)


问:
Should I be using separate 'domain' layer?
I have been reading a lot about domain layer and DDD. However I am still confused about it. To me they seem to be a fancy name for business classes however more modelled towards your application domain but then most programmers I have worked with create business object/entities and try to model it as closely as possible to the actual application objects.

So here's the question. In the Asp.net Web API application whose primary focus would be to get large amounts data(GET requests mostly) from different tables on the basis of certain inputs and some logic running as a result, is there really a business need for Domain layer and objects?

**Another thing that I find troubling when I read about DDD is that both DAL and BLL link to Domain Layer which can introduce dependency issues when updating certain parts of the application in the future.

答:
I think the business object/entities you are describing aren't actually domain objects in the DDD-sense, if you are applying DDD your business logic would be contained in the Domain Objects themselves; the entities you are describing (having business logic in a separate layer) seem to be Anemic.

If you want to know whether to use DDD you would have to establish whether or not the domain you are working in is sufficiently complex to involve Domain experts as "[f]undamentally, DDD is the principle that we should be focusing on the deep issues of the domain our users are engaged in, that the best part of our minds should be devoted to understanding that domain, and collaborating with experts in that domain to wrestle it into a conceptual form that we can use to build powerful, flexible software." Eric Evans

The fact that you are essentially displaying data from different tables on the basis of certain inputs and some logic would lead me to believe that your domain is not complex enough to warrant applying DDD.

In order to address your last concern, a common DDD architecture would not have the DAL and BLL link to the Domain Layer, the DAL would be abstracted behind a repository which would expose and persist your Domain objects; business logic would be contained in the Domain objects themselves, and your "BLL" would actually be a service or application layer that uses the repository for access to the domain objects, it is "a thin layer which coordinates the application
activity. It does not contain business logic. It does not
hold the state of the business objects, but it can hold
the state of an application task progress". (from the book domain driven design quickly page 30)


问:
Most efficient way of searching very large strings of text in java
I have a question that I have been thinking about recently but I am still not sure of the answer(s) so I would like a broader opinion.

Imagine the scenario where text strings of up to lets say 500,000,000 characters are processed in Java.  But each string of text is searched for the words "the", "and" and "yes".

What is the most efficient way of completing this task?

答:
Efficient in terms of space or size? Will the string change, and if so will it be appended to or arbitrarily changed? How is the string created in the first place i.e where does it come from?

Not knowing the answers to these crucial questions I be tempted to think of (and throughly test) a number of approaches:

Think about indexing substrings at the time of string creation. You need to create this string originally, either by reading it from a file, growing it as part of an algorithm's output, or generating it in its entirety algorithmically. At time of creation, as the characters are 'going into' the string, think about searching in the input stream and indexing positions in the string that the substrings occur so at the end you then have a table mapping the substrings to list of locations that the substrings start at. This means that you are building an index at the time of string creation/reading (much like an insert into a DB). You need to consider whether the string changes though and although appending works OK with this approach, insertion is not so easy (although after a mid-string change, adjusting the index of substrings wouldn't require a new computation, just calculated offset additions or subtraction). If you need to search for arbitrary words then at the time of build, create an index that maps all words to locations in the string. It'll be a very big index, but you haven't indicated whether you are interested in speed or space.

Consider using Java language constructs that already exist. You may need to subdivide the string into arrays of substrings to ensure in-memory operations, and then use pattern matching or split() on the substrings and check the beginning and end of those strings to ensure that you haven't subdivided on a word you are looking for.

Consider using tools in the underlying OS - for example, if you're on *nix platform then execute a 'grep' on the string (saved as a file?) or similar tool. The work on searching efficiently has already been done by the OS command developer and has undertaken decades of continual improvement and the additional time of firing up a shell and grepping may well be outweighed by the efficiency of the tool.

This sounds like DNA sequence matching and there will be an existing body of knowledge covering the search of these sequences which may be useful to this problem for you. I'd definitely check that out.

You'd need to test these, and it will depend on whether your string is constantly changing or not. My feeling is that the building of indexes at the time of creating/updating the string is probably the right way to go.


问:
How to run a Fortran code more than 10^9 times in ftn95?
I need to run a Fortran code more than 10^9 times in ftn95. When I try to run my code more than 10^9 times it gives a error message "this loop will never be executed". In a book I read that if we declare a variable like integer(kind=16)::k then it will be able to run more than 10^9 times but in ftn95 its not working.

So if anyone know about this please tell me how to handle large integers in ftn95. Since I started to write code in fortran just before some days I don't know much about this language.

答:
Just use two nested loops. The outer loop would for example loop from i=1 to i=1000000 and the inner loop (inside the body of the outer loop) would loop from j=1 to j=10000. Et voilà, a 1010-times running thing.

```<code> DO i=1, 1000000
   DO j=1, 10000
     CALL something()
   END DO
 END DO
</code>```

The CALL something() would be done 1010-times

Notice that 1010 is not representable as a 32 bits integer. You might try to use an 8 byte integer:

```<code>INTEGER (KIND=8) :: k
DO k=1, 10000000000_8
  CALL someotherthing(k)
END DO
</code>```

The _8 suffix on the 10000000000 tells that that constant is an 8 bytes (64 bits) integer.

BTW, I never coded in Fortran in my life (I much prefer Common Lisp, Ocaml, or C++11). But I did read a few books about it. So you have to check by yourself if my code is correct.

You might need to upgrade your compiler. Did you consider using a recent version (4.9 and soon 5.0) of GCC which provides gfortran, and you might want to switch to some more recent standard (e.g. Fortran 2008 at least).

Body:
Just use two nested loops. The outer loop would for example loop from i=1 to i=1000000 and the inner loop (inside the body of the outer loop) would loop from j=1 to j=10000. Et voilà, a 1010-times running thing.

 DO i=1, 1000000
   DO j=1, 10000
     CALL something()
   END DO
 END DO

The CALL something() would be done 1010-times

Notice that 1010 is not representable as a 32 bits integer. You might try to use an 8 byte integer:

INTEGER (KIND=8) :: k
DO k=1, 10000000000_8
  CALL someotherthing(k)
END DO

The _8 suffix on the 10000000000 tells that that constant is an 8 bytes (64 bits) integer.

BTW, I never coded in Fortran in my life (I much prefer Common Lisp, Ocaml, or C++11). But I did read a few books about it. So you have to check by yourself if my code is correct.

You might need to upgrade your compiler. Did you consider using a recent version (4.9 and soon 5.0) of GCC which provides gfortran, and you might want to switch to some more recent standard (e.g. Fortran 2008 at least).


问:
Would I rather use Core Data or save files to the system?
I'm developing an iOS app which basically fetches a JSON from a remote location, parses it and instantiates classes for a couple of its elements. For some visualization, this should give you a basic idea of what my json looks like:

```<code>{
  "match": [
    {
      "id": 1,
      "date": "1960-01-01",
      "team 1": 1,
      "team 2": 2
    },
    {
      "id": 2,
      "date": "1960-01-02",
      "team 1": 1,
      "team 2": 3
    }
  ],
  "team": [
    {
      "id": 1,
      "name": "Team Red"
    },
    {
      "id": 2,
      "name": "Team Green"
    },
    {
      "id": 3,
      "name": "Team Yellow"
    }
  ]
}
</code>```

This JSON can get quite heavy, once it's completely filled. For my current demo-system I'm talking of 40k lines and ~2 MB file size, but it could easily get way beyond that with my live data. Obviously I'm not loading everything at once, but instead loading the bare basics, that include a couple of required IDs, so I can then make API requests to fetch just the IDs I need for whatever I want to do.

In Swift I've implemented each of the JSONs arrays for further processing:

```<code>class Match
  - id
  - date
  - teams

class Team
  - id
  - name
</code>```

To save traffic and not have each user to reload everything every time they start the app I want to cache the results, more specifically save them somewhere. But here is where it gets tricky, and where my question lies:

Should I rather create a CoreData representation of each element in order to save them via Core Data and query through them, or could I just save the resulting JSON to the file system, load it once the app starts and re-parse it at that point?

The main advantage of Core Data is from my understanding that I can actually query through my entries and link them, so I could more easily ask "What's the name of the teams from match #1?". Are there any other advantages for me to use Core Data, and which (dis)advantages could you see in writing the JSON file to the disk?

答:
I would highly recommend CoreData over an ad hoc solution.

1)  It's faster than loading and parsing raw NSData every time you need information.  CoreData does some caching implicitly and you only have to store the information that's relevant to you (thus smaller file size too).

2)  It is a core framework so there is a tremendous amount of support available for any issues you encounter.  Whereas, a custom file storage is going to have problems very specific to your use case and be very difficult to get help with.

3)  There are a number of CoreData 3rd party libraries that remove nearly all of the boilerplate code that it requires; almost to the point that NSManagedObject classes can be treated like any object.  (caveat: NSManagedObjectContext NSPersistentStoreCoordinator and NSManagedObjectModel still need to be set up, but there are code templates for each).

The query-able aspect is a plus and with relationships it's tremendously easy to jump from object to another related object.

Ultimately, the learning curve is steep, but I found it very worthwhile once I got a good working prototype.


问:
Should a newcomer to Perl learn both Perl 5 and 6?
I have started playing around with Perl 5 lately, and it seems very interesting. I would like to spend some time learning it more in depth when I can.

My question, since Perl 6 is slowly taking place (I believe...) and is said to break backward compatibility, is this: am I better learning Perl 5 and then Perl 6, or is learning Perl 6 directly a better time investment according to you?

If the changes from Perl 5 to 6 are making it hard to understand Perl 5, I should certainly start with Perl 5 to be able to read "old" scripts, then check Perl 6. There is also the "Perl 6 is not yet completely released" problem. I know there's an early adopter implementation for Perl 6, but if Perl 6 isn't officially released before some more years, I'll stick to 5 for now.

I would certainly like some insight on this. Feel free to discuss related stuff. My interest in scripting languages is fairly new.

Thanks!

答:
In answer to the question in the headline: yes!

As you pointed out, focusing on Perl 5 is by no means a waste of your time, since the vast majority of examples, tutorials, and applications in Perl will be from the 5 branch.

This said, you should certainly keep up with the Perl 6 project and its progress.  I took some time to learn Python 3 before it's first release, just so I understood what changes were being made and why.  This helped me when migrating from the 2.x codebase to 3.x.

I wouldn't invest too much time learning the ins/outs of Perl 6; a deep understanding of Perl 5 will serve you better for the time being.  But once it's been released (whenever that bloody is), a basic understanding of Perl 6 will help you keep moving forward.


问:
Attempting to make a Cross Domain AJAX request to a Server I don't own
I'm aware that javascript programs running in a browser are bound to the same-origin policy which prevents them from requesting services from a server that is on a different domain. What I've gathered from that is that lets say a script on www.mysite.com could not request a service from www.myothersite.com or even mysite.com.

If I run the following code from www.mysite.com:

```<code>var link = "https://www.myothersite.com/jobs-feed.xml";
$.ajax({
      type:"GET",
      url: link,
      dataType: "xml",
      success: function(text){
              alert(text);
      }
})
</code>```

It will result in this error appearing in the console:

```<code>XMLHttpRequest cannot load
www.myothersite.com/jobs-feed.xml.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'www.mysite.com' is therefore not allowed access.
</code>```

I've read that there is a number of ways to prevent this error and make a cross domain AJAX request successfully.

JSONP - This requires the data being returned in JSON format but otherwise it will allow JS programs running in browsers to request data from another server in a different domain. Something that is usually prohibited because of the same-origin policy.

Cross Origin Request -
Makes use of HTTP headers to allow for a cross-domain ajax request.  It requires CORs enabled Browser and Server.

Now here is my question, If I'd like to go with a COR request and I don't have access to the server to enable it for COR's what should I do? Should I contact the server admin and ask them to allow me to connect? I'm not very knowledgeable when it comes to Computer Networking and Servers, it's definitely not my strong point.

But from what I've gathered the error above is usually an issue with the server not allowing the requesting domain access to the data? Is that correct?

If so how can I overcome this? ideally, JSONP would be a desired option but the data is not in JSON format, in my case it's XML.

Any help would be appreciated.  I've been looking around at numerous links online and trying to get my head around CORs and cross domain ajax requests. They've definitely helped me to realize what is going wrong, but I am unsure about how I might go about enabling COR's.

If this is more of a question for SO I apologize, I'm more looking for the opinions of others in the programming community.

Thank you for any help.

答:
Fundamentally, you can't take advantage of someone else's AJAX services unless they explicitly give you permission.

There may be all sorts of sensitive information that could be exposed as a result.

My browser protects me from this by enforcing cross-origin policies.

Of course, I could defeat this by modifying my browser to ignore cross-origin concerns. But then I'm just hacking myself.


答:
What I would do:

Contact the 3rd party site, and ask if they could include you in
their CORS policy, if not then

Make sure there's no JSONP or similar "public access" point to use, if not then

Use a CORS proxy (There's quite a few out there: https://www.google.dk/search?q=free+cors+proxy&oq=free+cor - But do know that you now trust the CORS provider to be the middleman of all information), if your information is too sensitive for this then

Build or install your own CORS proxy that you trust

Title: Attempting to make a Cross Domain AJAX request to a Server I don't own

Body:
I'm aware that javascript programs running in a browser are bound to the same-origin policy which prevents them from requesting services from a server that is on a different domain. What I've gathered from that is that lets say a script on www.mysite.com could not request a service from www.myothersite.com or even mysite.com.

If I run the following code from www.mysite.com:

```<code>var link = "https://www.myothersite.com/jobs-feed.xml";
$.ajax({
      type:"GET",
      url: link,
      dataType: "xml",
      success: function(text){
              alert(text);
      }
})
</code>```

It will result in this error appearing in the console:

```<code>XMLHttpRequest cannot load
www.myothersite.com/jobs-feed.xml.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'www.mysite.com' is therefore not allowed access.
</code>```

I've read that there is a number of ways to prevent this error and make a cross domain AJAX request successfully.

JSONP - This requires the data being returned in JSON format but otherwise it will allow JS programs running in browsers to request data from another server in a different domain. Something that is usually prohibited because of the same-origin policy.

Cross Origin Request -
Makes use of HTTP headers to allow for a cross-domain ajax request.  It requires CORs enabled Browser and Server.

Now here is my question, If I'd like to go with a COR request and I don't have access to the server to enable it for COR's what should I do? Should I contact the server admin and ask them to allow me to connect? I'm not very knowledgeable when it comes to Computer Networking and Servers, it's definitely not my strong point.

But from what I've gathered the error above is usually an issue with the server not allowing the requesting domain access to the data? Is that correct?

If so how can I overcome this? ideally, JSONP would be a desired option but the data is not in JSON format, in my case it's XML.

Any help would be appreciated.  I've been looking around at numerous links online and trying to get my head around CORs and cross domain ajax requests. They've definitely helped me to realize what is going wrong, but I am unsure about how I might go about enabling COR's.

If this is more of a question for SO I apologize, I'm more looking for the opinions of others in the programming community.

Thank you for any help.


问:
What can slow a developer down?
What things tend to slow a developer down?

Please try to refrain from posting answers that:

are slow now but useful in the feature. (TDD, Refactoring, ...)

list a distraction.

答: I would say burnout.</p>

Title: What can slow a developer down?

Body: I would say burnout.


答:
Yes to Perl 5

Sure, go learn Ruby and even Python, but Perl is different.  And intelligent beyond reason.  Perl is one of those languages that you can learn things you never wanted and be glad you did and yet will have to re-read the Camel book every couple of years just so you don't fully mentally purge your perlisms.

Perl is of alien syntax, even to the most seasoned professionals.  Personally, I believe you will expand your horizons with Perl.

Perl 5 is what I consider to be Perl 1.5.  Perl 6 is what I consider Perl 2.0, maybe should even be named something different completely, so yes both 5 and 6 are worth learning in their own right and for their own merits.  Disclaimer=I'm still struggling with Perl6 myself...

Title: Should a newcomer to Perl learn both Perl 5 and 6?

Body:
I have started playing around with Perl 5 lately, and it seems very interesting. I would like to spend some time learning it more in depth when I can.

My question, since Perl 6 is slowly taking place (I believe...) and is said to break backward compatibility, is this: am I better learning Perl 5 and then Perl 6, or is learning Perl 6 directly a better time investment according to you?

If the changes from Perl 5 to 6 are making it hard to understand Perl 5, I should certainly start with Perl 5 to be able to read "old" scripts, then check Perl 6. There is also the "Perl 6 is not yet completely released" problem. I know there's an early adopter implementation for Perl 6, but if Perl 6 isn't officially released before some more years, I'll stick to 5 for now.

I would certainly like some insight on this. Feel free to discuss related stuff. My interest in scripting languages is fairly new.

Thanks!


答:
AFAIK, there's not much difference between the two. Consider that a C++ class is really a block of data with a special, hidden data structure at the beginning called a vtable. This vtable contains all the pointers to the methods contained within the class.

Now you see its not much different from a javascript prototype - which is a bunch of pointers to functions that comprise the js class.

However, in practice the difference is huge. The C++ one restricts you to not being able to dynamically add, remove or replace those function pointers. This means the compiler knows in advance what they are, and so it can optimise them away completely. It also means it knows exactly where the functions are and can even inline the methods if it thinks its worth it (for many property methods, getID() { return id;} for example, this makes perfect sense).

So in a C++ binary, you often get code that is simply linear steps of program instructions. The CPU will load chunks of code into the cache and execute them as fast as it can. This is what makes modern CPUs perform.

Where CPUs stop performing is if when they have to stop and load a chunk of code from somewhere else. So, in the case of a javascript program where the functions are not known at compile time, and could be anywhere, the compiled program code will instead of jump instructions to the method location. If you're unlucky this can mean the CPU has to stop what its doing, load a new block of code containing the method, execute it, and the return where it came from. You can see this is way less efficient than simply reading 'id' in my simple example.

Note that this isn't a C++ thing. Very early C+ compilers were written as translators to C, so a C++ class would be turned into C code that had a struct and a set of function pointers which would then be compiled by a C compiler.

I've glossed over many complications (including some C++ polymorphism) and optimisations and 'workarounds' CPU and compilers can do to make this work better, but you get the fundamental idea behind it, mainly that compile time processing is faster than runtime processing.

If you want to design a fast language, make it so as much information can be calculated in the compile stage so it doesn't have to be done at runtime. You could design a prototype-based class system and if you could parse the entire program and figure out beforehand where each function was, then you could compile it to machine code that performed as well as a C++ program. The problem is that such a parsing might be more complex than running it! (note that some C++ compilers have a run-time optimisation mechanism where runtime info is calculated and used to feed back into subsequent compiles!)

Title: Is prototypal inheritance inherently slower?

Body:
I see Javascript 6 will add traditional class based inheritance, and one argument I hear is that classes are inherently much faster than prototypes because they can be optimized away by the compiler when doing (JIT) compilation to native code or to bytecode. That sort of makes sense to my mind, but I'm not nearly an advanced enough programmer to really understand this stuff.

The argument I always saw for prototypal inheritance (PI) was that it conserves memory, which is mostly a completely moot point these days. Personally, I like PI and always felt it "makes sense" in a dynamic language; like it is a luxury you can just as well afford if you already settled for the performance limitations of an interpreted dynamic language.

In C++, classes makes sense because of the limitations that comes with the C++ philosophy that everything takes a back seat to maximum possibility for performance.

Of course you can have PI in C++ and there is a well known design pattern for that, but I'm talking about built-in inheritance in a dynamic language.

If one was looking at the fastest possible implementation of prototypal inheritance in a fictional dynamic language, what would necessarily be the drawbacks with regards to performance vis-à-vis traditional classes?

What if you add the feature to the fictional language that you can specify that some objects are "final" and their prototype chain cannot be changed at runtime? (Coexisting with traditional PI) Also add optional static typing or type hinting if that helps the prototypal language.

Since this might be considered a bit of a vague question, I'm adding:

I guess I'm looking for the thoughts on the subject from people who are more clever and more interested in language theory and/or compiler/interpreter writing than me. Hope that is still an ok question.

This is not about Javascript 6 at all, I just brought it up because Javascript is the most successful prototypal language and it is interesting that they are adding native classes even though Javascript seemed to be doing fine without them (both popularity wise and having some jaw-dropping benchmark improvements in the last few years). I'm also not saying that I believe or think that Javascript is slow.

Really, I'm more interested in learning more about programming languages, possibly with the goal of some day constructing my own dynamic language.

ContentLicense: CC BY-SA 4.0


问:
Is Doctype needed for HTML5 documents
Recently I had a job interview and one of the questions was "Is doctype needed for HTML 5 documents?". I've answered "no" but have a feeling that I might be wrong. From the w3 it looks like it is absolutely required, but if I type a simple HTML like

```<code><html>
    <body>
        <input type="color" disabled/>
    </body>
</html>
</code>```

save it as HTML and try to open in Chrome - it would work perfectly well, with a new color input (disabled). That input is HTML5 as well as attribute.

So the question is - do I need to specify doctype or not? What would be the correct answer for the interview?

答:
I, too, would have answer "no" (wrongly, as it happens).

However, http://www.w3.org/TR/html5/syntax.html#the-doctype  says :

8.1.1 The DOCTYPE

A DOCTYPE is a required preamble.

DOCTYPEs are required for legacy reasons. When omitted, browsers tend
  to use a different rendering mode that is incompatible with some
  specifications. Including the DOCTYPE in a document ensures that the
  browser makes a best-effort attempt at following the relevant
  specifications.

BTW, G.I.Y.F

Title: Is Doctype needed for HTML5 documents


问:
C-library - newbie guide
I have been asked to provide a C-library of my code (which I have written in a high-level language). I will hire a programmer to implement my code in C. I would like a short introduction to what a "C-library" means before I start this process.

Is it correct that I can provide a C-library and that the people who use it will not be able to see the actual source code?

I understand that the library will inlude .h-files which determine how the people that I give the code to will interact with the library. Can I have just one of these files so that the internal structure is hidden?

In this situation, I assume that the library should be dynamically linked. Why is that?

答:
Yes

Yes

It doesn't have to be dynamically linked.

In detail: When creating a library (doesn't have to be in C, but I assume this means it needs to expose its functionality in the form of exported C functions) then the source code is turned into the equivalent machine instructions. While a skilled hacker could turn this machine code back into a higher level language, its really awkward and the resulting decompilation is really difficult for a human to understand. So you're pretty much safe from anyone stealing your algorithms, unless they're really worth the effort.

In order to use a library like this, you need a way to tell programs that link with the lib what is inside it, this is typically done with a header file. A single header containing only those exported functions is fine. The only reason people use multiple headers is because they don't want the trouble of maintaining duplicates and so simply ship the headers used in development.

The choice of dynamic or static is up to you. A dynamic library can be replaced with a newer version easily. This is the most common reason to ship in this format.

Title: C-library - newbie guide


问:
If you take a year or two out from being a developer, is it really that hard to get back into it?
I've been working as a developer for about 3 years now (straight from uni), I'm wondering, if I take a year or two out would it be impossible to get back into the industry?

I didn't get the gap year thing out of my system after uni, and I'm thinking that I should probably do it before I hit 30 (24 now), my main concern is that if I leave the industry now, I might not get back into it at all and end up working some dead end job.

The way I see things is, that general concepts / design patterns etc remain similar over the years, and it is mostly coding syntax / actual implementation that evolves, so it shouldn't move on dramatically.

Also, women developers (yes there are some out there!) take years out to have kids and still carry on with their career afterwards, so it can't be impossible.

Ultimatum : Would taking a year or two out destroy the (small) career I've built up so far?

答: The only problem is you may not want to get back anymore, otherwise it should not be harder than you learning programming for the first time.</p>


答:
When you want to write a w3c standard-conformant HTML5 document, then <!DOCTYPE html> is required.

But in practice you don't always need a doctype because any common web browser will render your document regardless. However, some browsers will then use a legacy mode in which some features are not interpreted correctly and instead in a way an earlier version of the browser handled it (most of them layout-related).

Which answer is right for this interview? That depends on the mentality of the person who interviewed you. In a job interview it doesn't matter if you are right or wrong. It only matters what impression you make on the interviewer.

Title: Is Doctype needed for HTML5 documents

Body:
Recently I had a job interview and one of the questions was "Is doctype needed for HTML 5 documents?". I've answered "no" but have a feeling that I might be wrong. From the w3 it looks like it is absolutely required, but if I type a simple HTML like

```<code><html>
    <body>
        <input type="color" disabled/>
    </body>
</html>
</code>```

save it as HTML and try to open in Chrome - it would work perfectly well, with a new color input (disabled). That input is HTML5 as well as attribute.

So the question is - do I need to specify doctype or not? What would be the correct answer for the interview?


问:
Beginner's UnitTests for MVP Presenter class
In my application, I have a user settings form with roughly 20 checkboxes and a few other controls. The checked state, enabled state and texts of these controls are bound to about 60 properties of the presenter class, which is drawing the information from the model class with the business logic.

Now I wrote a unit test method "TestLoadData", where the LoadData method of the presenter class is called (which itself calls the LoadData method in the model, which then notifies the presenter).

After this, I have 60 assertions on the properties of the presenter class, followed by 40 assertions on the properties of the model class (20 "enabled"-properties are presenter only), because I want to check if every value is correctly loaded.

So I have a real big (100-lines) TestMethod, which I think is very bad test design.

(All numbers are approximated)

Is it better to write one small 5 lines test-method for each property?
How much worse is it to have this big test method?

Does it really make a difference?
Am I perhaps only too lazy to write 60 small test methods?

Or should the settings form depend on more than one presenter class,
each holding only small parts of the 60 properties?

答:
If I were you I would write small tests for each, because then it is much more eye catching what went wrong. While with one big test you only get 1 bit of information when running the test (either everything is ok, or something is bad), if you have a test for each property you will see which one (ore ones) are broken.

If the loading you make needs significant initialization, then put that into a test-init method. Unit test frameworks usually let you define a method that runs before every test method in a class.


答:
The correct answer would be "It depends".

A DOCTYPE is optional for HTML5 documents in the XHTML syntax (i.e., XHTML5 documents):

XML documents may contain a DOCTYPE if desired, but this is not required to conform to this specification.

A DOCTYPE is required for HTML5 documents in the HTML syntax:

Documents must consist of the following parts, in the given order:

[…]

3. A DOCTYPE.

Exceptions

HTML5 documents in the srcdoc attribute of an iframe element don’t need a DOCTYPE:

2. Optionally, a DOCTYPE.

Title: Is Doctype needed for HTML5 documents


答:
There's really two things to understand:

prototypal inheritance has nothing to do with performance at all. The performance issues come from runtime changes to the inheritance structure.

prototypal inheritance (and flexible object structures) are not so much inherently slower, as they are harder to optimize.

To illustrate the first claim, Ruby would be a flagship example of class based objects being abysmally slow. The problem generally persists throughout Smalltalk-like langauges, e.g. Objective-C, that employ message passing for method calls. The Objective-C runtime uses some nifty method caching to tackle the issue, but it did take them a while to get that far.

What makes method calls cheap is that the compiler (or JIT or runtime even) has some definite knowledge about the structure of an object. Be that explicitly given in terms of language features, or implicitly inferred from static analysis, the knowledge exists and the compiler can use that to optimize.

Now when the structure can change at runtime, this makes things a little tricky, because you need good heuristics to detect which portions of the code are worth being optimized at all (you want a good ratio between the frequency of the code being run to the frequency at which it changes and the cost of optimizing it), to get the best overall runtime characteristics.

So what is the point of classes in dynamic languages? Well, there must be one, because there's numerous JavaScript class systems (like that of Ext). Sure, familiarity for programmers used to classes is one reason. But the real benefit comes from helping to ensure explicit definitions of object types. Such a class definition is one (albeit complex) statement. With vanilla JavaScript constructors, you have a whole bunch of statements, that are grouped together, if you're lucky. The class structure is really just a side effect of imperative code, if you will. Class declarations are unsurprisingly meant to facilitate a more declarative style.

It's worth to note that the Self language that really made prototypal inheritance explicit (although it's really straight forward to achieve in a language with message passing), was created for an environment where you programmed a fully interactive system while it was running. You could actually see an object on screen. This allowed for a clean declaration that was still modifiable at runtime, because the declaration and the result were so intimately coupled. Without such a coupling, fiddling with object structure at runtime can quickly become an unintelligible mess that is really hard to fit in your brain, let alone reason about.

You can pretty much get prototypal inheritance if you have good support for delegation. You just delegate all unimplemented calls to an object that you consider a prototype and you're done. It's more flexible. However it's equally harder to optimize.


问:
Is self referencing tables a good idea for geographical data?
I am creating a design for different Geographical types where each type is just a little "place holder" in over all heirarchy.

One example is

Zip code Belongs to Territory Belongs to District

Other would be

Zip code belongs to State belongs to Some Region

We have two schools of thought one is that:

```<code>  1  create different tables like Zipcode, Territory, Regions etc
</code>```

other is that just create one table which is called Geographical
  Entity and then everything is just a type so you can assign a Type Id
  to each geographical entity and self reference the table

Now, if I go by design #1 then I don't have to worry about any non traditional decision. I can create one class in OO space and then map to each table. Also, imposing business level rules such as Territory can do such and such things but Distrtict can not. And also things like a Territory can belong to District but District can not belong to Territory are all contained in design itself.

However, If I go to Design #2. It is extensible such that if we have a new Geographical type called "XYZ" then we do not need to add a new table for that. We can simply add  a new type into Geography type and it would be addressed.

I find Design #2 extensible but unnecessarily complex. Am I right thinking it that way? Or that's the way to go?

答:
There are at least two aspects of database design that your question touches on.

The first is the issue of class/subclass design.  What is the best design for classes and subclasses when designing a relational database?  (This issue is also known as types and subtypes or generalization and specialization).

The second is the issue of representing a hierarchy in relational data.  What is the best design to make insertions quick and easy?  What is the best design to make queries quick and easy, especially searching the subtree.

These two sound like the same issue, but they are not.  There are situations where subclasses arise, but there is no hierarchy (except for the inheritance hierarchy).  There are other situations that arise where there is a hierarchy, but all the participants are of one class, as far as the designer is concerned.

With regard to classes and subclasses, I recommend you look into Martin Fowler's treatment of "table inheritance", particularly "single table inheritance" and "class table inheritance".  There are benefits and drawbacks to each choice.

With regard to representing a hierarchy, I recommend you look into "adjacency list model" and "nested set model".  Adjacency list is so simple that most newbies learn the technique without ever learning its name.  Nested sets is less well known, and is only useful under some special circumstances.  It does, however, permit traversing a subtree without using recursion.

I'm not going to go into more detail here, because it's not clear whether you are interested in both of these issues or just one of them.