问:
When am I ready to start using Jquery for Javascript?
I was told not to use Jquery as a beginner because it would hamper my learning of Javascript.  Now I've read a couple books on Javascript, read loads of sites, and made a Javascript web app.  Am I ready for Jquery? If not, then how will I know when I'm ready?</p>

答:
Wow, I know this may go against some people's ideas about crawling then walking and then running.  But Javascript is not some awesome language you need to totally understand and then you'll be a whizbang programmer.

Just use JQuery and have fun.  Use it wiseley, use it cleverly!

I did my company's website 3 years ago with just Javascript and replaced nearly everything I did with JQuery over the last year.

Knowing every last IE6 browser quirk is not going to help in the long run, so just go for it man!

OwnerDisplayName: Cornucopia

LastEditorDisplayName: Cornucopia


问:
What copyright date for an update to an open-source project from last year?
In 2011, I released some open-source code that was licensed using the Apache license. As such, all the source files have this boiler plate message at the top:

```<code>/*
   Copyright 2011 My Name

   Licensed under the Apache License... <blah blah>
*/
</code>```

So now it's 2012, and I am readying to release a version 1.1. As such, most all of the source files have been touched in some way. And some new source code files have been added.

How do I update the copyright date on the existing files?  Is the following the correct update to each source file? (i.e. change 2011 to "2011-2012")

```<code>/*
   Copyright 2011-2012 My Name

   Licensed under the Apache License... <blah blah>
*/
</code>```

Do the new source files get Copyright 2011-2012 applied equally as well? Or does the new code just get Copyright 2012?

答:
Understand that copyright does expire - leaving aside complicated rules suffice to say that the year of copyright defines when the knowledge becomes public domain.

If you have a source file created in 2006 containing package that is evolving for say another 5 years. Now if you had a file that has remained unchanged since 2006 on a package that got release in 2012- you have a choice to put either date as a copyright date.

I guess there is no such thing as Copyright 2011-2012  there needs to be only one integer for year in the copyright.

However, note that copyright grants a very long duration (essentially lifetime of the author, plus a number of years after death) so this is not quite worrying!

ContentLicense: CC BY-SA 3.0


问:
Omitting inheritance in programming languages
I am developing my own programming language. It's a general purpose language (think staticlly typed Python for the desktop, i.e. int x = 1; ) not intended for the cloud.

Do you think it's okay not to allow inheritance or Mixins? (given that the user would at least have interfaces)

For example:
Google Go, A systems language that shocked the programming community by not allowing inheritance.

答:
Do you think it's okay not to allow inheritance or Mixins? (given that the user would at least have interfaces)

You can do a lot of very useful work without implementation inheritance or mixins, but I wonder whether you should have some kind of interface inheritance, i.e., a declaration that says if an object implements interface A then it also needs to interface B (i.e., A is a specialization of B and so there is a type relationship). On the other hand, your resulting object need only record that it implements both interfaces, so there's not too much complexity there. All perfectly doable.

The lack of implementation inheritance has one clear downside though: you will be unable to construct numeric-indexed vtables for your classes and so will have to do hash lookups for every method call (or figure out a clever way to avoid them). This could be painful if you're routing even fundamental values (e.g., numbers) through this mechanism. Even a very good hash implementation can be expensive when you hit it multiple times in every inner loop!


问:
Is there another name for Sql Azure's programming language?
According to this page on MSDN the sql language used on Sql Azure is called transact-sql (the same as on sql server).  But is this the only way to refer to programming on Sql Azure?

The Sql Azure variant of transact-sql doesn't support a bunch of features including global temporary tables, distributed queries and system tables; and has partial support for other areas.

So is calling it transact-sql appropriate and does anyone know if another name has taken unofficial hold (azure-sql, a-sql ...)?

答: As far as i know, is also called transact-sql. Is the same language, just with different features. But i also think they should give a different name like transact-azure or something like that. ;)</p>


答:
In the hyphenated form, the first date and the second date serve different purposes.

The first date serves to indicate when the earliest material in the file was authored. Implicitly you're saying that any material in this file that was authored prior to that date is not part of what you are claiming copyright to. For example, if I take a file from you in 2006 and I start adding to it, my "Copyright 2006-8" indicates that anything in versions prior to 2006 wasn't covered by this notice.

The last date serves to indicate the latest copyright date for any material in the file. So if the copyright is held by a corporation, 99 years from then the corporation's claim on the content would have expired.

However, it basically doesn't matter because copyright notices are not required anyway. You have copyright whether or not the notice is there. And even when there is such a notice, it's understood that there may be material covered by copyright that's not covered by the notice. (If you don't put a copyright notice in a file and I modify it, I may add a copyright notice that only covers my work. Yours is still there though.)

Basically: If you make significant changes, adding new protected expression authored either before the earliest year or after the latest year in the notice, bump the corresponding year.

Title: What copyright date for an update to an open-source project from last year?

Body:
In 2011, I released some open-source code that was licensed using the Apache license. As such, all the source files have this boiler plate message at the top:

```<code>/*
   Copyright 2011 My Name

   Licensed under the Apache License... <blah blah>
*/
</code>```

So now it's 2012, and I am readying to release a version 1.1. As such, most all of the source files have been touched in some way. And some new source code files have been added.

How do I update the copyright date on the existing files?  Is the following the correct update to each source file? (i.e. change 2011 to "2011-2012")

```<code>/*
   Copyright 2011-2012 My Name

   Licensed under the Apache License... <blah blah>
*/
</code>```

Do the new source files get Copyright 2011-2012 applied equally as well? Or does the new code just get Copyright 2012?


答:
In fact, we find more and more that using inheritance is sub-optimal because (among others) it leads to tight coupling.

Implementation inheritance can always be replaced by interface inheritance plus composition, and more modern software designs tend to go into the direction of using inheritance less and less, in favour of composition.

So yes, not providing inheritance in particular is a completely valid, and very in vogue design decision.

Mixins, on the other hand, aren’t even (yet) a mainstream language feature, and languages that do provide a feature called “mixin” often understand very different things by it. Feel free to provide it, or not. Personally I find it very useful but implementing it right may be very hard.

Title: Omitting inheritance in programming languages

Body:
I am developing my own programming language. It's a general purpose language (think staticlly typed Python for the desktop, i.e. int x = 1; ) not intended for the cloud.

Do you think it's okay not to allow inheritance or Mixins? (given that the user would at least have interfaces)

For example:
Google Go, A systems language that shocked the programming community by not allowing inheritance.


问:
Why is it optimal to schedule shorter jobs first on a uniprocessor?
On a uniprocessor, it is apparently optimal to schedule jobs that take less time first assuming non-preemptive scheduling - once a job runs, it must finish. Why?

I am confused about how the ordering would change the overall latency. Since a uniprocessor can only take on a single process at a time, wouldn't the latency be the same regardless of order?

答:
The measure of how good scheduler is would be average/total wait.

Assume you have a set of jobs J, within these you have job x which is the longest. Let y be any other job.

If you put x last, total wait time of the jobs executed before will be total(J)-time(x), while for any other it'll be total(J)-time(y). Thus only putting the longest job last minimizes wait time. Then you repeat that for set of remaining jobs J-{x}, and so on recursively, always putting longest one last. End result is, that you have them ordered from shortest to longest.


问:
A simple ways to improve the release quality in RAD environment
A bit of a background here - we are a small team (of 5) of RAD developers responsible for internal software development in a big non-software company. "Internal software" varies from a desktop .NET application using MSSQL server as a backend to Python scripts running on the background  to MS Word documents and templates - a zoo of technologies.

The whole team consist of all-arounders able to get the requirements from users, code it up, test it and deploy into production. Once the software in the production it is being looked after by another team but it usually easy for us to intervene if something goes wrong.

All sounds good so far, but there is a problem - being a RAD team we have to release often, and there is no day going by without us releasing new versions of one or two applications(or it could be a script, updated word document, C++ console app, etc) into the production. We do a development testing and also do involve end-users by letting them run the software in UAT environment ...

... but the bugs are creeping in to production anyway. Users do understand that these bugs and the occasional instability is the price they are paying for getting what they want really quickly, but at the same time it got us thinking - perhaps we could improve our development or a release practices to improve the stability of the software and reduce the number of bugs we introduce when adding a new functionality.

The good thing - we don't really have much of the processes in the first place, so it should be easy to start improving, the bad thing - being a small RAD team we don't really have the much time and resources to implement something big, but we have been thinking about the following initiatives and would welcome any feedback, tips, hints and suggestions.

Currently some of the applications are being released into the production straight after the developer testing, bypassing the user acceptance testing. That practice should be discontinued and even a small change has to be tested by a end-user. Each application will have a dedicated beta-tester selected from the end-users. Only after a beta-tester has ok-ed the new release it is promoted from test to production environment.

We don't conduct code reviews - but we'll start doing code reviews before one of us checkin the changeset. I was also thinking about a "rollout review" - basically one of the developers has to sit next with the other watch him/her doing the software rollout (copy binaries, update configs, add new table to database, etc) - it usually only takes a 5-10 minutes so it won't take much of a "rollout review" time.

How to miminise the rollback time when a new release is proven to be buggy enough to be pullout from production and to be replaced by a good previous version. We do store a history of all releases (as a binaries) to make it easy to go one version back - and though it is quick "overwrite a newly released binaries with a previous versions binaries" it is still a manual process which is error prone and demanding at times "what if the rollback will fail and will render the system unusable instead of buggy".

This is where we ran out of our ideas and we'd like to get your feedback on these and if you could share some simple release / dev process improvement advices - that would be awesome.

答:
As others have pointed out, adding regression testing will help to avoid the same defects appearing in the future. However, if you're encountering new defects, then it may be time to add assertions (a.k.a. contracts) to the code that specify the pre-conditions, post-conditions, and invariants of the classes and methods.

For example, if you have a class where a method can only accept numbers between 10 and 25 (this is called the pre-condition), you would add an assert statement at the beginning of the method. When this assertion fails, the program will crash immediately and you'll be able to follow the chain of methods that led to that failure.

Python, PHP and other programming languages are dynamically typed and don't add many conditions to methods. All that's needed for something to work is that it implements a particular method. I suspect that you need more conditions on your methods. You need to define and test to ensure that a method can actually work in its environment.

For C/C++ programs, I found that adding assertions to test memory allocation was very helpful in reducing the number of memory leaks in the program.


问:
When and how to use the advanced features of git?
I'm not exactly a new git user but I have never used any of its advanced features such as tags, branches, merging and others. I haven't even used anything equivalent features from other VCS software. My projects have been so simple that I have only needed commits and sometimes diffs.

Now I'm planning to open-source a server project of mine which probably will get a lot bigger and it probably needs to be organized better. Git can probably help me with that but how?

The development methods are scrum and TDD if that matters.

答:
tags, branches, merging

IMO these are basic functions of any decent VCS, not particularly advanced features of Git.

I suggest reading some of the excellent online guides such as:

http://gitimmersion.com/

http://progit.org/

http://gitready.com/

http://book.git-scm.com/


答:
since you're open sourcing a server project, you need to know the following commands

remote

push

pull

fetch

link http://gitref.org/remotes/

@Joonas' link to resources are good enough, though I added these commands since you'll need them in an open source development.

Title: When and how to use the advanced features of git?

Body:
I'm not exactly a new git user but I have never used any of its advanced features such as tags, branches, merging and others. I haven't even used anything equivalent features from other VCS software. My projects have been so simple that I have only needed commits and sometimes diffs.

Now I'm planning to open-source a server project of mine which probably will get a lot bigger and it probably needs to be organized better. Git can probably help me with that but how?

The development methods are scrum and TDD if that matters.


问:
How much Code Coverage is "enough"?
We are starting a push for code coverage here at my work, and it has got me to thinking.... How much code coverage is enough?

When do you get to the point of diminishing returns on code coverage?  What is the sweet spot between good coverage and not enough?  Does it vary by the type of project your are making (ie WPF, WCF, Mobile, ASP.NET)  (These are C# classes we are writing.)

答:
Coverage is a metric to keep an eye on, but it shouldn't be the ultimate goal. I've seen (and admittedly written!) plenty of high coverage code - 100% coverage (TDD, of course), yet:

bugs still come up

design can still be poor

you can really kill yourself shooting for some arbitrary coverage target - pick your battles :p

There's a "The Way of Testivus" entry that I think is appropriate to reference here :)

ContentLicense: CC BY-SA 2.5

Title: How much Code Coverage is "enough"?


问:
How can I convert PPT files to PNG in PHP without COM?
I need to convert Powerpoint files to PNG in PHP. I can do the conversion with using COM in PHP but COM is only supported on Windows. I need to do this for both Windows and Linux.

I am wondering if someone give me hints about that conversion.

答:
I can think of two solutions, a creative one and one that won't work (yet).

The creative one is to convert Powerpoint files to something a bit more Linux friendly, by calling OpenOffice's converters via the command line. And then convert to PNG. Creative, to say the least, and of course it requires that you can install OpenOffice on your server.

The other solution is the PHPPowerPoint library, currently in alpha. It only works with Microsoft's OpenXML format, and it's of a similar lineage as PHPExcel and PHPWord. I'm pretty sure that it doesn't utilize COM, but since it's still alpha and very recent it most probably won't do exactly what you want. But you can always build upon it.

Both approaches are highly problematic. But so is Powerpoint, so I guess you expected that when you asked.


问:
Are there any opensource APIs that help analyze code?
As an example, let's say that I need to check for a certain usage of C# code and warn the user that that is a bad pratice. There are multiple usages that I want to detect, such as:

Resource not being released by developer (in a heavy COM environment)

Instance should be created using Activator instead of new (I don't have control of the API I'm analyzing)

Others

The implementation of the API can be in any language, but I'll be mostly analyzing c# and vb.net.

Suitable languages:

C#

Python

Other

答:
No need to reinvent wheel. StyleCop already does this.

It also allows for user rules via extension API. For example detecting the Activator usage should be rather easy thing to do (however detecting legitimate usage of Activator may be very non-trivial task, but that would apply to any code analysis solution).

There is also ReSharper which (in addition to being extensible on its own in a similar way) can integrate StyleCop directly into Visual Studio, so the analysis can be done as the programmer types the code without having to manually launch a separate tool to check the conventions.

StyleCop can of course also be launched on its own via GUI or from command line (so integration into whatever build system/CI you are using is possible).


答:
In addition to the basic useful commands others have mentioned, I'll mention some others, perhaps a little less well-known git commands:

```<code>git commit --amend
</code>```

Allows you to change the very last commit in your history. Use it if you for instance want to add additional fixes to the previously made commit.

```<code>git cherry-pick commit_id
</code>```

You can grab just a specific changeset and apply it to your history; no need to merge the entire branch.

```<code>git reflog
</code>```

Reflog is a mechanism to record when the tip of branches are updated. In other words this can be extremely useful to use when you want to for instance rollback to a specific state through the use of e.g. git reset --hard commit_id .

```<code>git stash
</code>```

Not ready to commit yet but need to change gears and make a quick change for someone else? Save your working copy in a temporary place, and then use git stash pop to get it back.

```<code>git pull --rebase
</code>```

This command will save any commits you might have in a temporary place, grab any new ones you might be missing from your tracking branch and stick yours back on the end. Keep the history clean and say goodbye to those merge commits.

Body:
In addition to the basic useful commands others have mentioned, I'll mention some others, perhaps a little less well-known git commands:

git commit --amend

Allows you to change the very last commit in your history. Use it if you for instance want to add additional fixes to the previously made commit.

git cherry-pick commit_id

You can grab just a specific changeset and apply it to your history; no need to merge the entire branch.

git reflog

Reflog is a mechanism to record when the tip of branches are updated. In other words this can be extremely useful to use when you want to for instance rollback to a specific state through the use of e.g. git reset --hard commit_id .

git stash

Not ready to commit yet but need to change gears and make a quick change for someone else? Save your working copy in a temporary place, and then use git stash pop to get it back.

git pull --rebase

This command will save any commits you might have in a temporary place, grab any new ones you might be missing from your tracking branch and stick yours back on the end. Keep the history clean and say goodbye to those merge commits.


答:
Matěj Zábský's answer might be what you are looking for, but to answer your actual question you might take a look at the new Microsoft Roslyn project. It's a public API which allows analysis of C# code.

More importantly, we are opening up the C# and Visual Basic compilers
and exposing all that rich information and code analysis to be
available for your use. We expose a public API surface and provide
extension points in the C# and VB language services.

This opens up new opportunities for VS extenders to write powerful
refactorings and language analysis tools, as well as allow anyone to
incorporate our parsers, semantic engines, code generators and
scripting in their own applications.

Title: Are there any opensource APIs that help analyze code?

Body:
As an example, let's say that I need to check for a certain usage of C# code and warn the user that that is a bad pratice. There are multiple usages that I want to detect, such as:

Resource not being released by developer (in a heavy COM environment)

Instance should be created using Activator instead of new (I don't have control of the API I'm analyzing)

Others

The implementation of the API can be in any language, but I'll be mostly analyzing c# and vb.net.

Suitable languages:

C#

Python

Other

ContentLicense: CC BY-SA 4.0


答:
Learn the core first:

If you take the time to understand how git works, then you will be able to easily understand all of the advanced things you can do with it.  But let me emphasis: if you do not learn the core structure of git, all of the advanced things will be "black boxish" and confusing for a long time.

A brief explanation:

At the core of git is a database of objects.  For the purpose of this discussion, I will describe the three most fundamental objects in git:

blob: Just data.  The contents of a file, for example.  The ID of the blob is generated using the SHA1() hash of the content.  In this way, if any of the content of the file changes, a new blob object will be created.

tree: Just a list of blobs and trees.  A tree is used to reference other blobs and trees, effectively creating a directory structure.  The ID of the tree is generated using the SHA1() of the IDs that it refers to (roughly).  In this way, if any of the blob IDs or tree IDs referenced change, then a whole new tree object is created.

commit: A commit contains a date, who, tree ID, commit message, comment, parent commit IDs, and maybe some other misc. info.  The ID of the commit is generated by the SHA1() hash of its content.  Therefore, if the exact same commit was made at a different time of day, it would actually be a different commit.

So a commit object points to a tree which points to other trees and blobs.  That way, from a given commit, you can tell exactly what files were present, in what directories, and the exact content of the files.

People call git a version control system, and while it can do that, it is better to think of it as a snapshot management system.  Git is really good at knowing, at each commit, what the contents of the repository were.

In fact, the only thing that creates a "history" is the fact that each git commit embeds what it's parent commit(s) were.  In reality, git couldn't care less, but from a human perspective, this is really important to be able to know how the software evolved over time.  It also forms the basis for a lot of features in git.

Understanding that a git commit ID is ultimately based on the contents of the entire repository at that point in time, then it also makes sense that the commit ID is not changeable (eg, immutable).  Furthermore, the entire history is immutable as well, because a given commit ID is ALSO based on the Parent Commit ID, and so on and so forth.

This embodies the best of two worlds... One is the ability to know that your history has never been messed with, and cannot have been.  The other is to know that you can rewrite history seamlessly with git, but you will get a new set of Commit IDs, etc...

Branches: In git, branches are very lightweight.  In fact, if you look in .git/refs/heads/master, you will likely find a 41 byte file which refers simply to a commit ID.  Strange?  No... Just a human friendly reference to a given point in time in the repository.  Rather like using a domain name instead of an IP address.

When you switch branches, git simply looks up the commit ID for the new branch, looks at the tree ID embedded in that commit, and goes through the actual working copy -- adding/removing/updating the files on disk until it matches everything specified by the tree and sub-trees and blobs, which were ultimately referenced by that new branch.

For example:

```<code>Branch 444 -> Commit 323 -> Tree 232 -> Subtree 343 -> Blob 454 -> File code.php
</code>```

git commit --amend: If you make a mistake and commit your work, but wish to replace that commit, then you can use this command to replace that commit with a new one.  But keep in mind, that the old one still exists.  It has a different ID, and a different content, but it is still "hanging" around in your database (git reflog).  These dangling objects are cleaned up from time to time with garbage collection.

I hope this helps give you a firm direction on the core of git.  It will take some time and playing and research to really understand the guts of it, but if you do that, the rest will be really easy.

Body:
Learn the core first:

If you take the time to understand how git works, then you will be able to easily understand all of the advanced things you can do with it.  But let me emphasis: if you do not learn the core structure of git, all of the advanced things will be "black boxish" and confusing for a long time.

A brief explanation:

At the core of git is a database of objects.  For the purpose of this discussion, I will describe the three most fundamental objects in git:

blob: Just data.  The contents of a file, for example.  The ID of the blob is generated using the SHA1() hash of the content.  In this way, if any of the content of the file changes, a new blob object will be created.

tree: Just a list of blobs and trees.  A tree is used to reference other blobs and trees, effectively creating a directory structure.  The ID of the tree is generated using the SHA1() of the IDs that it refers to (roughly).  In this way, if any of the blob IDs or tree IDs referenced change, then a whole new tree object is created.

commit: A commit contains a date, who, tree ID, commit message, comment, parent commit IDs, and maybe some other misc. info.  The ID of the commit is generated by the SHA1() hash of its content.  Therefore, if the exact same commit was made at a different time of day, it would actually be a different commit.

So a commit object points to a tree which points to other trees and blobs.  That way, from a given commit, you can tell exactly what files were present, in what directories, and the exact content of the files.

People call git a version control system, and while it can do that, it is better to think of it as a snapshot management system.  Git is really good at knowing, at each commit, what the contents of the repository were.

In fact, the only thing that creates a "history" is the fact that each git commit embeds what it's parent commit(s) were.  In reality, git couldn't care less, but from a human perspective, this is really important to be able to know how the software evolved over time.  It also forms the basis for a lot of features in git.

Understanding that a git commit ID is ultimately based on the contents of the entire repository at that point in time, then it also makes sense that the commit ID is not changeable (eg, immutable).  Furthermore, the entire history is immutable as well, because a given commit ID is ALSO based on the Parent Commit ID, and so on and so forth.

This embodies the best of two worlds... One is the ability to know that your history has never been messed with, and cannot have been.  The other is to know that you can rewrite history seamlessly with git, but you will get a new set of Commit IDs, etc...

Branches: In git, branches are very lightweight.  In fact, if you look in .git/refs/heads/master, you will likely find a 41 byte file which refers simply to a commit ID.  Strange?  No... Just a human friendly reference to a given point in time in the repository.  Rather like using a domain name instead of an IP address.

When you switch branches, git simply looks up the commit ID for the new branch, looks at the tree ID embedded in that commit, and goes through the actual working copy -- adding/removing/updating the files on disk until it matches everything specified by the tree and sub-trees and blobs, which were ultimately referenced by that new branch.

For example:

Branch 444 -> Commit 323 -> Tree 232 -> Subtree 343 -> Blob 454 -> File code.php

git commit --amend: If you make a mistake and commit your work, but wish to replace that commit, then you can use this command to replace that commit with a new one.  But keep in mind, that the old one still exists.  It has a different ID, and a different content, but it is still "hanging" around in your database (git reflog).  These dangling objects are cleaned up from time to time with garbage collection.

I hope this helps give you a firm direction on the core of git.  It will take some time and playing and research to really understand the guts of it, but if you do that, the rest will be really easy.


问:
Is there a general method to evaluate the optimality of an optimization algorithm?
is there a general method to evaluate the optimality of an optimization algorithm, for example an algorithm solving an otherwise NP-hard or NP-complete problem?

The only method I came up so far is comparing the results of the algorithm against already known optimal solutions.

If not, are there specific methods for some special problems?

EDIT To clarify: By optimality I mean how close the result is to an optimal solutions result.

答:
The problem of determining whether a program has 'optimality performance' A or 'optimality performance' B for just about any definition of 'optimality performance' is undecidable in general (proof below). This implies that there is no single method that can always tell you how optimal an algorithm is.

There are however methods that are often applied when analyzing approximation algorithms. Often, approximation algorithms are evaluated by their guarantees on how far its solution is from the optimal solution. I'll give an example problem and approximation, which I will prove using the 'lower bound' method, which is a very commonly used method to prove ratios.

The problem in question is the 'Truck Loading' problem: we have a lot of identical trucks (as many as we like), each capable of carrying a load weighing at most T. We have n objects we wish to load in these trucks for transport. Every object i has a weight w_i, where w_i <= T (so there are no items that can't fit on a truck even by themselves). Items cannot be divided into parts. We'd like to fill up trucks so that we need as few trucks as possible. This problem is NP-complete.

There is a very easy approximation algorithm for this problem. We simply start loading a truck with items, until the truck is so full that the next item won't fit. We then take another truck and load this truck with this item that didn't fit on the previous truck. We don't load any more items on this truck: instead, we take a new truck, we fill it with lots of items again until it no longer fits, put that last item on its own truck again and so forth.

This algorithm is a so-called 2-approximation for the problem: it uses at most twice as many trucks as the optimal solution would need. The 'at most' is crucial: we might be lucky and find the optimal solution, but at least we won't do too bad.

To prove this, we first define a lower bound on the optimal number of trucks we need. For this, imagine that we are allowed to cut items into parts: we could then easily fill every truck but the last one completely. The number of trucks we'd need if we did that is a lower bound for the number of trucks we need for the original question: in the 'best' case the optimal solution always fills every truck completely, in which case the number of trucks is equal, but if the optimal solutions leaves trucks unfilled, then it can only need more trucks.

Now we look at our approximation algorithm. Note that in every step, we (partially) fill up two trucks. Also note that by how the algorithm works, the items in the first truck and the item in the second truck together cannot fit in the first truck, so their sum is at least T. This means that every step, we load at least a full truck worth of items on two trucks. Now compare this to our lower bound: in that case, we load a full truck worth of items on one truck. In other words, our approximation algorithm computes (in linear time) a solution that looks very much like our lower bound 'solution', but uses two trucks instead of one. Hence, we use at most twice as many trucks as the optimal algorithm, because we use at most twice as many trucks as our lower bound on the optimal algorithm.

This algorithm gives a constant-factor approximation: it is at most 2 times as bad as the optimal solution. Some examples of other measures: at most C more than the optimal solution (additive error, quite uncommon), at most c log n times as bad as the optimal solution, at most c n times as bad as the optimal solution, at most c 2 ^ (d n) times as bad as the optimal solution (very bad; for instance, general TSP only admits algorithms with this kind of guarantees).

Of course, if you want to be sure that the factor you prove is the best factor you can prove, you should try to find instances in which the solution your algorithm gives is indeed as bad as it possibly can be.

Also note that we sometimes use approximation algorithms on problems that are not NP-hard.

I learned this (among a lot more) in the approximation algorithms course at my university.

Undecidability proof: let P be a problem and A and B be approximation algorithms for P where A and B do not have the same 'optimality' for some sensible definition of 'optimality', and where the running time of A and B is both omega(1) (strictly slower than constant time, ie, they become slower for larger instances) and where A and B both always halt.

Let D be a program that claims that it can compute the following: given some program C computing an approximation for P, decide whether it is as good as A or as good as B for sufficiently large inputs (you can therefore use this to categorize programs according to their optimality).

We can then use D to solve the halting problem. Let E be a program and F be an input for this program. We will use D to decide whether E will halt on input F.

We design a program G that does the following: given an input S for problem P, it runs E on F and A on S in parallel: it executes E for a while, then A, then E again and so forth. If E halts on F, it stops running A and instead runs B on S and returns B's result. If A halts before E halts, it returns A's result.

Using D on G now decides whether E halts on F: if E halts on F, then for sufficiently large inputs S, E halts on F before A halts on S (because the time it takes E to halt does not depend on the size of the input, unlike A). D therefore reports that G has the optimality characteristics of B. If E doesn't halt on F, D will report that G has the optimality characteristics of A.


问:
What to call pure JavaScript standalone (web)apps for which I've not written any server side code?
I've been writing a few tools as standalone webapps for which I have written no server side code and it strikes me that I'm not sure what people call such things.

I like them because they can be distributed as a single file that anybody with a web browser can run. Typically all the funky stuff is done by calling AJAX web APIs like those provided by Stack Exchange, MediaWiki, Google, etc.

The following terms all seem plausible but might also cover other things or not tell the whole story:

client-only

pure JavaScript

standalone webapp

web script

web tool

browser app

Is one of these terms or something else in common use for such apps / tools?

Here's links to some of my little tools on GitHub: travel-se-airport-tags.html, travel-se-1-or-2-answers.html, travel-se-stats.html

There are some much more app-ish examples in the 10k Challenge...

答:
Google makes a distinction between two types of Installable Web Apps available in the Chrome Web Store:

Many installable web apps are hosted apps—normal websites with a bit of extra metadata. You can build and deploy hosted apps exactly as you would build and deploy any web app, using any server-side or client-side technologies you like. The only difference is that you must provide a small manifest file that describes the app.

If you want your app to work especially well offline or to be tightly integrated with the Google Chrome browser, you can create a packaged app. A packaged app is just a web app that the user downloads. Packaged apps have the option of using the Google Chrome Extension APIs, allowing packaged apps to change the way Chrome behaves or looks.

For the apps you linked on Github, however, I think the term I generally hear in circulation is "in-browser app(lication)".

I like the distinction because "browser app" could refer to a web browser itself, as opposed to an application that runs inside of one.

I think it's important to note that the distinction between 'in-browser' and 'standalone' or 'desktop' apps will likely be diminishing to the point of irrelevance in coming years; it's possible to create mobile apps with little more than HTML5, CSS3, and JavaScript today, and Windows 8 is (supposedly) moving to HTML5 as the preferred platform for 'native' apps.


答:
There's a contradiction,

"webapps that have no server side code", "the funky stuff is done by calling AJAX web APIs"

These applications are still web apps, you've just not written the server side code.

EDIT

I've updated your question, to my knowledge there isn't a broadly understood term for an application that consumes solely public APIs.  I won't suggest another competing term.

Title: What to call pure JavaScript standalone (web)apps for which I've not written any server side code?

Body:
I've been writing a few tools as standalone webapps for which I have written no server side code and it strikes me that I'm not sure what people call such things.

I like them because they can be distributed as a single file that anybody with a web browser can run. Typically all the funky stuff is done by calling AJAX web APIs like those provided by Stack Exchange, MediaWiki, Google, etc.

The following terms all seem plausible but might also cover other things or not tell the whole story:

client-only

pure JavaScript

standalone webapp

web script

web tool

browser app

Is one of these terms or something else in common use for such apps / tools?

Here's links to some of my little tools on GitHub: travel-se-airport-tags.html, travel-se-1-or-2-answers.html, travel-se-stats.html

There are some much more app-ish examples in the 10k Challenge...


问:
How can I sell a legacy program rewrite to the business?
We have a legacy classic ASP application that's been around since 2001.  It badly needs to be re-written, but it's working fine from an end user perspective.

The reason I feel like a rewrite is necessary is that when we need to update it (which is admittedly not that often) then it takes forever to go through all the spaghetti code and fix problems.  Also, adding new features is also a pain since it was architect-ed and coded badly.

I've run cost analysis for them on maintenance but they are willing to spend more for the small maintenance jobs than a rewrite.  Any suggestions on convincing them otherwise?

答:
If at all possible do what you can to make the application better as it is right now.

If you are dissatisfied about the documentation, then after you have spent time figuring things out WRITE THEM DOWN for the next maintainence session.  Frequently when you see a code base for the first time, just a short lists of "therefores" (to answer the whys the code cannot) can help immensely understanding what goes on.

Improve incrementally!


问:
Prerequisites for developing an application with Unicode support
What could be the necessary prerequisites to be taken when developing an application with Unicode support in the context of

Web applications

Desktop applications

Embedded applications

Prerequisites to be taken care of relating to

Type casting and conversion

Data Storage

Fallback in case of no Unicode support

Transition from a database without Unicode support to a database with Unicode support

Answers pertaining to real-world projects are preferred

答:
Python already works in Unicode.

Type casting and conversion.

Doesn't mean much.  If you mean decoding bytes to find Unicode characters or encoding Unicode characters into bytes, then this is present in the language, libraries, etc.

Data Storage

Is generally bytes.  Therefore, the IO libraries encode to write and decode to read.  They default to OS settings, but you can override them.

Fallback in case of no Unicode support

It's not clear what this can even mean.

Transition from a database without Unicode support to a database with Unicode support

This is a one-time translation from ASCII data to Unicode.  Some RDBMS's have tools for this.  Other RDBMS's require you to export the data, change the schema (or DB settings) and reimport the data.


问:
Easiest way to create static HTML file with sortable and filterable table?
I want to create a static HTML file I can email to someone with a lot of data, and have that data sortable and filterable.  What is the easiest to use library or package I can use to get this off the ground?</p>

答:
Check this one at Matt Kruse's Javascript Toolbox.

Also you can find DHX DHTMLX very useful.


答:
You can't. You need one of three things to change HTML structure semantically

JavaScript, event handlers and dom manipulation

Forms, servers and postbacks to change the page and send a new one

CSS hackery, things like remodelling the CSS based on the :active state or manipulate checkboxes :checked state.

In theory it's possible to implement this with HTML and CSS alone but that's going to a be a nightmare.

Why don't you just add a link to a google document with a sortable table in it, in your email.

Of course using JavaScript to implement a sortable table isn't hard.

```<code>table.addEventListener("click", function (ev) {
  if (ev.target.tagName === "th") {
    sortTable(ev.target);
  }
});

form.addEventListener("change", function (ev) {
  applyFilters(ev);
});
</code>```

Just implement sortTable and applyFilters

Title: Easiest way to create static HTML file with sortable and filterable table?

Body: I want to create a static HTML file I can email to someone with a lot of data, and have that data sortable and filterable.  What is the easiest to use library or package I can use to get this off the ground?</p>

Body:
You can't. You need one of three things to change HTML structure semantically

JavaScript, event handlers and dom manipulation

Forms, servers and postbacks to change the page and send a new one

CSS hackery, things like remodelling the CSS based on the :active state or manipulate checkboxes :checked state.

In theory it's possible to implement this with HTML and CSS alone but that's going to a be a nightmare.

Why don't you just add a link to a google document with a sortable table in it, in your email.

Of course using JavaScript to implement a sortable table isn't hard.

table.addEventListener("click", function (ev) {
  if (ev.target.tagName === "th") {
    sortTable(ev.target);
  }
});

form.addEventListener("change", function (ev) {
  applyFilters(ev);
});

Just implement sortTable and applyFilters


答: Use XML not HTML, XML is meant to hold data, HTML is meant to create a webpage. Using XML also allows you to use XSLT to manipulate the stored data. Though depending on your definition of large amount of data it may be best to allow access to a database with the information, or import the information to database on their end.</p>


答: In any recent and decent development environment, the main prerequisite is good developers. Given that, it's the non-Unicode part that's hard (is this input ISO-8859-1 or -15?).</p>

Title: Prerequisites for developing an application with Unicode support

Body:
What could be the necessary prerequisites to be taken when developing an application with Unicode support in the context of

Web applications

Desktop applications

Embedded applications

Prerequisites to be taken care of relating to

Type casting and conversion

Data Storage

Fallback in case of no Unicode support

Transition from a database without Unicode support to a database with Unicode support

Answers pertaining to real-world projects are preferred


问:
Keep it simple now, or program with the future in mind?
I'm currently coding a new application for my company that is rather involved. To meet the deadline, the functionality has been toned down quite a bit so that we can have something ready to go for launch.

I've been given the task of getting version 1 up and running by the end of the month. I'm about halfway through development and I've come to the point now that there is an end in sight.

Yesterday, I spent some time coming up with a very nice easy solution for one of the requirements and am quite proud of how it turned out. This morning the version 2 document was sent out, and there is a requirement in there that will require the code I wrote yesterday to be either gutted, or severely changed. It would require a lot of work in the future if I leave it the way it is. I can take an extra day now to make my current solution more robust so that the v2 feature will be able to be added with a lot less effort, but that will put me a bit behind for the extra coding it would require.

I don't know if I'll be doing v2. It might be me or it might be a co-worker, or even an intern.

If you were in my shoes, would you spend the time now to make it easier in the future, or would you leave your solution and deal with it when the time comes?

答:
If the deadline is Carved In Stone, just finish what you have to meet it. Make sure that you inflate the estimates for v2 to accomodate for the code changes for the new requirement. Also be sure to briefly document what you think will need to change for the new v2 features so that a co-worker can pick it up if you're reassigned to something else.

If there's enough flexibility in the deadline (1 day, by the sound of it, so aim for 2.5 days extension) then sure, go ahead and code for the known future!


问:
How should I extend an existing Service?
Our system's main functionality is encapsulated in a service, let's call it X.

There are requests coming in to X-Manager service which deal with all validations and security issues, and activates X's functionality after everything passed.

We now want to extend X's functionality with a new module, let's call it Y, but without changing X's code too much, preferably without changing it at all.

Also, Y may be able to work on it's own some day (and not only extending X)

The main idea now in the team is to make X-Manager call Y with X instead of just calling X, so that Y will do it's thing and then Y Will call X's functionality instead of X-Manager.

I don't know why but this smells icky to me, I hope I managed to explain this well...

Is there any better way of doing this?

答: What you propose is a simple composition and there is absolutely nothing wrong with it. Even less since the X-Manager acts as a facade abstracting this subdivision away for the outside world. In short: this is the perfect way to do it ;)</p>


答:
Leave as it as it is.

Developers actually APPRECIATE a legacy project that does what it is supposed to do and no more.

What, today, may seem like a good idea for "staging" the codebase to meet a "future" requirement, will in all likelihood act as an obstacle to understanding the code in the future. No one likes to deal with partially implemented functionality and vestiges of forgotten phantom requirements. I'm not saying that will be the case, but things often turn out that way despite the best intentions.

Title: Keep it simple now, or program with the future in mind?

Body:
I'm currently coding a new application for my company that is rather involved. To meet the deadline, the functionality has been toned down quite a bit so that we can have something ready to go for launch.

I've been given the task of getting version 1 up and running by the end of the month. I'm about halfway through development and I've come to the point now that there is an end in sight.

Yesterday, I spent some time coming up with a very nice easy solution for one of the requirements and am quite proud of how it turned out. This morning the version 2 document was sent out, and there is a requirement in there that will require the code I wrote yesterday to be either gutted, or severely changed. It would require a lot of work in the future if I leave it the way it is. I can take an extra day now to make my current solution more robust so that the v2 feature will be able to be added with a lot less effort, but that will put me a bit behind for the extra coding it would require.

I don't know if I'll be doing v2. It might be me or it might be a co-worker, or even an intern.

If you were in my shoes, would you spend the time now to make it easier in the future, or would you leave your solution and deal with it when the time comes?


问:
In PHP, how do you code with scalability in mind?
I know this may be a general question, but what exactly goes into scaling for all the users you will encounter, even if not in the next few months? I did some research and most of what is done is server side, with caches and other similar stuff. Any points in the right direction would be helpful.</p>

答:
"Even if not in the next few months" smells like premature optimization. Don't do that:

It's not worth it. Many people, when realizing a project, believe that their project will be the second Facebook. Then they release it, and then they notice that ten visitors per month is the best they can do. Spending less money and time on optimizing for further scalability and more time thinking about the project itself would help.

It's like with bottlenecks and profiling: you always have an impression that you know perfectly well where the bottleneck is, and in most cases, you discover that you were wrong when profiling. Do your application first. See how is it used. Profile it. Gather BI data. Gather performance metrics. Analyse it. Check if your analysis was right. Make the predictions about the future, based on your analysis, then optimize for scalability what you really need to optimize.

For example, a scalable web application must be able to be hosted on several servers. The last project I've done for my customer was intended to be scalable. There was a choice: either we spend 1.5 months more in order to make the web app work on several servers, or the customer buys a high quality server (one machine only) and the web app is hosted on this machine only. It was much less expensive to buy an expensive server, counting both the direct cost (price of the server vs. price of 1.5 months of work) and the long term savings (power consumption of one high quality server vs. power consumption of several low-end servers). Now the app is running for a few months, and according to the metrics, if there would be a problem with scalability one day, it would concern in first place the database, and in second place the network infrastructure (switches, routers, etc.).

Now, an application may be more or less scalable on several points:

Database: according to my personal experience, most scalability-related problems come from the database. Hopefully, there are plenty of ways to make the database scalable for every industry-grade database engine, and even before that, there are plenty of ways to improve the database structure and to optimize the queries. Caching helps too.

Network: bandwidth can be a real issue in some configurations, and sometimes you can't do anything about it without doing expenses you can't afford. To avoid being blocked on this level, you can optimize the visual design of the website in order to have less images or better compressed images, optimize the layout of the page, reduce the HTTP requests (through CSS sprites), reduce the quantity of HTML code sent (through AJAX), etc. HTTP compression is a must-have. Browser caching too, but your metrics may show that many clients have an empty cache.

CPU and memory usage: porting an application to be hosted by several servers can be painful too, both on infrastructure (hardware) level and on application (software) level. To avoid this, use extensive caching and profile the application, removing progressively the bottlenecks.


答:
Scalability is very much language agnostic, so there is no PHP specific thing for it. Key factor is to have decoupled subsystems, communicating via language agnostic protocols (so for example if you have to call webservice from your PHP code, don't use PHP's serialize, but rather JSON, even if both components are currently both implemented in PHP). This will allow you to replace components with other alternatives, perhaps developed in other technologies.

You can find many examples of scalable architectures implemented using PHP on highscalability.com blog

Title: In PHP, how do you code with scalability in mind?

Body: I know this may be a general question, but what exactly goes into scaling for all the users you will encounter, even if not in the next few months? I did some research and most of what is done is server side, with caches and other similar stuff. Any points in the right direction would be helpful.</p>


答:
Avoid falling prey (early) to the Second System Effect.  Here are some good techniques to apply:

Definitely avoid de-railing version 1 just because of what you see coming up in version 2.  Planning ahead is fine, but the creator of the v2 specs should be responsible for the failure of v2, not v1.

(If possible) see if you can have the creator re-work the requirements for version 2 that won't require the larger changes now - and then plan for them later, maybe for v3.

Keep YAGNI in mind, but try to code for extensibility in mind - avoid magic numbers, hard-coded values, write good unit tests or code contracts, etc.  Applying good techniques early on will make refactoring and code changes less painful along the way.

Most software projects that grow like cities are successful in the long run.  Evolutionary planning only into the limited future lets your software release on-time and with the functionalities required at release - and no more.  See this excerpt from Carl Sagan:

The arrangement [of a city] might be more efficient if all civic systems were
constructed in parallel and replaced periodically (which is why
disastrous fires—the great conflagrations of London and Chicago, for
example—are sometimes an aid in city planning). But the slow accretion
of new functions permits the city to work more or less continuously
through the centuries.

Carl Sagan, Cosmos: http://www.eridanus.info/genesis.html


答:
Good answers. I would only add - what I do in a case like this is take a good diff so I can capture what I've done and squirrel it away in a safe place. Then if the opportunity comes to do it again in the next version, it will be easy.

In general, a good developer anticipates future requirements, but when a deadline is looming, it's time to respond to bugs in what you've already got and not "rock the boat".


答: Do not add code today for next month's requirement. Today you should write the cleanest code you can for the requirements you have.  I'm skeptical that a day's work now will save multiple days later.  I've heard claims like that, and can't recall a single case where it was true.  You might be able to convince me by showing some code, but my experience tells me that is unlikely.</p>


答:
Worrying about scalability now is probably not worth it: if your project takes off and hits the mark from where you cannot scale by adding more hardware, you'll have enough cash rolling in to fund more thorough measures; if it doesn't, then any effort you make now is a waste of your time and resources.

That said, there are a few things you can and should do to keep your application maintainable, and if you follow these guidelines, factoring in scalability will be much easier later on in the game. An ideal solution will allow you to swap out the entire data storage code with only minimal changes to the program logic and no changes at all to the presentation code.


答:
What you are describing sounds a little like a single page application.

A single-page application (SPA), also known as single-page interface (SPI), is a web application or web site that fits on a single web page with the goal of providing a more fluid user experience akin to a desktop application.

In an SPA, either all necessary code – HTML, JavaScript, and CSS – is retrieved with a single page load, or the appropriate resources are dynamically loaded and added to the page as necessary, usually in response to user actions. The page does not reload at any point in the process, nor does control transfer to another page, although modern web technologies (such as those included in HTML5) can provide the perception and navigability of separate logical pages in the application. Interaction with the single page application often involves dynamic communication with the web server behind the scenes...


问:
Make a big deal out of == true?
There is a colleague of mine who constantly writes:

```<code>if (someBool == true)
</code>```

It drives me up the wall!  Should I make a big deal of it or just drop it?

答:
You think that's bad? How about:</p>

```<code>if(someCondition) {
  return true;
} else {
  return false;
}
</code>```

Title: Make a big deal out of == true?

Body:
You think that's bad? How about:

if(someCondition) {
  return true;
} else {
  return false;
}


问:
What is the best/easiest way to get my degree, already being an experienced developer?
I have been an active professional software developer (mostly utilizing .NET) for the past five years and, without being too full of myself, I would say I'm a very competent developer. I stay intimately up to date with the latest tools, the industry, and modern standards/practices. I work for a fairly high-level IT company and I swing just fine with the rest of them. I am even up to date on the latest team dynamic methodologies and feel like I have good leadership/management/people skills.

However, I never got my degree. I learned and am learning everything I know on my own from hundreds of books and experiences. I ran my own software company for a while until it took a big hit from the economy a year or so ago. It took a LONG time and A LOT of applications, but I finally found the job I have now.

Like an idiot I dropped out of college to forgo paying more tuition and I started my company and as life goes, I now wish I had stayed and got the degree. I have student loans that are in default and I'm working my hind end off to pay off those debts now that I am making a fair amount of money again.

I have hit too many ceilings without this degree. For one, I will never make as much as someone with the same level of knowledge and experience, but also has a degree. Also, the amount of effort it took to get a job in the industry without a degree was exhausting and depressing.

Now I am wondering what the best way for me to go about getting my degree is?

Are there online schools that would offer this degree?

Would an online school even be a good choice?

Would my knowledge and experience in the industry help me finish schooling faster/cheaper?

Have any of you ever found yourself in a similar position? If so, how did you overcome all the barriers put in front of you?

Have any of you ever had student loans in default and tried to go back to school later? How did you deal with that and how did it affect you?

答:
Get a degree outside of the computer science realm.  Do something you enjoy so that you have a future in that market.  If you really enjoy software, then go there.  If you want to be management, logistics, or whatever, get a degree there.

Take a real serious look into whether you want to be a coder and/or what kind of coder you want to be.  If you're happy with web-apps/whatever, latest trends, then that's where to put your effort.

I agree with the sentiment that if all you want is a piece of paper, then go to the cheapest accredited institute you can find.  But remember, my wife who has a degree from an Ivory League school has more open doors than I do with my basic (smaller/unknown) state school degree


问:
What is the point of the string.Empty property
Why was the property string foo = string.Empty included in the BCL? It seems more verbose and no clearer than just using an empty string (string foo = "")

答:
I'm not 100% sure of the sources where I learned these, but some of the points for using it include:

Each string in a .NET assembly is unique, so having

```<code>string foo = "";
string bar = "";
</code>```

results in 2 strings in the output assembly since strings are immutable.  Having both reference string.Empty reduces assembly size.

Explicitness.  When you come across string.Empty the intent is clear that it's supposed to be an empty string.  But if you come across foo = "" did the programmer remove the contents of the string while testing and forget to add it back, or is it supposed to be that way?

Body:
I'm not 100% sure of the sources where I learned these, but some of the points for using it include:

Each string in a .NET assembly is unique, so having

string foo = "";
string bar = "";

results in 2 strings in the output assembly since strings are immutable.  Having both reference string.Empty reduces assembly size.

Explicitness.  When you come across string.Empty the intent is clear that it's supposed to be an empty string.  But if you come across foo = "" did the programmer remove the contents of the string while testing and forget to add it back, or is it supposed to be that way?


问:
Should I Prefer Session Timeouts Based off of Prime Numbers?
While researching some information regarding managing state and session in web applications, I stumbled across this nugget of information:

67 is the first useful prime number after 60. (Yes, 61 is a prime,
  too, but it's too close to 60 to be of use.) Setting timeouts in
  durations of primes is common because it lessens the likelihood that
  two timeout sessions will overlap.

Of course, that's completely anecdotal and may not in any way be the
  reason why they chose 67 minutes, but that's always made sense to me.

At first glance, this seems to make perfect sense to me, and traditionally, I've never given a lot of thought to the variance of sessions timing out, but I wonder how much (if any) this strategy has been put into place in practice? Would making a change to timeouts ending on prime numbers really have that much of an effect long-term in a large scale application? Or would a change like this go mostly unnoticed?

In other words, is this really anecdotal? Or is it something that should be strongly considered as a best practice?

答:
I believe what the author was getting at was not that two web sessions would be less likely to end at the same time if they were each 67 minutes long, but rather that the end of web sessions would be less likely to overlap with other events (like the server being cycled, backups going off, system going down for maintenance, updates being applied) that tend to be an exact number of hours (often 24 or a multiple of it) apart.

All of this only matters if important and timeconsuming work happens at session end (I have written systems that persist unsaved drafts on session end just in case).


答:
I can only assume here:

string.Empty has been defined for explicitness - when initializing a string, it may not be clear from context that "" was indeed explicitly meant as an initializer (instead of null or say " " or just as a place holder during testing). Using string.Empty is a definite answer to that sort of conundrum.

It may also be a throwback to C - an empty string in C is not an empty string. It is a character array whose first character is null (hence, empty), which is not the same as C#. My point here being that in different languages you would represent an empty string in different ways (and they may have different meanings) - having a string.Empty precludes such ambiguity.

As opposed to what others say about multiple objects - this is not a problem as any string literal will get interned on compilation. This includes the value of string.Empty - "". Any time either of these are repeated in code, the object will be retrieved from the intern pool. This is true per app domain.

Title: What is the point of the string.Empty property

Body: Why was the property string foo = string.Empty included in the BCL? It seems more verbose and no clearer than just using an empty string (string foo = "")


答:
Why not just "Javascript web app", or "browser-based Javascript app"?

As the comments have pointed out, just because you didn't write any server side code, it doesn't mean it's not a web app. So, "web app" actually does fit, but may be a little too vague for your purposes, due to the lack of server side code with the app itself, though technically, if you hook into any APIs at all, then someone had to write server side code somewhere, even if that someone wasn't you.

Calling it a "Javascript app" doesn't work, as there are cases where Javascript can be used to create applications that aren't actually web apps (Appcelerator Titanium Mobile, and Gnome 3 extensions come to mind).

On the same token, using "browser app" doesn't really work well, as browsers themselves can now host apps as extensions (such as the Chrome version of Angry Birds, or the Firebug Firefox extension, for example). Though, "browser-based Javascript app" could work, though it is a little wordy.

"Web tool" and "web script" might be able to work, but they're really vague (in my opinion). Likewise, "standalone webapp" doesn't mean much, either. Standalone from what? Does that mean it can run without a browser? Any webapp could be considered "standalone," if you think about it. "Client-only"? Again, seems rather vague, especially if you're dealing with non-technical people, or anyone who doesn't understand the client-server nature of the web.

"Pure Javascript", by itself, is generally in reference to the language (ie - Javascript without the use of frameworks or extensions like jQuery). A "pure Javascript web app" could be used, but seems a little wordy, and may provide inaccurate connotations of not using a JS framework.


问:
What happened to Borland Delphi?
I have the impression that Delphi isn't very popular anymore. But now at work I had to make some changes to an old Delphi program that we are still using. I used Borland Developer Studio 2006 and it was very pleasant and intuitive to work with, even though I had practically no previous exposure to it. Is Delphi still widely-used and I am simply not aware of it or are there other reasons for its decline? </p>

答:
Borland killed Delphi.

Writing an app using a version of Delphi a couple versions back just couldn't work.  Nothing worked.  Something simple like an FTP client, couldn't stay working.  Even simple Win API programming which work perfectly in VB6 and .NET, Delphi will work 15% of the time with the same code.  Borland only offered one Service Pack, leaving several bugs behind that they knew about.  If you want them fixed, you had no choice but to upgrade.  Judging from the users, the new version was littered with bugs, IDE crashes, and non-sense from Borland saying, "We have to keep ourselves profitable", implying that we have to keep paying them for the new versions which come out every year, otherwise they provide no support or fixes.

I was rooting for Delphi.  As a VB6 user I had to make a decision if I should switch to .NET, or Borland Delphi or C++.  The answer was clear, since Borland didn't care, then .NET.  Other users dropped Delphi and moved to .NET.  Even now, the thought of going to the new version of Delphi just makes me feel sick.  Memories how it just kept failing and nothing worked and Borland's greed, just make me want to stay away and not waste my time.  It's sad to see something go good, go so wrong.

Title: What happened to Borland Delphi?


答:
First, understand that the old-fashioned in-residence degree, involving in-person lectures and labs and tests, is going to carry more weight than almost any "online" degree.  If you actually suck it up and go back to school full-time to finish it, that will carry a LOT of weight with recruiters down the road.

Second, understand that you've learned some things about maturity and meeting schedule that the other undergraduates may not have learned yet.  This will put you ahead of the curve on schoolwork.

Start by talking with the college/university you left.  Find out whether you are eligible for readmission.  Find out whether you can get any kind of credit for work experience and independent learning since you left school.  (It never hurts to ask.  If they say "no", you've lost at most a few minutes.  If they say "yes", you've won.)

Figure out what you still have to do to graduate under your old degree plan, or under the current plan.  Write a pro forma plan.

Look at other degree options at the same university.  I once met a girl who'd changed her undergraduate major 13 times, and wound up a Hindi major, because, at that point, that carried the shortest path to graduation.  Check with other departments, and see if they'll give credit for independent learning or life experience.

If you're talking to a private college or university, it can't hurt to ask about direct admission into a Masters program, or a dual Bachelor's/Masters's unified program, if they have one.  You may find that the professors enjoy having someone around who has Been There And Done That.

Title: What is the best/easiest way to get my degree, already being an experienced developer?

Body:
I have been an active professional software developer (mostly utilizing .NET) for the past five years and, without being too full of myself, I would say I'm a very competent developer. I stay intimately up to date with the latest tools, the industry, and modern standards/practices. I work for a fairly high-level IT company and I swing just fine with the rest of them. I am even up to date on the latest team dynamic methodologies and feel like I have good leadership/management/people skills.

However, I never got my degree. I learned and am learning everything I know on my own from hundreds of books and experiences. I ran my own software company for a while until it took a big hit from the economy a year or so ago. It took a LONG time and A LOT of applications, but I finally found the job I have now.

Like an idiot I dropped out of college to forgo paying more tuition and I started my company and as life goes, I now wish I had stayed and got the degree. I have student loans that are in default and I'm working my hind end off to pay off those debts now that I am making a fair amount of money again.

I have hit too many ceilings without this degree. For one, I will never make as much as someone with the same level of knowledge and experience, but also has a degree. Also, the amount of effort it took to get a job in the industry without a degree was exhausting and depressing.

Now I am wondering what the best way for me to go about getting my degree is?

Are there online schools that would offer this degree?

Would an online school even be a good choice?

Would my knowledge and experience in the industry help me finish schooling faster/cheaper?

Have any of you ever found yourself in a similar position? If so, how did you overcome all the barriers put in front of you?

Have any of you ever had student loans in default and tried to go back to school later? How did you deal with that and how did it affect you?


问:
What is the name for the programming paradigm characterized by Go?
I'm intrigued by the way Go abandons class hierarchies and seems to completely abandon the notion of class in the typical object oriented sense. Also, I'm amazed at the way interfaces can be defined without the type which implements that interface needing to know.

Are there any terms which are/can be used to characterize this type of programming methodology and language paradigm (or perhaps specific aspects of it)? Is the Go language paradigm sufficiently new and distinct from the classical OOP paradigm and sufficiently important in the history of computer programming to warrant a unique name?

答:
Message passing between lightweight execution contexts, coupled with ability to create and destroy these contexts dynamically, is basically the actor model.

Programming languages tend to approach the expression problem in one of two ways: OO-languages tend to focus on making it easier to implement the same operations using different data types (e.g. "object I can click on with a mouse" might be a scrollbar, a window, a menu, a text-box, etc. - same operation, different data representations), while functional languages tend to focus on easily implementing new operations against the same underlying data types. By abandoning class hierarchies, Go seems to end up more on the "functional" side of this divide.

As Adam Crossland indicated in his comment, "type-ignorantly-implementing-interface" can be considered a form of duck-typing, which is highly prevalent in dynamic languages. (It's more technically correct, though, to consider this as a structural type system within Go. C++ templates are probably the most popular implementation of a structural type system today.)

Go has plenty of antecedents - I don't think any one of its ideas are original to the language. But I think that's generally the wrong measure for a language intended to be practical. Go looks like it mixes useful ideas from several different domains together in an elegant way, that (I think) would result in more productive programming than C# or Java might yield. I hope it gains traction.


答:
No object will be created for string.Empty.  Using "" will create an object that will most likely come from the string intern pool.

In the past, people have run tests and String.Empty comes out slightly faster, but its a micro-optimization.

String.Empty is this:

```<code>//The Empty constant holds the empty string value.
//We need to call the String constructor so that the compiler doesn't mark
//this as a literal.
//Marking this as a literal would mean that it doesn't show up as a field
//which we can access from native.
public static readonly String Empty = "";
</code>```

Body:
No object will be created for string.Empty.  Using "" will create an object that will most likely come from the string intern pool.

In the past, people have run tests and String.Empty comes out slightly faster, but its a micro-optimization.

String.Empty is this:

//The Empty constant holds the empty string value.
//We need to call the String constructor so that the compiler doesn't mark
//this as a literal.
//Marking this as a literal would mean that it doesn't show up as a field
//which we can access from native.
public static readonly String Empty = "";


问:
Is there a point to including a "change log" in every code file when you are using version control?
I was under the impression that a version control system eliminated the need to have "change logs" plastered everywhere in the code.  I've often seen the continued use of change logs, including big long blocks at the start of stored procedures with a big section blocked out for changes to the file and littering the code with things like:

```<code>// 2011-06-14 (John Smith) Change XYZ to ABC to fix Bug #999
</code>```

and:

```<code>// 2009-95-12 (Bob Jones) Extracted this code to Class Foo
// <commented-out code here>
</code>```

The reason for this, as it was explained to me, is that it takes too long to sift through our VCS logs trying to find who changed what and why, while having it in the code file itself, either at the top or near the relevant change, makes it easy to see who changed what and when.  While I see the point of that, it seems redundant and just kind of smacks of "Eh we don't really understand how to use our VCS properly, so we won't bother with that stuff at all."

What do you think?  Do you use both comments and the log?  Just the log?  Do you find that it's easier to code when you can see above a block of code that John Smith changed the method to check for XYZ a week ago, instead of having to search through logs and compare code files in a Diff tool?

EDIT:  Using SVN, but basically only as a repository.  No branches, no merges, nothing except log + storage.

答: The reason that we continue to maintain a change log in our comments section is for ease of use. Often when debugging a problem it's easier to scroll to the top of the file and read the change log than it is to open up the source control file, locate the file within it, and find the changes made</p>


问:
open source flash environments
I have been looking for a really good open source flash development environment with no success.  The best I could find would help in the development of pretty much everything, but I still needed to have Adobe Flash Professional in order to compile my work.  Is there a way I can develop Flash applications and not need to purchase Flash Pro?</p>

答:
Flash is proprietary property of Adobe.  I do not expect them to open source it any time soon.

Flex is a powerful, open source application framework that allows
  you to easily build mobile applications for iOS, Android™, and
  BlackBerry® Tablet OS devices, as well as traditional applications for
  browser and desktop using the same programming model, tool, and
  codebase.

Flex has a flash compiler though I think you need a license for it. Though I believe the license the flex flash compiler is less than the Flash Pro.

Title: open source flash environments


问:
Why do technical/programming phone screens focus on inheritance?
I've noticed that in most technical phone screens, programming questions tend to focus on inheritance. For instance:

If a class is intended to be inherited, what should you do with the destructor? (Answer: make it virtual)

What's the deal with public/private access?

What's "protected" for?

Etc. etc.

It strikes me that there are more meaningful questions to ask these days. And, IMHO, reliance on inheritance as the primary design solution to an OO problem is a bit problematic. Am I wrong? Is knowledge of inheritance quirks the best way to assess technical skill?

EDIT

Commenters have asked me to explain in more detail why I think reliance on OO-based questions is problematic. Let's see... Basically, my thinking is that there are plenty of cool, non-OO questions you could ask. For instance:

(C++) What's the difference between a map and a multimap?

(C++) What are the two different kinds of things you can use as template arguments?

(C#) What's an extension method?

(Perl) What restrictions, if any, exist on the number of arguments a function can take?

(Python) What are the different ways you can use import, and what are the consequences of those tactics?

I submit that the above questions are also pretty decent weed-out questions. So my question for this forum is: Why don't phone screeners ask questions like those above?

答:
The goal of a phone screen is generally to figure out which candidates it is worth spending the time and energy to interview in person.  So the goal is generally to weed out candidates that aren't worth the time to interview in person rather than to identify the best candidates.  That means that questions in phone screens tend to skew toward objective questions that deal with relatively basic topics and don't require any code or particularly detailed explanations.  The goal isn't to assess technical skill so much as to identify people that don't have the technical foundation to deal with the more interesting questions that would be asked in a face to face interview.  The interviewer likely wants to avoid more challenging questions because it is much more effective to ask those sorts of questions face to face where there are whiteboards and scratch paper and candidates are likely to have a much better chance of explaining themselves well.

Phone screen questions also tend to get handed down over time so whoever is interviewing you probably got a list of questions from someone else a few years ago that they've never bothered to update.  On the one hand, this means that questions tend not to keep pace with new developments and techniques.  But from the interviewer perspective, it's very helpful to have stable set of questions in order to make comparisons easier.  When an interviewer prepares a new set of questions, he or she is inevitably shocked that the candidates don't do nearly as well as was expected.  Inevitably, the interviewer assumes that certain things are "common knowledge" because they're so common in that particular developer's day-to-day tasks only to find that among programmers more generally, they're rather more esoteric.  If you have a relatively stable set of questions, it's a lot easier to judge how a candidate stacks up to prior candidates.


答:
Two reasons.

First because, in a phone-screen, you don't want to ask trivia questions. By trivia questions, I mean those that are easy to people who have used those features and difficult to those who haven't. You can't write well in an OO language without knowing about inheritance. You can without knowing about extension methods.

Second, because often the person doing the phone-screen isn't that technical. In some companies, the manager will do them; in others, a secretary or HR person will do them. In those cases, someone will usually Google for phone-screen questions with answers and these are the ones that come up most often.

Title: Why do technical/programming phone screens focus on inheritance?

Body:
I've noticed that in most technical phone screens, programming questions tend to focus on inheritance. For instance:

If a class is intended to be inherited, what should you do with the destructor? (Answer: make it virtual)

What's the deal with public/private access?

What's "protected" for?

Etc. etc.

It strikes me that there are more meaningful questions to ask these days. And, IMHO, reliance on inheritance as the primary design solution to an OO problem is a bit problematic. Am I wrong? Is knowledge of inheritance quirks the best way to assess technical skill?

EDIT

Commenters have asked me to explain in more detail why I think reliance on OO-based questions is problematic. Let's see... Basically, my thinking is that there are plenty of cool, non-OO questions you could ask. For instance:

(C++) What's the difference between a map and a multimap?

(C++) What are the two different kinds of things you can use as template arguments?

(C#) What's an extension method?

(Perl) What restrictions, if any, exist on the number of arguments a function can take?

(Python) What are the different ways you can use import, and what are the consequences of those tactics?

I submit that the above questions are also pretty decent weed-out questions. So my question for this forum is: Why don't phone screeners ask questions like those above?


问:
When am I ready to start using Jquery for Javascript?
I was told not to use Jquery as a beginner because it would hamper my learning of Javascript.  Now I've read a couple books on Javascript, read loads of sites, and made a Javascript web app.  Am I ready for Jquery? If not, then how will I know when I'm ready?</p>

答:
Should have already started

jQuery is the only syntactic sugar I find indispensable for daily development. Selectors and events make everything more pleasing.

Prototype and MooTools alter the way you write JavaScript while jQuery merely fills in the gaping holes that span between browsers.


问:
Can modern OO languages compete with C++'s array store performance?
I just noticed that every modern OO programming language that I am at least somewhat familiar with (which is basically just Java, C# and D) allows covariant arrays. That is, a string array is an object array:

```<code>Object[] arr = new String[2];   // Java, C# and D allow this
</code>```

Covariant arrays are a hole in the static type system. They make type errors possible that cannot be detected at compile-time, so every write to an array must be checked at runtime:

```<code>arr[0] = "hello";        // ok
arr[1] = new Object();   // ArrayStoreException
</code>```

This seems like a terrible performance hit if I do lots of array stores.

C++ does not have covariant arrays, so there is no need to do such a runtime check, which means there is no performance penalty.

Is there any analysis done to reduce the number of runtime checks necessary? For example, if I say:

```<code>arr[1] = arr[0];
</code>```

one could argue that the store cannot possibly fail. I'm sure there are lots of other possible optimizations I haven't thought of.

Do modern compilers actually do these kinds of optimizations, or do I have to live with the fact that, for example, a Quicksort always does O(n log n) unnecessary runtime checks?

Can modern OO languages avoid the overhead created by supporting co-variant arrays?

答:
Yes, one crucial optimization is this:

```<code>sealed class Foo
{
}
</code>```

In C#, this class can't be a supertype for any type, so you can avoid the check for an array of type Foo.

And to the second question, in F# co-variant arrays are not allowed (but I guess the check will remain in the CLR unless it's found unnecessary in optimizations at runtime)

```<code>let a = [| "st" |]
let b : System.Object[] = a // Fails
</code>```

https://stackoverflow.com/questions/7339013/array-covariance-in-f

A somewhat related problem is array bound-checking. This might be an interesting (but old) read about optimizations done in the CLR (covariance is also mentioned 1 place): Link

OwnerDisplayName: FredOverflow

Body:
Yes, one crucial optimization is this:

sealed class Foo
{
}

In C#, this class can't be a supertype for any type, so you can avoid the check for an array of type Foo.

And to the second question, in F# co-variant arrays are not allowed (but I guess the check will remain in the CLR unless it's found unnecessary in optimizations at runtime)

let a = [| "st" |]
let b : System.Object[] = a // Fails

https://stackoverflow.com/questions/7339013/array-covariance-in-f

A somewhat related problem is array bound-checking. This might be an interesting (but old) read about optimizations done in the CLR (covariance is also mentioned 1 place): Link

OwnerDisplayName: lasseespeholt


答:
D does not allow covariant arrays.

```<code>void main()
{
    class Foo {}
    Object[] a = new Foo[10];
}
</code>```

```<code>/* Error: cannot implicitly convert expression (new Foo[](10LU)) of type Foo[]
to Object[] */
</code>```

As you say, it would be a hole in the type system to allow this.

You can be forgiven for the mistake, as this bug was only just fixed in the lastest DMD, released on December 13th.

Array access in D is just as fast as in C or C++.

Title: Can modern OO languages compete with C++'s array store performance?

Body:
I just noticed that every modern OO programming language that I am at least somewhat familiar with (which is basically just Java, C# and D) allows covariant arrays. That is, a string array is an object array:

```<code>Object[] arr = new String[2];   // Java, C# and D allow this
</code>```

Covariant arrays are a hole in the static type system. They make type errors possible that cannot be detected at compile-time, so every write to an array must be checked at runtime:

```<code>arr[0] = "hello";        // ok
arr[1] = new Object();   // ArrayStoreException
</code>```

This seems like a terrible performance hit if I do lots of array stores.

C++ does not have covariant arrays, so there is no need to do such a runtime check, which means there is no performance penalty.

Is there any analysis done to reduce the number of runtime checks necessary? For example, if I say:

```<code>arr[1] = arr[0];
</code>```

one could argue that the store cannot possibly fail. I'm sure there are lots of other possible optimizations I haven't thought of.

Do modern compilers actually do these kinds of optimizations, or do I have to live with the fact that, for example, a Quicksort always does O(n log n) unnecessary runtime checks?

Can modern OO languages avoid the overhead created by supporting co-variant arrays?

Body:
D does not allow covariant arrays.

void main()
{
    class Foo {}
    Object[] a = new Foo[10];
}

/* Error: cannot implicitly convert expression (new Foo[](10LU)) of type Foo[]
to Object[] */

As you say, it would be a hole in the type system to allow this.

You can be forgiven for the mistake, as this bug was only just fixed in the lastest DMD, released on December 13th.

Array access in D is just as fast as in C or C++.

OwnerDisplayName: Peter Alexander


答:
D doesn't have covariant arrays. It allowed them prior to the most recent release (dmd 2.057), but that bug has been fixed.

An array in D is effectively just a struct with a pointer and a length:

```<code>struct A(T)
{
    T* ptr;
    size_t length;
}
</code>```

Bounds checking is done normally when indexing an array, but it's removed when you compile with -release. So, in release mode, there's no real performance difference between arrays in C/C++ and those in D.

Body:
D doesn't have covariant arrays. It allowed them prior to the most recent release (dmd 2.057), but that bug has been fixed.

An array in D is effectively just a struct with a pointer and a length:

struct A(T)
{
    T* ptr;
    size_t length;
}

Bounds checking is done normally when indexing an array, but it's removed when you compile with -release. So, in release mode, there's no real performance difference between arrays in C/C++ and those in D.

OwnerDisplayName: Jonathan M Davis


答:
Java answer:

I take it you haven't actually benchmarked the code, have you? In general 90% of all dynamic casts in Java are free because the JIT can elide them (quicksort should be a good example for this) and the rest are one ld/cmp/brsequence which is absolutely predictable (if not, well why the hell is your code throwing all those dynamic cast exceptions?).

We do the load much earlier than the actual compare, the branch is correctly predicted in 99.9999% (made up statistic!) of all cases so we don't stall the pipeline (assuming we don't hit the memory with the load, if not well that will be noticeable, but then the load is necessary anyhow). Hence the cost is 1 clock cycle IF the JIT cannot avoid the check at all.

Some overhead? Sure, but I doubt you'll ever notice it..

To help support my answer, please see this Dr. Cliff Click blogpost discussing Java vs. C performance.

OwnerDisplayName: Voo


答:
They are very useful for the candidate allowing them to weed out interviewers who think inheritance is the most important feature (or indeed only) of OO.

This generally means that they did a CS degree and this is all they remember about programming but have never actually programmed anything in an OO language in the real world.

This reflects courses on OO which concentrate purely on inheritance and the vital importance of a creating hierarchy of shape classes and the vexed question of "is a rectangle a square" or "is a square a rectangle".