问:
Fuzzy search for a sub-string without tokens
Let's say I have the following lines:

```<code>Lorem ipsum dolor sit amet, (tag) consectetur adipiscing elit.
Phasellus congue nisi vel lorem dignissim tristique. (tag)
Etiam vulputate lacus nec velit lobortis ut adipiscing mauris condimentum. (tag )
Vestibulum quis nulla id nisi ultricies placerat. (teg)
In tempus vulputate ante, quis suscipit nunc euismod in. (teg )
Phasellus iaculis diam in felis pellentesque tristique. (ta g)
(tag Praesent vestibulum sollicitudin velit, non mollis lacus scelerisque in.
Nunc ac erat enim, at lobortis libero. (interesting)
</code>```

There's supposed to be a tag in each line enclosed in parenthesis.  But as you can see the data is very dirty and there's extra spaces inside tags, missing parents, misspelled tags, etc.

How would I identify the lines containing "(tag)" or something similar?  The output I would expect in the example is to retrieve all lines, except for the last.

I need to compare a long string to a shorter sub-string, so something like Levenshtein distance wont work (or will it?).  Tokenized techniques seem to rigid, because although I might tokenize everything in parenthesis, what happens when a parenthesis is missing?

答:
I've done something similar to this a while back, only I was just matching words to a sought word. This might not help you, but it might give you an idea.

Essentially, what I did was something like this:

For each word in my range and did something similar to a diff. I considered the letter in the string and its position. For correct letters I gave a point, for correct position in the string I gave a point. For bad and placement I would remove a point, and for missing letters I would remove a point. (It's hard to remember, because I don't have access to the source anymore, but I think I also based the placement point off the distance from the expected position).

After I tallied up the 'score' of this word, I would normalize. I had an arbitrary threshold (found via trial and error, but it could be feedback driven) that I used to determine if it was close enough.

Then all of the words that were above the threshold were returned to the user in descending order.

IIRC, it wasn't terribly effective for short words, but overall, it was fairly effective for its implementation (search over a specific domain).

Hope that helps you off into a productive direction.


问:
Making an internship most effective, useful and fun for both parties
We're currently interviewing few candidates for an internship, which is a really new experience for us as a company and for me personally as a team lead/manager. </p>

<p>What would be the most effective and useful, yet fun approach for both sides here? How do we 'integrate' an intern into our development team and workflow without much disruption in such a way that he or she could be learning and yet be helpful? </p>

答:
Hehe, necromancing bounty ;)

About hosted internships, this requires :

time : you must follow your interns ; its a non-sens to recruit a resource without following it. Your interns planning must match the required work time (see below).

projects : as already said, they must have real work ; a demo project is not a real
project (deadlines, customers needs etc...)

relationship : relationship is more important than knowledge ; you
don't recruit an associal which work in the basement, do you ? :)

management : if you plan to hire them (see below), you have to treat them as employees ; how do they work with your management ?

In the most situation I encountered, the first three points were the keys : if you don't have time, real work and relationship for your interns, they'll not do something you'll consider as a well done/usefull work, they'll not learn how to work with YOU/YOUR COMPANY.

About the time, I have seen a lot of (fail) internships where the "tutor" didn't have time or where the interns worked 2 weeks a month for a 2 months project : 4 months to gets things done instead of 2 ? Is this acceptable ? In some case, it's not, especially if the work is "chopped".

For the third part, if you plan to hire them I believe its because you need them. The question is, do you hire them because they are good and gets things done or only because of the knowledge they acquired during the internships.

If you feel you don't really know what was done during the internships, the second reason may point out a lack of sharing, communication or management and you should ask if your management will be able to manage this.

ContentLicense: CC BY-SA 3.0


问:
How to make a recurring event? Such as an entry in a agenda
I have an entity (model) called Notification, shown to Users of the system. So far, Notifications were created and showed instantly to users when they were enabled, and hidden when disabled or deleted. Also, Users can close/cancel the Notification so they don't see it anymore and that action is persisted in a collection (database table) of Notifications viewed by Users. The system must now implement repetitions of those Notifications, like agendas or calendars in which entries can be repeated daily, weekly, monthly, etc. and also send a email to the User the day before the Notification instance date. Conceptually how it is implemented? How about calculation of repetition?

So far, I've been thinking of persisting three new properties on the Notification entity, one for the type of repetition (daily, weekly, etc.), one for the start date(time) and another for the end date(time) and a new collection (database table) where I save "instances" of those Notifications (not instances like class instance, but a more generic concept of a single occurrence of something), with properties like notification id and start and end date(time) of that instance. That way Notifications themselves wouldn't be presented to Users, but the instances of those Notifications.
Then, I thought of a scheduled task (cronjob) that runs couple of times a day, generating instances from Notifications collection calculating when those repetitions should happen and also sending email when calculated instance date is tomorrow.

Not sure if this is the best way and I'd like to hear recommendations. I started to implement it that way and so far it seems easy, but I'm about to start with the logic of the scheduled task (the hardest part) and I wonder if it will be very complex to calculate the date of the instances based on repetition specification (daily seems easy, add a day to the date value, but how about each third friday of the month?).

答:
I was with you up until the part where you mentioned storing "instances" using a cronjob. Of course every domain has different requirements, but I've found that most often the simplest and most effective way to manage recurring events is to be optimistic and persist variations.

By this I mean you have a recurring event/notification/anything with a start date, end date and frequency. This single entity alone allows you to draw the instances in the UI. The only time you should need to persist instance information is if someone cancels on a specific date, or makes a note for a specific date or whatever. So your recurring event can have collections of cancellations, notes, and other entities for specific dates (instances). This allows you to correctly draw the UI without having a persisted entity for each recurring event instance. Of course you'll need business logic to ensure that your recurring event doesn't have a cancellation or other instance information for a date on which the event will not occur.

Let me know if this makes sense or if you need any other clarification.

EDIT:

I have implemented such features by persisting the "Dismissals" and "Sent Mail" in separate collections for any given event. That is, when a user clicks to dismiss a notification you record in the database that the notification for 5/16/2012 has been read so that you know not to draw it in the UI.

As psr pointed out, doing all these calculations can take a toll on performance. I've found, however, that it's not a problem in any of my programs because databases are very fast and the biggest timespan you're ever looking at is usually a month or a few months. Also, I think it keeps your model much cleaner because you don't have to worry about creating and destroying instances in the database all the time in the cases where an event will recur indefinitely or the user changes the start and end dates.

That said, you will need a scheduled task to to send out the emails regularly. The task can look to see what events are coming up and which ones have emails that have already been sent out to figure out what emails to send.


问:
What would be the Impact of P=NP?
I am preparing for a test and I can't find a clear answer on the question: What would be the impact of proving that PTIME=NPTIME. I checked wikipedia and it just mentioned that it would have "profound impact on maths,AI,algorithms.." etc.

Anyone can give me an answer?

答:
This is covered in The Status of the P Versus NP Problem. Definitely worth a read.

A few salient points from the article (quoted from the What If P = NP? section):

Public-key cryptography becomes impossible.

Since all the NP-complete optimization problems become easy, everything will be much more efficient. Transportation of all forms will be scheduled optimally to move people and goods around quicker and cheaper. Manufacturers can improve their production to increase speed and create less waste.

Learning becomes easy by using the principle of Occam's razor—we simply find the smallest program consistent with the data. Near perfect vision recognition, language comprehension and translation and all other learning tasks become trivial. We will also have much better predictions of weather and earthquakes and other natural phenomenon.

P = NP would also have big implications in mathematics. One could find short, fully logical proofs for theorems but these proofs are usually extremely long. But we can use the Occam razor principle to recognize and verify mathematical proofs as typically written in journals. We can then find proofs of theorems that have reasonable length proofs say in under 100 pages. A person who proves P = NP would walk home from the Clay Institute not with $1 million check but with seven (actually six since the Poincaré Conjecture appears solved).

Title: What would be the Impact of P=NP?


答:
This is when separating interface from implementation is important.  Your interface should handle third Friday of every month and worse (The 3rd Friday of every month except move to the next business day that both parties to the contract agree is a business day based on the holiday table for the region the business is incorporated under), but you should only have to implement the cases that are real right now.

So I would make a scheduler interface that can be passed a time period, and the scheduler can fill the time period with instances when you tell it to.  The logic of how to do that lives inside the scheduler object.

As far as the cron job - you could use this design and have a cron job that creates new instances, but you may find you just don't need it.  It might be helpful to do something like the cron job if you need to write a database query against instances and you don't care about the logic of the schedule that created them.  If the cron job runs quickly enough you may be able to just trigger the job whenever you need the data to be current, instead of using cron.

Title: How to make a recurring event? Such as an entry in a agenda

Body:
I have an entity (model) called Notification, shown to Users of the system. So far, Notifications were created and showed instantly to users when they were enabled, and hidden when disabled or deleted. Also, Users can close/cancel the Notification so they don't see it anymore and that action is persisted in a collection (database table) of Notifications viewed by Users. The system must now implement repetitions of those Notifications, like agendas or calendars in which entries can be repeated daily, weekly, monthly, etc. and also send a email to the User the day before the Notification instance date. Conceptually how it is implemented? How about calculation of repetition?

So far, I've been thinking of persisting three new properties on the Notification entity, one for the type of repetition (daily, weekly, etc.), one for the start date(time) and another for the end date(time) and a new collection (database table) where I save "instances" of those Notifications (not instances like class instance, but a more generic concept of a single occurrence of something), with properties like notification id and start and end date(time) of that instance. That way Notifications themselves wouldn't be presented to Users, but the instances of those Notifications.
Then, I thought of a scheduled task (cronjob) that runs couple of times a day, generating instances from Notifications collection calculating when those repetitions should happen and also sending email when calculated instance date is tomorrow.

Not sure if this is the best way and I'd like to hear recommendations. I started to implement it that way and so far it seems easy, but I'm about to start with the logic of the scheduled task (the hardest part) and I wonder if it will be very complex to calculate the date of the instances based on repetition specification (daily seems easy, add a day to the date value, but how about each third friday of the month?).


问:
Design patterns - do you use them?
Being an IT student, I was recently given some overview about design patterns by one of our teachers. I understood what they are for, but some aspects still keep bugging me.

Are they really used by the majority of programmers?

Speaking of experience, I've had some troubles while programming, things I could not solve for a while, but Google and some hours of research solved my problem. If somewhere in the web I find a way to solve my problem, is this a design pattern? Am I using it?

And also, do you (programmers) find yourself looking for patterns (where am I supposed to look, by the way?) when you start the development? If so, this is certainly a habit that I must start to embrace.

UPDATE: I think when I ask if programmers do use them, I'm asking if when you have a problem to solve you think "Oh, I should use that pattern".

答:
Adding to Lunivore. Id like to quote this from the head first book

```<code>        ## **Three steps to great software** ##
</code>```

Make sure the software does what the customer wants

Apply good object-oriented principles

Strive for a maintainable, reusable design

It is during the third stage, after your system is working the way it is supposed to.Its time to apply the patterns to make your software ready for years to come.

Title: Design patterns - do you use them?

Body:
Adding to Lunivore. Id like to quote this from the head first book

        ## **Three steps to great software** ##

Make sure the software does what the customer wants

Apply good object-oriented principles

Strive for a maintainable, reusable design

It is during the third stage, after your system is working the way it is supposed to.Its time to apply the patterns to make your software ready for years to come.


问:
Programming with voice recogition software
I used Dragon Naturally Speaking very briefly a few years ago and was thinking if it would be a viable solution for programming?

I was thinking more so if you break your arm or something that would be a major hinderance to programming.

This same question on SO but was never answered.

答:
I can answer this one from personal experience.  A few years ago, I broke both arms in an accident.  Since my job was full-time programming, this was a problem.  With some help, I got Dragon installed on my laptop.

It was a waste of time.

Code isn't much like natural language; it is primarily written, not spoken.  I know exactly what y_z = (x < 0 ? -x : x) + 2; means, yet I have no idea how I'd pronounce it, nor do I care.

Being a written-only language, code is very precise at the character level.  There's a big difference between (x+2)*3 and (x+2*3).  Speech-to-text programs are good at paying attention to words, not characters.  Adding specific characters requires lots of saying things like "left parenthesis, x, plus sign, two, right parenthesis".

When I'm coding, I do a lot of moving and rewriting.  Speech-to-text is good for a single stream of language.  It isn't good for going back and forth all over the place.

A lot of the minute tasks in coding aren't equivalent to typing, which is all speech-to-text is good for.  Think about how often you change tabs to look at some other module of code, or how often you fold and unfold a function in your editor.

So if you have a speech-to-text program, give it a try and see for yourself.  I don't think you'll be too impressed.

Incidentally, don't break both arms at once.  Break one at a time, it's much easier that way.

If I had had only one broken arm, I'd have just done all my coding one-handed.  It'd still be quicker than using speech-to-text software.


问:
How do you handle / what do you charge for documentation, training, warranty, changes in scope etc…
I am working with a client right now that wants me to sign a contact with a warranty for a year for no additional charge. As well as any reasonable changes he wants during the contract that are outside of the guidelines for no additional charge while not affecting deadlines. And lastly documentation and training for all staff for no additional charge.

Red flags are going everywhere in this contract and I wanted to hear from professionals how you guys handle / what you charge for documentation, training, warranty, changes in scope etc...

答:
Me personally, I estimate what it costs me to do these things along with the rest of the project.

Then I look at how much money I would be getting in return.

I subtract the former from the later to estimate profit.

Then I decide if that's enough or if I want more.  If it's enough, I do it.  If it's not then I tell the customer I'm not willing to do the work for what they want to pay.  Either they give up trying to get something for nothing or they go find some other sucker.  It's a win for me in either case.

Of course the "changes outside the scope of the project that don't affect deadlines" is easy...there's so such thing so there's no problem giving that away for free.  Of course, that doesn't mean I'd agree to a contract with language that vague in it.


答:
This is simple, tell them no, submit a solution you feel is fair and if they aren't willing to work with you just walk away. Taking/signing a contract you know will lead to trouble isn't worth it in the long run it will cost you. There are plenty of people to work for willing to show you respect and pay you fairly that you don't have to lower yourself to work for those that won't respect you and are trying to get a "free lunch."

as Cape Cod Gunny comment bug fixing should be done for free, at least during the warranty period. factor that cost into the development costs or break it out as a cost for a warranty period if they ask for it that way. Deciding if something is really a bug or a change is an exercise left to the reader.

Title: How do you handle / what do you charge for documentation, training, warranty, changes in scope etc…

Body:
I am working with a client right now that wants me to sign a contact with a warranty for a year for no additional charge. As well as any reasonable changes he wants during the contract that are outside of the guidelines for no additional charge while not affecting deadlines. And lastly documentation and training for all staff for no additional charge.

Red flags are going everywhere in this contract and I wanted to hear from professionals how you guys handle / what you charge for documentation, training, warranty, changes in scope etc...


答:
So let me get this, The Idea is on no additional charge extending outside the initial declared charges at the time of contract right? Just factor in all the required things and estimate the charges up front declaring your fee and time for all the effort involved.

There are few things to consider here.

This may seem like a situation where the client does not trust you enough to do a good job and is just trying to buy insurance if you try to do a shabby job and hold you accountable.

This can also be the case where you are expected to give out a lot of free lunches like you fear.

As CapeCodGunny  Points out If the warranty only ensues Bug fixing and Ommisions. they should be done for free.

Options

Write your own follow up contract getting written and explicit definition of "Reasonable as agreed upon by you and the client", clear requirements and usage to understand any bugs/errors on your part and the list out the charges as per additional requirements.

Keeping in mind the first two considerations , ask your self why this situation has arisen and if it is really worth your time and effort and reputation to pursue this engagement further.


问:
How to use unit tests as a source of information?
A colleague of mine was once at a seminar about agile development, where he heard it is possible to use unit tests as technical documentation. Something like using unit tests as an example of how to use the class.

A quick Google search provided TDD and Documentation, which proves it should be possible. But looking at our code, I see that we obviously failed to implement unit tests in such a way.

In my opinion unit tests are there to test code as a minimal unit, even with help of mock and fake classes and functions.

So, the questions are:

Isn't it the task of functional tests to show how a class (or set of classes) should be used?

If it is possible to use unit tests as technical documentation, are there some guidelines on how to implement such unit tests?

答:
While functional tests can help you understand a whole piece of functionality, a unit test can help with understanding a small scope of code (like a single method).

Good unit tests will also server as good technical documentation, and there are a few things that can help write good, simple, and useful tests. The two most important points I've encountered are

Make sure that all your tests are independent. You should be able to run any subset of tests, in any order.

Make sure that you only test a single thing in each test. This keeps your tests specific, simple, but not brittle.


答:
Of course a customer wants everything for free, and a consultant wants to maximize income.  Consider the clients and your alternatives... then it's mostly a matter of negotiating your best deal, and walking away from unprofitable deals.

Many consultants charge per hour for all of the above, but then also throw in some answers and quick fixes off-the-clock to maintain good client relationships.

Warranty coverage is an insurance business, and most programmers are not insurance companies (either by capitalization or expertise).  Offering (re)insurance has bankrupted billionaires. YMMV.


答:
If you are applying TDD, then each unit test you wrote corresponds to a functionality of a class. So as you write tests you are actually creating the class functionalities, dependencies, exceptions and also class documentation.

If you are not applying TDD, still unit tests give you idea about the class and what it does. Unit test names are very descriptive so you don't need to create a documentation mostly.

Consider a unit test like

```<code>public void Customer_Service_Can_Register_New_Customers(){...}
public void Customer_Service_Cannot_Register_Customers_With_Duplicate_Emails(){...}
</code>```

These are self descriptive methods and easy to read too. So they also serve as documentation.

Title: How to use unit tests as a source of information?

Body:
A colleague of mine was once at a seminar about agile development, where he heard it is possible to use unit tests as technical documentation. Something like using unit tests as an example of how to use the class.

A quick Google search provided TDD and Documentation, which proves it should be possible. But looking at our code, I see that we obviously failed to implement unit tests in such a way.

In my opinion unit tests are there to test code as a minimal unit, even with help of mock and fake classes and functions.

So, the questions are:

Isn't it the task of functional tests to show how a class (or set of classes) should be used?

If it is possible to use unit tests as technical documentation, are there some guidelines on how to implement such unit tests?

Body:
If you are applying TDD, then each unit test you wrote corresponds to a functionality of a class. So as you write tests you are actually creating the class functionalities, dependencies, exceptions and also class documentation.

If you are not applying TDD, still unit tests give you idea about the class and what it does. Unit test names are very descriptive so you don't need to create a documentation mostly.

Consider a unit test like

public void Customer_Service_Can_Register_New_Customers(){...}
public void Customer_Service_Cannot_Register_Customers_With_Duplicate_Emails(){...}

These are self descriptive methods and easy to read too. So they also serve as documentation.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I'm from Slovenia and I code strictly in English. I have seen different programs coded in Slovenian because the client demanded so. Apparently it's easier to read the code like that.

So yes, people don't only code in English.

And I'm talking about the code itself, not software localization.


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

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

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

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

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

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

Also, can you suggest the sources for the same?

Edited:
Sources suggesting development of coding skills.

答:
Yes, practice is extremely important to develop programming skills and to keep them sharp.  However practice alone will only take you so far.  You also have to learn from people who know more than you.  There are techniques you have never heard of, practices whose benefits are not immediately obvious, and tricks that you could never invent yourself.

The way to learn new techniques, neat tricks, and useful practices are many.  Read books.  Talk to co-workers.  Ask questions. Review other people's code, and have them review yours.  Read blogs and articles on programming, including this site. In short, do not work in a vacuum.

Oh, and if you are not sure what NP-complete means, or if the big-O notation scares you, then you should probably take some theory of computation and algorithms classes.

ContentLicense: CC BY-SA 2.5

Title: How do I improve my coding skills?


问:
Should I follow an open source project's documentation patterns even if they are bad?
I've considered making modules and the like for various languages and other open source things. Where documentation is not specified but rather is communal de facto standard or entirely ad hoc; should I try to improve from that standard in my code if it is not in-line with what I've learned to be good documentation from reputable sources (Code Complete et al)?

Or should I maintain consistency over all, regardless of quality?

答: Maintaining consistency is probably better to do initially, but I would contact the project owner(s) and ask whether you can suggest improvements to their documentation. If they agree, justify your suggestions and provide examples.</p>


答:
Unit tests, if well written DO serve as some documentation of a class or method or whatever.

Well written ones lead to more understanding by being easy to figure out what they are testing, but even poor tests give the reader some idea of how the thing being tested is supposed to act, and what things the author thought were important to test.

Heck, I've been known to write unit tests for external libraries - not because they need testing, but because I want to make sure my understanding of the library is correct. And in the future, if someone has questions about how I'm using things, well there's my understanding, right in the test code.


答:
Consistency in a project is crucial both for the source code itself and the documentation. People who work on the project are habituated to use the standards they used for years, and would be lost in front of a piece of code or a part of a documentation which, in your opinion, is better, but which has nothing to do with the remaining codebase or documentation.

Also, be aware that it's not because you think that something is bad, it means that it is. Referring to Code complete doesn't change anything. What you may criticize might have its source in some elements related to the project, and while Code complete says it's bad, anyone who worked on the project for years would agree that in this specific case, it's the only choice.

If you want to improve the documentation of an existent open source project, gather some feedback from other people who participate to this project, and if you see that everyone agrees that the actual documentation is too bad, then well, you may want to rewrite it from scratch, following the best practices and keeping the consistency at the same time.

Title: Should I follow an open source project's documentation patterns even if they are bad?

Body:
I've considered making modules and the like for various languages and other open source things. Where documentation is not specified but rather is communal de facto standard or entirely ad hoc; should I try to improve from that standard in my code if it is not in-line with what I've learned to be good documentation from reputable sources (Code Complete et al)?

Or should I maintain consistency over all, regardless of quality?


答:
I find examples much easier to learn from than documentation and unit tests serve great as that.  Not only that, but they show me, by example, what NOT to do with a unit.

However, they can't be the only form of documentation.  One must realize that brains all work differently.  That's one thing I think people who recommend using JUST unit tests as your documentation or JUST the code completely miss.  Even more poignant is the fact that even single brains learn different things from different mediums.  I learn something completely different from a class diagram than I do just looking at code or reading API docs.

But at the end of the day, if diagrams and API docs are all you have then I'm probably screwed.  I need examples.  I need to see something being used.  I might search the code for this, and lacking any other examples that's what I'm stuck with, but this will never tell me as much as a good unit test.


问:
Using a DSN database connection is a bad practice?
During all my professional lifetime that I have been programming in Windows enviroments, I advised my friends and coworkers to not use a DSN database connection in their applications, based on my own personal conclusions, but I really haven't seen any evidence of them.

I know that using a DSN connection via ODBC data source, implies that this connection will use an ODBC driver. I know by some documentation that ODBC is an language-agnostic, OS-agnotic API to connect to databases, everything that carries this level of flexibility comes with some downpoints (could be possible that some specific functionability can't be used with ODBC) or could be that the performance could be lower than using a more direct API (OLEDB or other).

I know that using a DSN-less connection has some problems by itself like securely storing the access information to the database server/file ( can be solved with some kind of encrypter on the data), or unexpected changes in the name of provider used in the connection drivers (Specific case of old informix drivers).

Is this correct, or I'm missunderstanding something?

答:
I'll go out on a limb and say no it is not "bad practice".  It is a tool intended for flexible implementations.  I might never use it myself as I'd prefer to use the native api for database connections but it clearly has a purpose.  If you are writting client-ware to connect to arbitrary databases in different work environments, a DSN solution could reasonably save you a lot of work.  You'd write your connection libraries to use DSN via odbc and be able to talk to whatever data system they use.

To try and understand it better, maybe asking the question:

Is it "good practice" to use the db-native api to couple the client app with its backend thereby tying the application to a specific storage system?

You'd have to rewrite the client should you ever want to change the backend.  the DSN approach is backend agnostic so potentially better.

On the other hand, having homogeonous systems is itself a benefit when trying to hire someone to come in a fix/update/upgrade the system. Instead of hiring a 'generic DBS-using' contractor, you find yourself an Oracle, Access, MSSQL, or Mysql expert and they'd work in their area of expertise.

I'm always hesitant to outright call anything "bad".  It exists therefore it must have had a good reason to come into existance.  Truly (and I mean 100%) 'bad' things tend not to get widely adopted.  Maybe they become bad over time (shrug).


问:
How do I partially add PHP namespacing to a library without breaking existing code?
My company has created a modular PHP framework over the years, beginning long before PHP 5.3 added namespaces. Recently, we decided to start using namespaces in our library's new code, and we intend to namespace old code eventually. However, we have a few issues we are trying to work out to determine if adding namespaces to a pre-v5.3 codebase is just not a good idea:

Can I namespace a class but also import (use) the global namespace so all global classes do not need a \ prefix?

If we namespace an existing class in our library, how can we prevent all existing projects from breaking as soon as the framework upgrades? For example, can the library change the name of class ThemeEngine to \module\theme\ThemeEngine, but the existing websites call ThemeEngine without any code modification? If so, what would that code look like?

答:
Yea what I did in the end was use - 'use' to import the individual classes that I needed

for example instead of adding '/' in front of everything like:

```<code>\DateTime()
</code>```

I added under my namespace

```<code>namespace MyProject;
use DateTime;

...
DateTime();     //without \
...
</code>```

Body:
Yea what I did in the end was use - 'use' to import the individual classes that I needed

for example instead of adding '/' in front of everything like:

\DateTime()

I added under my namespace

namespace MyProject;
use DateTime;

...
DateTime();     //without \
...


问:
Reducing complexity of our custom framework
At our company, we have a custom software application using our own framework. The framework was built in approximately 2002 or 2003, long before I showed up at the company. Majority of the functions in the framework are solid so we still use them as we've never had any issues with them, I'm talking about the database functions and functions to grab get/post parameters and escape data, etc.

It used to be just me working on the projects so I never had any issues with the code-base, however we now have up to 6 developers who started working on the framework recently so things have become more complicated. In our current framework have it set up such as:

```<code>/cms/
/cms/modules/
/cms/modules/filemanager/
/cms/modules/filemanager/index.php
/cms/modules/pages/
/cms/modules/pages/index.php
/cms/...
</code>```

Now inside each index file of each module we have the following:

```<code>require_once '../../config.php';
require_once '../../database_functions.php';
require_once '../../url_functions.php';
</code>```

I am finding it more and more difficult to maintain the changes now and now that certain modules are interacting with other modules it is just getting crazy to maintain this among all of our development team.

It used to be very simple but now our page module actually integrates other modules into the main module, into placeholders basically so one can put any content from individual modules into the page.

The issue comes when we make a change to our gallery module and now I need to make changes on the front-end (html output), the gallery module itself, the database and then debug all the errors that come about in other modules that are currently using the data from the gallery module. It becomes a chain reaction of changes basically.

Does anyone have any suggestions of how to streamline things or a better way to control the maintenance of our application? We are still using a very structured way of coding using straight scripting and functions rather than OOP, as I am used to coding in C and I don't like to complicate anything more than necessary.

Aside from these issues, we don't use anything like versions in our software right now, we've distributed great work and clients love the software we give out, we just don't have versions on them and no builds or anything, which is probably a big mistake in itself.

Any ideas or suggestions or even a link out to somewhere that can help us figure out how to better structure our development process (if that's an issue) would be greatly appreciated.

答:
First off, you claim that your legacy 'core' libraries are solid.  My stance on that would be to isolate them from the dev team.  Embrace just a little bit of OOP by wrapping them in extended purpose built wrappers.  So if you need the db code for filemanager, write a dbfilemanager intermediary so that you can change it and not mess up 'pages'.  likewise add a dbpages for the same reason.

The 'good practice' is to not mess with robust, well-aged code and to simply extend it for specific purposes.

I personally do not mind if code is duplicated in the universe, particularly if it enables legibility and cohesiveness in a system's design.  In other words, even if you have a mostly similar function in DBFileManager and DBPages, at least your code paths don’t have cross-dependencies. You're code sounds like it is rapidly becoming spaghetti as subsystem-specific features are pushed into core libraries.  You'll be happier the sooner you stop doing that.

Regarding versions, they are just labels to help you identify the most likely culprit when something is not working. Versions also can make people think they need to buy the latest because their version number is so old.  Both reasons are very good and should be used to convince your company to start using them.


答:
I'm going to answer in a general way, not addressing any PHP specific issues.  The root of the problem is that your team has grown from 1 developer to 6 developers. As each new developer approaches the code base, s/he will see ways to innovate with the code and to use the structure in ways you didn't anticipate. Also - without a build and version control system, multiple developer committing simultaneous changes can lead to chaos.  Here are the steps I recommend:

Approach solving this problem as a team. Everyone should be aware of
the problem, and should participate in integrating best practices
into the development process. The team, as a whole, should agree on what will be the ongoing release, build and test process.

Agree on the release process, so that people are not stepping on
each other's changes. This means defining a release, version tagging
code, and branching as needed.

Start building automated unit/regression tests that developers run
before each check in. This allows each developer to record his/her assumptions about the code, and will alert other developers if they break those assumptions. There are many good web test frameworks out there. Pick one and start using it.

I'm assuming that at least some of those 5 other developers have experience working in a team environment, and will already have some suggestions about how to move ahead.

Title: Reducing complexity of our custom framework

Body:
At our company, we have a custom software application using our own framework. The framework was built in approximately 2002 or 2003, long before I showed up at the company. Majority of the functions in the framework are solid so we still use them as we've never had any issues with them, I'm talking about the database functions and functions to grab get/post parameters and escape data, etc.

It used to be just me working on the projects so I never had any issues with the code-base, however we now have up to 6 developers who started working on the framework recently so things have become more complicated. In our current framework have it set up such as:

```<code>/cms/
/cms/modules/
/cms/modules/filemanager/
/cms/modules/filemanager/index.php
/cms/modules/pages/
/cms/modules/pages/index.php
/cms/...
</code>```

Now inside each index file of each module we have the following:

```<code>require_once '../../config.php';
require_once '../../database_functions.php';
require_once '../../url_functions.php';
</code>```

I am finding it more and more difficult to maintain the changes now and now that certain modules are interacting with other modules it is just getting crazy to maintain this among all of our development team.

It used to be very simple but now our page module actually integrates other modules into the main module, into placeholders basically so one can put any content from individual modules into the page.

The issue comes when we make a change to our gallery module and now I need to make changes on the front-end (html output), the gallery module itself, the database and then debug all the errors that come about in other modules that are currently using the data from the gallery module. It becomes a chain reaction of changes basically.

Does anyone have any suggestions of how to streamline things or a better way to control the maintenance of our application? We are still using a very structured way of coding using straight scripting and functions rather than OOP, as I am used to coding in C and I don't like to complicate anything more than necessary.

Aside from these issues, we don't use anything like versions in our software right now, we've distributed great work and clients love the software we give out, we just don't have versions on them and no builds or anything, which is probably a big mistake in itself.

Any ideas or suggestions or even a link out to somewhere that can help us figure out how to better structure our development process (if that's an issue) would be greatly appreciated.


问:
Should Multiple Data Items be in Multi Unit Test Methods?
I often want to have the same unit test applied to data multiple items that are roughly equivalent (two non-empty strings).  Currently I implement these in multiple unit test methods, with names like MethodNonEmptyValidString1 and MethodNonEmptyValidString2.  This has a bit of a code smell to me.

Is it better to have the multiple data items in one method with multiple asserts?  Is there another design pattern that models this more accurately?

答:
Well, NUnit has a TestCase attribute for just this purpose, which seems to solve the problem neatly.

```<code>    [TestCase(NonMatchingName1, NonMatchingValue1)]
    [TestCase(NonMatchingName2, NonMatchingValue2)]
    public void TestNonMatchingAttribute(string name, string expectedValue)
    {
         //...
    }
</code>```

This type of structure solves the problem fairly well.

Body:
Well, NUnit has a TestCase attribute for just this purpose, which seems to solve the problem neatly.

    [TestCase(NonMatchingName1, NonMatchingValue1)]
    [TestCase(NonMatchingName2, NonMatchingValue2)]
    public void TestNonMatchingAttribute(string name, string expectedValue)
    {
         //...
    }

This type of structure solves the problem fairly well.


答:
Perhaps your naming is a bit uncreative and non-descriptive.

Anyway, using Java I would test the same thing with different data using one of two ways:

with JUnit, use TwiP

with TestNG, us data providers

Both allow feeding different sets of data to the same test method. Your tests will have names alluding to the parameters in your test output.

Title: Should Multiple Data Items be in Multi Unit Test Methods?

Body:
I often want to have the same unit test applied to data multiple items that are roughly equivalent (two non-empty strings).  Currently I implement these in multiple unit test methods, with names like MethodNonEmptyValidString1 and MethodNonEmptyValidString2.  This has a bit of a code smell to me.

Is it better to have the multiple data items in one method with multiple asserts?  Is there another design pattern that models this more accurately?


答: "Bad" is in the eye of the beholder.  Your "bad" may be their "beautiful".  Until and unless you become a significant contributor, you should follow the established style.</p>


问:
Impact of Website Redesign on Google Analytics
I just finished a redesign for a website that is currently using Google Analytics. I want to continue to use Google Analytics, but I'm not sure if I should create a new profile for the new site or simply use the old UA number.

The new website has a completely different URL structure and much of the content has been updated/deleted/added.

答:
It's just a choice you have to make. Google analytics tracks pages by both page title and url. Depending on how you are viewing the report, your new pages with the same page titles will still aggregate together (so the data will combine), whereas when viewing by page url (if the urls have been moved) will show up with new entries (and the data will start over). When viewing the content overlay reports however you will get some odd data because your content has changed.

I personally would just use the same UA number. This will also allow you to easily compare the performance of the new site vs. the old by comparing the data range moving forward to the date range before the site was redesigned. I have done this with a site and it worked well for tracking performance changes.

You should also consider the SEO impacts of making drastic changes to your site. That is a whole other issue altogether.


问:
Why do trees grow downward?
Why do trees grow downward in computer science?

I have a feeling it goes back to a printer, and that a program traversing a tree first prints the root, and uses the notion of a bottomless stack of paper to express the indefinite levels of recursion that might be encountered.

References:

Trees grow downward, having their roots at the top of the page and their leaves down below

From ON HOLY WARS AND A PLEA FOR PEACE.

by convention, trees are drawn growing downwards

From the Wikipedia article on tree data structures.

Real trees grow from their root upwards to the sky, but computer-science trees grow from the root downwards

From David Schmidt's lecture notes.

答:
Just a guess:

Tree structures grow downward (root at top, leaves at bottom) because people read from the top of the page toward the bottom. Furthermore, if you were to draw a large tree that spanned several pages, it would be awkward to ask the reader to skip ahead a few pages and then work backward.

Furthermore, whether the convention started for the reason explained above or for some other reason, we continue the practice today exactly because it is a convention. We have corresponding terms like top level node (meaning the root) that wouldn't make as much sense if we drew the structure with the root at the bottom.

Title: Why do trees grow downward?


问:
Is it considered bad practice to run different JavaScript for IE
Is it considered bad practice (and how bad) to run different JavaScript for IE? Currently im writing some JavaScript and the simplist way to work arround IE quirks seems to be to check for browser version and run different code

```<code>var browserName = navigator.appName;

if (browserName == "Microsoft Internet Explorer") {
  //Do some stuff
}
else
{
//Do other stuff
}
</code>```

It's quick and works well but does lead to duplication of code and feels "hacky".

答:
Yes

Inferring functionality from a user agent string is a weak and error-prone test. Though relatively common, in this day and age I would say it is certainly considered a bad practice.

For example jquery has a function for detecting which browser a user is using and it's been deprecated since version 1.3

Therefore: Don't do UserAgent sniffing to decide what the browser is or what it's capable of.

Best practice

The accepted best practice for handling the differences between browser capabilities is to use feature detection.

There are a few libraries around for this, the most well known is probably: Modernizr. Modernizr makes it easy to tailor your javascript to the abilities of a browser. It works by detecting what's available; not guessing based on a UserAgent string (except as a last resort fallback) and simply adding classes to the html tag. This makes it not-only possible to easily handle different cases in your js - but also to address certain deficiencies with css alone. e.g. (purely for illustration only):

```<code>ul.menu {
    display:none;
}
ul.menu:hover {
    display:block;
}

# A touch device can have no hover - so show it always
html.notouch ul.menu {
    display: block;
}
</code>```

Body:
Yes

Inferring functionality from a user agent string is a weak and error-prone test. Though relatively common, in this day and age I would say it is certainly considered a bad practice.

For example jquery has a function for detecting which browser a user is using and it's been deprecated since version 1.3

Therefore: Don't do UserAgent sniffing to decide what the browser is or what it's capable of.

Best practice

The accepted best practice for handling the differences between browser capabilities is to use feature detection.

There are a few libraries around for this, the most well known is probably: Modernizr. Modernizr makes it easy to tailor your javascript to the abilities of a browser. It works by detecting what's available; not guessing based on a UserAgent string (except as a last resort fallback) and simply adding classes to the html tag. This makes it not-only possible to easily handle different cases in your js - but also to address certain deficiencies with css alone. e.g. (purely for illustration only):

ul.menu {
    display:none;
}
ul.menu:hover {
    display:block;
}

# A touch device can have no hover - so show it always
html.notouch ul.menu {
    display: block;
}


答: Use the IE specific comments

Title: Is it considered bad practice to run different JavaScript for IE

Body:
Is it considered bad practice (and how bad) to run different JavaScript for IE? Currently im writing some JavaScript and the simplist way to work arround IE quirks seems to be to check for browser version and run different code

```<code>var browserName = navigator.appName;

if (browserName == "Microsoft Internet Explorer") {
  //Do some stuff
}
else
{
//Do other stuff
}
</code>```

It's quick and works well but does lead to duplication of code and feels "hacky".

Body:
Use the IE specific comments <!--[if IE &gt; 6]>... or something like that. Works on all super crappy browsers IE? -> IE8, but not on IE9+ which is considered sort of ok as a browser.

The bottom line, once you deal with super crappy browser that needs workarounds, it's ok to do whatever is necessary, but avoiding turning well written baseline code into a hackatron.

Hopefully, IE will go away one day, and you will be able to delete the hackatron code and leave the well written baseline only.


问:
websites that show real world scenarios for OOP beginners so that they can implement them
Since programmers learn more by implementing the real world scenarios rather then by gaining theoretical knowledge and concepts about programming, I wanted to know that is there any website that tells about real world scenarios for OOP learners so that they can practice their designing skills and implement these scenarios using c#?

Like which can help them making designing decisions for a problem for e.g in which scenario one should use abstract classes, interfaces, virtual overriding etc.

答:
This question is essentially a duplicate of https://stackoverflow.com/questions/1076336/how-to-gain-real-world-programming-skills-when-you-dont-work-for-a-software-com

or https://stackoverflow.com/questions/277106/looking-for-some-interesting-c-sharp-programming-problems

Both of these have many fine answers that should point you in the right direction.
A quick Google search got me: http://sixrevisions.com/resources/10-puzzle-websites-to-sharpen-your-programming-skills/

"Real world scenarios" is somewhat ambiguous, the main difference between tinker toy programs and professional programs is that more consideration is given towards security, scalability, compatibility, resource management, performance, etc.

You may want to consider finding websites/books/classes you are comfortable with that focus on syntax/concepts to use as a reference or guide as you go along.

And as others have already mentioned, the best way to learn programming is to simply start writing a program that does something you find interesting. Simple games (tetris, snake), tools (calculator, file browser), or open-source community projects are great places to get ideas.


问:
Array or Malloc?
I'm using the following code in my application, and it's working fine. But I'm wondering if it's better to make it with malloc or to leave it as is?</p>

```<code>function (int len)
{
char result [len] = some chars;
send result over network
}
</code>```

答:
In embedded programming, we always use static array instead of malloc when the malloc and free operations are frequent. Because of the lack of memory management in embedded system, the frequent alloc and free operations will cause  memory fragment. But we should utilize some tricky methods such as defining the max size of array and using static local array.

If your application is running in Linux or Windows, it is no matter using array or malloc. The key point lies in where you use your date structure and your code logic.

Title: Array or Malloc?


问:
I have one afternoon to extol the benefits of .NET over VB6... what do I say?
My company is a small twenty-man engineering firm. All the application programming here is done in VB6 by two people, who have taught themselves VB6 from an assembly background while working here for the past 25+ years, and myself.

As a result, the VB6 code is riddled with horrendous code smells, like tons of stringly typed variables, terribly long functions, hundreds of public global variables (some of which are preferred over passing around arguments and returning values,) and not a single object class. Refactoring is nigh impossible, and any changes require too much digging through code, and once made, always seem to introduce more holes.

My boss is realizing that VB6 is a dead technology, and is willing to listen to my pleas of moving to .NET for new development. We are moving forward to .NET, but he sees it as a way to keep up compatability with the newer Windows OS's, not as a way to write better code.

How can I best explain the benefits of .NET language over VB6, beyond mere up-to-date-ness? What can I say to best emphasize that the move to .NET is a good move but also that it means our current programming paradigm should also begin to change? As soon as my boss hears that Visual Basic .NET looks just like VB6, I know that his first instinct will be to simply convert our old code mess to .NET.

I understand that it will be impossible to change anyone's mindset in a single afternoon, but how can I at least convince my assembly-toting boss that things like strongly-typed variables, custom classes, and private fields aren't a total waste of time and energy?

答:
I have a customer whose flagship product is written in VB6 and maintained by 3 people. I came to help them because they had a partner that wanted them to call a web service. That's very hard to do from VB6, but easy from VB.NET or C#, and I wrote them a .NET assembly that looked to VB6 like a COM component so they could call it. Then they needed to offer a web service to someone. Then they wanted to write a little standalone utility and it was going to need to encrypt and decrypt some information, and to parse some XML. I taught them to write that in .NET. Over the last 5 years or so, more and more of their code is in .NET even though the flagship product hasn't shrunk at all. There are parts of it they hate - every app has them - and where they can they are pulling these parts out (now the shrinking starts) and putting them into services or separate utilities. The rest of it will be converted holus-bolus to .NET. Yup, bad variable names and all - to my mind there are plenty of benefits to moving to .NET even if they don't change their current programming paradigm. These include:

you can use the latest Visual Studio with better searching, better Intellisense, faster builds, etc

you can integrate with a decent source control system (ie not VSS)

there are libraries that come with .NET for free that make short work of things like encryption, XML parsing, image processing, and more

internationalization and localization is much easier on a .NET project (this, with an inquiry from a huge Canadian customer who would need both French and English versions, may have tipped the balance for my client)

inexpensive control libraries (Telerik, Infragistics, ComponentOne etc) give you amazing capabilities for almost no cost

it will be much easier to find temporary help, like a summer student, in circumstances where the time spent to teach them VB6 is not worth it (don't discuss how you feel about teaching it to a new fulltime hire)

your application will be UAC aware, so it will run better on Vista, 7, and 8. It won't need to be run in XP compatibility mode

There's more, but surely that's enough?

The matter of programming paradigms, strong typing, the compiler is your friend, encapsulation is your friend and so on is to my mind (and I get paid to have these opinions) entirely separate. If you want to die on that hill go ahead, but you'll be dying with a copy of VB6 open.


答:
The convention appears to stem from the Coffman-Graham Algorithm which is designed:

"...for arranging the elements of a partially ordered set into a sequence
  of levels. The algorithm chooses an arrangement such that an element
  that comes after another in the order is assigned to a lower level,
  and such that each level has a number of elements that does not exceed
  a fixed width bound W."

Their paper from 1972 (PDF) shows a directed acyclic graph being drawn from top to bottom. It is a short step to represent a tree in the same manner.

There is some further commentary on this visualisation in this article on Layered Graph Drawing.

Title: Why do trees grow downward?

Body:
Why do trees grow downward in computer science?

I have a feeling it goes back to a printer, and that a program traversing a tree first prints the root, and uses the notion of a bottomless stack of paper to express the indefinite levels of recursion that might be encountered.

References:

Trees grow downward, having their roots at the top of the page and their leaves down below

From ON HOLY WARS AND A PLEA FOR PEACE.

by convention, trees are drawn growing downwards

From the Wikipedia article on tree data structures.

Real trees grow from their root upwards to the sky, but computer-science trees grow from the root downwards

From David Schmidt's lecture notes.


答:
Short Answer: There is nothing you can do to change their minds based on the criteria you listed in the question which are all technical. This is the equivalent of a religious debate. The quickest route to failure is to present an argument that is not from the point of view of the audience, in this case business owners.

Longer Answer: Change in business is driven by one thing and one thing only. Profit to the bottom line.

... how can I at least convince my assembly-toting boss that things like
  strongly-typed variables, custom classes, and private fields aren't a
  total waste of time and energy?

They can not only be a waste of time and energy but more importantly they cost you money! You must be able to quantitatively show that your suggestions will lead to a substantial profit over time. Just claiming clean code is "better" isn't enough, because clean code costs way more to produce.

If you can articulate how the cost of using modern technology will lead to ($COST + X) * TIME = $PROFIT, where X is a non-trivial postive number and TIME is relatively short you can create a compelling scenario.

Another way to calculate the ROI ( Return On Investment )

If this ROI/ROR is a trivial number, especially over a long period of time, you don't have much of a business case either.

How does your company actually make their money?

how many lines of code? how many customers? how much revenue a year
  does this software produce? is revenue mostly support contracts? or
  new licenses? is the target market stable? expanding? contracting?
  is the software a loss leader to some other much more profitable product?

It is hard for a good business man to ignore money laying on the table.

Of course you have to be able to back up your statements with hard facts. This means you need to be able to provide real numbers that show you really understand the actual business and not just academic technical details.

Not just the Pros

Also providing a detailed risk analysis and what these risks would $COST if they happened, would go along way in convincing them that you have a realistic case and aren't just whining that you don't want to be doing VB6 anymore.

Teaching old dogs new tricks

... What can I say to best emphasize that the move to .NET is a good move
  if and only if our current programming paradigm also begins to change? ...

Changing or Not Changing the programming paradigm to be as idiomatic as possible of the new technology is part of the risk analysis. But this is a separate argument only after you have proven there is significant money to be made by making a change in the first place.

Business people tend to listen to business cases just like technical people tend to listen to technical cases. All your cases in your question are espousing technical merits which are academic at best in your situation.

Prediction

I am making a few assumptions here VB6 app, small shop, few developers, 2 older developer/business owners is pointing to a niche market app that is probably mature ( bugs and work arounds are known ), fairly feature complete and relatively stable, regardless of the "mess" the code base is. This leads me to believe that the small user base isn't growing dramatically year over year either, which leads me to the following conclusion.

That there really isn't going to be any real compelling business reason to change technical direction with this application. And up porting to VB.Net is a waste of time as well because you will just have the mess but now with more of it, and 2/3 of the development team not dedicated to learning anything new. Good luck.

Title: I have one afternoon to extol the benefits of .NET over VB6... what do I say?

Body:
My company is a small twenty-man engineering firm. All the application programming here is done in VB6 by two people, who have taught themselves VB6 from an assembly background while working here for the past 25+ years, and myself.

As a result, the VB6 code is riddled with horrendous code smells, like tons of stringly typed variables, terribly long functions, hundreds of public global variables (some of which are preferred over passing around arguments and returning values,) and not a single object class. Refactoring is nigh impossible, and any changes require too much digging through code, and once made, always seem to introduce more holes.

My boss is realizing that VB6 is a dead technology, and is willing to listen to my pleas of moving to .NET for new development. We are moving forward to .NET, but he sees it as a way to keep up compatability with the newer Windows OS's, not as a way to write better code.

How can I best explain the benefits of .NET language over VB6, beyond mere up-to-date-ness? What can I say to best emphasize that the move to .NET is a good move but also that it means our current programming paradigm should also begin to change? As soon as my boss hears that Visual Basic .NET looks just like VB6, I know that his first instinct will be to simply convert our old code mess to .NET.

I understand that it will be impossible to change anyone's mindset in a single afternoon, but how can I at least convince my assembly-toting boss that things like strongly-typed variables, custom classes, and private fields aren't a total waste of time and energy?

ContentLicense: CC BY-SA 4.0


问:
How to read from a database, and write to a file asynchronously / non blocking way in Java
I'm trying to modify a serial program that reads from a database, and writes results to a file, this is done in a blocking way and I think we can get performance boost of there is a memory buffer and have the file being written in the "background" asynchronously

I can think of the "job interview" solution, using Threads, shared resource, syncronized blocks etc... but I'm sure there is a better way (is there a nice little "delayed write" library out there that will do it for me?)

Does any of the java.util.concurrent package offer any help? java.nio? or perhaps JMS/ActiveMQ?

What about PipedOutputStream / PipedInputStream as a basis for my buffer?

How do I implement a delayed / background / buffered / non-blocking / asynchronous file writter in Java?

答:
It's been a while, but perhaps this article on JSR 203 may offer some guidance. An example of what you may be after is given as:

```<code>AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("Path to file"));
ByteBuffer buffer = ByteBuffer.allocate(capacity);

Future result = channel.write(buffer, 100); // Write capacity bytes to the file starting at position 100

boolean done = result.isDone(); //Indicate if the result is already terminated
// Alternatively...
int bytesRead = result.get(); // You can also wait for completion
</code>```

Of course, before going down this route you should consider that you are not indulging in premature optimisation. Make sure you have proof that an asynchronous operation will actually benefit your application.

Body:
It's been a while, but perhaps this article on JSR 203 may offer some guidance. An example of what you may be after is given as:

AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("Path to file"));
ByteBuffer buffer = ByteBuffer.allocate(capacity);

Future result = channel.write(buffer, 100); // Write capacity bytes to the file starting at position 100

boolean done = result.isDone(); //Indicate if the result is already terminated
// Alternatively...
int bytesRead = result.get(); // You can also wait for completion

Of course, before going down this route you should consider that you are not indulging in premature optimisation. Make sure you have proof that an asynchronous operation will actually benefit your application.


问:
Eloqua API Full Code Example in JAVA
Is there anyone out there who has mastered to retrieve some data programmatically from Eloqua?

First of all, I'm more or less a newbie, as far as JAVA. I can follow tutorials, take directions and will Google till my fingers bleed. I understand the basics and am slightly familiar with OOP. My main problem is that I have a Friday deadline (and tomorrow is Thanksgiving).

At any rate, all the Eloqua code snippets (that I've been able to find) illustrate one aspect of a specific issue, and that's it.

In my case, I would greatly appreciate a JAVA project of some sort, with all the necessary files to do web services (WSDL, SOAP and perhaps WSIT) and the main class and all that included.

No, I don't want you to do my work for me! Just give me enough to find my way around, enter the information I need to retrieve and all that. I'll take it from there.

Any pointers, links or suggestions?

答:
Well, it's been a while but here are some projects on GitHub that may offer some guidance:

Ruby: landcentral/eloqua

JavaScript (Node.js): Eloqua/eloqua-request

There is also a TopLiner article going into some detail with Java and Eclipse. It was noted that there may be some issues with it and the comments indicate possible paths to take to fix them.

Title: Eloqua API Full Code Example in JAVA


答:
The first thing you say is that VB6 is no longer supported by Microsoft. Whilst you can keep it running, you have to understand its options in the long-term are nil. I don't even know if VB6 apps will run on Windows8, or if the IDE itself will run on Win8.

So, you effectively have to do a rewrite eventually, and if that's the case, you might as well start now rather than later, giving you plenty of time to figure out which new tech you want to use (while VB.NET sounds ideal, this is your opportunity to try something more cutting-edge, like make the app work on iPads).

In the short term, you can mitigate the problem a little by introducing new sections as COM components for the existing app to consume, hopefully these components will remain when the inevitable rewrite happens.

I wouldn't bother with technical arguments over why .NET is better than VB6. You will be on to a losing argument there, technology in itself never solves problems. Its up to you how you apply that technology, and if the VB6 app is solving stuff for you, there's no argument to answer. You can talk about ease of maintenance, or availablility of experienced staff, but once you do that you admit that your existing staff have no expertise in the new tech and will have to be trained, and then take some time to fully get up to speed with it. You will also have to answer the questions about how a lot of rewrites end up worse than the original project (sometimes due to the lack of expertise, sometimes due to too-grand designs).


答:
Give him the "old car new vs car" analogy:

Yes both will probably get you to your destination. However the new car doesn't need a crank, it doesn't need a choke, it doesn't need maps, its wheels do not lock when you brake sharply, and finally you are far more likely to walk away from a car crash.

VB6 is legacy, its the new COBOL

.NET has better frameworks

.NET has better tooling

.NET has better performance

.NET has better IDE

.NET has better language support

.NET has better features

.NET has better community support


问:
Why does DirectX use a left-handed coordinate system?
I considered posting on Stack Overflow, but the question strikes me as being far too subjective since I can't think of a reasonable technical explanation for Microsoft's choice in this matter. But this question has bugged me for so long and the issue keeps coming up in one of my projects, and I have never actually seen an attempt at explaining this:

OpenGL uses a right-handed coordinate system, where the +Z part of the world coordinate system extends toward the viewer.

DirectX uses a left-handed system where the +Z part of the world coordinate extends into the screen, away from the viewer.

I never used the Glide API, so I don't know how it worked, but from what I can gather, it uses a left-handed system as well.

Is there a technical reason for this? And if not, is there some conceptual advantage to a particular handedness of a coordinate system? Why would one choose one over the other?

答:
Interesting fact.

Direct3D (not DirectX - DirectX also covers input, sound, etc) actually doesn't have a left-handed co-ordinate system.

It's perfectly capable of supporting both RH and LH systems.  If you look in the SDK documentation you'll see functions such as D3DXMatrixPerspectiveFovLH and D3DXMatrixPerspectiveFovRH.  Both work, and both produce a projection matrix that can be used successfully with your co-ordinate system of choice.  Hell, you can even use column-major in Direct3D if you wish; it's just a software matrix library and you are not required to use it.  On the other hand, if you want to use it with OpenGL you'll find that it also works perfectly well with OpenGL too (which is perhaps the definitive proof of the matrix library's independence from Direct3D itself).

So if you want to use an RH system in your program, just use the -RH version of the function.  If you want to use an LH system, use the -LH version.  Direct3D doesn't care. Likewise, if you want to use an LH system in OpenGL - just glLoadMatrix an LH projection matrix.  None of this stuff is important and it's nowhere near the huge issue that you sometimes see it made out to be.


问:
Why is 80 characters the 'standard' limit for code width?
Why is 80 characters the "standard" limit for code width? Why 80 and not 79, 81 or 100? What is the origin of this particular value? </p>

答:
Another common line length limit in the days of fixed pitch fonts was 72 characters. Examples: Fortran code, mail, news.

One reason was that columns 73-80 of a punch card were often reserved for a serial number. Why a serial number? If you dropped a card deck, you could pick the cards up in any order, line up the upper left corners (which always had a diagonal cut) and use a card sorting machine to get them back in order.

Another reason for the 72-character limit was that common fonts were 10 points high and 6 points (1/12") wide. An A4 or 8.5" wide page could hold 72 characters in a 6" wide column and still have room for margins of over an inch.


问:
Is Perl still a useful, viable language?
I know it may have been asked before, but here goes nothing...

Is Perl still something that would be considered useful? If someone was a new programmer (either completely new to programming or just a few month/years of experience) would Perl be something to be considered worthwhile to learn?

Is Perl still used with frequency? Is it still popular?

Or is Perl dying out compared to languages like Python, Ruby, PHP, ASP.NET, etc.?

Basically it boils down to this:

Is it still used/is it still used frequently? If yes, is it dying? If no, will it make a come back?

Is it something that would be worth learning?

How does it compare in demand to languages like Python in both popularity and usability/viability? Could languages like Python or Ruby be considered replacements for Perl?

Also, will newer versions of Perl really bring a large improvement to the Perl community, and perhaps bring Perl back to centerstage compared to other languages?

EDIT:

Okay, I suppose here's a better, reworded question:

Is Perl still growing, or is it "dying"? Is it still a language worth learning and using? What projects does it really "shine" in compared to other languages? What makes Perl a language to choose? Essentially: is Perl growing obsolete compared to other languages, and if so, do you expect that to change, or to continue?

And thank you to everyone who has answered so far, the discussion has been really interesting!

答:
Perl is definitely not dying. It has just never been as hyped up as some other languages have been.

While it is true, that Perl itself is an old language, it has a vibrant and very productive community, the value of which is in the CPAN library. I don't think any language has a library as extensive and as comprehensive as CPAN. Nothing even comes close. In CPAN you will find thousands of modules and frameworks, that do just about anything you can imagine. Need a web server? There's HTTP::Server. Need a standalone database? There's Muldis::DB. Whatever your needs happen to be, you will usually find several modules that fulfill your need, you just have to pick the one that fits your app best.

As for Ruby, Python and other competitors, i think healthy competition has been a tremendous benefit to Perl. Anything that other languages got, the Perl community rewrote in Perl. For example, when Ruby was flying on the success of Rails, Perl got Dancer, which is in many ways better then Rails.

Perl is definitely not dead, nor is it dying. There's just nothing flashy going on around it, there's no company, that would benefit from hyping up Perl, so it doesn't get much media attention, and not every kid knows Perl, so there's less talk about it.

It's been more then 6 months since your original post. In case you have still not decided, do yourself a favor and learn Perl.


答:
It seems to me that this is a situation where you will need to put on your politician hat instead of your programming one. You must be very mindful how you make your argument and that you do not antagonize your audience. Make sure that you show the advantages of .Net instead of showing the disadvantages of VB. Arguing the disadvantages of VB will put your coworkers in a position where they need to defend their decisions and force them to admit that a language they have a heavy investment in is a bad language. Instead, show them how moving to .NET will augment the tools they have available to them and make their life easier.

My ideal way of making this argument would be find a task or piece of code that everybody is constantly complaining about and fix it using .NET. I'm not especially familiar with VB, but here is a short list of annoying tasks that would probably be made easier by using .NET instead of VB.

String Manipulation

XML Parsing

Searching/Matching/Regex

Math (newer languages usually have faster, more comprehensive math libraries)

GUI building/design

Pick any one of the the above tasks, or some other task specific to the projects you usually work on, and sit down with them and actually write some code, from scratch, that handles the problem quickly and easily. Actually showing the process of writing the code will show off the tools that newer versions of VS bring to the table and provide evidence that moving to .NET will not make anybody's life harder.

Going into this, you absolutely, positively must do you're homework. If you show up unsure of how tools work, or have code that doesn't work correctly, you are never going to be able to win them over to your side.


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
I think you've hit the nail on the head with this statement

I'd hate to take things at face value and not think about them critically

I ignore almost all Best Practices when it doesn't come with explanation on why it exists

Raymond Chen puts it best in this article when he says

Good advice comes with a rationale so
  you can tell when it becomes bad
  advice. If you don't understanding why
  something should be done, then you've
  fallen into the trap of cargo cult
  programming, and you'll keep doing it
  even when it's no longer necessary or
  even becomes deleterious.


问:
How do you handle / what do you charge for documentation, training, warranty, changes in scope etc…
I am working with a client right now that wants me to sign a contact with a warranty for a year for no additional charge. As well as any reasonable changes he wants during the contract that are outside of the guidelines for no additional charge while not affecting deadlines. And lastly documentation and training for all staff for no additional charge.

Red flags are going everywhere in this contract and I wanted to hear from professionals how you guys handle / what you charge for documentation, training, warranty, changes in scope etc...

答:
The definition of reasonable is going to be a landmine.  Large contracting companies can often offer a year's support for 1/3 of the headline cost, but they have at least two advantages:

they have an agreed and finalized functional spec and

they have enough manpower and resources that if they over-run on one job, they absorb the loss and chalk it up to experience (i.e. the self-insure against unsuccessful projects).

If you can't do both those things, don't sign.

Documentation and training is a different matter, offering it for free is a reasonable thing.   Offer a specific number of days of training (total, not per staff member).


问:
How much should app iphone or ipad development cost?
I'm an iOS developer (freelancer) and i want to know how much cost to build an app? and how should i do to estimate the price? like this app http://www.finalcad.fr/en/index.html</p>

答:
Typical contractor rates are in the $75-$150 range. Other than that, it really depends on your app. Here are some common considerations:

How many different views/pages does your app have? Is it 4 or 5 pages that have no real interaction, or a complicated tree of resources that is ever changing? Are these pages static, or generated on the fly?

What level of interaction do those pages have? Is it a wall of text with 2 buttons? Does it have a scroll view that pre-loads images ala Google Maps? Does it use pre-existing functionality in iOS, or are you rendering custom OpenGL ES stuff?

Will you be interacting with web services? Are you just reading RSS feeds, or posting/retrieving? Syncing issues can add a lot of cost to a project just because cell coverage is intermittent by nature.

Will you be using custom or default graphics? If custom, how does the developer get them? Will they be pre-sliced, or a raw PSD? Did the designer customize stuff that isn't easily changed, and will this cause custom objects to need to be created?

What's your timeline? Is this a rush job that needs to be done by the weekend, or can this be done gradually over the next 3 months.

What dependencies does this project have? Will I be including images/pdf's/video that is coming from a third party? Will it be provided at the beginning of a project, or sent intermittently during? Believe it or not, this can greatly change how an app is built.

If you can nail down some of those questions, it will give us a better idea of how to answer your question. For orders of magnitude, think of it this way: App development is a game of tens of thousands, not hundreds. Very basic apps will cost north of $1000 easily, and something as complicated as the app you link to can cost >$75,000 very easily (check out this link for the example of what it cost to develop Twitterific)


答:
First off I think you should change the question (not on stackexchange but within your company).   It's not so much why is .Net better that VB6, but more like since VB6 is no longer supported it is time to move on, but to what.    Ask the stakeholders what should that 'new' technology be?  Maybe it's not .Net.

But it sounds like you need to move to a new technology AND get some good programming patterns and practices in place.  The answer to the second part is much harder.  You probably have to do it in small section of the application and prove it worth while, that is it is more stable, easier to maintain, etc.


问:
Using version control to manage site backups?
Last week I started making daily backups of my relatively small (~300mb) site. The backups are zipped, so it's less space, but it will quickly add up, especially as my site gets bigger.

I was thinking of unzipping the latest backup, and from now on just using mercurial to add/update files from newer backups.

Are there any drawbacks to this? Is there a better way to do it?

答:
Git is a great way to go as others' mentioned. For database (like MySQL), you should be able to create a cron job that runs a script to backup the database and to rotate the the log files.

s, and use daily logging I do something like:

/usr/sbin/logrotate -s status-file logrotate.conf

mysqldump --tables --add_drop_table --user=my-db-username --password='my-password' --host=dbase-server my-database > /the/backup/dir/my-database.sql

My logrotate.conf says to do daily logs, compress, rotate every 14 day. I wildcard it to apply to all *.sql files.


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

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

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

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

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

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

Also, can you suggest the sources for the same?

Edited:
Sources suggesting development of coding skills.

答: I would say that you should read up on design patterns, such as Builder, Factory, Composite, and eventually Observer, Mediator, and Flyweight.  Design patterns aren't the end-all-be-all for coding solutions, but they demonstrate how to implement theoretical concepts of object oriented programming.</p>

Title: How do I improve my coding skills?


问:
Do DVCSes discourage continuous integration?
Say there is a team of ten agile developers. Every day they each pick a task from the board, commits several changes against it, until (by the end of the day) they have completed the task. All developers check in directly against trunk (Google-style, every commit is a release candidate, using feature toggles etc).

If they were using a centralized CVS like SVN, every time one of them commits, the build server will integrate and test their changes against the other nine developers' work. The build server will be pretty much running continuously all day.

But if they were using a DCVS like git, the developer may wait until they complete the task before pushing all their local commits together up to the central repository. Their changes will not be integrated until the end of the day.

In this scenario, the SVN team is continuously-integrating more frequently, and discovering integration problems much faster than the git team.

Does this mean DVCSs are less suitable for continuous teams than older centralized tools? How do you guys get around this deferred-push issue?

答:
Build servers are cheap. Just have your CI server pick up all the branches you know about.

Jenkins has support to check multiple git repositories and get the 'latest' from any of those in a single job. I'm sure there are similar solutions with other tools.


问:
How to use unit tests as a source of information?
A colleague of mine was once at a seminar about agile development, where he heard it is possible to use unit tests as technical documentation. Something like using unit tests as an example of how to use the class.

A quick Google search provided TDD and Documentation, which proves it should be possible. But looking at our code, I see that we obviously failed to implement unit tests in such a way.

In my opinion unit tests are there to test code as a minimal unit, even with help of mock and fake classes and functions.

So, the questions are:

Isn't it the task of functional tests to show how a class (or set of classes) should be used?

If it is possible to use unit tests as technical documentation, are there some guidelines on how to implement such unit tests?

答: The idea of tests as acceptance criterias/documentation is an excellent one. However, unit tests tend to focus on architecture/code design rather than user stories - trying to document higher level use cases or requirements can be awkward. I haven't looked much into it (yet), but Behavior Driven Development might help with that problem.</p>


问:
What would be the Impact of P=NP?
I am preparing for a test and I can't find a clear answer on the question: What would be the impact of proving that PTIME=NPTIME. I checked wikipedia and it just mentioned that it would have "profound impact on maths,AI,algorithms.." etc.

Anyone can give me an answer?

答:
The impact of proving P=NP would include renewed interest in finding a reduction algorithm.  People would also try to find some lower bounds on the constants associated with the reduction algorithm.

Proving P=NP would not be as significant as other answers claim, because it could come in the form of a zero knowledge proof.  Knowing P=NP without knowing the reduction algorithm would be little different than the present situation.

Imagine if someone proved that the reduction algorithm existed but is O(sqrt(n)+2^4096).

Title: What would be the Impact of P=NP?


问:
Why aren't there other programming languages that compile to Python bytecode?
In Java, there are multiple languages that compile to Java bytecode and can run on the JVM -- Clojure, Groovy, and Scala being the main ones I can remember off the top of my head.

However, Python also turns into bytecode (.pyc files) before being run by the Python interpreter.  I might just be ignorant, but why aren't there any other programming languages that compile to python bytecode?

Is it just because nobody bothered to, or is there some kind of inherent restriction or barrier in place that makes doing so difficult?

答:
I say that Mason Wheeler is right. It's mostly an issue with the Global Interpreter Lock which makes concurrency a very thorny issue. Since there are other VMs that do concurrency really really well comparatively it makes sense to develop languages for those. Also Python has had a major language shift recently and many of the libraries have not caught up making compatibility a mild nightmare at times. For instance because I use PIL for vision work, I have to code in Python 2.7 or lower. This is not the case with the JVM or CLI setups which particularly in the latter's case were designed with language interop in mind.

Did some more research and apparently there are actually two GILs not just the one. The other controls Imports.


问:
Build functionality around the design, or the other way around?
When you build an application, is it better to design the UI first (in Photoshop or whatever), then implement the functionality following the UI you just designed, or do the programming and build the design as you go?

Advantages I see using UI as reference:

the app will end up very UI-friendly :)

like pdr mentioned, if working for a client, he gets exactly what he imagined

Disadvantages:

the programming will get more complicated, so development time increases

any others? :D

答:
Generally, you want to work with the users, in order to make sure you're building something they will find useful.  This is the best way to build applications that support the users' existing workflow.

On the other hand, simply supporting existing workflows may miss an opportunity to build a category-breaking killer app:  computer support can sometimes enable an entirely different workflow.  This is a higher-risk option (if it is available at all), but it may occasionally pay off big.

As far as functionality is concerned:  after thoroughly understanding the users' requirements, you need to make sure the core functionality actually does what they need.  Then (ideally) you should make sure the UI properly reflects this core functionality, so that a user can understand what actions he is performing.  Doing this while also supporting workflows as mentioned above (whether traditional or novel) can be nontrivial.

In any case, start with your users.  The more you understand the user's needs, the more likely you will be to produce usable software.