问:
developing an android app that include a C++ toolkit
I'm a java developer and I want to develop an android app that capture a photo and extract its bags of visual words. To extract those bags of words I use the TOP-SURF toolkit which is written in C++

I'm new to C++ development and I want to know how to develop an android app that use this toolkit

I read about the NDK. It's the solution?

答:
The problem with the NDK (the main reason why the official docs say not to use it solely as a performance boost) has to do with the fact that whatever C/C++ code you write for your Android app, it will still, at some point, be called from Java code via JNI. And JNI calls are slow.

That being said, you can avoid granular JNI calls, and get good performance in certain situations. The best thing to do is to do a small Proof of Concept for your app.

Here's what I'd do:

Install the great Eclipse Sequoyah plugin in your Eclipse (which should already have the Android Eclipse plugin)

Get the source code for your library. Either build it as an Android library and add that to your project (you can do this using the NDK) or just add the source code of that library to your App's project

Try to write a Native Activity that does some simple API calls towards your library. Once that's working, do some benchmarks to see if you can get user friendly response times for some of the usual operations you intend to implement

Avoid the Android Emulator, it's simply terrible. Use a real Android device.


问:
When should one use composition instead of re-writing the functionality?
Say, I have a class A which has methods m1,m2,m3,m4,m5.... m100.

I am making another simpler class B and I require only m2,m3 and m5 in B.

Should I be ideally using compositions and put a reference of A inside of B and just delegate the functionality ?

or I should just re-write[copy=paste] those 2-3 methods out of class A ?

答:
Ideally, don't cut and paste code.  Duplicating functionality inevitably leads to errors in one and a slow divergence of hacks (need to make an 'easy' change in one leading to an 'ugly' change in the other).  The key to this is to refactor it in such a way that the ugliness in the original class can be hidden away as best as possible, and a new layer of code in front of the ugly leads to 'abandon in place' of parts of the ugly.

The ultimate goal, despite the 'legacy' nature of A is to dry up the code so that B and A share a common base class. Even if you can't get there, that is the ultimate destination.

The first step in this process is to make that abstract class that implements just the subset of common methods to B and A.

Once you have this, you make a pair of implementation classes - B and A'.  A' is an anti-corruption layer / wrapper that wraps around A and passes through the method calls as appopriate.

(This is where it gets a little ugly)

Without knowing if the 5 methods (that are part of the abstract class) change the state of A in a way used by the other 20 methods it can be difficult to consider the proper design.

Lets call all the methods a .. z. The methods a, e, i, o, and u are the ones that are to be implemented in class B.  If, in A, the method a modified state used by b and e - then it is probably best that a and e are both pass through.

On the other hand, if aeiou do not change any state used by the other methods, they can be completely encapsulated within the abstract class.

Now, if you can make a change to the legacy code - its a rather minor one - make an interface (iA)that defines every method in A that A implements and A' implements. One can then refactor every passing around of A to iA.

Then, you can change the iA foo = new A() to iA foo = new A'(new A())

Now, you've got a class B that extends the abstract class, A' that extends the abstract class and implements iA which provides identical functionality to A.  The code for aeiou is as isolated from A as possible so that changes to it in the abstract class make the appropriate changes to both B and A'.

ContentLicense: CC BY-SA 3.0


问:
How do I improve my coding skills?
Here's a bit information about me, before starting with the question.

I am a Computer Science Undergraduate, Java being my primary coding language.

The basic problem in my University are the teaching standards. No one is concerned about teaching coding knowledge to students, rather than just theoretical knowledge.

The effect being, most of my fellow college mates don't understand programming at all.

Even I haven't been able to come out of the traditional programming environment, which limits my coding to an extent.

What are the possible ways by which I can develop and expand my programming/coding skills.

Also, can you suggest the sources for the same?

Edited:
Sources suggesting development of coding skills.

答:
I can only suggest the thing what has worked for me. I had dream to learn programming language and create chess engine with it. I have left spend time on books, articles and small samples. So i decided to check real projects which has better documentation for developer.I have chosen one and started to read the project day by day. Don't think that passing days waste of time while reading. It is much better than spend time reading on articles and books. You will highly encounter many thing which is not clear at first sight but day by day this will change if you try research patiently. Don't expect to understand everything in a week.You have to hold your low Self-Esteem when you don't understand some things.Just try to discover how this *ucking awesome thing is working and enjoy.

Choose an existing project which you have passion for it.Start to read codes, debug it and try to understand how the things works everyday. Also use the project for yourself. Then start to add some features which you want. Even try to write same or similar application.

ContentLicense: CC BY-SA 2.5

Title: How do I improve my coding skills?


问:
Web App vs. Desktop App Regarding Deployment
I'm taking on an opportunity for a local business to develop a small, simple timesheet manager (they still record time by hand) and am currently in the planning phases. It will include basic functionality such as managing employee information, logging time worked on a weekly basis for payroll, and generating reports for administration.

I've developed Windows Forms applications for a while and am fairly confident my coding skills are where they need to be for this project, but I'm fairly new to both ASP.NET and the concept of developing a full desktop system as opposed to individual applications, so my questions will probably sound very elementary. I'm mainly struggling with understanding how to choose between ASP.NET and Windows Forms with regard to deployment down the road. Hopefully you guys can offer some insight.

I'm still a bit fuzzy on how database/web application hosting works. If I develop for desktop, will the database need a physical server if more than one workstation/client wants access? Could one of the workstations act as a server (there are under 20-30 employees at any given time, so data size shouldn't be an issue)? Would an ASP.NET system require purchasing a web host? Or, can the web files be hosted on a local computer/server with IIS as an intranet? Can virtualization fit somewhere in all this?

I guess it boils down to: Can I get them up and going for free, or is a server/hosting cost implied either way?

Thanks in advance!

答:
If your WEB APP is going to run in Explorer, Safari, Chrome, Firefox from a Pc, Mac, Android smartphone, Blackberry and Iphone.... do a WEB APP

If not, a simple and fast Desktop app will do the work...

By the way do not confuse WEB APP with "Explorer APP".


问:
how to create a data model for the following problem
How to tackle 2-D and 3-D space in data ? lets say you are working on a power grid problem. You need to represent Towers; transmission lines; transformers and every thing else in a 2-D space. How would you design a Data Model for this 2-D space ? I can use a

```<code>class tower  {
int x_cor;
int y_cor;
string power_properties
}
</code>```

But how to represent the ... say map of the power grid itself ?
is there some standard solution to this ? some logical template people follow here ?

i want to be able to slice this map by shape or area etc; i should be able to compose small maps to make  a large one ..  So what is the solution here ??
By the way i am not working on a power-grid project (LOL) so please keep answers generic ..

P.S. non-noobs please help me make the question better.

答:
Simple Features Data Model is both an OGC and ISO standard (ISO 19125) that specifies a common storage model of mostly two-dimensional geographical data (point, line, polygon, multi-point, multi-line, etc.).

Most of the spatial extensions for SQL (Oracle Spatial, Postgis, MySQL Spatial Extensions, etc...) implement to varying degree this Standard.


问:
Is it poor practice to name a property/member the same as the declaring type in C#?
For instance, a class like:

```<code>class Dog { } //never mind that there's nothing in it...
</code>```

and then a property like:

```<code>Dog Dog { get; set; }
</code>```

I've been told that if I can't come up with a more imaginative name for it, then I must use:

```<code>Dog DogObject { get; set; }
</code>```

Any thoughts on how to name these better?

答:
It's perfectly fine to call it Dog and this is in fact what Microsoft recommends in the Framework naming guidelines:

CONSIDER giving a property the same name as its type.

For example, the following property correctly gets and sets an enum value named Color, so the property is named Color.

And here is the example they use in the above guide:

```<code>public enum Color {...}
public class Control {
    public Color Color { get {...} set {...} }
}
</code>```

Body:
It's perfectly fine to call it Dog and this is in fact what Microsoft recommends in the Framework naming guidelines:

CONSIDER giving a property the same name as its type.

For example, the following property correctly gets and sets an enum value named Color, so the property is named Color.

And here is the example they use in the above guide:

public enum Color {...}
public class Control {
    public Color Color { get {...} set {...} }
}


问:
Icons for my program
I'm developing a simple text editor, just to practice a little bit.

I'm developing it under Linux but since I am using Qt as GUI Framework I can easily compile this on a Windows or Mac with the same code (in other words, it's cross-platform).

Qt offers a function QIcon::fromTheme(). This function allows me to get the standard Icon for e.g. the New Document Icon and use it for whatever I want. These Icons are sadly only available on Linux. However, I wrote a simple function to save these icons as PNG files in different formats (16x16 up to 1024x1024) so that I can use these on a Windows as well.

Now my question, is it even legal to use these images on windows as well? And would you find it strange if such icons appear in a windows program? Because Linux has a whole different style than windows... Same thing with OS X'.

The New Document Icon for example would look similar to this:

http://findicons.com/files/icons/2455/web_icons/48/empty_document_new.png

答:
Icons, like all other products of human creative effort, are automatically copyrighted to their authors. By default, you have no right to redistribute them. Whether or not you may reuse or or sell them with your program depends entirely on the license under which they are available.

Being the standard icon for a particular platform has no bearing on that; the image is protected under copyright as this particular drawing of a document page. This means that you could freely draw your own representation of an empty page and use that, but to reuse the actual image used elsewhere, you must find out under what conditions the entire desktop environment you're using is licensed to you, and whether this covers the bundled images or not.

Title: Icons for my program


答: It depends on the licensing for your theme.  A lot of them are Creative Commons Attribution-NonCommercial-ShareAlike, but some are GPL, or even commercial.  I highly doubt any of the licenses limit you to one operating system, but if you're redistributing your application to people outside your organization, you'll have to deal with the redistribution terms of the specific license.  The default theme probably follows the same license as the rest of Qt.</p>

Title: Icons for my program

Body:
I'm developing a simple text editor, just to practice a little bit.

I'm developing it under Linux but since I am using Qt as GUI Framework I can easily compile this on a Windows or Mac with the same code (in other words, it's cross-platform).

Qt offers a function QIcon::fromTheme(). This function allows me to get the standard Icon for e.g. the New Document Icon and use it for whatever I want. These Icons are sadly only available on Linux. However, I wrote a simple function to save these icons as PNG files in different formats (16x16 up to 1024x1024) so that I can use these on a Windows as well.

Now my question, is it even legal to use these images on windows as well? And would you find it strange if such icons appear in a windows program? Because Linux has a whole different style than windows... Same thing with OS X'.

The New Document Icon for example would look similar to this:

http://findicons.com/files/icons/2455/web_icons/48/empty_document_new.png


答:
I would say that you should try and either

A) Come up with a consistent look and feel for your application over the whole set of computing devices you support to gather a brand awareness.

B) Stick with the look and feel of each environment so that your app looks as polished and "in-place" as possible.

Title: Icons for my program


问:
What language has integrated "list insertion" as part of code *syntax*?
Many programming languages permit natural manipulation of strings, and some languages permit the manipulations of lists too.

More often then not (always?), these operations are done as procedure calls, or as member functions.

Many programming languages do implement in syntax the fairly typical set {prepend, replace, append} on lists (and/or strings).

I would like to know if there as/was a programming language that has a syntax that minimises/rationalises/orthogonalises the insertion syntax of items into a list by syntax design?

Python - as a simple example - has only: https://stackoverflow.com/questions/18033339/python-insert-operation-on-list

```<code>mylist.insert(10,'5')
</code>```

Note: In python list insertion is implemented as a member function.

But: Python does have some syntactic sugar for removing elements from a list: e.g.

```<code>del mylist[4:7]
</code>```

I like to know of any languages actually try to integrate (or have strategy) for list insertion as part of the syntax?

An example of insertion by construction: Here is some code from a fairly typical "Brand X" language, demonstrating typical prepend/replace/append operations {or operators, vis-à-vis syntatic sugar}, notice there is no obvious syntax for {in place} inserting (or removing) from the middle of a list.  {It has to be done "by construction", or by calling a procedure}

```<code># Demonstration of prefix, replace and append operations to a string {or list} #
string s := "23XX78";
"1"    +=: s;    # Prefix a char "1" to the string "in place" #
s[4:5] := "46";  # In place replace a char at pos 2 in a string #
s      +:= "9!"; # Append a string "9!" char to the string #
#
  Although inserting into a list is intuitive,
  * it is by construction (hence prone to typos/index-flips)
  * it is not "in place"
  e.g. ...
#
s:=s[:4]+"5"+s[5:];

print(s)
</code>```

Output: "123456789!"

Another example for strings:

```<code>s[:4]+="5"
</code>```

答:
F# provides a :: operator that is used both for construction and destructuring:

```<code>(* this will append 1 as a head to a list containing 2 and 3 *)
let lst = 1 :: [2; 3]
> [1; 2; 3]

(* this will use pattern matching to destructure the list and return
   the sum of first two elements; if not possible, then the first element; otherwise 0 *)
let func = function | a::b::_ -> a + b | h :: _ -> h | _ -> 0
func lst
> 3
</code>```

There's also a @ operator for concatenating lists:

```<code>(* this will return a concatenated lists *)
let longer = lst @ lst
> [1; 2; 3; 1; 2; 3]
</code>```

Using those two, you can insert an element in the 'middle' of the list like this:

```<code>let a, b = [1; 2], [4; 5; 6]
let c = a @ (3 :: b)
> [1; 2; 3; 4; 5]
</code>```

We're talking regular singly linked lists here, however, so no indexing into the list. You have to split it by other means (function calls) if you want the element inserted at an arbitrary position.

The same applies to other ML family members: SML, OCaml, Scala and also Haskell (it uses : and ++ respectively, though).

Body:
F# provides a :: operator that is used both for construction and destructuring:

(* this will append 1 as a head to a list containing 2 and 3 *)
let lst = 1 :: [2; 3]
> [1; 2; 3]

(* this will use pattern matching to destructure the list and return
   the sum of first two elements; if not possible, then the first element; otherwise 0 *)
let func = function | a::b::_ -> a + b | h :: _ -> h | _ -> 0
func lst
> 3

There's also a @ operator for concatenating lists:

(* this will return a concatenated lists *)
let longer = lst @ lst
> [1; 2; 3; 1; 2; 3]

Using those two, you can insert an element in the 'middle' of the list like this:

let a, b = [1; 2], [4; 5; 6]
let c = a @ (3 :: b)
> [1; 2; 3; 4; 5]

We're talking regular singly linked lists here, however, so no indexing into the list. You have to split it by other means (function calls) if you want the element inserted at an arbitrary position.

The same applies to other ML family members: SML, OCaml, Scala and also Haskell (it uses : and ++ respectively, though).


问:
What's the relationship between meta-circular interpreters, virtual machines and increased performance?
I've read about meta-circular interpreters on the web (including SICP) and I've looked into the code of some implementations (such as PyPy and Narcissus).

I've read quite a bit about two languages which made great use of metacircular evaluation, Lisp and Smalltalk. As far as I understood Lisp was the first self-hosting compiler and Smalltalk had the first "true" JIT implementation.

One thing I've not fully understood is how can those interpreters/compilers achieve so good performance or, in other words, why is PyPy faster than CPython? Is it because of reflection?

And also, my Smalltalk research led me to believe that there's a relationship between JIT, virtual machines and reflection. Virtual Machines such as the JVM and CLR allow a great deal of type introspection and I believe they make great use it in Just-in-Time (and AOT, I suppose?) compilation. But as far as I know, Virtual Machines are kind of like CPUs, in that they have a basic instruction set. Are Virtual Machines efficient because they include type and reference information, which would allow language-agnostic reflection?

I ask this because many both interpreted and compiled languages are now using bytecode as a target (LLVM, Parrot, YARV, CPython) and traditional VMs like JVM and CLR have gained incredible boosts in performance. I've been told that it's about JIT, but as far as I know JIT is nothing new since Smalltalk and Sun's own Self have been doing it before Java. I don't remember VMs performing particularly well in the past, there weren't many non-academic ones outside of JVM and .NET and their performance was definitely not as good as it is now (I wish I could source this claim but I speak from personal experience).

Then all of a sudden, in the late 2000s something changed and a lot of VMs started to pop up even for established languages, and with very good performance. Was something discovered about the JIT implementation that allowed pretty much every modern VM to skyrocket in performance? A paper or a book maybe?

答: 2 out of 3: There is no relationship between "meta-circular" and "high-performance" language runtimes. Meta-circular runtimes which achieve high performance do so by JIT-compiling to native code, and running the native code. There is no reason why your hi-perf Python runtime has to be written in Python, or Lisp in Lisp, etc. But if you think that your language is more powerful, expressive, etc. than the others, why not use it to write its own runtime? Or if you don't think that your language is somehow "better" than others, why are you going to the trouble to implement it at all?


问:
Is there a data structure for this type of list/map?
Perhaps there's a name for what I want, but I'm not aware of it. I need something similar to a LinkedHashMap in Java, but where it returns the 'previous' value if there's no value at the specified key.

That is, I have a list of objects stored by an integer key (which is in units of time in my case):

```<code>; key->value
10->A
15->B
20->C
</code>```

So, if I were to query for a value for key 0-9, it would return null. The special part is if I queried for something 10 <= i <= 14 it would return A. Or, for i >= 20, it would return C.

Is there a data structure for this?

答:
You are looking for a NavigableMap.  This is a subtype of SortedMap that also has some functions available besides the nature of the map being sorted.  Note that the Navigable map "is intended to supersede the SortedMap interface." (Java SE 6 Collections Framework Enhancements).  Everything that currently implements SortedMap implements NavigableMap and this is likely to remain true.

In particular, the method floorKey(K key) which "returns the greatest key less than or equal to the given key, or null if there is no such key.

This is just one of many methods that allow you to get specific keys or submaps of the map.

ceiling / floor (the entry that is higher / lower than the parameter)

access of keys or map in descending order

head / tail (the entries less / greater than a given key)

higher / lower (the next key that is higher or lower than parameter)

submap (given two keys, return the map that is between the two keys)

Java has two implementations of the NavigableMap - the TreeMap and the ConcurrentSkipListMap.

If you look at the idea/implementation of a skip list you will see why it would work really well with such a structure and its queries.


问:
Making some methods mostly contain method calls, while others doing "the lowest level" work
So I thought about this, and I don't know if it's included or not in any methodology.

I think the advantages of this coding style is that, at the lowest level, the code is extremely testable, and then the integration tests should also be very easy to build.

I also think this would make the code more readable and the UML would be understood faster.

So here's my example:

```<code>class CoolObject{
var member1; //needed for instance in lifecycle events
var member2; //same comment

   //This method could be for instance an event handler
   //Notice this contains only assignments and method calls. No library calls or lower level stuff
   [public] method high_level(params...){
    var local_var1;
    var local_var2;
    local_var1 = call method lower_level1(param1,param2);
    local_var2 = call method lower_level2(param1, local_var1);
    member1 = call method lower_level3(local_var2);
   }

   //Notice this contains only library calls and lower level processing
   [private] method lower_level1(param1, param2){
    return param1 + param2 + libraryXXY123.function142(current_date);
   }

   //Notice this contains only library calls and lower level processing
   [private] method lower_level2(param1, param2){
     var return_value;
     loop over param2{
        if(condition){
           add param1 to return_value;
        }
     }
     return return_value + libraryASDF123.function3132(system_user);

   }

}
</code>```

Please note that this is not written in any specific language, as I only wanted to illustrate the concept.

So do you know some methodologies that use this, or that warn against it?
Please elaborate on the answer, as I think this would be a good idea, and would like this either confirmed, or the opposite.

答:
It is called "layered design".

The idea is that your system design is separated into "layers".  Each layer provides an interface for the layer above it.  Each layer calls only methods from the layer immediately below it.

The canonical reference to this approach is Dijkstra's paper "The Structure of the T.H.E. Multiprogramming System".  It is required reading in this racket.


问:
Difficulties With TDD & Refactoring (Or - Why Is This More Painful Than It Should Be?)
I wanted to teach myself to use the TDD approach and I had a project I had been wanting to work on for a while. It wasn't a large project so I thought it would be a good candidate for TDD. However, I feel like something has gone awry. Let me give an example:

At a high level my project is an add-in for Microsoft OneNote that will allow me to track and manage Projects more easily. Now, I also wanted to keep the business logic for this as decoupled from OneNote as possible in-case I decided to build my own custom storage and back end some day.

First I started with a basic plain words acceptance test to outline what I wanted my first feature to do. It looks something like this (dumbing it down for brevity):

User clicks create project

User types in title of project

Verify that the project is created correctly

Skipping over the UI stuff and some intermediary planning I come to my first unit test:

```<code>[TestMethod]
public void CreateProject_BasicParameters_ProjectIsValid()
{
    var testController = new Controller();
    Project newProject = testController(A.Dummy<String>());
    Assert.IsNotNull(newProject);
}
</code>```

So far so good. Red, green, refactor, etc. Alright now it needs actually save stuff. Cutting out some steps here I wind up with this.

```<code>[TestMethod]
public void CreateProject_BasicParameters_ProjectMatchesExpected()
{
    var fakeDataStore = A.Fake<IDataStore>();
    var testController = new Controller(fakeDataStore);
    String expectedTitle = fixture.Create<String>("Title");
    Project newProject = testController(expectedTitle);

    Assert.AreEqual(expectedTitle, newProject.Title);
}
</code>```

I'm still feeling good at this point. I don't have a concrete data store yet, but I created the interface how I anticipated it would look.

I'm going to skip a few steps here because this post is getting long enough, but I followed similar processes and eventually I get to this test for my data store:

```<code>[TestMethod]
public void SaveNewProject_BasicParameters_RequestsNewPage()
{
    /* snip init code */
    testDataStore.SaveNewProject(A.Dummy<IProject>());
    A.CallTo(() => oneNoteInterop.SavePage()).MustHaveHappened();
}
</code>```

This was good until I tried to implement it:

```<code>public String SaveNewProject(IProject project)
{
    Page projectPage = oneNoteInterop.CreatePage(...);
}
</code>```

And THERE is the problem right where the "..." is. I realize now at THIS point that CreatePage requires a section ID. I didn't realize this back when I was thinking at the controller level because I was only concerned with testing the bits relevant to the controller. However, all the way down here I now realize I have to ask the user for a location to store the project. Now I have to add a location ID to the datastore, then add one to the project, then add one to the controller, and add it to ALL of the tests that are already written for all of those things. It has become tedious very quickly and I can't help but feel like I would have caught this quicker if I sketched out the design ahead of time rather than letting it be designed during the TDD process.

Can someone please explain to me if I've done something wrong in this process? Is there anyway this kind of refactoring can be avoided? Or is this common? If it is common are there any ways of making it more painless?

Thanks all!

答:
https://frontendmasters.com/courses/angularjs-and-code-testability/  From about 2:22:00 to the end (about 1 hour).  Sorry that the video isn't free, but I haven't found a free one that explains it so well.

One of the best presentations of writing testable code is in this lesson.  It's a AngularJS class, but the testing part is all around java code, primarily because what he is talking about has nothing to do with the language, and everything to do with writing good testable code in the first place.

The magic is in writing testable code, rather than writing code tests.  It's not about writing code that pretends to be a user.

He also spends some time writing the spec in the form of test assertions.


问:
API Caching Layer
Primer: We have a mobile app being served by an API (written in PHP). The main point of the app is to display products from a large items table in the database, in a multitude of different configurations. Categories, suggested items, user compiled feeds, "similar to" feeds. Basically most, if not all of the display data comes from a single table, however the filtering and sorting is really what the app does.

Some feeds are fairly simple such as "get all items that are in one of these categories using an items to category link table". Others are more complex using fulltext search to filter, along with category filters and stock filters and sometimes we may even require that the results have an additional filter such as "exclude items from any category that doesn't have 10 matching items in that category" (sort of like a self regulating, category filter invalidation).

We are now in the process of trying to speed up the API and looking to start putting the tech in, to allow us to scale. We've already decided on certain things like seperated search engines (i.e. elasticsearch for fulltext replacement e.c.t.). However one thing which i'm a little "new" in, is caching the API feeds.

My only caching experience has been either caching full webpage outputs in things like magento/wordpress. Or caching complex objects that are built from several queries and processes.

I've decided, object caching probably isn't suitable here, as most of the final object data comes from a single table. So object caching would not provide much speed improvement.

I'm currently figuring i need to cache the final output collection of objects, as its really the complex filtering and sorting which slows everything down. But that's where i get stuck...

First of all, should we cache the entire collection of objects, or just store a collection of the object id's, and still go to the database to do the final data lookup (my theory being, that with all the different compilation of feeds, the memory usage would grow quite quickly caching all the objects themselves).

Secondly, do we cache the very final output of the feed, or do we try and find a common point at which we can create a cached copy of the feed that isnt quite right. So for example, rather than caching "similar products to X where the similar products are in 1,2,3 categories", we would instead cache "similar products to X", then on each request, get the collection from cache, and do the additional filtering manually after retrieving the "base collection".

Hopefully that all makes some sort of sense,a nd apologies if its a little rambly. I'm a little out of my depth with this one, but im keen to learn. No doubt whatever solution i decide to implement first, will need many, many iterations before we deem it "correct". But at the moment, i just don't have any experience in this, to give myself a suitable, appropriate starting point, to start development.

答:
Things like this tend to highly depend on both data structures and application design. Very much like with performance optimization in general, there is no ultimate answer that fits all cases. The best answer one can probably give you is to find out, what the exact bottlenecks are. Analyze that data and decide for a caching strategy that is most likely to avoid These problems. Implement it as "proof of concept", then measure again. Repeat this until you are satisfied with the results.

And most important: Try it with a fairly representative amount of data that you expect later in production. Things usually go fast when only 10 database records are involved, no matter what you code. This is no longer true with 10.000 (or 10 mio. records).

Title: API Caching Layer


问:
xml based programming languages
I was looking at wikipedia - Category:XML-based programming languages.

Why would someone take this approach for designing a language?

What are the advantages of it?

I can only think of disadvantages.

hard to maintain

hard to read

hard to write

答: I could see something like that being handy in an XML-heavy environment (think XSLT), where you presumably already have decent XML editors and it might be useful to be able to generate code using the same toolset.  It also might make it easier to write correctness verifiers or other tools to ensure that the code follows certain standards or rules (e.g., a schema defines where the business logic has to go, and/or ensures that all variables are initialized in a consistent fashion).</p>

Title: xml based programming languages


答:
Code Is Data.

Or rather, programs are data. A source file is just a specific serialization of this program. This idea is e.g. common in homoiconic languages like Lisp. Such a language tears down the barriers between the program code, and the data it is operating on. This can be extremely powerful and expressive, although I would not call the appearance of Lisp code “beautiful” or “easy to read”.

XML is the structured data serialization format to the current-day enterprise programmer. There are large toolchains established around XML processing.

Defining a language meant to operate on XML in XML can be interesting because of this Homoiconicity. An example is XSLT. In theory, this allows metaprogramming, but no sane person would do this, right?

Templating languages are interested in having little seperation between data and code. Using an XML document as a template/program is interesting when the output is XML or HTML.

Storing code of a general purpose language in XML can still be interesting. Storing an Abstract Syntax Tree serialized to XML instead of source code is viable when this code is manipulated via an IDE, where it is presented in a more human-readable form, e.g. for visual programming. This is not unlike Smalltalk environments, where the “source code” is just a representation of the actual bytecode image.

Interestingly, XML documents are sometimes used for templating code … *shudder* (dependency injection). I ascribe this to the ubiquity of XML in some toolchains / the mindshare XML has as a go-to structured data format.

Title: xml based programming languages

Body:
I was looking at wikipedia - Category:XML-based programming languages.

Why would someone take this approach for designing a language?

What are the advantages of it?

I can only think of disadvantages.

hard to maintain

hard to read

hard to write


答:
XSLT is the only XML Programming language that I have used, I haven't had the chance/opportunity to get into the others.

we have one main Application that shoots out one XML file to a Database, and several other Applications can take that file and apply an XSLT file to it to extract the data that those other applications need, this alleviates the need for exporting a new set of Data for each new application that comes along. I think that is a major plus.  you only have to code one XSLT file for the new application to decode the information that is already being produced rather than having to produce new information for a new application.

I realize that I haven't touched on any of the other languages that you have listed, but I have given you an idea of a good place for the use of such a language.  still not sure if I completely answered or even partially answered your question.  but hopefully I have given some insight.

Title: xml based programming languages


答:
XML makes almost no sense absent historical and political context. SGML was even harder to write, read, and maintain, but it had the ISO stamp of approval put on it in 1986 which made it perhaps the first data declaration language to have such an imprimatur.

It was sufficiently useful and documented to inspire Tim Berners-Lee to use it as the foundation of HTML in the early 1990s. Remember, he was intending to create a world wide web and basing it on an extant ISO standard would help further that considerably.

Then in the late 1990s with the web quite well entrenched, the World Wide Web Consortium started an initiative for standard structural markup for data interchange. The hype-factor surrounding XML reached unprecedented levels of "we're not sure what to do with this, but I bet it'll be really cool".

As it stands, what XML is mostly good for is structured data interchange between disparate systems. As amon has noted, there are some specific domains where it has broader utility. I'm just glad that it is now possible to encode graffiti in a standardized markup so  that in the future, kids won't have to risk life and prosecution but instead do their tagging with paint-wielding remotely-controlled drones.

Title: xml based programming languages


答:
What you are looking for is a symbol table that supports ordered operations.
And in your case it is the floor operation.

The hash implementation of a symbol table is the fastest, but it doesn't offer those ordered operations.

But tree implementation of symbol tables does.
An example of that in Java is the TreeMap class

Title: Is there a data structure for this type of list/map?

Body:
Perhaps there's a name for what I want, but I'm not aware of it. I need something similar to a LinkedHashMap in Java, but where it returns the 'previous' value if there's no value at the specified key.

That is, I have a list of objects stored by an integer key (which is in units of time in my case):

```<code>; key->value
10->A
15->B
20->C
</code>```

So, if I were to query for a value for key 0-9, it would return null. The special part is if I queried for something 10 <= i <= 14 it would return A. Or, for i >= 20, it would return C.

Is there a data structure for this?


答: More than the actual coding, the important thing is to come up with a good programming structure. This is something your program has done, because things are well sorted out, and it follows logically from one step to another. It could lay a good foundation for similar programs, and if it needs to be changed, its good structure makes it easier to change than would otherwise be the case.</p>

Title: Making some methods mostly contain method calls, while others doing "the lowest level" work

Body:
So I thought about this, and I don't know if it's included or not in any methodology.

I think the advantages of this coding style is that, at the lowest level, the code is extremely testable, and then the integration tests should also be very easy to build.

I also think this would make the code more readable and the UML would be understood faster.

So here's my example:

```<code>class CoolObject{
var member1; //needed for instance in lifecycle events
var member2; //same comment

   //This method could be for instance an event handler
   //Notice this contains only assignments and method calls. No library calls or lower level stuff
   [public] method high_level(params...){
    var local_var1;
    var local_var2;
    local_var1 = call method lower_level1(param1,param2);
    local_var2 = call method lower_level2(param1, local_var1);
    member1 = call method lower_level3(local_var2);
   }

   //Notice this contains only library calls and lower level processing
   [private] method lower_level1(param1, param2){
    return param1 + param2 + libraryXXY123.function142(current_date);
   }

   //Notice this contains only library calls and lower level processing
   [private] method lower_level2(param1, param2){
     var return_value;
     loop over param2{
        if(condition){
           add param1 to return_value;
        }
     }
     return return_value + libraryASDF123.function3132(system_user);

   }

}
</code>```

Please note that this is not written in any specific language, as I only wanted to illustrate the concept.

So do you know some methodologies that use this, or that warn against it?
Please elaborate on the answer, as I think this would be a good idea, and would like this either confirmed, or the opposite.


答:
I'll concentrate on XSLT rather than XML-based languages in general.

There's a history here, of course. XSLT was conceived as a successor to DSSSL, the styling language for SGML, and tried to get right what DSSSL had got wrong. One of the major problems with DSSSL was perceived as being its (Scheme-like) syntax, and there was a widespread feeling that the solution lay in using the same syntax for the stylesheet and the data; after all, the idea was that a stylesheet should consist largely of structured data rather than program logic, and much of that data would consist of proforma ("template") data for adding to the result tree, with some parameterization.

XSLT is often perceived as being excessively verbose. For XSLT 1.0, which many people are unfortunately still using, that's probably true, but the problem was largely solved with XSLT 2.0, which is often a lot more concise that other ways of solving the same problem.

There are certainly drawbacks. You're pretty well obliged to use a purpose-designed editor (but then, most programmers use syntax-directed editors for every language, don't they?). The language isn't quite as composable as it might be (though again, XSLT 2.0 largely fixes that). But there are also significant advantages:

XSLT is widely used by non-programmers, and for them it's very much a plus that they only have to learn one syntax, not two. Remember, it's all the little details like how to handle character encoding and escaping of special characters.

The ability to process XSLT code using XSLT is a lot more useful than you might imagine. Nearly all big XSLT projects take advantage of this capability, and it can bring very big benefits. For example, I saw one online banking system that had a couple of hundred forms in its UI, each generated by its own stylesheet, but the stylesheets were generated from a common library of code giving great reuse and consistency of look and feel.

There's a benefit that I wouldn't have expected, which is that the use of a constrained syntactic framework like XML forces the language designers to maintain a level of lexical consistency as the language evolves and at the same time provides great extensibility. The XQuery WG is always debating how to extend the language without breaking compatibility or introducing quirks; XSLT has no such problems, because it's basically a question of defining new elements and attributes.

Title: xml based programming languages


答:
one of the biggest advantages of an XML based language is that it looks easy to implement

no really, there are a ton of validating parsers available which will diagnose the syntax related compile errors and give you the AST for free

the execution is also simply iterating over said AST and keeping a map of the functions and variables

Title: xml based programming languages


问:
As developers is it our job to report issues if no one else in the org seems to care?
edit:

I should point out; My personal view was that I should be proactive.  I know sometimes I have to bite my tongue, and I wanted to get the communities input(was this one of those times).

I couldn't find a more appropriate place to ask it in the SO family of sites.

Here is the scenario --

small org < 70 employees

no qa department

website viewed by thousands everyday.

I am the sole website developer

I have never had a single complaint that the site is broken in IE6

I've discovered our site has not worked in IE6 for years. The person I replaced who created it must have been "testing" it only on IE7.  I fired up Virtual PC and with IE6, and our site is a complete mess.  You can not select some menu items they are so garbled.  It looks terrible.

So again,  Is it our job to proactively seek out bugs, or do we just fix what the customer requests....

Personally, I want to leverage this opportunity with my org to drop any expectation of  IE6 support or compatibility.

答: In General, report it. In this special case, add the proposal that a IE6 upgrade hint script should be added to the site. There are a bunch out there for free, including other outdated browsers as well. IE6 was already far outdated in 2011, it is even more in 2013.</p>

OwnerDisplayName: Doug Chamberlain


问:
When is it reasonable to create my own programming language?
Are there types of killer applications, classes of algorithmic problems, etc., where it is better, in the long run, to create my own language?

PS: Just to be sure, I mean a new programming language and a compiler, not a new compiler for an existing language.

EDIT: Thank you for the answers. Can you provide some examples, where it is absolutly unnecessary to create a DSL or cases in which a DSL might be a good idea?

答:
Generally speaking the answer would be a big NO. Of the hundreds of languages out there there is usually one that will suit your problem.

However there are circumstance where it is a rational option to develop a new language:-

When one of your competitors now owns one of your main development platforms. I am thinking of Googles current reliance on Java and their development of "go", (it helps if you have an author of the most successful language ever on the payroll!).

When you have to write a ton of code for a new platform and the existing languages are verbose and error prone -- e.g. php for web development.

When you come across problems of scale and parallelism which were never encountered before because nobody ever had this much hardware to process this much data before -- e.g. Scala and (to a certain extent GO).


答:
Why would you actually want list insertion as part of syntax? It's a fairly uncommon operation, and I'd question the wisdom of creating special syntax for this when a regular function should work just fine.

Note that if you are using a Lisp, it's trivial to add new syntax using macros.

Here's an example in Clojure:

```<code>(defmacro insert [list at [start end] in target]
     (when-not (and (= "at" (name at)) (= "in" (name in)))
       (throw (Error. "Syntax error: should be like (insert <values> at [3 4] in <target-list>)")) )
     `(let [target# ~target ]
        (concat
          (take ~start target#)
          ~list
          (drop ~end target#))))

(insert [:a :b :c] at [3 4] in [1 2 3 4 5])
=> (1 2 3 :a :b :c 5)
</code>```

Note that this isn't a function: we have genuinely created new syntax (see the "at" and "in" symbols - this wouldn't work as a regular function)

I still don't recommend doing this (you should normally prefer a regular function), but the feature is there if you want it....

Title: What language has integrated "list insertion" as part of code *syntax*?

Body:
Many programming languages permit natural manipulation of strings, and some languages permit the manipulations of lists too.

More often then not (always?), these operations are done as procedure calls, or as member functions.

Many programming languages do implement in syntax the fairly typical set {prepend, replace, append} on lists (and/or strings).

I would like to know if there as/was a programming language that has a syntax that minimises/rationalises/orthogonalises the insertion syntax of items into a list by syntax design?

Python - as a simple example - has only: https://stackoverflow.com/questions/18033339/python-insert-operation-on-list

```<code>mylist.insert(10,'5')
</code>```

Note: In python list insertion is implemented as a member function.

But: Python does have some syntactic sugar for removing elements from a list: e.g.

```<code>del mylist[4:7]
</code>```

I like to know of any languages actually try to integrate (or have strategy) for list insertion as part of the syntax?

An example of insertion by construction: Here is some code from a fairly typical "Brand X" language, demonstrating typical prepend/replace/append operations {or operators, vis-à-vis syntatic sugar}, notice there is no obvious syntax for {in place} inserting (or removing) from the middle of a list.  {It has to be done "by construction", or by calling a procedure}

```<code># Demonstration of prefix, replace and append operations to a string {or list} #
string s := "23XX78";
"1"    +=: s;    # Prefix a char "1" to the string "in place" #
s[4:5] := "46";  # In place replace a char at pos 2 in a string #
s      +:= "9!"; # Append a string "9!" char to the string #
#
  Although inserting into a list is intuitive,
  * it is by construction (hence prone to typos/index-flips)
  * it is not "in place"
  e.g. ...
#
s:=s[:4]+"5"+s[5:];

print(s)
</code>```

Output: "123456789!"

Another example for strings:

```<code>s[:4]+="5"
</code>```

Body:
Why would you actually want list insertion as part of syntax? It's a fairly uncommon operation, and I'd question the wisdom of creating special syntax for this when a regular function should work just fine.

Note that if you are using a Lisp, it's trivial to add new syntax using macros.

Here's an example in Clojure:

(defmacro insert [list at [start end] in target]
     (when-not (and (= "at" (name at)) (= "in" (name in)))
       (throw (Error. "Syntax error: should be like (insert <values> at [3 4] in <target-list>)")) )
     `(let [target# ~target ]
        (concat
          (take ~start target#)
          ~list
          (drop ~end target#))))

(insert [:a :b :c] at [3 4] in [1 2 3 4 5])
=> (1 2 3 :a :b :c 5)

Note that this isn't a function: we have genuinely created new syntax (see the "at" and "in" symbols - this wouldn't work as a regular function)

I still don't recommend doing this (you should normally prefer a regular function), but the feature is there if you want it....


问:
Maths needed to understand theory behind Haskell's type system?
Recently, I've become deeply interested in Haskell.

While attempting to learn new concepts (e.g. the forall keyword and ST monad) and Haskell's type system in general, I continually run into concepts from category theory and lambda calculus. So, I wonder:

What other branches of mathematics are important to a strong
understanding of Haskell's type system?

Can I forego a rigorous study of these maths and instead focus on certain pertinent concepts? (e.g. quantifiers in lambda calculus.) If so, which concepts are essential?

I'm hoping to pick up Types and Programming Languages soon, however, please  suggest any alternative reading resources you feel appropriate.

答:
No, you don't need to pick up a book on category theory to understand Haskell.

I've been using Haskell for a few years, and picked up some category theory out of curiosity, it's really not necessary. On one hand, it's cool to see how all these abstractions fit in to "the big picture", but I didn't go "Oh my gosh I just need to make this a profunctor from the Maybe category to []s and then I can save the princess!".

Now depending on what you're doing with Haskell type theory is on the fence.

If you're just learning haskell don't go trying to understand every nuance of the type system. Please don't, it's like trying to learn C++ template meta-programming first. Fancy types are excellent tools, but having a good understanding of functional programming beats understanding impredicative polymorphism.

Now let's say after a year or two of Haskell you're looking to understand every subtle piece of how Haskell's type system works, then yes, some type theory might be helpful.

It will help you understand some of the logic behind how things work, plus it's frankly a really cool branch of computer science IMO that is worth looking at. You can cherry pick the parts your interested in and still learn a decent amount.

For Haskell, looking at STLC, HM type systems (System F) and perhaps the lambda cube (Haskell is System Fw iirc) and iso-recursive types. Types and Programming languages is a great resource for starting out and covers all of these and much more.

If you really want to drink the cool-aid and discover you're a budding type theorist, go poke at Agda or Coq. These feature "dependent types", one step farther along in the lambda cube than Haskell. Dependent types let types depend on terms. This means the types are powerful enough to actually prove theorems. For the curious, googling "curry howard isomorphism" should bring up some interesting results.


问:
How to refactor an OO program into a functional one?
I'm having difficulty finding resources on how to write programs in a functional style. The most advanced topic I could find discussed online was using structural typing to cut down on class hierarchies; most just deal with how to use map/fold/reduce/etc to replace imperative loops.

What I would really like to find is an in-depth discussion of an OOP implementation of a non-trivial program, its limitations, and how to refactor it in a functional style. Not just an algorithm or a data structure, but something with several different roles and aspects - a video game perhaps. By the way I did read Real-World Functional Programming by Tomas Petricek, but I'm left wanting more.

答:
I don't think it's really possible to refactor the program completely - you would have to redesign and reimplement in the correct paradigm.

I've seen code refactoring defined as a "disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior".

You could make certain things more functional, but at its core you still have an object oriented program. You can't just change small bits and pieces to adapt it to a different paradigm.


问:
Is it a bad idea to create a class which will only have one instance?
Is it bad coding practice/design to make a class which will only be instantiated once?

I have some variables and functions that can be grouped together under a class to "look good" (for a lack of a better description) since they are somewhat related, but they can just be global variables and global functions.

(Btw, I am using JavaScript, AngularJS, Express, MongoDB.)

答:
There are singleton classes and that is a common design pattern.

There are also classes that never get instantiated. If you have functions that DO NOT operate on any persistent state (e.g., they take the input and transform it), you can usually use a static method. In some languages (like Java) these static methods would be declared in a class, but the class itself will never be instantiated.


答:
A single instance for a class makes sense if the object represents a single resource, like a ethernet connexion or the operating system task manager for instance.

Functions are put in a class only if they act on the variables of instances of that class, otherwise the maintainer will be confused about the intention of that class.

Usually, a good reason exists why your app has global variables. Try to find the common purpose of them and design a class around this purpose. It will not only make the design clear, but your mind as well.

Title: Is it a bad idea to create a class which will only have one instance?

Body:
Is it bad coding practice/design to make a class which will only be instantiated once?

I have some variables and functions that can be grouped together under a class to "look good" (for a lack of a better description) since they are somewhat related, but they can just be global variables and global functions.

(Btw, I am using JavaScript, AngularJS, Express, MongoDB.)


答:
The singleton pattern is common. It allows you to enforce single instance of class.

But for some it is too common, so it becomes an anti-pattern. The reason for this is because it is practically same as global state. And any global state is hard to mock and test and hard to debug. But at the same time, having to explicitly pass this one instance everywhere in your code can cause code to bloat up a lot. But this will make you think about proper architecture. If bunch of classes use this one singleton, you might thing they are related somehow and create common ancestor for them, that will encapsulate this one instance for them.


答: It's bad to assume something is universally bad. In your case, maybe it would be a good idea, but given that you're using a language that's not OO at the core it's more appropriate probably to just use loose methods and variables and put them in a common library that you include in your other work.</p>


答:
Is it bad coding practice/design to make a class which will only be instantiated once?

No, even if only instantiated once, you need a class for it. But don't suppose you will always only need one instance, now and in the future.

Suppose you make a game, and you have a player class:

```<code>class Player {
    ...
}
</code>```

You will instantiate one player class in your game, and use always the same object. Nothing wrong with it.

However, don't make a Singleton out of it! Today you design your game and think "Well, it will always be a one-player game. I will use a Singleton for my Player". But in version 2, you may want to implement multiplayer - and then you are getting into trouble. You will have to rewrite and adapt a lot of code, because your design does not support instantiating multiple players.

The same is with caches. Or loggers. Or network interfaces. Today, you think you will only need one, always, for sure. But in a future version you need to add a second. Be aware of this situation.

Body:
Is it bad coding practice/design to make a class which will only be instantiated once?

No, even if only instantiated once, you need a class for it. But don't suppose you will always only need one instance, now and in the future.

Suppose you make a game, and you have a player class:

class Player {
    ...
}

You will instantiate one player class in your game, and use always the same object. Nothing wrong with it.

However, don't make a Singleton out of it! Today you design your game and think "Well, it will always be a one-player game. I will use a Singleton for my Player". But in version 2, you may want to implement multiplayer - and then you are getting into trouble. You will have to rewrite and adapt a lot of code, because your design does not support instantiating multiple players.

The same is with caches. Or loggers. Or network interfaces. Today, you think you will only need one, always, for sure. But in a future version you need to add a second. Be aware of this situation.


问:
How to handle licensing of Ruby on Rails code, which contains a LGPL library?
My company wants to release the code for a Ruby on Rails demo app, which includes our own LGPL'd library code.

It it legally kosher for me to state that the contents of the entire repo are released under the LGPL, although it includes "stock" Ruby on Rails files which are generated with every app, like boot.rb and application.rb?

答:
To be entirely sure, you need to consult with a lawyer. This is a legal question that can only be answered definitively by an experienced professional in this field.

I don't know if those "stock" Ruby on Rails files are considered to be part of the framework or part of the application, so there are a few possibilities.

If you also have the framework itself in your repository, it is ethically best to release only the files of your application under the (L)GPL and release the files belonging to the framework under their original (MIT) license.

If you don't (re-)distribute the entire Rails framework, but only a few files that get customized for every application (but are still considered part of the framework), you are probably fine with releasing the entire repository under (L)GPL, on account of the sublicense grant in the MIT license of the Rails framework. But only a lawyer can tell for sure if this interpretation of the licenses is correct.

If you don't (re-)distribute the Rails framework and those "stock" files (boot.rb, application.rb, etc.) are considered to be part of the application, then you are definitely fine with releasing the entire repository under (L)GPL.


答:
There is no problem with writing a class that ends being instanced only once.

If putting some variables and functions together within a class makes sense, has semantic value or makes the code simpler to read and manipulate, then so be it, maintainers will be thankful.

What can be very wrong though, is to enforce uniqueness from within.

Many people tend to fire the singleton pattern as soon as they think they'll only need one instance of something. See for example how you haven't described your context in depth, yet most answers already suggest you to use a singleton. And then the design might be screwed because if you need another instance at some point for whatever reason, the class will prevent you from doing it without changing a lot of code.

So as a conclusion, one instance is fine, but make sure to know whether:

you only need one instance, or

you cannot have more than one instance (a very, very rare case in my experience).


问:
Where did the notion of "one return only" come from?
I often talk to programmers who say "Don't put multiple return statements in the same  method." When I ask them to tell me the reasons why, all I get is "The coding standard says so." or "It's confusing." When they show me solutions with a single return statement, the code looks uglier to me. For example:

if (condition)
   return 42;
else
   return 97;
```

<p>"<em>This is ugly, you have to use a local variable!</em>"</p>

<pre class="lang-c prettyprint-override"><code>int result;
if (condition)
   result = 42;
else
   result = 97;
return result;
</code>```

How does this 50% code bloat make the program any easier to understand? Personally, I find it harder, because the state space has just increased by another variable that could easily have been prevented.

Of course, normally I would just write:

return (condition) ? 42 : 97;
```

But many programmers eschew the conditional operator and prefer the long form.

Where did this notion of "one return only" come from? Is there a historical reason why this convention came about?

答:
It's always easy to link Fowler.

One of the main examples that go against SESE are guard clauses:

Replace Nested Conditional with Guard Clauses

Use Guard Clauses for all the special cases

double getPayAmount() {
    double result;
    if (_isDead) result = deadAmount();
    else {
        if (_isSeparated) result = separatedAmount();
        else {
            if (_isRetired) result = retiredAmount();
            else result = normalPayAmount();
        };
    }
return result;
};
```

  <p>                                                                                <img src="https://i.stack.imgur.com/mKbQM.gif" alt="http://www.refactoring.com/catalog/arrow.gif"></p>

<pre class="lang-c prettyprint-override"><code>double getPayAmount() {
    if (_isDead) return deadAmount();
    if (_isSeparated) return separatedAmount();
    if (_isRetired) return retiredAmount();
    return normalPayAmount();
};
</code>```

For more information see page 250 of Refactoring...

Body:
It's always easy to link Fowler.

One of the main examples that go against SESE are guard clauses:

Replace Nested Conditional with Guard Clauses

Use Guard Clauses for all the special cases

double getPayAmount() {
    double result;
    if (_isDead) result = deadAmount();
    else {
        if (_isSeparated) result = separatedAmount();
        else {
            if (_isRetired) result = retiredAmount();
            else result = normalPayAmount();
        };
    }
return result;
};

double getPayAmount() {
    if (_isDead) return deadAmount();
    if (_isSeparated) return separatedAmount();
    if (_isRetired) return retiredAmount();
    return normalPayAmount();
};

For more information see page 250 of Refactoring...


问:
MVC shared model different required fields on different type
I have a model called Car and depending on what type of Car the user select the view is presented differently. For example the user selects from a grid of different cars and depending if it is a Volvo or a Kia or a Ford the view must allow different fields to be editable. For example with a Volvo the color is editable and is mandatory but with a Kia it is not.

I would like to use the one Car class to bind the view but want the client side validation to pick up the required fields based on what type of car.

I want to go only to one Action method for the Update

what is a good way to approach this problem...? create a base class and inherit from it? will this give me binding problems..?

答:
If all the cars have the same properties and behaviour then I would have a single car class and make it implement IValidatableObject interface. In the 'Validate' method look at the type of the car and add an error accordingly.

With regards to client side validation, you will have to implement a custom validator in jQuery or library of your choice. I personally use KnockoutJS along with KnockoutJS Validation plugin. Simple example can be found here: https://stackoverflow.com/questions/241145/jquery-validate-plugin-how-to-create-a-simple-custom-rule


问:
What kind of problems is an Android beginner likely to encounter in using Scala?
I am a hobbyist programmer who makes and maintains one production system, largely coded in Python, which now has to be ported to Android.  I don't know Java at all. However, SL4A in Android makes Python a bit of a second class citizen re APIs, such as Google Cloud Messaging etc. However, for me, Java appears intimidating with its verbose syntax and strict typing.  Scala's syntax is more appealing and seems like a possible compromise.

From this question and this one on Stack Overflow it seems that Scala development on Android is feasible.  However, as a 'beginner', I would like to know what problems I might encounter by using Scala instead of Java. The available information that I can find on the 'Net (including the question from this site cited above) is from early 2012, at the latest, and I imagine the situation has changed since then.

答:
Although Scala will feel a bit more comfortable compared to Java if you're used to a scripting language like Python, there are a few significant disadvantages in using it in Android development.

It is less common, so you'll have a harder time getting support on sites like StackOverflow. You may have to translate your code to Java to reach a wider audience.

It is not trivial to set up, especially when you're not familiar with Eclipse and Java yet.

The Android APIs themselves were not designed for Scala, so using them may still feel as awkward as using Java in the first place (strict typing, required type annotations, incompatibility with Scala paradigms).

Most of the articles discussing it are, as you say, out-of-date which may indicate that using Scala on Android has fallen out of favour with developers who've tried it.

It will increase the size of your applications, perhaps not significantly, but it's still a factor

Since you're a beginner, it would be a much better idea to get over the initial burden of learning Java and making a few simple applications to get the hang of Android concepts. You'll be able to get full support, which will make development less frustrating in general. Also note that a lot of Scala concepts will be easier to understand if you already know Java.

Nevertheless, if you want to get started with Scala on Android, here are some useful resources:

http://code.google.com/p/scalaforandroid/ (Traditional way of working with Scala on Android)

http://fxthomas.github.io/android-plugin/ (A promising new way, worth checking out)

https://github.com/pocorall/scaloid (A library that makes the Android APIs easier to use with Scala)

Lastly, a bit anecdotal perhaps, I've been developing Android apps for about 3 years now and I recently tried to get started with Scala myself, because I really like the language. Unfortunately, it took so much fighting with Eclipse, packages and build scripts that after spending an entire afternoon on it, I just gave up. Your mileage may vary, but to avoid frustraton, I would definitely recommend to get started with Java first.


问:
Does anyone use virtual machines for web development, and why?
I see a few developers that like to use virtual machines for web development.  Are there others that do this? If there are, why do you do it?  Are there any pros / cons to developing on a VM rather than in a non virtualised environment?

I would think things are slower in a VM.

答:
I use a virtual machine to map subdomains of virtualbox.me (I own the domain) to subdirectories of a folder on my host machine shared to the guest.

With this setup, I just create a new directory and immediately have a new project under it's own subdomain, i.e. /home/pete/virtualwww/my-super-project maps to http://my-super-project.virtualbox.me/

I've written up guide for replicating this (it uses mod_vhost_alias and VirtualDocumentRoot) here:

http://otaqui.com/blog/1652/setting-up-a-virtualbox-virtual-machine-for-web-development-with-multiple-sites-using-mod_vhost_alias-and-virtualdocumentroot/


问:
Java convention for if/else if order
I have an if/else if structure that on some cases does nothing. From the code I have seen in my career, the "empty" case is normally left out. But when I wrote my code, it just doesn't feel right to leave this case out, but to show it as a real case that simply does nothing. For example, in a case where something is done when a number is below 5 and above 10, but in between nothing is done:

```<code>int a = 4
if(a < 5) {
  do something
} else if(a >=5 && a <= 10) {
  // do nothing
} else if(a > 10) {
  do something else
}
</code>```

The reason I thought this is a better option is because:

The is how I though about the problem in my mind.

This shows the reader of the code that I thought of all the possibilities and didn't forget one by mistake.

So I was wondering if this convention is either accepted by the programming community or it is shunned upon.

答:
I would avoid to define the do nothing case explicit by giving the intervall. I would use an else-branch for that

```<code>int a = 4
if(a < 5) {
  do something
} else if(a > 10) {
  do something else
} else {
     //This should mean: (a >=5 && a <= 10)
     // do nothing

     // Maybe log something here
     // or even add an assertion while development to ensure that the
     // branch is only reached in expected cases:
     assert (a >=5 && a <= 10) : "I expected 'a' to be 5<=a<=10, but a is:"+a;
}
</code>```

Title: Java convention for if/else if order

Body:
I would avoid to define the do nothing case explicit by giving the intervall. I would use an else-branch for that

int a = 4
if(a < 5) {
  do something
} else if(a > 10) {
  do something else
} else {
     //This should mean: (a >=5 && a <= 10)
     // do nothing

     // Maybe log something here
     // or even add an assertion while development to ensure that the
     // branch is only reached in expected cases:
     assert (a >=5 && a <= 10) : "I expected 'a' to be 5<=a<=10, but a is:"+a;
}


问:
Integrate a Python Project with a Visual Studio C++ Console Application?
I now have a Python project that is in charge of generating the simulation data and visualizing the simulation and processed data. A C++ console application is already available in my Visual Studio.

The processing sequence is as follows:

Python project generates the raw data into data.txt.

Visual Studio C++ console application takes in data.txt and processes the data, and finally outputs results.txt.

Python project takes in results.txt and visualizes it with matplotlib.

I am now doing it manually, and it works perfectly ok for one run. However, it becomes extremely troublesome when I want to have multiple runs.

Questions:

How may I integrate them together? Integrate Python project into Visual Studio or integrate C++ console application into Spyder (my Python IDE)?

Currently, I manually enter the debugging parameters in the C++ console application debugging property. How may I make it automatic? i.e. After Python project generates data.txt, the data.txt gets automatically taken in as parameters by the C++ console application?

答:
IDE stands for Indegrated Development Environment. It is not concerned with running your application except for debugging. There is no point integrating the IDEs, the user won't have them installed.

What you should do is make of of the applications run the other, directly, not involving either IDE.

You can execute external process from Python using the subprocess module (python3 doc).

You can execute external process from C++ using the system function (windows doc) (platform independent, not very powerful, but should be enough for your purpose) or using the windows-specific CreateProcess interface (on POSIX, you use the exec interface), but I don't think you need this direction just now.


问:
Is it OK to use same variable to store similar stuff sequentially?
Say I have a variable name len in a function and several strings. Can I use this to store length of those strings one after the other or should I create separate variables?
Basically this:

```<code>size_t len;
len = string1.size()
....//some code
len = string2.size()
...//more code
</code>```

versus

```<code>size_t str1len, str2len;
str1len = string1.size()
....//some code
str2len = string2.size()
...//more code
</code>```

All are local variables within a function BTW.

答:
I would use the same variable name but separate scopes to ensure that I do never accidentally use a length value of the wrong String</p>

```<code>{
  size_t len;
  len = string1.size()
  ....//some code
}
{
  size_t len;
  len = string2.size()
  ...//more code
}
</code>```

Body:
I would use the same variable name but separate scopes to ensure that I do never accidentally use a length value of the wrong String

{
  size_t len;
  len = string1.size()
  ....//some code
}
{
  size_t len;
  len = string2.size()
  ...//more code
}


答:
Usually it's rather confusing. However the second options you list does not look right either. Instead you should:

For simple things like str.size(), just use that expression where you need it and don't store it in variable at all.

Split the code out to helper functions, so you only process one string in one helper.

At least limit the scope of the variables with a block (see MrSmith42's answer)

Title: Is it OK to use same variable to store similar stuff sequentially?

Body:
Say I have a variable name len in a function and several strings. Can I use this to store length of those strings one after the other or should I create separate variables?
Basically this:

```<code>size_t len;
len = string1.size()
....//some code
len = string2.size()
...//more code
</code>```

versus

```<code>size_t str1len, str2len;
str1len = string1.size()
....//some code
str2len = string2.size()
...//more code
</code>```

All are local variables within a function BTW.


答:
You are not simply checking the value of a for the sake of it. It probably means something.

Thus I would prefer to see:

```<code>Boolean sell = a < 5;
Boolean buy = a > 10;
Boolean error = a >= 5 & a <= 10;
// or even:
Boolean error = !sell & !buy;
/* ^ (that's single source principle: if 5 changes to 6 one day,
 * you don't have to remember to change it in two places) */
</code>```

And then:

```<code>if (sell) {

} else if (buy) {

} else if (error) {

}
</code>```

Isn't it clearer?

Furthermore, could a be both less than 5 and greater than 10??

Rather not, so those elses are clearly redundant. (Unless you change the value of a within one of your if blocks, mind you, If you only evaluate a once, however - as in my example - you don't have to worry about it).

Hence:

```<code>Boolean sell = a < 5;
Boolean buy = a > 10;
Boolean error = !sell & !buy;

if (sell) {

}
if (buy) {

}
if (error) {
    // handle error
}
</code>```

This is way clearer and more flexible in my opinion - if some conditions are no longer mutually exclusive, as it can happen, you won't need to do much refactoring at all.

Title: Java convention for if/else if order

Body:
I have an if/else if structure that on some cases does nothing. From the code I have seen in my career, the "empty" case is normally left out. But when I wrote my code, it just doesn't feel right to leave this case out, but to show it as a real case that simply does nothing. For example, in a case where something is done when a number is below 5 and above 10, but in between nothing is done:

```<code>int a = 4
if(a < 5) {
  do something
} else if(a >=5 && a <= 10) {
  // do nothing
} else if(a > 10) {
  do something else
}
</code>```

The reason I thought this is a better option is because:

The is how I though about the problem in my mind.

This shows the reader of the code that I thought of all the possibilities and didn't forget one by mistake.

So I was wondering if this convention is either accepted by the programming community or it is shunned upon.

Body:
You are not simply checking the value of a for the sake of it. It probably means something.

Thus I would prefer to see:

Boolean sell = a < 5;
Boolean buy = a > 10;
Boolean error = a >= 5 & a <= 10;
// or even:
Boolean error = !sell & !buy;
/* ^ (that's single source principle: if 5 changes to 6 one day,
 * you don't have to remember to change it in two places) */

And then:

if (sell) {

} else if (buy) {

} else if (error) {

}

Isn't it clearer?

Furthermore, could a be both less than 5 and greater than 10??

Rather not, so those elses are clearly redundant. (Unless you change the value of a within one of your if blocks, mind you, If you only evaluate a once, however - as in my example - you don't have to worry about it).

Hence:

Boolean sell = a < 5;
Boolean buy = a > 10;
Boolean error = !sell & !buy;

if (sell) {

}
if (buy) {

}
if (error) {
    // handle error
}

This is way clearer and more flexible in my opinion - if some conditions are no longer mutually exclusive, as it can happen, you won't need to do much refactoring at all.


问:
Marking specific pieces of drastically changed open source code
I have taken a small chunk of open-source code, around a hundred lines, and found that for whatever reason, I have modified it so drastically that my end result has essentially no resemblance to the original. Maybe a line or two, and a few variable names, are carried over, but the diff is just one or more big chunks of - followed by big chunks of +.

If I'm now distributing my code, it seems clear to me that I should globally credit the original author for providing a foundation, and include the license under which I acquired the code. I'm wondering what my responsibilities in the social or technical dimensions are to mark specific changes, though. Am I rudely misrepresenting the original author's work when I say that mine is derived from it without pointing out the particular lines that were carried over? Is it helpful for another coder looking at my version if I include comments annotating what I've kept and why?

I've used someone else's code as a starting point, taking primarily the ideas and not the substance. Ignoring any legal aspects,* what kind of precise, targeted change documentation should I ideally provide?

What is proper etiquette for releasing a complete rewrite of an existing project? is closely related, but I've already chosen option 1. Best practices when forking code base is also related but doesn't address the specificity of attribution.

*Various aspects of which have already been covered here.

答:
Your basic obligation is to follow the original author's license terms.  But beyond that, it's a good idea to mark off the section with comments that indicate the original source of the code.  That allows others to follow the chain back to its origin, and bugs in one might be present in the other.

That said, there are many examples of open source or free software where this isn't the practice.  In fact, the larger the project, the less likely it is that you'll find such micro-attributions.


答:
You are asking two questions in one.

No, there's nothing bad having a class that will only have one instance.

Grouping variables and methods in a class without  a real reason for it is bad design.


问:
How relevant are "Requests per second" benchmarks?
Whenever a new framework is released it is a given that someone somewhere will benchmark it against other available solutions.

One interesting benchmark is the "Requests per second" benchmark. For example look it this benchmark:

Now AFAIK Zend framework and Symfony are 2 of the biggest frameworks out there with major companies supporting them. Did the developers make a mistake when designing the framework that resulted in that (relatively) low threshold?

If I'm planning to build a web site/app and expecting (relatively) high traffic, should I pay attention to this benchmark? Will my site/app surely go down at the presented figures?

Simply I'm asking you as a software architect how you would strategically take into account this benchmark when planning a new project.

答:
Just looking at that graph and leaving out the 2 paragraphs below the graph (in the linked article) easily gives a distorted picture. Let me quote from the article:

I’m not surprised, Slim is the fastest because it’s a micro framework.
  The Quick Start project didn’t use any templates or layout which
  obviously contributed to the reading. Zend1 is twice faster than
  Symfony2 and Zend2 but in my experience the number will quickly go
  down in a real live setup.

Frameworks should speed up development, performance is a secondary
  concern. Zend 2 and Symfony2 could do better but it’s not bad. There
  are ways to improve those numbers on production servers. Don’t
  reinvent the wheel, learn and use frameworks. There are various
  options which balance between performance and features.

So what you should do is: pay attention to that remarks. Benchmarks show that a framework executes that specific benchmark with a certain performance, and one should be really, really careful when trying to deduce any real-world decisions from them.


答:
A benchmark typically has little relationship with the code that one ends up writing - it is very unusual for them to test anything close to real world cases, partly because by the time you reach a real world situation there are going to be many more things in play than your application framework. There will be bottlenecks in logic, in data access, all over the place.

Also different frameworks are typically for somewhat different things, so it is unusual for a benchmark like "requests per second" to be equally relevant to different frameworks that offer different things. For example the fastest one on the survey linked in the question is a microframework that does relatively little, so you get faster response times, but you're likely to have to write a lot more code to get things done with it.

That doesn't mean they are completely useless- there are a few cases where some benchmarking can be helpful- the two that I can see off the top of my head are:

Choosing a framework - in a situation like yours, you might take particular benchmarks into account when you have identified several frameworks that all fulfil your exact needs and need something beyond  your immediate requirements to help you decide which one to use. Ideally, though, you would write your own benchmarks to confirm how you like working with each one- the writing would probably be more important than the benchmark.

Deciding how much optimisation is premature - if you know you are using a framework that turns requests around very quickly indeed, you might not need to work on caching and other optimisations, which can save you time to focus on your actual application design rather than on infrastructure to support it. Even just having a finger-in-the-air indication as to how a framework stacks up in these types of scenario can be useful for your design choices.

Title: How relevant are "Requests per second" benchmarks?

Body:
Whenever a new framework is released it is a given that someone somewhere will benchmark it against other available solutions.

One interesting benchmark is the "Requests per second" benchmark. For example look it this benchmark:

Now AFAIK Zend framework and Symfony are 2 of the biggest frameworks out there with major companies supporting them. Did the developers make a mistake when designing the framework that resulted in that (relatively) low threshold?

If I'm planning to build a web site/app and expecting (relatively) high traffic, should I pay attention to this benchmark? Will my site/app surely go down at the presented figures?

Simply I'm asking you as a software architect how you would strategically take into account this benchmark when planning a new project.


答:
Here's one way to design this feature.

Classes

```<code>public class Car {}

public class Ford : Car {}

public class BMW : Car {}
</code>```

Controller

```<code>public ActionResult Index()
{
    var car = new BMW();

    return View(car);
}
</code>```

The above is just test code. Now the key part is this. In the Views\Shared folder, create a new folder named EditorTemplates. In that new folder, create two partial views:

Ford.cshtml

```<code>@model CarViews.Controllers.Ford

<p>This is a Ford</p>
</code>```

bwm.cshtml

```<code>@model CarViews.Controllers.BMW

<p>This is a Bmw</p>
</code>```

Then in the Index view you can do this:

```<code>@model CarViews.Controllers.Car

@Html.EditorFor(m => m)
</code>```

Depending on what type of car you pass in, the editor view specific to that type will be rendered for you. As you add new cars to the system, you simply add new cshtml files for those cars.

Title: MVC shared model different required fields on different type

Body:
I have a model called Car and depending on what type of Car the user select the view is presented differently. For example the user selects from a grid of different cars and depending if it is a Volvo or a Kia or a Ford the view must allow different fields to be editable. For example with a Volvo the color is editable and is mandatory but with a Kia it is not.

I would like to use the one Car class to bind the view but want the client side validation to pick up the required fields based on what type of car.

I want to go only to one Action method for the Update

what is a good way to approach this problem...? create a base class and inherit from it? will this give me binding problems..?

Body:
Here's one way to design this feature.

Classes

public class Car {}

public class Ford : Car {}

public class BMW : Car {}

Controller

public ActionResult Index()
{
    var car = new BMW();

    return View(car);
}

The above is just test code. Now the key part is this. In the Views\Shared folder, create a new folder named EditorTemplates. In that new folder, create two partial views:

Ford.cshtml

@model CarViews.Controllers.Ford

<p>This is a Ford</p>

bwm.cshtml

@model CarViews.Controllers.BMW

<p>This is a Bmw</p>

Then in the Index view you can do this:

@model CarViews.Controllers.Car

@Html.EditorFor(m => m)

Depending on what type of car you pass in, the editor view specific to that type will be rendered for you. As you add new cars to the system, you simply add new cshtml files for those cars.


答:
If you are really going to introduce those variables as a shortcut for the expressions, and you cannot easily split up that code into two functions, I would definitely go for the second alternative. And I would write it this way:

```<code> size_t str1size = string1.size()
 ....//some code
 size_t str2size = string2.size()
 ...//more code
</code>```

don't use the name "len" when the original name is "size" (will be more consistent in naming)

declare and assign in one statement. That will help you to prevent a copy/paste error where you copy the first line down below and forget to change the second variable name.

Body:
If you are really going to introduce those variables as a shortcut for the expressions, and you cannot easily split up that code into two functions, I would definitely go for the second alternative. And I would write it this way:

 size_t str1size = string1.size()
 ....//some code
 size_t str2size = string2.size()
 ...//more code

don't use the name "len" when the original name is "size" (will be more consistent in naming)

declare and assign in one statement. That will help you to prevent a copy/paste error where you copy the first line down below and forget to change the second variable name.


问:
How to check for vulnerabilities in web application
I have developed a web application using zend framework, mysql, and other client side technologies like javascript, jquery ajax, kendo grid, and so on.

I have completed development and have done several rounds of testing to make sure the functional part is correct.

Now I would like to check for the vulnerabilities in my application - vulnerabilities such as

```<code>           * sql injection
           * ajax vulnerabilities
           * others
</code>```

which I don't know of. I would like to ask you guys how to check this and make the application secure.  What methods should I use to secure my application?

答:
You have a few options, but before you delve in to them I'd take a very good look at the Open Web Application Security Project. OWASP has some brilliant documents and guidelines.

Personally, I'd begin by conducting a full and proper code review. Rather than checking for traditional issues, take a strong look at Secure Coding practice. (Once again, OWASP has some guidelines for this)

Things such as sanitisation checking, use of eval() and so on. From here you should be able to gain some insight - if only from looking at your code from a different point of view.

You could also do some static source code analysis which may pick up some of the above issues; however these shouldn't be the only form of source code analysis you do. It is a very good complimentary approach for a full and proper code review however. OWASP maintains a list of such tools here.

Once you've gained some confidence in the source code, you can begin to have a little fun! This is where 'black box' techniques, such as fuzzing come in to play.

I recommend using something like the Zed Attack Proxy (ZAP) - give your application a good browse, preferably locally if you're on a shared host - or have a server that has critical applications running/is maintained elsewhere.

Try and use every bit of functionality in your site using this proxy. What this proxy can be used for, is check that any client facing parameters can't be given malicious input that will cause a security risk. However, what this proxy can actually do is much more - and it's worth digging in to the docs and looking at some of the advanced features.

If this still returns nothing then security really becomes an ongoing task:

Checking error logs for suspicious entries (third parties using fuzzers, scanners or otherwise doing "peculiar" things.

Internal Server Errors - can be a sign that someone is trying something

Server load logs, for DoS attacks and so on.

Keeping up to date with the security releases regarding any dependencies you're using

Not to overplay OWASP, as I've referred to them numerously in this answer - but it truly is a great project, and something I think every web developer should look in to.

It's also worth pointing out that security should be a concern as soon as the project is conceived, and if you don't take secure coding in to account when you begin - you may have a nightmare when you're trying to retrospectively secure an application.

Good luck!

ContentLicense: CC BY-SA 4.0


问:
What are the reasons for great performance differences running the same program?
I wrote a Python program that has to perform some expensive spatial searches while holding lots of data in memory. I tried to improve the performance, that is tried different approaches (see my question here for example).

First, and maybe not so surprisingly, I found great performance differences when running the same code on two different machines (up to 6 x faster on one machine).

Then however and very much to my own surprise, running the exactly same code on the same machine on two different days showed great performance differences.

To give you a rough idea what I mean by great.

Machine 1, day 1: 11 minutes

Machine 1, day 2: 2 minutes

There was no reboot in the meantime by the way.

What could be possible reasons for this difference? How can I can I make sure my system is ready for high performance when I start running my program?

答:
This has a lot to do with the OS, the other processes running, and the amount of memory being used. The OS will let each process have a certain number of CPU cycles before it switches to the next process. If there are lots of other processes, it will be longer between each time your program gets access to the CPU. Also, since your program holds lots of data in memory, when the CPU switches to a different process, this data may have to be moved out of memory. This will require it to be temporarily written to disk which is a slow process (relative to other operations in a computer).

Basically there are many factors that can cause the difference in time. However, in most systems, you can set your program to run with greater importance than other processes. This will differ based on the OS you run. That could help to speed up the running time because your program will be given a higher priority to run over other processes.


问:
Is it possible to combine C/C++ with web languages?
I would like to create a web application (meaning that will run from browser). The point is that I want to write just the UI in HTML5 + CSS + JS (or maybe even some PHP). On the other hand, I want to write the functionality of the application in C or C++. Then, I want to combine the code about the UI and functionality. Therefore, I would like to ask, whether it is possible to combine C/C++ code with web markup/programming languages?</p>

答:
There are a couple ways of using C or C++ in the web world.

The ancient method is CGI.  With this approach you have a web server that is configured to launch CGIs fork and exec the CGI when requested.  The problem with this is that the fork and exec is rather heavy weight.  If you have 1000 simultaneous connections, it means you have 1000 processes running - not ideal.

Moving a step closer to the web server, in particular apache this time, one could write a module for it in C which handles the code.  This lives within the web server as a library and is much faster, though it means tightly integrating with the apache environment which isn't always trivial. The most recent book for this approach was published in 1999 and is likely a bit dated.

Other web programming languages and stacks have moved to an application server structure.  With this approach, it is designed for hosting lightweight (rather than the heavy fork and exec) processes, often with a focus on a web facing interface for the applications.

Wikipedia lists a few C++ application servers:

Tuxedo - Based on the ATMI standard, is one of the original application servers.

Tntnet - Includes a template engine which allows embedding C++ code in HTML pages. Templates are compiled before run-time, and thus
  very fast. Multi-threaded, supports object lifetime via scoped
  variables.

CPPSERV - C++ servlet container.

Wt - A web toolkit similar to Qt permitting GUI-application-like web development with
  built-in Ajax abilities.

POCO C++ Libraries - A collection of open source class libraries including Poco.Net.HTTPServer.html

CppCMS

The key point with this is you likely need to work within another framework.  Writing a multithreaded scalable web application is beyond the means of most programmers.

Do realize that hosting may be an issue.  Nearly every web host offers php, and many offer tomcat (java).  You would have to do some digging to find one that offers one of the above application servers (very few offer cgi now days and even fewer would allow for random application just to run).

One of the advantages of languages that were coupled to an application server early in their development is that the structure of the application is consistent (java has the .war file which is the same no matter what container you deploy to - unless you've written container specific code).  C++ containers appear to be incompatible between each other (I welcome any corrections on this matter).


问:
Is it safe to display information about old passwords on login failure?
When I changed my Facebook password yesterday, by mistake I entered the old one and got this:

Am I missing something here or this is a big potencial risk for users.

In my opinion this is a problem BECAUSE it is FaceBook and is used by, well, everyone and the latest statistics show that 76.3% of the users are idiots [source:me], that is more that 3/4!!

All kidding aside:

Isn't this useful information for an attacker?

It reveals private information about the user!

It could help the attacker gain access to another site in which the user used the same password

Granted, you should't use use the same password twice (but remember: 76.3%!!!)

Doesn't this simply increase the surface area for attackers?

It increases the chances of getting useful information at least.

In a site like Facebook 1st choice for hackers and (bad) people interested in valued personal information shouldn't anything increasing the chance of a vulnerability be removed?

Am I missing something? Am I being paranoid? Will 76.3% of the accounts will be hacked after this post?

答:
In my humble opinion:

It's a very bad practice

It tells an attacker: "you are getting warmer"

No hint whatsoever about a password should be given other than "wrong password or username". Notice that the message should even leave you with the doubt of whether you enter the wrong password or the wrong username.

Facebook just might as well tell you:

"Sorry, the password you entered belongs to the user John Smith"

or

"Sorry, the password you entered is off by two characters"