答:
Manufacturing lines are full of queues. Think of a line of empty bottles heading for a filling machine. First-in-first-out is a natural way to apply a process sequentially to many objects. Queues are also used to decouple one process from another: the filling machine doesn't have to stop immediately if there's a short-term problem with the labeling machine.

Queues are used in software in about the same ways. The output of one process can be queued for input to another process. This is true whether you're talking about inter-process communication, inter-thread communication, or simply breaking a complicated process into parts that might all be handled by the same thread.

In operating systems, queues are often used to process inputs in order. The file system might read blocks from a storage device and add them to a queue, for example. Or interrupts that handle things like key presses and mouse movements create events that are added to an event queue so that you don't get "uqeeu" instead of "queue" when you're typing.

For a simple student assignment, I think any task that accepts some number of inputs and then processes them would work. For example, you could have them write a simple postfix expression evaluator. It'd have three parts:

read an input, add it to the input queue, and repeat until there are no more inputs

get an item from the queue

if the item is a number, push it onto the argument stack

if the item is an operator, pop the necessary arguments and evaluate

add the result to the output queue

repeat until the stack is empty

read an item from the output queue, print it, and repeat until the output queue is empty


问:
Ruby workflow in Windows
I've done some searching and quite haven't come across the answer I am looking for. I do not think this is a duplicate of this question. I believe Windows could be a suitable development environment based on the mix of answers in that question.

I have been developing in Ruby (mostly Rails but not entirely) for about a year now for personal projects on a Macbook Pro however that machine has faced an untimely death and has been replaced with a nice Windows 7 machine. Ruby development felt almost natural on the Mac after doing some research and setting up the typical stack. My environment then included the standard (Linux like) stuff built into OSX, Text Wrangler, Git, RVM, et al. Not too much of a deviation from what the 'devotees' tend to assume.

Now I am setting up my new Windows box for continuing that development. What would my development environment look like? Should I just cave and run Linux in a VM? Ideally I would develop in Windows native. I am aware of the Windows Ruby installer. It seems decent but its not exactly as nice as RVM in the osx/linux world. Mercurial/Git are available so I would assume they play into the stack. Does one develop entirely in Windows? Does one run a webserver in a Linux VM and use it as a test bed while developing in Windows? Do it all in a VM?

What does the standard Windows Ruby developer environment look like and what is the workflow? What would a typical step through be for adding a new feature to an ongoing project and what would the technology stack look like?

答:
I've done a lot of smallish, personal projects in Ruby on Windows 7. I haven't found it too terribly difficult to work with, but there were a few amenities that I needed to set up for myself:

I used the Windows Installer to set up the Ruby environment. It's
worked fine for me so far. However, if you think you need more than
one version of Ruby running, there's a add-on called Pik that
aims to recreate the functionality of RVM.

I made a point of upgrading the console somewhat. Some people
will suggest Cygwin. I'm a bit to lazy to bother, but I grabbed
Console2, which allows for a good deal of customization,
including tabs. I also hear tell that UnixUtils is a nice addition,
if you find yourself the grepping type.

That being said, I do have VirtualBox set up with both Linux Mint
and Ubuntu. I don't develop on them, mainly because I'm more
comfortable in the Windows environment, but it's nice to have them
around so I can test my code out in there and make sure it works on
both platforms.

I haven't bothered with a robust IDE for my Rubying yet. Notepad++
has done good by me so far, and I haven't found that it has impeded
my ability to code. I did use Netbeans awhile back, with a Ruby
plugin. It seems to be good for setting up your file system for creating
Ruby Gems if that's your goal.

I guess my testimony comes down to this: I have no problems programming Ruby on Windows. The things I've mentioned here take maybe 5 minutes to set up, max. If you're more comfortable running it in a VM or Dual Booting, that could work as well, but I don't think it's entirely necessary unless you're more comfortable in that environment. Happy coding!

(Somewhat depressingly, my low reputation disallows me from linking to all the things I mentioned up there. A Google search will turn them up. Also I realize this is late. I'm more posting it in the hopes that future stumblers upon the same question will find it useful)

ContentLicense: CC BY-SA 3.0

Title: Ruby workflow in Windows


问:
Differentiating between user script input formats
I have a .NET project at work that provides a couple of (Iron)Python scripts to the customers, to allow them to customize the output of the program. The application generates code for certain machines, and supports a couple of different formats.

Until recently, we only provided a script for one format. We're expanding upon that to include support for the others.  If the user is using a script, they select their input script before generating the output code. A script designed for Format1 output is going to cause errors if they're trying to generate Format2 output. I need to deal with this.

One option would just be to let the customers use common sense, and if they load the wrong script it will just fail, or worse, produce inaccurate data. I'm inclined to provide a little more protection than that.

At the moment I'm considering putting a shebang-style comment line at the top of the script, ala:

```<code># OUTPUT - Format1
</code>```

If the user tries to run a Format2 process with a Format1 script, it will warn them. Alternatively I could create different file extensions for the input scripts that vary by type.

The file-type comment approach helps prevent the script from actually loading improperly, at the cost of failing to warn the user until they've already selected it, via a dialog box. Using different file extensions would allow me to cut down on visual clutter when providing a File Dialog, but doesn't actually stop them from loading the wrong script.

So I'm really not sure if the right approach is to just leave it alone, or provide some safeguards.

答:
Well, no one is answering, so I suppose I'll say what we ended up doing. We ended up putting a programmatic check in the script that ensures the process passed has the correct identifying attribute (in this case, an Enum, which IronPython can compare as a string). If a process with the wrong identifying Enum is passed the script will warn the user and terminate.

Nothing prevents the user from deleting that check from their own script. The same could be said for changing the file extensions or writing a shebang-type line. Nevertheless, it does seem to get the job done without putting in too much effort.

OwnerDisplayName: KChaloux


问:
GPS accuracy with software
I spoke with a guy who claimed that he's working (programming) on a GPS-system that is going to be accurate to the centimeter.

Is this even possible?

What is the limiting factor, the big distance between the satellite and the GPS, or is it the software?

Can the software be improved to make a GPS accurate to centimeters?

答:
Civilan GPS signals are intentionally degraded because they only use one signal. All the details are available online at GPS.gov.

Military GPS uses two singles to be much more accurate.

Civilian devices can be augmented with other signal sources to be more accurate than the published Military specs. Of course the Military can augment their systems even more the same way.

Is Military GPS More Accurate Than Civilian GPS?

The accuracy of the
  GPS signal in space is actually the same for both the civilian GPS
  service (SPS) and the military GPS service (PPS). However, SPS
  broadcasts on only one frequency, while PPS uses two. This means
  military users can perform ionospheric correction, a technique that
  reduces radio degradation caused by the Earth's atmosphere. With less
  degradation, PPS provides better accuracy than the basic SPS.

It takes more hardware to make the device more accurate, more sensors reading more signals. Without the augmented signals, there is nothing that software alone can do that isn't already being done.

Title: GPS accuracy with software


答: It is my understanding that by gathering data over time you can get that kind of accuracy out of GPS.  It requires a unit that is not moving, it's for survey work and the like, not navigation.</p>

Title: GPS accuracy with software

Body:
I spoke with a guy who claimed that he's working (programming) on a GPS-system that is going to be accurate to the centimeter.

Is this even possible?

What is the limiting factor, the big distance between the satellite and the GPS, or is it the software?

Can the software be improved to make a GPS accurate to centimeters?


答:
In the good old days the US DoD had a thing called "Selective Avalibilty" -SA- - they turned this off at the beginning of the century making Civilain use of GPS more accurate, enabling things like car navigation etc. Prior to that Differenctial GPS was a widely used system for those that required greater accuracy than could be achieved with SA- DGPS is done using a ground base station at a known coordinate, that transmits the error in the GPS signal to close by GPS recievers.

Using DGPS is still possible to increase the accuracy of a GPS fix today, although its rarely used as GPS is currently accurate enough for most purposes. Other means to get higher accuracy are to plonk the receiver down for anything from an hour to a day or two and average the fix. (Surveyors use this technique.) - you need to understand what GPS accuracy is - if they say it's accurate to 10 meters, they usually mean "you are with in 10 meteres 90% of the time" or something like that. I have never seen a GPS state a 100% of the time figure.
It is therefore entirely possible to get sub-centimeter fixes from GPS (e.g. A marketing guy might claim 1 cm and then in the fine print put "Accurate to 10mm 10% of the time".

Why is this accuracy needed in your friends case? There are a few cases (surveying) where it is.  The earths model (WGS84) used by GPS is not that accruate, let alone the maps, and unlikely to be for along time, whats the point of being out by less than 1 centimetre when the error in your map has more than 1 meter error?

Title: GPS accuracy with software


问:
Non-zero exit status for clean exit
Is it acceptable to return a non-zero exit code if the program in question ran properly? For example, say I have a simple program that (only) does the following:

Program takes N arguments. It returns an exit code of min(N, 255). Note that any N is valid for the program.

A more realistic program might return different codes for successfully ran programs that signify different things. Should these programs instead write this information to a stream instead, such as to stdout?

答:
I know of a case I think is acceptable. I know of a testing framework that exits with the total number of test failures. So, for example, if the test runner completes with no failed tests it exits with zero. If one test failed, even though the test runner itself ran propely, it exits with one 1. If two fail it returns 2, etc. This goes up to 250, which means "250 or more test failures".

It uses exit codes > 250 to signify abnormal exits.

While this violates convention, it works well in practice.

Title: Non-zero exit status for clean exit


答:
There is a limit for averaging GPS position due to real random variation in the atmosphere. With single channel L1 civilian GPS this is typically 10-20 cm after 10-20mins.
Military GPS uses a second channel L2 at a slightly difference frequency so it can estimate some of the atmospheric effect and allow for it.

It is possible to make cm accurate differential readings of the relative positions of two nearby receivers over the same time period - since the atmosphere effects will cancel out - although you won't know your absolute position on Earth any more accurately. You can get a differential signal from a broadcast fixed beacon in a known place then you have an accurate and known absolute position. There are networks of fixed beacons run either by national mapping agencies or GPS makers - and depending how far away the nearest one is - tis can also give cm precision in a few minutes.

With special survey units which can communicate and transmit the signal phase (Real Time Kinematic - RTK GPS) you can make mm accurate position measurements of a moving GPS unit in real time, relative to a fixed base station.

Title: GPS accuracy with software


答: You can use software to compare the readings from 2 (or more) matched GPS receivers which are looking at the same set of satellites to cancel out any differences in (the many sources of) absolute errors.  If you stick one on a centimeter accurate benchmark, and the other is nearby with the same sky view, you can use software to compute the difference and add that to the known benchmark location.</p>

Title: GPS accuracy with software


答:
It really depends what you are trying to convey with the code.  DB2, for example returns 100 if there is no data found, various other positive values for warnings, and negative values for errors.  Oracle does something similar.

So, if there are different success states, it may be worth using varying return values.

Title: Non-zero exit status for clean exit

Body:
Is it acceptable to return a non-zero exit code if the program in question ran properly? For example, say I have a simple program that (only) does the following:

Program takes N arguments. It returns an exit code of min(N, 255). Note that any N is valid for the program.

A more realistic program might return different codes for successfully ran programs that signify different things. Should these programs instead write this information to a stream instead, such as to stdout?


问:
Implementing a "state-machine" logic for methods required by an object in C++
What I have: 1 hypothetical object/class + other classes and related methods that gives me functionality.

What I want:

linking this object to 0 to N methods in realtime on request when an event is triggered

Each event is related to a single method or a class, so a single event does not necessarily mean "connect this 1 method only" but can also mean "connect all the methods from that class or a group of methods"

Avoiding linked lists because I have to browse the entire list to know what methods are linked, because this does not ensure me that the linked methods are kept in a particular order (let's say an alphabetic order by their names or classes), and also because this involve a massive amount of pointers usage.

Example:

I have an object Employee Jon, Jon acquires knowledge and forgets things pretty easily, so his skills may vary during a period of time, I'm responsible for what Jon can add or remove from his CV, how can I implement this logic?

答:
With regard to 1. and 2.

What you're describing doesn't really sound like a 'state machine' to me (And i'm afraid that I couldn't make much sense of the example in the context of what you described).

A state machine typically involves transitioning between known states when a a condition is hit for that particular state;  it sounds more like you're trying to store a list of event subscriptions which may change arbitrarily over time - for this you probably need something like the Observer pattern.

With regard to 3.

I have never encountered any situation in C++ where a hand-written linked list is at all desirable; you should prefer the standard libraries as a general rule-of-thumb.  std::deque or std::map might be a good starting point as a means to storing subscribers/observers.

Using a modern C++11 compiler, you could implement a std::map< std::string, std::function<T>>  for each of the events which you wish to subscribe to (with the string/key being used to identify the observer's target for later removing or modifying the subscription).

std::function< T > lets you use any kind of callable object, lambda, function or curried function binder as the subscriber, whose callable signature matches T.

for example, with std::function< void() > you could reasonably use

```<code>std::function<void()> fred = [](){ std::cout << "hello world"; };
fred();  // call the lambda
</code>```

or

```<code>struct foo {
    void operator() () { std::cout << "hello world"; }
};

std::function<void()> bob = foo();
bob();  // call the functor
</code>```

or

```<code>void foo() { std::cout << "hello world"; }

// ---------------------------------------

    std::function<void()> blah = foo;
    blah();   // call the function
</code>```

or

```<code>class MyClass
{
public:
    void func() { std::cout << "hello world" << std::endl; }
};

// -----------------------------------------------------

    MyClass obj;
    std::function<void()> meow = std::bind( &MyClass::func, obj );

    meow();  // Call the member function using the object
</code>```

From this, It should be fairly easy to imagine a container full of std::function objects.  Of course, you could also wrap std::function in another class if needed (which would take you a little closer to the GoF Observer Pattern).

Body:
With regard to 1. and 2.

What you're describing doesn't really sound like a 'state machine' to me (And i'm afraid that I couldn't make much sense of the example in the context of what you described).

A state machine typically involves transitioning between known states when a a condition is hit for that particular state;  it sounds more like you're trying to store a list of event subscriptions which may change arbitrarily over time - for this you probably need something like the Observer pattern.

With regard to 3.

I have never encountered any situation in C++ where a hand-written linked list is at all desirable; you should prefer the standard libraries as a general rule-of-thumb.  std::deque or std::map might be a good starting point as a means to storing subscribers/observers.

Using a modern C++11 compiler, you could implement a std::map< std::string, std::function<T>>  for each of the events which you wish to subscribe to (with the string/key being used to identify the observer's target for later removing or modifying the subscription).

std::function< T > lets you use any kind of callable object, lambda, function or curried function binder as the subscriber, whose callable signature matches T.

for example, with std::function< void() > you could reasonably use

std::function<void()> fred = [](){ std::cout << "hello world"; };
fred();  // call the lambda

or

struct foo {
    void operator() () { std::cout << "hello world"; }
};

std::function<void()> bob = foo();
bob();  // call the functor

or

void foo() { std::cout << "hello world"; }

// ---------------------------------------

    std::function<void()> blah = foo;
    blah();   // call the function

or

class MyClass
{
public:
    void func() { std::cout << "hello world" << std::endl; }
};

// -----------------------------------------------------

    MyClass obj;
    std::function<void()> meow = std::bind( &MyClass::func, obj );

    meow();  // Call the member function using the object

From this, It should be fairly easy to imagine a container full of std::function objects.  Of course, you could also wrap std::function in another class if needed (which would take you a little closer to the GoF Observer Pattern).


问:
Observer pattern for unpredictable observation time
I have a situation where objects are created at unpredictable times. Some of these objects are created before an important event, some after. If the event already happened, I make the object execute stuff right away. If the event is forthcoming, I make the object observe the event. When the event triggers, the object is notified and executes the same code.

```<code>if (subject.eventAlreadyHappened()) {
    observer.executeStuff();
} else {
    subject.subscribe(observer);
}
</code>```

Is there another design pattern to wrap or even replace this observer pattern? I think it looks a little dirty to me.

答:
An alternative would be as follows.

Observers are notified of the event through the method

```<code>// Method on all observers.
void notify(Event event)
</code>```

All new objects are subscribed to the notification, so the subject, instead
of

```<code>if (subject.eventAlreadyHappened()) {
    observer.executeStuff();
} else {
    subject.subscribe(observer);
}
</code>```

does simply

```<code>subject.subscribe(observer);
</code>```

When the event occurs, the subscribed observer are notified, and the event is cached:

```<code>// Method on subject.
void handleEvent(Event event)
{
    // lastEvent is a member variable of subject.
    lastEvent = event;
    ...
    for (Observer observer : subscribedObservers())
    {
        observer.notify(event);
    }
}
</code>```

When a new object is subscribed, it is notified immediately if the event
has occurred already:

```<code>// Method on subject.
void subscribe(Observer observer)
{
    // Add observer to list.

    ...

    if (lastEvent != null)
    {
        observer.notify(lastEvent);
    }
}
</code>```

Finally, the observer has a method notify:

```<code>// Method on observer.
void notify(Event event)
{
    executeStuff();
}
</code>```

So basically the difference is that the subject immediately sends
a notification to a newly subscribed object if at the moment of subscription
the event has already occurred.

I hope this helps.

Body:
An alternative would be as follows.

Observers are notified of the event through the method

// Method on all observers.
void notify(Event event)

All new objects are subscribed to the notification, so the subject, instead
of

if (subject.eventAlreadyHappened()) {
    observer.executeStuff();
} else {
    subject.subscribe(observer);
}

does simply

subject.subscribe(observer);

When the event occurs, the subscribed observer are notified, and the event is cached:

// Method on subject.
void handleEvent(Event event)
{
    // lastEvent is a member variable of subject.
    lastEvent = event;
    ...
    for (Observer observer : subscribedObservers())
    {
        observer.notify(event);
    }
}

When a new object is subscribed, it is notified immediately if the event
has occurred already:

// Method on subject.
void subscribe(Observer observer)
{
    // Add observer to list.

    ...

    if (lastEvent != null)
    {
        observer.notify(lastEvent);
    }
}

Finally, the observer has a method notify:

// Method on observer.
void notify(Event event)
{
    executeStuff();
}

So basically the difference is that the subject immediately sends
a notification to a newly subscribed object if at the moment of subscription
the event has already occurred.

I hope this helps.


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

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

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

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

Thanks!

答:
This is perhaps slightly off-topic, but hopefully still useful feedback for anyone considering doing video tutorials

If the video is basically slides with speaking, please provide a non-video version with images and a transcript as well.

I can read far faster than people can talk, and it can be incredibly frustrating having to sit through even a short video - especially so when I'm listening to music, and just want to know how to do whatever the tutorial is teaching.

(This has the added benefit of allowing the content of the tutorial to be indexed, thus increasing exposure to the tutorial in general.)

ContentLicense: CC BY-SA 2.5


问:
Releasing patches and updates to web service users
I have written one web services using Java. Its already live (up and running).

During development I have SVN (repository) + Jira for task maintenance + Maven for building the web services. Now I have some small update for my web services and I have created that task in Jira and committed the files in svn with respect to Jira-Id after all testing, etc.

Say my web services is used by 10 clients, we did not give our source code to them.

Is there any steps/procedure available to release patch/updates?

Is there any way to render/create the change log at the build time (maven)?

How do I manage the change log for all version or Patch updates during build time?   (Automatically)

答:
If you use maven already, then consider making a private maven repository accessible to your customers providing your binary artifacts, and have your installations have "pom.xml" file for assembling the final installation.

Use the "[...)" syntax to specify you want the newest version within the given range.

You can then use a simple "mvn clean package" at the client to get the newest version.


答:
I think there is a precedent if the exit code is returning meaningful, relevant information to the caller and the definition of success isn't really binary. The precedent I'm thinking of is robocopy which returns a slew of different things depending on what happened.

I'll add that we always end up having some debugging because of this -- most utility assume exit code 0 == success so get freaked out when robocopy returns 1 because it copied stuff not zero because it didn't copy stuff but didn't get an error either.

Title: Non-zero exit status for clean exit


问:
What kinds of projects is SCRUM considered to be suitable for?
I have been using SCRUM in three different projects over the last four years. One of SCRUM's advantages seems to be its flexibility and adaptability, e.g. wrt to changing customer requirements. Another advantage is that management can easily track the progress of a project.

SCRUM's flexibility can be an advantage e.g. when implementing a web application, where the requirements change very fast and the customers really understand what they want after they've seen a prototype.

On the other hand there are other kinds of software projects (e.g. in aerospace industry) where the requirements are pretty fixed: you get a requirement specification document and you have to come back six months later with working software and complete documentation. For this kinds of projects I doubt that the flexibility offered by SCRUM is needed (in the sense that you do not need to build prototypes and show them to the customer to get feedback on the requirements): you rather need a very structured and systematic approach, which is probably repeated over and over again for each project with little room for surprise.

So is SCRUM considered by its proponents a general-purpose software development
methodology or is it considered especially suited for certain categories
of projects or application areas?

For example, I recently looked at the website of a company producing
software for the aerospace industry and noticed that they are using the
V-model. Would a SCRUM proponent say that SCRUM is less suited for this
kind of projects or rather suggest that this company should try switching
to SCRUM?

Note that I am not asking for the opinion of the readers of this forum, but
I want to know what is the established opinion among SCRUM proposers: is SCRUM considered general-purpose or rather suitable for certain classes of
projects only? In the latter cases, for what kinds of projects?

答:
Please note that Scrum is not a methodology, but a framework.

Scrum will work best in a cross-functional team from 5 to 9 developers working on a medium to large size project (from 4 months to multiple years). If your project is larger, you can scale with Scrum of Scrums.

I will not discuss the cross-functional thing here, but here are what the official Scrum Guide is telling for the team size:

Optimal Development Team size is small enough to remain nimble and large enough to
  complete significant work. Fewer than three Development Team members decreases interaction
  and results in smaller productivity gains. Smaller Development Teams may encounter skill
  constraints during the Sprint, causing the Development Team to be unable to deliver a
  potentially releasable Increment. Having more than nine members requires too much
  coordination. Large Development Teams generate too much complexity for an empirical process
  to manage. The Product Owner and Scrum Master roles are not included in this count unless
  they are also executing the work of the Sprint Backlog

A sprint is about one month.

Sprints are limited to one calendar month. When a Sprint’s horizon is too long the definition of what is being built may change, complexity may rise, and risk may increase. Sprints enable predictability by ensuring inspection and adaptation of progress toward a goal at least every calendar month. Sprints also limit risk to one calendar month of cost.

I think it doesn't make sense to use a framework based on an iterative process with projects smaller than 4 months. 4 months = 4 sprints. You must also consider that you get a more accurate velocity after 3 sprints.

That said, I personally use a limited version of Scrum for smaller projects. But you can't really call it Scrum then. In that particular case, you are using some core principles of Scrum in your own implementation of the framework.


问:
How to stop a .NET application from being duplicated?
I have created a .net windows form application that I want to restrict from being duplicated. I want this application to be portable, so I would like to allow it to be moved. How would I be able to do this without managing it through a remote server?</p>

答:
That's a pretty elusive target.

The tighter you bind your application to a particular location, the less happy your customers will be with you whenever the inevitable computer maintenance comes up.  And it comes up quite frequently.

One trick is to bind to particulars within the hardware of the device.  MS Windows XP and additional MS products are a good case study on this approach.  This usually requires a phone home or call to somewhere approach.

Another method is to have the application phone home with the registration code to receive an unlock signal.  Win 7 and Win 2008 enterprise licensing use this approach.  Quite a few other applications do this as well.  Again, generally, you need a remote server available to be called.  MS allows enterprises to set up their own license servers though.

Dongles are yet another method.  They're kind of expensive to get started with, and they don't slow down the true crackers (or is that crackerz?).

You could always time-bound your activation codes, say for 24 hours or a week.  After the time period expires, a new code has to be issued.

At some point, you need to trust that your users aren't going to rip you off.  If you think about it, they're trusting you to give them a quality product, so it's not unfair for some of that trust to be reciprocated.


问:
Python and only Python for almost any programming tasks!
Am I wrong if I think that Python is all I need to master, in order to solve most of the common programming tasks?

EDIT
I'm not OK with learning new programming languages if they don't teach me new concepts of programming and problem solving; hence the idea behind mastering a modern, fast evolving, with a rich set of class libraries, widely used and documented, and of course has a "friendly" learning curve programming language.

I think that in the fast evolving tech industry, specialization is key to success.

答: I wouldn't say that you are wrong at all. Python is a multi-domain, general-purpose programming language.</p>


问:
Why is there no service-oriented language?
Edit:

To avoid further confusion: I am not talking about web services and such. I am talking about structuring applications internally, it's not about how computers communicate. It's about programming languages, compilers and how the imperative programming paradigm is extended.

Original:

In the imperative programming field, we saw two paradigms in the past 20 years (or more): object-oriented (OO), and service-oriented (SO) aka. component-based (CB).

Both paradigms extend the imperative programming paradigm by introducing their own notion of modules. OO calls them objects (and classes) and lets them encapsulates both data (fields) and procedures (methods) together. SO, in contrast, separates data (records, beans, ...) from code (components, services).

However, only OO has programming languages which natively support its paradigm: Smalltalk, C++, Java and all other JVM-compatibles, C# and all other .NET-compatibles, Python etc.

SO has no such native language. It only comes into existence on top of procedural languages or OO languages: COM/DCOM (binary, C, C++), CORBA, EJB, Spring, Guice (all Java), ...

These SO frameworks clearly suffer from the missing native language support of their concepts.

They start using OO classes to represent services and records. This leads to designs where there is a clear distinction between classes that have methods only (services) and those that have fields only (records). Inheritance between services or records is then simulated by inheritance of classes. Technically, its not kept so strictly but in general programmers are adviced to make classes to play only one of the two roles.

They use additional, external languages to represent the missing parts: IDL's, XML configurations, Annotations in Java code, or even embedded DSL like in Guice. This is especially needed, but not limited to, since the composition of services is not part of the service code itself. In OO, objects create other objects so there is no need for such facilities but for SO there is because services don't instantiate or configure other services.

They establish an inner-platform effect on top of OO (early EJB, CORBA) where the programmer has to write all the code that is needed to "drive" SO. Classes represent only a part of the nature of a service and lots of classes have to be written to form a service together. All that boiler plate is necessary because there is no SO compiler which would do it for the programmer. This is just like some people did it in C for OO when there was no C++. You just pass the record which holds the data of the object as a first parameter to the procedure which is the method. In a OO language this parameter is implicit and the compiler produces all the code that we need for virtual functions etc. For SO, this is clearly missing.

Especially the newer frameworks extensively use AOP or introspection to add the missing parts to a OO language. This doesn't bring the necessary language expressiveness but avoids the boiler platform code described in the previous point.

Some frameworks use code generation to produce the boiler plate code. Configuration files in XML or annotations in OO code is the source of information for this.

Not all of the phenomena that I mentioned above can be attributed to SO but I hope it clearly shows that there is a need for a SO language. Since this paradigm is so popular: why isn't there one? Or maybe there are some academic ones but at least the industry doesn't use one.

答:
Because <5% of code is actually defining a service, and I would argue a substantially less amount of time. Once the interface is defined, it's largely done. The rest of the time is spent in OO (or alternatives) making things work.

Simply put, it's not a big win to make a specialized language for that small slice of the problem. If anything, having two languages (one for the service and one for the implementation/consumption) is just asking for added integration complexity.

[edit for the OPs clarification that it's internal application layout, not application boundary]:

The main goal of having such a service layout is to have thin touchpoints between services. My original reason still holds (imo) and add to that answer the fact that relatively few problems suit themselves well towards an internal application structure that is service based. So not only are you addressing a small slice of the problem, but a lower percentage of problems overall.


答:
Service Orientation was/is an architectural answer to integration problems. Integration ideally is an all-inclusive solution which fits any existing language, product, device, resource into a bigger picture.

There is no need for some new language, as the very problem is about having too many languages already, which causes high interoperability cost.

However, there was one kind of language introduced, the web service definition language. WSDL is meta language of S.O.A. (and there is another abandoned one for REST named WADL)

Title: Why is there no service-oriented language?

Body:
Edit:

To avoid further confusion: I am not talking about web services and such. I am talking about structuring applications internally, it's not about how computers communicate. It's about programming languages, compilers and how the imperative programming paradigm is extended.

Original:

In the imperative programming field, we saw two paradigms in the past 20 years (or more): object-oriented (OO), and service-oriented (SO) aka. component-based (CB).

Both paradigms extend the imperative programming paradigm by introducing their own notion of modules. OO calls them objects (and classes) and lets them encapsulates both data (fields) and procedures (methods) together. SO, in contrast, separates data (records, beans, ...) from code (components, services).

However, only OO has programming languages which natively support its paradigm: Smalltalk, C++, Java and all other JVM-compatibles, C# and all other .NET-compatibles, Python etc.

SO has no such native language. It only comes into existence on top of procedural languages or OO languages: COM/DCOM (binary, C, C++), CORBA, EJB, Spring, Guice (all Java), ...

These SO frameworks clearly suffer from the missing native language support of their concepts.

They start using OO classes to represent services and records. This leads to designs where there is a clear distinction between classes that have methods only (services) and those that have fields only (records). Inheritance between services or records is then simulated by inheritance of classes. Technically, its not kept so strictly but in general programmers are adviced to make classes to play only one of the two roles.

They use additional, external languages to represent the missing parts: IDL's, XML configurations, Annotations in Java code, or even embedded DSL like in Guice. This is especially needed, but not limited to, since the composition of services is not part of the service code itself. In OO, objects create other objects so there is no need for such facilities but for SO there is because services don't instantiate or configure other services.

They establish an inner-platform effect on top of OO (early EJB, CORBA) where the programmer has to write all the code that is needed to "drive" SO. Classes represent only a part of the nature of a service and lots of classes have to be written to form a service together. All that boiler plate is necessary because there is no SO compiler which would do it for the programmer. This is just like some people did it in C for OO when there was no C++. You just pass the record which holds the data of the object as a first parameter to the procedure which is the method. In a OO language this parameter is implicit and the compiler produces all the code that we need for virtual functions etc. For SO, this is clearly missing.

Especially the newer frameworks extensively use AOP or introspection to add the missing parts to a OO language. This doesn't bring the necessary language expressiveness but avoids the boiler platform code described in the previous point.

Some frameworks use code generation to produce the boiler plate code. Configuration files in XML or annotations in OO code is the source of information for this.

Not all of the phenomena that I mentioned above can be attributed to SO but I hope it clearly shows that there is a need for a SO language. Since this paradigm is so popular: why isn't there one? Or maybe there are some academic ones but at least the industry doesn't use one.


答:
I'll offer an answer to my own question to see how many people agree and disagree.

Some possibilities:

It seems to be difficult to construct a SO language. Mostly because of the separation of the implementation of services and their composition. There are a couple of academic solutions I heard of at university (no reference, sorry) but it doesn't seem to make it into the industry. But I count this as a excuse, not a real reason. OO languages and compilers are pretty difficult to implement, too, yet there are solutions on the market for a long time.

Programmers use OO languages for SO because they don't understand OO and use it in a wrong way. I say wrong because there are two fundamental concepts in OO which contradict SO:

Functionality goes to the class where the data is located that they work on. Code and data are coupled together in the same module. It's not OO style to have separate classes that work on the data of other classes. That's Züllighofen's Tools-and-materials approach (WAM) which matches the SO paradigm.

Objects create other objects and form networks of objects. They can create hierarchies or whatever complex relations. Services always form flat networks which are composed from the outside. Services usually have only one instance (Singleton) whereas objects are instantiated as often as the entity they represent exists. Records in SO are not connected in networks.

Some features of OO look similar to SO, or can be used to facilitate what is needed for SO so it comes in handy to use a OO language.

The dependency-inversion principle in OO is similar to the way services are composed externally.

Singleton objects are like services, object factories are like service locators.

OO also has interfaces which is similar to service interfaces.

Inheritance of classes can similar (the same?) as inheritance of services and records.

OO and SO are useful for different kinds of problems. So in every applications it is tempting to use either paradigm here or there. Having a separate language would hamper switching between the two within the same program.

SO is not only a programming paradigm but also a program behavior: web services, operating system components etc. are SO but don't need to be written in a SO language necessarily. This kind of "binary components" is very natural and successful. But it's a different thing: it's how programs communicate with each other, not how the program communicates internally. I guess people mix that up often enough.


答:
I'll turn the question around and ask "what would an SO language look like?"

How would those contracts between modules get written?

How would the fundamental mechanics of operation get executed?

Services oriented is a property of the application, not necessarily the language used.  The service is a construct which relies upon a function.  The function is a construct that relies upon the mechanics of a programming language to translate operation into machine executable instructions.

BPEL is  a possible example of an SO language, but it is very high level and relies upon modules being available for it to utilize.  Those modules are in turn written in non-BPEL languages so work can be performed (aka translated into machine language).

Great Q and gave me a good moment's reflection.


答:
While this is not a solution, it may help shed some light on some of the threats and your options. As @GlenH7 says "That's a pretty elusive target.". I need to mention here that I am not an excerpt in this field, so take the advice with a grain of salt!

You could use the technique of binding your software key to the Hard Drive Volume Serial Number. The downsides are:

1 - If your user re-formats the disk, they will probably need to contact you again unless they use the same old serial number.

2 - There are programs that allows for Hard disk serial number change. So if your user knows about this, he can distribute the software and use this program to fool your program. To prevent this, you may need more information about the hardware to incorporate it in your code. You may then want to use a utility to provide such information such as CPUID-PRO.

The other threat is the the end-user may be able to reverse engineer your code from assemblies and get your db schema as well. I am not sure there are easy and effective ways against that.

Title: How to stop a .NET application from being duplicated?

Body: I have created a .net windows form application that I want to restrict from being duplicated. I want this application to be portable, so I would like to allow it to be moved. How would I be able to do this without managing it through a remote server?</p>


答:
Python is an extremely flexible general-purpose programming language, it has been used to write nearly anything imaginable, except OS kernel (QUICK UPDATE: in fact it has: http://mail.python.org/pipermail/python-announce-list/2004-July/003220.html).

However, it's always good to learn new languages, especially one that is very different from the languages you already know about.

Title: Python and only Python for almost any programming tasks!

Body:
Am I wrong if I think that Python is all I need to master, in order to solve most of the common programming tasks?

EDIT
I'm not OK with learning new programming languages if they don't teach me new concepts of programming and problem solving; hence the idea behind mastering a modern, fast evolving, with a rich set of class libraries, widely used and documented, and of course has a "friendly" learning curve programming language.

I think that in the fast evolving tech industry, specialization is key to success.


问:
What is Rainbow (not the CMS)
I was reading this excellent blog article  regarding speeding up the badge page and in the last comment the author waffles (a.k.a Sam Saffron) mentions these tools:

dapper and a bunch of custom helpers like rainbow, sql builder etc

Dapper and sql builder was easy to look up but rainbow keeps pointing me to a CMS, can someone please point me to the real source? Thanks.

Obviously the architecture of these [SE] sites is uber cool and ultra fast so no comments on that thanks.

答:
Author apparently refers to Dapper.Rainbow micro-ORM used in Stack Exchange Data Explorer.

Project home page at NuGet Gallery - http://nuget.org/packages/Dapper.Rainbow

Trivial micro-orm implemented on Dapper, provides with CRUD helpers.

  ...

  The implementation was extracted from http://data.stackexchange.com source at: http://code.google.com/p/stack-exchange-data-explorer/ .

  Data explorer uses "Rainbow" exclusively for all database access.

  ...

Authors

    Sam Saffron

  ...

Title: What is Rainbow (not the CMS)


问:
De-facto standards for customer information record
I'm currently evaluating a potential new project that involves creating a DB for typical customer information (userid, pwd, first & last name, email, adress, telfnr ...). At this point, requirements are only roughly defined.

The customer DB is expected in the O(millions) of records. In order to calculate some back-of-the-envelope numbers for DB sizing and evaluate potential DB options & architectures, I'm looking for some de-facto standards for these kind of records. In particular, the std size of every field (first name, last name, address,...) or typical avg for a simple customer record would be great info.

With so many e-commerce websites out there, there should be some kind of typical config that can be reused and avoid re-inventing the wheel.

Any ideas?

---- edit ----

The answers seems to be steering towards adopting an standard customer record vs designing your own. I would like to stress that the focus of this question is to locate a reference for field sizing for a customer object, and avoid figuring that out on my own.(I've emphasized that part on the original text -now in bold-)

答: I'd say you need to find standards for EDI systems. There are hundreds of 'standard' documents, so you'd need to choose one based on your requirements. For example, here's a format for TRADACOMS invoice that you could grab fields you want from.</p>


答: Carrier phase tracking can achieve an accuracy of 0.2 centimeter. At that point, you need to clearly define "accuracy" because maps, or even the earth's shape aren't that well defined.</p>

Title: GPS accuracy with software


答:
The nice thing about standards is that you have so many to choose
  from. - Andrew Stuart Tanenbaum

Things like this are very specific to a customer and the industry, anything generic will include everything and the kitchen sink. Especially EDI type formats, they were organically defined over a decade or more in most cases and include everything every company on the committee ever wanted. They were supposed to be industry generic, and they became extremely industry specific and extremely brittle.

There is no royal road to the design or information you want. Do the time and the effort to get the requirements and get a concrete estimate. Otherwise you will be more wrong than correct. The only way to know what you need to know is to ask the questions and figure it out yourself.

Many CRM systems use what is now called an Expando object pattern, previously known as a dynamic property pattern. It is basically a key value pair dictionary construct. Except for very special cases it is considered an design Anti-Pattern and should be avoided.

I have designed and built at least 8 custom CRM solutions in the last 20 years, each and everyone had different requirements and none of the data models ( logical or physical ) would have worked across the board for all the domains.

Specific solutions for specific cases will always be better designs.

Title: De-facto standards for customer information record

Body:
I'm currently evaluating a potential new project that involves creating a DB for typical customer information (userid, pwd, first & last name, email, adress, telfnr ...). At this point, requirements are only roughly defined.

The customer DB is expected in the O(millions) of records. In order to calculate some back-of-the-envelope numbers for DB sizing and evaluate potential DB options & architectures, I'm looking for some de-facto standards for these kind of records. In particular, the std size of every field (first name, last name, address,...) or typical avg for a simple customer record would be great info.

With so many e-commerce websites out there, there should be some kind of typical config that can be reused and avoid re-inventing the wheel.

Any ideas?

---- edit ----

The answers seems to be steering towards adopting an standard customer record vs designing your own. I would like to stress that the focus of this question is to locate a reference for field sizing for a customer object, and avoid figuring that out on my own.(I've emphasized that part on the original text -now in bold-)


答:
Yes

You would be wrong to think that any single language can do everything without considering other languages.

I think that in the fast evolving tech industry, specialization is key to success.

I can't think of a better way to shoot yourself in the foot. Learning and mastering a language is great, but you mention you aren't comfortable with learning new languages if they "don't teach me new concepts of programming and problem solving."

Languages don't teach you these concepts, thick dusty tomes and many years working closely with people better then yourself does. These basic patterns, concepts, and principals of design transcend languages and can be applied in many different scopes.


问:
Is case after case in a switch efficient?
Just a random question regarding switch case efficiency in case after case; is the following code (assume pseudo code):

```<code>function bool isValid(String myString){
   switch(myString){
   case "stringA":
   case "stringB":
   case "stringC":
      return true;
   default:
      return false;
}
</code>```

more efficient than this:

```<code>function bool isValid(String myString){
   switch(myString){
   case "stringA":
      return true;
   case "stringB":
      return true;
   case "stringC":
      return true;
   default:
      return false;
}
</code>```

Or is the performance equal? I'm not thinking in a specific language but if needed let's assume it's Java or C (for this case would be needed to use chars instead of strings).

答:
It quite depends on compiler. However, as a simple rule, switch is uses JUMP statement (equivalent to GO TO statement) to start from desired point on match condition. So in this case, if multiple condition jumps to same segment or code or different it doesn't add additional conditional check overhead.

One more comparison :

the code if(arg == CASE_1 || arg == CASE_2 || arg == CASE_3) will actually add conditional check with arg == CASE_1 as well as arg == CASE_2 even if arg is actually CASE_3. On the other hand, switch will result in only 1 comparison operation in either way.

In both the above case, i think number of CPU cycles will be identical - because they will amount to 1 condition check and one pop instruction. However, the later will take 2 more redundant instruction in memory. So it is slightly inefficient from code size point of view.


答:
Efficiency shouldn't be your concern here.

Code complexity and maintainability should be your primary concern here.

You should question whether you're operating at the appropriate level of abstraction here.

Emphasis: Why do you feel the need to reach for this hammer (i.e. many case statements in a switch block)?

Recommendation: Take a look at this question on SO.

Title: Is case after case in a switch efficient?

Body:
Just a random question regarding switch case efficiency in case after case; is the following code (assume pseudo code):

```<code>function bool isValid(String myString){
   switch(myString){
   case "stringA":
   case "stringB":
   case "stringC":
      return true;
   default:
      return false;
}
</code>```

more efficient than this:

```<code>function bool isValid(String myString){
   switch(myString){
   case "stringA":
      return true;
   case "stringB":
      return true;
   case "stringC":
      return true;
   default:
      return false;
}
</code>```

Or is the performance equal? I'm not thinking in a specific language but if needed let's assume it's Java or C (for this case would be needed to use chars instead of strings).


问:
The best way to have a pointer to several methods - critique requested
I'm starting with a short introduction of what I know from the C language:

a pointer is a type that stores an adress or a NULL

the * operator reads the left value of the variable on its right and use this value as address and reads the value of the variable at that address

the & operator generate a pointer to the variable on its right

So I was thinking that in C++ the pointers can work this way too, but I was wrong. To generate a pointer to a static method I have to do this:

```<code>#include <iostream>

class Foo{
    public:
    static void dummy(void){ std::cout << "I'm dummy" << std::endl; };
};

int main(){
    void (*p)();
    p = Foo::dummy; // step 1
    p();
    p = &(Foo::dummy); // step 2
    p();
    p = Foo; // step 3
    p->dummy();
    return(0);
}
</code>```

Now I have several questions:

Why does step 1 work?

Why does step 2 work too? Looks like a "pointer to pointer" for p to me, very different from step 1.

Why is step 3 the only one that doesn't work, and is the only one that makes some sort of sense to me, honestly?

How can I write an array of pointers or a pointer to pointers structure to store methods (static or non-static from real objects)?

What is the best syntax and coding style for generating a pointer to a method?

答:
what is the best syntax and coding style for generating a pointer to a
  method?

Don't. Use std::function<void()>.

Now, on to the steps. Step 1 is technically illegal, but your compiler allowed it by implicitly taking the address for you. Step 2 is how it should be done. The name of a static function (in this case, Foo::dummy) is a function lvalue and must have it's address taken to be legal C++ and yield a function pointer.

Step 3 simply doesn't make any sense at all. You're trying to assign ... a run-time function pointer ... to a type? That makes no sense whatsoever. And then you try to access ... a member ... of a function pointer? Does not compute.

There are two parts to the answer "What do I do when I want to X in C++?". The first part, for C veterans only, is "Forget whatever you think you learned in C". The second part is about doing X.

how can i write an array of pointers or a pointer to pointers
  structure to store methods ( static or non-static from real objects )

```<code>std::vector<std::function<void()>> arr;
</code>```

le done.

Body:
what is the best syntax and coding style for generating a pointer to a
  method?

Don't. Use std::function<void()>.

Now, on to the steps. Step 1 is technically illegal, but your compiler allowed it by implicitly taking the address for you. Step 2 is how it should be done. The name of a static function (in this case, Foo::dummy) is a function lvalue and must have it's address taken to be legal C++ and yield a function pointer.

Step 3 simply doesn't make any sense at all. You're trying to assign ... a run-time function pointer ... to a type? That makes no sense whatsoever. And then you try to access ... a member ... of a function pointer? Does not compute.

There are two parts to the answer "What do I do when I want to X in C++?". The first part, for C veterans only, is "Forget whatever you think you learned in C". The second part is about doing X.

how can i write an array of pointers or a pointer to pointers
  structure to store methods ( static or non-static from real objects )

std::vector<std::function<void()>> arr;

le done.


问:
Ruby using the Gosu framework: why it runs slow first time?
I'm creating a Ruby game using the Gosu framework. All good.

Sometimes, when I run the game, it has some kind of slow startup, and probably it will be rather slow during the whole game. So I close it and... open it again. It is very likely that it will startup quickly and the whole game will run smoothly and fast.

Why is that? What is this phenomenon? Is it faster because of some cache stored or whatever since the first run? (But why would cache be stored? If the app dies, I would expect no references at all etc...)

Ruby, Windows 7.

答: Windows will wait until that memory is needed for something else before paging out your game's files. But when it does, they will have to be reloaded from the hard drive, which is le expensive.</p>


答: You may be able to solve many problems with it but it won't always be the best tool for the job.</p>


问:
Why did Golang discontinue the "netchan" package?
The Golang "netchan" package seems to have been discontinued.

That makes me think that the concept of "networked channels" were not a good practice after all.  (Why wouldn't them just "let it be" otherwise?)

Is this the case?  And if it is, why is that?

答:
The old netchan was too intricate.

The problem is to find a way to provide Go channel semantics on top of
  network hardware and software that, as always, finds a way to defeat
  all attempts at clean design.

I will continue to ponder.

-rob

new netchan


答:
Layout of case labels is not the bottleneck in this code - string comparison is.

Typically for case labels the compiler is just going to generate a simple jump table and go to the appropriate line of code depending on the value being tested.  This is important knowledge - the code that you write in a high-level language often bears very little resemblance to the low-level representation of it that the compiler generates.  So you can't make a direct observation about potential performance just by looking at the high-level code.

In the case of C#/Java/whatever, languages which allow strings to appear as case label entries, the rules change.  Now the compiler can no longer generate a jump table, it has to do a lot of string comparisons to determine the appropriate branch to follow.  And strings are slow.

If you're worried about efficiency of this code, then consider using an enum instead.  If you can't (or won't), you can get extra performance out of it by putting the most commonly hit conditions at the top.  If this isn't a performance-critical part of your program then do nothing - it's already good enough.


问:
How do you find partners for open source projects?
I've created a few open-source projects in the past, and had some success. The process was generally the following: I'd start alone, create something that works, promote it, and finally (maybe) get some contributions.

I have less that to contribute to open-source now, but I still have ideas and can still code :) So I wonder if there is a place or a way to meet people (online), discuss ideas and design, and then start working together on the project?

The reason I'm thinking about an online way to do this, with strangers, is that while I do have programmer friends, we only very rarely have the same needs and interests at the same time. It seems to me that it would be easier to find such in match in the online global community.

Any insight?

答:
Repositories like GitHub, CodePlex, BitBucket not only provide free hosting for open source projects, but also ideally suited for online collaboration. Placing your project code at one of them would be a good starting point.

Interesting project ideas tend to magnet congenial developers around them. One of good continuously and actively evolving examples is FSharpX.

Mentioning your project repository at popular blogs and StackExchange sites may also help attracting right people.


答:
I don't think there is a single place for this This heavily depends on the area of the software you develop. If you for instance create software for navigation aspects for gliders doing a winch launch a general site won't give you many contributors, but you have to go into the glider community and find developers there.

The best way is to get users in the area the software is for. Once you have users they will have ideas. And the more users you have, the more likely it gets that some of them are developers and look into it and try to improve it.

Starting a project with "strangers" from the Internet is hard. I tried that multiple times with people from different mailing lists and most of them failed since we didn't really cooperated well as we knew each other too little. In my experience it is better to have somebody bootstrap the project and then get contributors.

What helps in general is to have some documentation about the general architecture and where to look for. I sometimes look at software I'm using and extend it to fit my needs but have to spent quite sometime till I have the first working patch.

It's also useful to have English comments and identifiers, even if that isn't your native language as that's simply, unless you're writing code very specific to a a specific area. (a tax software for German taxes should use German wording etc.)

Title: How do you find partners for open source projects?

Body:
I've created a few open-source projects in the past, and had some success. The process was generally the following: I'd start alone, create something that works, promote it, and finally (maybe) get some contributions.

I have less that to contribute to open-source now, but I still have ideas and can still code :) So I wonder if there is a place or a way to meet people (online), discuss ideas and design, and then start working together on the project?

The reason I'm thinking about an online way to do this, with strangers, is that while I do have programmer friends, we only very rarely have the same needs and interests at the same time. It seems to me that it would be easier to find such in match in the online global community.

Any insight?


问:
REST: How to store and reuse  REST call queries
I'm learning C# by programming a real monstrosity of an application for personal use. Part of my application uses several SPARQL queries like so:

```<code>const string ArtistByRdfsLabel = @"
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?artist
WHERE
{{
    {{
        ?artist rdf:type <http://dbpedia.org/ontology/MusicalArtist> .
        ?artist rdfs:label ?rdfsLabel .
    }}
    UNION
    {{
        ?artist rdf:type <http://dbpedia.org/ontology/Band> .
        ?artist rdfs:label ?rdfsLabel .
    }}
    FILTER
    (
        str(?rdfsLabel) = '{0}'
    )
}}";

string Query = String.Format(ArtistByRdfsLabel, Artist);
</code>```

I don't like the idea of keeping all these queries in the same class that I'm using them in so I thought I would just move them into their own dedicated class to remove clutter in my RestClient class.

I'm used to working with SQL Server and just wrapping every query in a stored procedure but since this is not SQL Server I'm scratching my head on what would be the best for these SPARQL queries. Are there any better approaches to storing these queries using any special C# language features (or general, non C# specific, approaches) that I may not already know about?

EDIT: Really, these SPARQL queries aren't anything special. Just blobs of text that I later want to grab, insert some parameters into via String.Format and send in a REST call. I suppose you could think of them the same as any SQL query that is kept in the application layer, I just never practiced keeping SQL queries in the application layer so I'm wondering if there are any "standard" practices with this type of thing.

答:
You can always store them in a Database table and retrieve them on application start up or on first use. With proper caching the performance would be as good. The advantage is that they can be changed without recompiling the application.
A dedicated static class or even storing them as resources is a good idea as well.</p>


答:
You shouldn't be creating dynamic queries. Your best bet in that environment would be to create stored procedures.  Make sure your stored procedures are also not dynamically generated.  Each field needs to be parameterized to avoid the risk of a sql injection attack. It's also a separation of concerns violation.  Your application code should consist of application logic.  Your database should contain your database queries.

Not to mention, these dynamically generated queries will become a nightmare to maintain.

Title: REST: How to store and reuse  REST call queries

Body:
I'm learning C# by programming a real monstrosity of an application for personal use. Part of my application uses several SPARQL queries like so:

```<code>const string ArtistByRdfsLabel = @"
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?artist
WHERE
{{
    {{
        ?artist rdf:type <http://dbpedia.org/ontology/MusicalArtist> .
        ?artist rdfs:label ?rdfsLabel .
    }}
    UNION
    {{
        ?artist rdf:type <http://dbpedia.org/ontology/Band> .
        ?artist rdfs:label ?rdfsLabel .
    }}
    FILTER
    (
        str(?rdfsLabel) = '{0}'
    )
}}";

string Query = String.Format(ArtistByRdfsLabel, Artist);
</code>```

I don't like the idea of keeping all these queries in the same class that I'm using them in so I thought I would just move them into their own dedicated class to remove clutter in my RestClient class.

I'm used to working with SQL Server and just wrapping every query in a stored procedure but since this is not SQL Server I'm scratching my head on what would be the best for these SPARQL queries. Are there any better approaches to storing these queries using any special C# language features (or general, non C# specific, approaches) that I may not already know about?

EDIT: Really, these SPARQL queries aren't anything special. Just blobs of text that I later want to grab, insert some parameters into via String.Format and send in a REST call. I suppose you could think of them the same as any SQL query that is kept in the application layer, I just never practiced keeping SQL queries in the application layer so I'm wondering if there are any "standard" practices with this type of thing.


答:
You may also consider the Resource File (the one with .resx extension in VS) for this task. It may serve like a dictionary , a pair of < key, value > to store/access your "blobs of text" much easily. Here you are couple links: MSDN

.Resx file, VISUAL STUDIO 2010

How to use application resource files (.resx) to efficiently create a localizable ASP.NET Web application


问:
Amazon SOA: database as a Service
There is an interesting interview with Werner Vogels which is partly about how Amazon does Service Oriented Architecture:

For us service orientation means encapsulating the data with the
  business logic that operates on the data, with the only access through
  a published service interface. No direct database access is allowed
  from outside the service, and there’s no data sharing among the
  services.

I do not understand that. Why do they need to 'wrap' a database into some layer if it already can be consumed as a service by other service through database adaptors? Does Amazon do that just because they need to expose the database to third parties or because of anything else?

Why "no direct database access is allowed"? What are the advantages of such an architectural decision?

答:
Not allowing "direct database access" from an application allows the underlying database, and even the schema, to change without having to change the client applications.

Clients simply code to the service interface, never needing to know how the data is persisted.

OwnerDisplayName: Martin Lee

Title: Amazon SOA: database as a Service

OwnerDisplayName: Ray Toal


答:
I agree with Ray Toal's point.  Another is that a service that owns its own data becomes the only place where business rules to guarantee its integrity and proper usage need to be maintained.

Maintain it in one place rather than forcing clients to duplicate that logic.  Keeps things nice and DRY.

Title: Amazon SOA: database as a Service

Body:
There is an interesting interview with Werner Vogels which is partly about how Amazon does Service Oriented Architecture:

For us service orientation means encapsulating the data with the
  business logic that operates on the data, with the only access through
  a published service interface. No direct database access is allowed
  from outside the service, and there’s no data sharing among the
  services.

I do not understand that. Why do they need to 'wrap' a database into some layer if it already can be consumed as a service by other service through database adaptors? Does Amazon do that just because they need to expose the database to third parties or because of anything else?

Why "no direct database access is allowed"? What are the advantages of such an architectural decision?

OwnerDisplayName: duffymo


答:
Python (despite my misgivings about it) simply can't^H^H^H^H^Hshouldn't be used for everything, the same way my slip joint pliers aren't used as a screwdriver.

SQL?  Stored procedures?  Startup scripts?  HTML (already mentioned) and XSLT?  C library wrappers?


问:
function works fine without return value in c++
I forgot to write return 'a'; in the show function and return 0; in main function but it works fine in Code::Blocks.

```<code>#include <iostream>

using namespace std;

char show()
{
  cout<<"this is show function"<<endl;
}

int main()
{
  show();
}
</code>```

I am using Code::Blocks 10.05 in Ubuntu 12.04.
Why does this code work fine in Code::Blocks but not in Turbo C++?

答:
UB as said before.  Might work today, might not work tomorrow on a different processor/compiler.

For some fun forensics, here's a fun and mildly-related thing to try (orig in C, also "worked/bugged" in our C++ setup at the time), it was a fun bug for a bit:

Define a function which returns a floating point in a c or cpp file, nothing complex, just float/double foo(){ whatever body; return someFloat;}.

Use said function in a c file or cpp file (which will assume default-int), without including the header file.  Note: depending on your compiler you might need to add a declaration of the wrong type (int foo();).  Our compiler at the time just assumed the function was ok, didn't have the identifier issue without an included header.

Call the second function (which uses the first) a few times throughout the code.  Note that a value is added but never popped off the processor's floating point stack with each call to foo().

Be amazed how NaN starts popping up in totally innocuous operations later on.  Once that stack gets overflowed (the 9th call in our case), every FP operation becomes a NAN.  So you get fun stuff like 10.0 + 1.0 => NaN.

The trick for us at the time was to find that offending function, since the NaN would occur much later, and not always in the same spot (enjoy the multithread on this one).

If you can reproduce this and have a debugger which lets you check out the processor's register state easily- this is a fun bug to play with.  Ours at the time was a flavor of gcc 4.1 (or maybe 4.4, don't recall the exact year), with a 64-bit itanium processor.

(sorry to the mods for the extra stuff- not sure where that goes, but it is kinda related to the OP, if not feel free to copy this where it better belongs).

ContentLicense: CC BY-SA 4.0


答:
what is the best syntax and coding style for generating a pointer to a method?

According to C++ Faq lite's paragraph about "Pointers to member functions", in general you should use a typedef to create the pointer, and a macro when calling the member function (points 33.5 and 33.6 respectively).

This makes it simpler to call the method on a given object.

In your example you are using a static method, so you don't need an object to call it.

However here is what your code would look like following these recommendations, when calling a non static member function :

```<code>// define the macro to use pointer to methods
#define CALL_MEMBER_FN(object,ptrToMember)  ((object).*(ptrToMember))

class Foo{
    public:
    void dummy1(void){ std::cout << "I'm dummy 1" << std::endl; };
    void dummy2(void){ std::cout << "I'm dummy 2" << std::endl; };
};

int main(){
    // define the PointerToFooMember type. Note that you can use it for dummy1 and dummy2 as well
    typedef void(Foo::*PointerToFooMember)();
    PointerToFooMember ptr = &Foo::dummy1;

    // create an object to call the method later
    Foo foo;

    // call the method
    CALL_MEMBER_FN(foo, ptr)();
}
</code>```

Title: The best way to have a pointer to several methods - critique requested

Body:
I'm starting with a short introduction of what I know from the C language:

a pointer is a type that stores an adress or a NULL

the * operator reads the left value of the variable on its right and use this value as address and reads the value of the variable at that address

the & operator generate a pointer to the variable on its right

So I was thinking that in C++ the pointers can work this way too, but I was wrong. To generate a pointer to a static method I have to do this:

```<code>#include <iostream>

class Foo{
    public:
    static void dummy(void){ std::cout << "I'm dummy" << std::endl; };
};

int main(){
    void (*p)();
    p = Foo::dummy; // step 1
    p();
    p = &(Foo::dummy); // step 2
    p();
    p = Foo; // step 3
    p->dummy();
    return(0);
}
</code>```

Now I have several questions:

Why does step 1 work?

Why does step 2 work too? Looks like a "pointer to pointer" for p to me, very different from step 1.

Why is step 3 the only one that doesn't work, and is the only one that makes some sort of sense to me, honestly?

How can I write an array of pointers or a pointer to pointers structure to store methods (static or non-static from real objects)?

What is the best syntax and coding style for generating a pointer to a method?

Body:
what is the best syntax and coding style for generating a pointer to a method?

According to C++ Faq lite's paragraph about "Pointers to member functions", in general you should use a typedef to create the pointer, and a macro when calling the member function (points 33.5 and 33.6 respectively).

This makes it simpler to call the method on a given object.

In your example you are using a static method, so you don't need an object to call it.

However here is what your code would look like following these recommendations, when calling a non static member function :

// define the macro to use pointer to methods
#define CALL_MEMBER_FN(object,ptrToMember)  ((object).*(ptrToMember))

class Foo{
    public:
    void dummy1(void){ std::cout << "I'm dummy 1" << std::endl; };
    void dummy2(void){ std::cout << "I'm dummy 2" << std::endl; };
};

int main(){
    // define the PointerToFooMember type. Note that you can use it for dummy1 and dummy2 as well
    typedef void(Foo::*PointerToFooMember)();
    PointerToFooMember ptr = &Foo::dummy1;

    // create an object to call the method later
    Foo foo;

    // call the method
    CALL_MEMBER_FN(foo, ptr)();
}


问:
Ajax application: using SOAP vs REST ?
I'm building an ajax heavy application (client-side strictly html/css/js) which will be getting all the data and using server business logic via webservices.

I know REST seems to be the hot topic but I can't find any good arguments.  The main argument seems to be its "light-weight".

My impression so far is that wsdl/soap based services are more expressive and allow for more a more complex transfer of data.  It appears that soap would be more useful in the application I'm building where the only code consuming the services will be the js downloaded in the client browser.

REST on the other hand seems to have a smaller entry barrier and so can be more useful for services like twitter in allowing other developers to consume these services easily.  Also, REST seems to Te better suited for simple data transfers.

So in summary SOAP is useful for complex data transfer and REST is useful in simple data transfer.

I'm currently under the impression that using SOAP would be best due to the complexity of the messages but perhaps there's other factors. What are your thoughts on the pros/cons of soap/rest for a heavy ajax web app?

EDIT:

While the wsdl is in xml, the data I'm transferring back and forth is actually in JSON. It just appears more natural to use wsdl/soap here due to the nature of the app.  The verbs GET and POST may not be enough.  I may want to say something like: processQueue, or executeTimer. This is why my conclusion has been wsdl/soap would be good for bridging a complex layer between two applications (client and server) whereas REST would be better (due to its simplicity) for allowing many developer-users to consume resources programmatically.

So you could say the choice falls along two lines

Will the app be verb-oriented (completing tasks: use soap) or noun-oriented (consuming resources: use REST)

Will the api be consumed by few developers or many developers (REST is strong for many developers)?

Since such an ajax heavy app would potentially use many verbs and would only be used by the client developer it appears soap/wsdl would be the best fit.

答:
If you are doing an AJAX heavy application then one pro about REST is you have the option of using JSON as your data-interchange format instead of XML. JSON requires less markup than XML so that would speed up your application since you would be sending less data over the wire.

It also seems that REST is over taking SOAP with web services, and its always a good thing to use a technology that is more widespread when you bring on new developers or if you want other developers to consume your data.

The pro for SOAP is that it already has structure built into it, but I don't see why you can't build your own structure into your REST solution.

EDIT: When I did telecom programming our phone switch only supported SOAP and not REST. I found that SOAP required a bunch of boilerplate stuff that just got in my way when I didn't need it.

Title: Ajax application: using SOAP vs REST ?


答:
SOAP and REST are not the only options. There is another called Direct Web Remoting.

Check it out.

SOAP requires mashalling/serializing. REST requires adherence to GET POST paradigm, often times, neither of these are necessary for a straightforward transmission of data from client to server.

This is the notion of Direct Remoting. The POJO (plain old Java Object) that exists on the server, exists on the client. The methods that are defined to be visible are called by the client and the return type is essentially the AJAX callback.

Hope that helps.
All the best!
Nash

Title: Ajax application: using SOAP vs REST ?

Body:
I'm building an ajax heavy application (client-side strictly html/css/js) which will be getting all the data and using server business logic via webservices.

I know REST seems to be the hot topic but I can't find any good arguments.  The main argument seems to be its "light-weight".

My impression so far is that wsdl/soap based services are more expressive and allow for more a more complex transfer of data.  It appears that soap would be more useful in the application I'm building where the only code consuming the services will be the js downloaded in the client browser.

REST on the other hand seems to have a smaller entry barrier and so can be more useful for services like twitter in allowing other developers to consume these services easily.  Also, REST seems to Te better suited for simple data transfers.

So in summary SOAP is useful for complex data transfer and REST is useful in simple data transfer.

I'm currently under the impression that using SOAP would be best due to the complexity of the messages but perhaps there's other factors. What are your thoughts on the pros/cons of soap/rest for a heavy ajax web app?

EDIT:

While the wsdl is in xml, the data I'm transferring back and forth is actually in JSON. It just appears more natural to use wsdl/soap here due to the nature of the app.  The verbs GET and POST may not be enough.  I may want to say something like: processQueue, or executeTimer. This is why my conclusion has been wsdl/soap would be good for bridging a complex layer between two applications (client and server) whereas REST would be better (due to its simplicity) for allowing many developer-users to consume resources programmatically.

So you could say the choice falls along two lines

Will the app be verb-oriented (completing tasks: use soap) or noun-oriented (consuming resources: use REST)

Will the api be consumed by few developers or many developers (REST is strong for many developers)?

Since such an ajax heavy app would potentially use many verbs and would only be used by the client developer it appears soap/wsdl would be the best fit.


问:
How does team development work?
This is a pretty generic question but one I've been wondering about for a while: is there a standardized, generally accepted, or even just systematic way that people write code as a group?

For example, in a project written in C++, does one developer write one class, which he passes off to the next developer with a quick explanation of what each method does?

答:
I've never seen a formalised, standardised way to do this - but I've seen two common patterns.

Feature Ownership - each developer takes exclusive responsibility for a particular feature of the system, and implements this through all appropriate layers.

Key Advantage: one developer, with a full understanding of the entire feature, can work through all layers in a consistent fashion.

Key disadvantage: Because many different developers end up working on the each component, you can end up with a distinct lack of consistency unless you have good conventions in place.

Component Ownership - each developer takes exclusive responsibility for a specific component/layer (UI, services, data access, data schema etc). Features are implemented by collaboration between devs.

Key Advantage: each component is written by a single developer, ensuring it has a consistent style and "unity of vision".

Key disadvantage: There are always some components requiring more development than others - resulting in an unbalanced load on certain developers.

Though, these are exclusive - even if a particular team subscribes primarily to one, some things tend to be done the other way.

In my experience, feature ownership has been more successful in the long term than component ownership, primarily because system knowledge is more spread out, helping to address key person risk. But, that's just my experience.

Title: How does team development work?


答:
in Agile, the answer is however the team wants it to work

could be features, could be stories, could be tests, could be tasks, could be paired, could be...whatever.

some dev shops transfer code ownership at shift change and use three shifts in time zones 8 hours apart for continuous development

some dev shops assign entire subsystems to one person

there are many ways...

Title: How does team development work?

Body:
This is a pretty generic question but one I've been wondering about for a while: is there a standardized, generally accepted, or even just systematic way that people write code as a group?

For example, in a project written in C++, does one developer write one class, which he passes off to the next developer with a quick explanation of what each method does?


问:
Should I cache the data or hit the database?
I have not worked with any caching mechanisms and was wondering what my options are in the .net world for the following scenario.

We basically have a a REST Service where the user passes an ID of a Category (think folder) and this category may have lots of sub categories and each of the sub categories could have 1000 of media containers (think file reference objects) which contain information about a file that may be on a NAS or SAN server (files are videos in this case). The relationship between these categories is stored in a database together with some permission rules and meta data about the sub categories.

So from a UI perspective we have a lazy loaded tree control which is driven by the user by clicking on each sub folder (think of Windows explorer). Once they come to a URL of the video file, they then can watch the video.

The number of users could grow into the 1000s and the sub categories and videos could be in the 10000s as the system grows.

The question is should we carry on the way it is currently working where each request hits the database or should we think about caching the data?

We are on using IIS 6/7 and Asp.net.

答:
There really isn't enough information, as per Thorbjørn's comments.

Caching, when done wrong, can cause you & your users lots of grief. Make sure you need to worry about caching before over-complicating your application.

So, in the absence of information that indicates you really need to cache, don't cache.

[General rule of optimization: If you need to ask if I should do something, the answer is no]*

* It would be a statement, not a question, in most places where the answer is yes.


答:
First, ensure that the code is partitioned in such a way that your data provider can be switched easily. We're talking interface segregation and the other SOLID principles here.

Next you need to know the answer to the following:

1) Will the data change frequently?
2) Does the application poll your REST service frequently to get these updates?
3) Is the database used for other purposess?
4) Are you aware of any current performance issues?
5) Is the data updated by your application and do those updates need reflecting in the app?

The interesting thing is that by using the database, you are technically caching the data already. That's what a database does. A lot of R&D goes into making the database as fast as possible at retrieving data. It uses its own memory cache for frequently used data for example.

So ask yourself what do you hope to gain by swapping cache providers? And What are the current limitations that need addressing?

If you are not currently experiencing any slow downs I'd simply say "no, no need to switch".

It's a really big topic. Caches tend to do really well when the data needs to be geographically distributed, but there is a huge overhead in terms of management.

I'm doing a project at the moment where I'm making exactly the same sorts of decisions.

My solution so far is to use the database only and hit it lots with polling requests from each client. Sounds yucky, but it scales (in testing) far more than I'll need, the code is very simple.

That said, my code uses a sort of repository pattern which abstracts the main application's data provider from the database code. If I wanted to swap in a cache provider like GemFire, it would require a pretty tiny amount of code to do.

Title: Should I cache the data or hit the database?

Body:
I have not worked with any caching mechanisms and was wondering what my options are in the .net world for the following scenario.

We basically have a a REST Service where the user passes an ID of a Category (think folder) and this category may have lots of sub categories and each of the sub categories could have 1000 of media containers (think file reference objects) which contain information about a file that may be on a NAS or SAN server (files are videos in this case). The relationship between these categories is stored in a database together with some permission rules and meta data about the sub categories.

So from a UI perspective we have a lazy loaded tree control which is driven by the user by clicking on each sub folder (think of Windows explorer). Once they come to a URL of the video file, they then can watch the video.

The number of users could grow into the 1000s and the sub categories and videos could be in the 10000s as the system grows.

The question is should we carry on the way it is currently working where each request hits the database or should we think about caching the data?

We are on using IIS 6/7 and Asp.net.


答:
As Jarrod pointed out, if you follow a generic standard, you will definitely end up with a record format that includes a lot of things your system will never need. Since you already know that there will be a fairly large number of records, it's likely that you'll get unnecessary performance issues because you're supporting data that will never be used. Conversely, it's also likely that the standard won't include fields that you do need, which will be a painful problem to solve; either you break the standard by adding these fields, or you'll have to find some (probably clunky) way of including the non-standard fields within the standard.

I think the real problem here isn't about finding a one-size-fits-all standard (which will almost always be one-size-fits-NONE) but that you have been tasked to estimate a solution where the requirements aren't specified yet. In these cases, I think the only professional thing to do is to make a minimum estimate based on the requirements you do have, and then make a maximum estimate based on all possible undefined requirements that you think might come up. Sure enough, the estimate might become ridiculously rough, in which case you should explain to whoever tasked you with this, that it's just not feasible to make a good estimate until the requirements are more well-defined.


问:
Git: Fixing a bug affecting two branches
I'm basing my Git repo on A successful Git branching model and was wondering what happens if you have this situation:

Say I'm developing on two feature branches A and B, and B requires code from A. The X node introduces an error in feature A which affects branch B, but this is not detected at node Y where feature A and B were merged and testing was conducted before branching out again and working on the next iteration.

As a result, the bug is found at node Z by the people working on feature B. At this stage it's decided that a bugfix is needed. This fix should be applied to both features, since the people working on feature A also need the bug fixed, since its part of their feature.

Should a bugfix branch be created from the latest feature A node (the one branching from node Y) and then merged with feature A? After which both features are merged into develop again and tested before branching out?

The problem with this is that it requires both branches to merge to fix the issue. Since feature B doesn't touch code in feature A, is there a way to change the history at node Y by implementing the fix and still allowing the feature B branch to remain unmerged yet have the fixed code from feature A?

Mildly related: Git bug branching convention

答: Use a distinct commit to fix the bug in one branch, then cherry-pick that commit into the other branch.</p>


问:
Non-blocking ORM issues
I asked a question on SO, and found that there are no non-blocking ORMs for my favorite web framework.  By non-blocking I mean an ORM with callback support for asynchronous retrieval. The ORM would be supplied with a callback or some such to execute when data has been received.

I want to create one, but I have some questions that blocking me from starting development:

What issues might be encountered when developing ORM?

Does supporting non-blocking retrieval dramatically increase the complexity of an ORM?

Why are there so few non-blocking ORMs around?

Update: It looks like I have to improve my question. We have solutions that already allow us to receive data in non-blocking way, and I believe that most companies that use such solutions use raw SQL. We want to create a more generic solution that we can reuse in future projects. What difficulties might we encounter?

Update 2: Preferred language is python, but I'm interested in principles. This question is actually for me, as I will look at platforms which already have non-blocking ORM.

答:
What issues might be encountered when developing ORM?

You'll need to address the laundry list of issues required to bridge the Object Relational Impedance Mismatch, as well as dealing with idiosyncrasies of SQL provided by each RDBMS vendor. The more advanced your requirements get, the worse your troubles would be in this department: for example, SQL that you generate to implement results paging will differ rather dramatically between Oracle, SQL Server, and mysql. Fortunately, this is not different between blocking and non-blocking ORM implementations, so if there is an open-source ORM for Python, you would be able to heavily borrow from it to address nearly all these issues.

Does supporting non-blocking retrieval dramatically increase the complexity of an ORM?

The biggest issue that you are going to face is that the connection library for accessing the RDBMS itself would be blocking. This is another difference that you must address. Managing the threads invisible to your users will be the additional challenge for you. In addition, loading of dependencies on demand would be a challenge, because the operation is perceived as synchronous by the users of your framework: after all, they do not normally expect a notification on when it's OK to access a collection property of their object.

Why are there so few non-blocking ORMs around?

I can only speculate on this last point, but I think it has to do with low demand for such frameworks: since you can partially simulate non-blocking ORM by adding another level of threading to your application code as needed, and keep the regular blocking kind everywhere else, developing a specialized framework for it would seem suboptimal.

Title: Non-blocking ORM issues