答:
I think that your library should be generic and not tied to vector/array types unless absolutely necessary. The genericity is provided by the iterators - they are the interface between the algorithm and the container.

Look at what interface C++ algorithms provide.  A given algorithm simply requires a couple of iterators with certain properties and that's it. As long as a container provides such an iterator, the algorithm doesn't care about the container per se.

Once you're thinking in terms of iterators, std::array and std::vector behave identically: they both have forward- and backward random access iterators. If the algorithm can use such iterators, you can use it on both std::array and std::vector.

I don't quite believe that you're using iterators as the interface, since if you did, the type of the container the iterator comes from doesn't figure anywhere in your interface. Well, unless you explicitly want std::array<T>::iterator - that'd be very bad style, indeed.

Title: Specific reasons to create own array class over using std::array?

Body:
What specific conditions or requirements should you create your own array over using std::array?

Here is my background:

I'm developing a small simple library that a small group of people will use and hopefully build upon. The current structure allows for both std::vector and std::array using iterators, however, a lot of the people do not like and cannot seem to use std::array and find the notation confusing to work with the library.

I have attempted to make my library work for better for std::array however, it dawned on me that maybe I should provide my own and adding in the functionality needed?

For example: library::array<int, 2> myArray; myArray.fill(1, 100); and I thought it would be a good project in order for me to develop my skills, particularly in templates and other sorting algorithms.


问:
Git Staging: When to stage? What to do if modification occurs afterwards
I'm rather new to the broad world of Git. I have read the manual and have been practicing but I am confused about few aspects of it, which I couldn't figure out after searching for.

I'm wondering:

In a project (post first commit), when is the right moment to stage source files? Right before committing? Right after adding/deleting or modifying?

If files are staged midway between two commits, and then they get modified, what happens with Git? Does it need care about content changes when it was stated and what it become since?

If I create a new file, stage it and then want to delete it, why does Git ask me to use "-f" flag and a simple "git -rm file.ext" won't work?

I have read "What stage means" and various other subjects of the manual and other tutorials on Git but as I said, I still don't understand the above matters.

So, if you could, please answer the questions with your own words and examples so I might have a better chance of understanding it.

Thank you.

答:
I think you are taking it too seriously. Staging is just selecting the stuff you want to include in the next commit. It is very rarely important when or how you do the staging; and if you have a lot of staged and unstaged changes at any given moment, you probably need to revise your development process.

In a project (post first commit), when is the right moment to stage source files? Right before committing? Right after adding/deleting or modifying?

I usually do it right before committing (unless I notice some typo, so I have to make a last-moment correction and stage it too). The process is the following: edit, run tests, stage, commit. If you stage before the testing, chances are the tests will fail and you will have to make changes and stage them too, so why not leave it until the commit time?

If files are staged midway between two commits, and then they get modified, what happens with Git? Does it need care about content changes when it was stated and what it become since?

It will show you the diff between the current state of the repo and (last commit + staged changes). When you stage some of the new changes, it will just recalculate the (last commit + staged changes) state.

If I create a new file, stage it and then want to delete it, why does Git ask me to use "-f" flag and a simple "git -rm file.ext" won't work?

Now I'm guessing here, but it's probably because the staged info may be important (otherwise you wouldn't stage it), but it's not yet under version control (like a file you can remove with git -rm). So git wants to make sure you know what you are doing.

ContentLicense: CC BY-SA 3.0


问:
What are appropriate metaphors for the pieces of a word processor?
A word processor is a complicated creature of many layers and pieces, but it represents a relatively simple concept: a piece of paper with writing on it. This leads to the problem of having many abstractions without enough intuitive names to describe those abstractions. Not everything can be a document. The solution to this sort of problem is usually finding powerful metaphors that make life easier.

Here are some of the abstractions for a document that need intuitive names:

The data structure that breaks up plain text into meaningful pieces such as chapters, sections, headings, and various kinds of emphasis. This is the most abstract document because it avoids all rendering information like fonts, colors, underlines, or alignments.

The data structure that provides text with rendering information such as fonts, colors, sizes, alignments. This also represents a document, but at a level that is closer to the printed page. It probably uses an instance of the first kind of document to help generate the content.

The data structure that arranges glyphs into lines of text. This document can be given the number of a desired paragraph, a position within that paragraph, and a maximum width in pixels, and it produces a data structure that represents a line of text ready to draw. It makes sense to base this document abstraction upon an instance of the previous document abstraction because they both represent documents at different stages in the rendering process.

The final data structure stores lines of text in their relative positions on the screen or page. It is capable of drawing an entire screen of text, inserting figures, and making columns. It knows which part of the document is currently visible, handles scrolling or dividing the document into pages for printing. This document abstraction is the very closest to the paper, but does that make it most worthy to be called document, or is the most abstract layer the true document since it is what the user is truly editing?

All four concepts are documents in their own way, but I can't call them all documents; that would be confusing. What is the proper metaphor to use here? Something that intuitively reflects the complexity of the task better than a document?

On top of all that, there are three different ways to represent a position within a paragraph.

Measured in characters from the start of the paragraph

Measured as a line number starting from the first line of the paragraph and then measured in characters from the start of the line

Measured in pixels as the paragraph is rendered on the screen

These three representations are all positions, but things become confusing if I call them all positions. I need a simple way to distinguish them, something that fits well with the improved metaphor that I'll use to distinguish the four kinds of document.

I have looked into typography in search of good metaphors, but nothing jumps out at me.

I have also considered a metaphor from constructing a building. The first kind of document could be a Blueprint, the second kind could be a Foundation. Unfortunately #3 and #4 aren't clear, and it doesn't seem to help with the issue of paragraph positions.

答:
Not exact but the best I could relate is:

Document and Document Parts.

Text Attributes

Text Lines

Character Attributes

2nd set:

character indents

position as an x,y coordinate

pixel indent


问:
Ruby: Multithreading a CSV with output
I have a script written in Ruby that has maxed out a core in my server's Xeon processor for the last 2 hours.  Since it's currently only using 1 of four possible cores, I want to try and rewrite the script to take advantage of all four cores.

I can use the .each_slice(n) method on the array that contains my data, but I'm curious as to what would then be the best/most efficient way to then write this data to a file.  It seems that I have a couple options.

Pass the file object to the functions being called by the Thread.new function (I assume this is legal in ruby?) and have them write as they see fit.

Have each function store the results in arrays, return the array on completion and let the main program then write to the disk.

Pass the same array object to each item and have them all add to it, then sort it.

My assumption is that although 2 would probably be more memory intensive, it'll by far be most efficient method.  Is there a different way to accomplish what I'm doing?

答:
You didn't mention if it matters what order the output is in. If it really doesn't matter I'd use a single-threaded Queue to receive messages from multiple reader/processor threads. Then another thread could be in charge of reading from the Queue and writing to the output file.

If order matters then your #2 seems a good idea.

I am concerned that with your suggestions #1 and #3 that if one is not very careful with the locking around the shared output object (file pointer or array) that one would be in 'undefined behavior' territory.

Title: Ruby: Multithreading a CSV with output


答:
The purpose of the staging area is to have a flexible space for your commit. I think this will become clearer if you contrast git to version control systems that are centralized, such as subversion.

Subversion

In subversion you can select to commit certain files of your working copy. But only the complete files. Now: What if you want to stage file A, not file B, and the parts of file C that relate to file A yet not the parts that depend on changes in file B (since then you would have a problem with commit consistency).

Git

Git solves this by providing the staging are as second working copy. Within the staging area you are putting together a snapshot that you will commit (roughly speaking).

Therefore within the staging area you can create a snapshot that includes changes to A and a version of file C which only reflects the changes in A.

For the specific questions

You can stage at any point you want. i personally prefer to stage right before I launch the commit.

When having changes in a file staged and then changing that file in the working copy, you have not altered the staged file of course. You can either decide whether to stage those as well or whether not to stage thos changes. I.e. if you run git gui citool you will see diffs of staged and unstaged versions (nice and simple tools for line-wise staging and committing).

Git is cautious here, which is probably a good thing.

General commit strategy: Granular commits

I think when talking about the question "When should I stage", one should also talk about commit habits.

Centralized VCS

In centralized version control systems where you commit to a central server, it was important for you co-workers that your commits are complete and well-tested. So people would try to commit not-so-often and then commit the state of complete files to minimize the possibility of an error. Thus, a commits tend to be quite large chunks which include lots of changes (if they are not simple fixes). The changes in a commit can be totally unrelated.

Git

In Git a commit is performed locally, only pushing them out to a server makes them public. Therefore a commit is cheap in a sense. A commit in the subversion sense is rather comparable to several git commit followed by git push. This difference matters.

Git allows you to commit single lines of code, even if you have changed other lines in the same file as well. This gives you a lot of benefits since you can for example commit a security bugfix in line 100 while having changed lines 300-350 introducing a new feature.

You can separate different changes in different commits. This separates them nicely in your version history and even allows you to revert one but not the other.

Your commit does not necessarily have to reflect a "compiling" state of your working copy (although I try to keep it that way).

So where is the "quality control" and build-guarantee in a commit that a subversion user would expect? It is shifted to other actions in git. You still want to push out a functioning state of the program in a public repository. Therefore you make sure that tests are successful and the program works before pushing out your changes.

Also, try to utilize branches to the max. When commiting lots of small changes you will end up with a pretty big version history. If you work in branches, you can categorize those granular commits by the branch name and then merge them back (option --no-ff will also preserve that these features lived in a unique branch).

I.e. you can keep the habit of merging to the master branch only, if the branch is in a good state. You can also use tags to track milestones and releases.

Now to come back to staging: Once you commit a few lines per commit, you will stage directly before commiting. (At least that is how I do it).

Title: Git Staging: When to stage? What to do if modification occurs afterwards

Body:
I'm rather new to the broad world of Git. I have read the manual and have been practicing but I am confused about few aspects of it, which I couldn't figure out after searching for.

I'm wondering:

In a project (post first commit), when is the right moment to stage source files? Right before committing? Right after adding/deleting or modifying?

If files are staged midway between two commits, and then they get modified, what happens with Git? Does it need care about content changes when it was stated and what it become since?

If I create a new file, stage it and then want to delete it, why does Git ask me to use "-f" flag and a simple "git -rm file.ext" won't work?

I have read "What stage means" and various other subjects of the manual and other tutorials on Git but as I said, I still don't understand the above matters.

So, if you could, please answer the questions with your own words and examples so I might have a better chance of understanding it.

Thank you.


问:
Specific reasons to create own array class over using std::array?
What specific conditions or requirements should you create your own array over using std::array?

Here is my background:

I'm developing a small simple library that a small group of people will use and hopefully build upon. The current structure allows for both std::vector and std::array using iterators, however, a lot of the people do not like and cannot seem to use std::array and find the notation confusing to work with the library.

I have attempted to make my library work for better for std::array however, it dawned on me that maybe I should provide my own and adding in the functionality needed?

For example: library::array<int, 2> myArray; myArray.fill(1, 100); and I thought it would be a good project in order for me to develop my skills, particularly in templates and other sorting algorithms.

答:
How many dimensions are needed?

C++ Template programming may require some code duplication for each level of higher dimension.

Address calculation is the easy part. A simple approach can be used for dimensions up to a dozen.

For a 3-dimensional example:

Let the size of the array be [m, n, p]

For each dimension, we calculate a "weight vector" by successively multiplying terms:
 [p*n, p, 1]

To access the element at [i, j, k], its linearized element index can be calculated as:
[i, j, k] dotproduct [p*n, p, 1]
or ((((i * n) + j) * p) + k)

For higher dimensions, care must be taken to reduce the time spent in multiplications needed for element address calculation.

What are the typical sizes of the array, to the order of magnitude?

For small-sized arrays (less than 1000 elements), basically any design and implementation will work, unless proven otherwise by a profiler.

For medium-sized arrays (as long as it can still fit entirely in the computer's memory or the application's address space), performance will be an increasingly important concern.

For large arrays (which cannot fit as a contiguous piece of memory), architecture concern will dominate.

Architecture / Memory Layout

Driving forces:

Size / scale

Performance

Computational platform

Interoperability (with other code / libraries)

Access semantics

Available choices:

Contiguous memory (the easiest, most straight-forward choice)

Non-contiguous memory (example: tiled array)

Memory-mapped file

Distributed across multiple machines in a network

Does your implementation need to support high performance?

As a ballpark, anything requiring more than one billion elementary operations per second can be considered high-performance for the purpose of choosing a design.

Designing for high-performance will impose constraints on:

Choice of computational platform

Choice of memory layout

Computational platform?

If high performance is not needed, scalar C++ code will be sufficient.

Otherwise, a high-performance computational platform will be needed.

This will impose constraints on:

Choice of memory layout

Computational choices

Scalar C++

Multi-core computing

Manual threading

Concurrent programming library (Intel TBB, Microsoft PPL/AMP)

Compiler-assisted (OpenMP)

Parallel programming languages. Example: Cilk, Brook

Open-soure library (OpenCV)

SIMD (Single-Instruction Multiple Data) example: Intel SSE2, AVX, ARM NEON, PowerPC AltiVec

GPU programming (CUDA, OpenCL)

Does the array need to be accessible by other libraries, without copying?

If so, your array's memory layout must be compatible with that other library you are using.

For small array sizes, or for access patterns where writes (modifications) occur infrequently, copying is not an issue.

For large arrays which are both read and written very frequently, data copying can become an performance issue.

A story where a bad combination of data copying and access semantics can cause an increasingly disproportionate performance issue:

Consider two modules, each of which has its own copy of a 100 MB array, and which they have to keep synchronized at regular intervals.

Suppose that one of the modules freely modifies its own copy, without keeping track of which region of the array is being modified.

When the time comes to perform synchronization, the first module will have to copy the entire 100 MB array over, because it cannot tell which part needs synchronization.

The user of the first module will complain that "if I am only modifying a few elements of this array, why is the library taking so long to synchronize?"

Lesson: by requiring modifications to go through an API call, access semantics can be used to reduce inefficiency in data copying.

Access semantics.

Boils down to three questions:

Who computes the memory address of elements? given the subscripts (i, j, k)

How is the array's lifetime (ownership) managed?

Is the array implementation being notified of which part of the array is modified?

Choices:

Direct access to underlying memory, no API call.

The array implementation will not know which part of the array is modified / used.

Direct access to underlying memory, requiring a API call to lock/unlock an array view.

Known as "advisory locks" because it cannot enforce access control.

An advisory lock is still useful, because by locking/unlocking the library is notified of current users of the array, as well as the region being modified.

API method for reading and writing one element at a time

Easiest to implement and use

Slowest

API method for copying an array view at a time

Copies between a sub-rectangle of your array and a normal C/C++/Java array

Good balance between high-performance and safety

Allows your array implementation to use a different memory layout

Design of the library interface and syntax

...

If you have made it thus far, congratulations, you can start designing the interface and the syntax!


问:
What is the most obscure sorting algorithm you know?
I just read about cyclesort via a sortvis.org blog post.
This is probably the most obscure one I have heard of so far, since it uses maths that I am not familiar with (detecting cycles in permutations of integer sets).

What is the most obscure one you know?

答: Ever heard of Patience sorting? Well now you have...</p>

ContentLicense: CC BY-SA 2.5


问:
What is the purpose of the stand-up and its duration in agile methodologies?
I used to work in a waterfall methodology and now I am in a team that is following an agile methodology. It seems they are doing it wrong. For example, we have stand-ups that last 25+ minutes daily, which is really annoying. Additionally, I feel more like I am justifying my salary to management than anything else.

Am I wrong to feel this way? Is this how stand-ups are usually conducted?

答:
For Scrum, Ken Schwaber and Jeff Sutherland explain:

Daily Scrum

The Daily Scrum is a 15-minute time-boxed event for the Development
  Team to synchronize activities and create a plan for the next 24
  hours. This is done by inspecting the work since the last Daily Scrum
  and forecasting the work that could be done before the next one. The
  Daily Scrum is held at the same time and place each day to reduce
  complexity. During the meeting, the Development Team members explain:

What did I do yesterday that helped the Development Team meet the Sprint Goal?

What will I do today to help the Development Team meet the Sprint Goal?

Do I see any impediment that prevents me or the Development Team from meeting the Sprint Goal?

The Development Team uses the Daily Scrum to inspect progress toward
  the Sprint Goal and to inspect how progress is trending toward
  completing the work in the Sprint Backlog. The Daily Scrum optimizes
  the probability that the Development Team will meet the Sprint Goal.
  Every day, the Development Team should understand how it intends to
  work together as a self-organizing team to accomplish the Sprint Goal
  and create the anticipated Increment by the end of the Sprint. The
  Development Team or team members often meet immediately after the
  Daily Scrum for detailed discussions, or to adapt, or replan, the rest
  of the Sprint’s work.

The Scrum Master ensures that the Development Team has the meeting,
  but the Development Team is responsible for conducting the Daily
  Scrum. The Scrum Master teaches the Development Team to keep the Daily
  Scrum within the 15-minute time-box.

The Scrum Master enforces the rule that only Development Team members
  participate in the Daily Scrum.

Daily Scrums improve communications, eliminate other meetings,
  identify impediments to development for removal, highlight and promote
  quick decision-making, and improve the Development Team’s level of
  knowledge. This is a key inspect and adapt meeting.

Other methodologies may have different rituals and even different Scrum teams may optimize the way they do this differently.  The key idea is a quick get together to make sure the team is on track to deliver.  It should not be a management status report.  It is however one of the agile ideas that is more easily subverted.


答:
TL;DR

When properly executed within an appropriately-sized Scrum team, the daily stand-up should never take more than 15 minutes or so. If it takes longer, either the team is too big or you have a process problem.

The Purpose of the Stand-Up

The daily stand-up is a commitment and coordination meeting for the entire team. It is designed to ensure that the entire team is aware of impediments, what stories are done or not-done, and what tasks are ready to be pulled from one team member's to-do list into someone else's.

It's important that the Scrum Master and the Product Owner be active participants in the stand-up, but if the team is reporting to either of them then your Scrum process may be well and truly broken. A related answer on Project Management Stack Exchange has a 10-point list of "project smells" at the bottom, some of which may apply in your case. Even if they don't apply, you should definitely re-evaluate the effectiveness of your stand-ups at your next Sprint Retrospective.

Respect the Time-Box

While I dislike the "three questions" as a concrete format precisely because they tend to lead to meetings that resemble a status pull, I'd be remiss if I didn't point to Mike Cohn's canonical description of the Daily Scrum. The page says, in part:

By focusing on what each person accomplished yesterday and will accomplish today, the team gains an excellent understanding of what work has been done and what work remains. The daily Scrum meeting is not a status update meeting in which a boss is collecting information about who is behind schedule. Rather, it is a meeting in which team members make commitments to each other.

There's a lot more detail and some concrete examples on that page. However, for the purposes of your question, it is explicitly stated that:

Scrum daily standup meetings are strictly time-boxed to 15 minutes. This keeps the discussion brisk but relevant.

The time-box is the foundation of Scrum. While most time-boxes within Scrum can be adjusted by the team as a result of the inspect-and-adapt cycle, it is considered poor practice to extend the length of the stand-up. If the time-boxing principle isn't being respected within your process, that's generally a very whiffy "project smell."

Title: What is the purpose of the stand-up and its duration in agile methodologies?

Body:
I used to work in a waterfall methodology and now I am in a team that is following an agile methodology. It seems they are doing it wrong. For example, we have stand-ups that last 25+ minutes daily, which is really annoying. Additionally, I feel more like I am justifying my salary to management than anything else.

Am I wrong to feel this way? Is this how stand-ups are usually conducted?


问:
How to make a "git push" update files on your web host?
I have a few sites which are all hosted on the same web hosting service under shared hosting. My web host supports Git and I have SSH access to it, and I also have Git setup on my laptop as well. </p>

<p>I want to make it so that when I do a "git push origin master", it will automatically update the files on my web server, and also save a backup of the previous commit's files so I can easily rollback if I want to. Is this possible? </p>

答:
This is summarized from Using Git to manage a web site

The key to the process is the server side hook 'post-receive' (more on git hooks at Customizing Git - Git Hooks and the githooks man page).  This hook runs after the server has received all of the data.

Once the server receives the data, it runs git checkout -f  The -f option will force a checkout to the head even if there are local differences.

```<code>#!/bin/sh
GIT_WORK_TREE=/var/www/www.example.org git checkout -f
</code>```

Put that in the hooks/ directory as post-receive and executable.  Of course, the path changes to where you have your webserver's files (the use of GIT_WORK_TREE sets the environment variable so that you don't need to juggle dot files and git settings on the server).

For rolling back, one should tag each release (this can be done as part of the post-commit hook too).  By tagging the release one can easily identify the spot to rollback to, though that likely involves logging into the server and checking out that tag.

Body:
This is summarized from Using Git to manage a web site

The key to the process is the server side hook 'post-receive' (more on git hooks at Customizing Git - Git Hooks and the githooks man page).  This hook runs after the server has received all of the data.

Once the server receives the data, it runs git checkout -f  The -f option will force a checkout to the head even if there are local differences.

#!/bin/sh
GIT_WORK_TREE=/var/www/www.example.org git checkout -f

Put that in the hooks/ directory as post-receive and executable.  Of course, the path changes to where you have your webserver's files (the use of GIT_WORK_TREE sets the environment variable so that you don't need to juggle dot files and git settings on the server).

For rolling back, one should tag each release (this can be done as part of the post-commit hook too).  By tagging the release one can easily identify the spot to rollback to, though that likely involves logging into the server and checking out that tag.


问:
Best practices for execution of untrusted code
I have a project where I need to allow users to run arbitrary, untrusted python code (a bit like this) against my server. I'm fairly new to python and I'd like to avoid making any mistakes that introduce security holes or other vulnerabilities into the system. Are there any best-practices available, recommended reading, or other pointers you can give me make my service usable but not abusable?

Here's what I've considered so far:

Remove __builtins__ from the exec context to prohibit use of potentially dangerous packages like os. Users will only be able to use packages I provide to them.

Use threads to enforce a reasonable timeout.

I'd like to limit the total amount of memory that can be allocated within the exec context, but I'm not sure if it's even possible.

There are some alternatives to a straight exec, but I'm not sure which of these would be helpful here:

Using an ast.NodeVisitor to catch any attempt to access unsafe objects. But what objects should I prohibit?

Searching for any double-underscores in the input. (less graceful than the above option).

Using PyPy or something similar to sandbox the code.

NOTE: I'm aware that there is at least one JavaScript-based interpreter. That will not work in my scenario.

答:
TL;DR Use a chroot/jail and run as a custom user without any privileges.

The best practice for executing untrusted code is to segregate it via a system sandbox.  For the most security:

create a container with only Python and it's dependencies and the container's dependencies

create a container without all devices that aren't absolutely necessary (ie. network and storage)

create a container with restrictions on memory and process usage

recreate the container with every run (or at the very least with each unique user and max time period)

run as a user with the least privilege needed

run as a user that doesn't have the permissions to write files

You also follow standard practices for running things securely in a chroot.  You can rebuild the chroot's filesystem with each call as well is particularly paranoid.  Typically you just make user unable to make modifications to the filesystem the chroot runs in.


答:
it represents a relatively simple concept: a piece of paper with writing on it.

That would be a text editor.  A Word Processor is a text editor with various extensions to aid in the task of writing.  It's most akin to the old layout staff at a newspaper, or perhaps a document secretary, than a simple piece of paper.

Name Suggestions for stages of a Word Processor Document

Document (or "SavedDocument" or "UserDocument") is the core data structure, which is what you save to disk.  It contains the main text, chapter/subchapter breaks, any index markers, emphasis styles, footnotes, and anything else that the user might intentionally declare.  This may include specific formatting, in addition to styles, but only if specified by the user.

StyledDocument is a Document with its saved information expanded based on a StyleTemplate, into specific page sizes, fonts, colors, alignments, and other information.

TypesetDocument is a StyledDocument with all of the characters translated to the necessary glyphs and so forth, but without final processing that may vary based on its form of output.

RenderedDocument is a TypeSetDocument with the final steps necessary to output to a final medium, be it paper or screen.

Name suggestions for position within a range:

(You don't want entirely different names based on your origin, do you?  A document, paragraph, or selection within a paragraph can all have distinct positions...)

naturalPosition: number of characters from the start of the paragraph, without regard to lines.

wrappedPosition: number of lines within a pararaph, and number of characters from the start of a line.

renderedPosition: numeric X,Y coordinates based on the final rendering device, be it pixels or not.

One more thing

Please hear my plea, on behalf of all who may come after you, to choose your names and metaphors early, and if at all possible to keep them consistent from your initial diagrams through your class and property names and all the way to your user interface.  If you find the names and metaphors lacking latter on, take the time to refactor them so as to keep your code as intuitive and self-documenting as possible.

If you take my names for the first suggestion, you'll probably have to wind up with a "ScreenTypesetDocument" and a "ScreenRenderedDocument", with corresponding "PrinterTypesetDocument" and "PrinterRenderedDocument" for when someone wants to print something.  But if you decide that "Rendered" is the wrong word and you want it to be "Drawn" instead, make sure to re-name all three classes and not just the abstract "RenderedDocument".

Title: What are appropriate metaphors for the pieces of a word processor?

Body:
A word processor is a complicated creature of many layers and pieces, but it represents a relatively simple concept: a piece of paper with writing on it. This leads to the problem of having many abstractions without enough intuitive names to describe those abstractions. Not everything can be a document. The solution to this sort of problem is usually finding powerful metaphors that make life easier.

Here are some of the abstractions for a document that need intuitive names:

The data structure that breaks up plain text into meaningful pieces such as chapters, sections, headings, and various kinds of emphasis. This is the most abstract document because it avoids all rendering information like fonts, colors, underlines, or alignments.

The data structure that provides text with rendering information such as fonts, colors, sizes, alignments. This also represents a document, but at a level that is closer to the printed page. It probably uses an instance of the first kind of document to help generate the content.

The data structure that arranges glyphs into lines of text. This document can be given the number of a desired paragraph, a position within that paragraph, and a maximum width in pixels, and it produces a data structure that represents a line of text ready to draw. It makes sense to base this document abstraction upon an instance of the previous document abstraction because they both represent documents at different stages in the rendering process.

The final data structure stores lines of text in their relative positions on the screen or page. It is capable of drawing an entire screen of text, inserting figures, and making columns. It knows which part of the document is currently visible, handles scrolling or dividing the document into pages for printing. This document abstraction is the very closest to the paper, but does that make it most worthy to be called document, or is the most abstract layer the true document since it is what the user is truly editing?

All four concepts are documents in their own way, but I can't call them all documents; that would be confusing. What is the proper metaphor to use here? Something that intuitively reflects the complexity of the task better than a document?

On top of all that, there are three different ways to represent a position within a paragraph.

Measured in characters from the start of the paragraph

Measured as a line number starting from the first line of the paragraph and then measured in characters from the start of the line

Measured in pixels as the paragraph is rendered on the screen

These three representations are all positions, but things become confusing if I call them all positions. I need a simple way to distinguish them, something that fits well with the improved metaphor that I'll use to distinguish the four kinds of document.

I have looked into typography in search of good metaphors, but nothing jumps out at me.

I have also considered a metaphor from constructing a building. The first kind of document could be a Blueprint, the second kind could be a Foundation. Unfortunately #3 and #4 aren't clear, and it doesn't seem to help with the issue of paragraph positions.


问:
Is Pair Programming also used to train less experienced developers and bring them up to speed?
I am familiar with Agile and Pair Programming (http://en.wikipedia.org/wiki/Pair_programming).  I thought Pair Programming was used if there was a complex requirement i.e. two sets of eyes is better than one.

Is Pair Programming also used to train less experienced developers and bring them up to speed?

Also, how often is it used e.g. all the time i.e. the two developers will work together at one screen permanently or perhaps one day per week? I have read an Agile book, which talks about this concept but it does not mention frequency of use.

答:
Pair programming should not be used to train inexperienced or less-skilled developers.

Studies and meta-studies that support pair programming on a general, conceptual level, almost invariably find that the gains in quality and productivity only outweigh the added cost when both programmers are at roughly the same skill level.

In fact, this has pretty much become a "rule" in academic settings. Universities which recommend the practice also state explicitly that students should find a partner with the same skill level. Not better, not worse - the same.

Note that "skill level" here is domain- and task-specific. Pairing a brilliant UI developer with a brilliant algorithm designer or database developer is no better than pairing a brilliant UI developer with a totally green UI developer.

The studies (corroborated by my own personal experience) show that inexperienced developers (in some area) learn faster when paired, and highly-skilled developers can catch serious misunderstandings and design problems much earlier, negating much of the time spent on debugging and rework.

However, there is a gradient of almost 10x the productivity for the least vs. most skilled developers. Pairing someone highly-skilled with someone very green is very much like pairing a driving instructor with a student. You don't have real co-operation, you have a driver and a passenger, a master and an apprentice. If the apprentice "drives" then the master is too busy monitoring and correcting errors to get any work of his own done. On the other hand, if the master "drives" and the apprentice is told to watch and learn, the master is less productive due to the interruptions and the apprentice does not learn very effectively.

This is a no-win situation. If new developers need to be trained, then call a spade a spade and train them. Or apprentice them, have them "shadow" a more experienced developer for a while. But don't call it "pair programming" and expect to get good results. Those only occur when both partners have similar skill sets.

Note: For those who can't view the study, here is another one making similar claims:

Evaluating Pair Programming with Respect to System Complexity and Programmer Expertise.

To quote the abstract:

The observed benefits of pair programming in terms of correctness on the complex system apply mainly to juniors, whereas the reductions in duration to perform the tasks correctly on the simple system apply mainly to intermediates and seniors.

Pairing a senior with a junior negates the time benefit that applies to seniors. There is still an improvement in correctness over what the junior would normally produce, but it is not proven to be better than what the senior would produce on his own.

Keep in mind that this is just a single study, whereas the first study is an actual meta-analysis which incorporates several different studies. It is by far the best resource I've found. Anyone who is truly interested in learning about the actual research should consider getting an ACM membership, because that's where all of these studies are published.


问:
Object Oriented Programming Concepts and Interviews
I'm an Object Oriented Programming fanatic. I have always believed in modelling solutions in terms of objects. It is something that comes to me naturally. I work with a services start up that essentially works on application development using OOP languages. So I tend to test understanding of OOP in the candidate being interviewed.

To my shock, I found very very few developers who really understood OOP. Most candidates brainlessly spit out definitions they mugged up from some academic book on object oriented programming but they don't know squat about what they are saying. Needless to say I reject these candidates. However, over the course of time, I ended up rejecting almost 98% of the candidates. Now this gets me thinking if I'm being over critical about their OOP skills. I still believe OOP is fundamental and every programmer MUST GET it. Language knowledge and experience is secondary.

Do you think I'm being over critical or do I just get to interview bad programmers unfortunately?

EDIT:

I usually interview programmers with 2 to 5 years of experience. The position that I usually interview for is Ruby/Ruby on Rails application developer.

答: haven't you imagined that OOP might not be the pinnacle of all knowledge?  there are other ways to think, after all.  Even more, there are lots problems out there where OOP isn't the best answer.


问:
MVC or Extract Service Layer
we have an application that is built with .Net MVC.  We are now tasked with exposing API's to third parties.  Members on our team want to just continue down our current path and just use more controllers so we can reuse the backend of our current application.  Logic tells me we need to create a seperate service layer when more clients are going to be accessing it, but .Net MVC seems to take care of all of this.  Is it really acceptable architecture to use controllers in a stand alone application to expose API's and what would be the potential gains of extracting the service layer out?</p>

答:
I have seen ruby on rails applications with a rest-api that can render their content as human readable hmtl or as machine readable json or xml based on the mime type.

If Webgui and service api are quite similar you can try this, too.

If Webgui and service api are different i would not try to force the service into mvc but create a seperate thin servicelayer that wraps modell with autentification/security.

OwnerDisplayName: Lizzard

Title: MVC or Extract Service Layer


问:
Refactoring jQuery spaghetti code to use DDD
Most of my client side code ends up as a long script in one file the mostly looks like this:

```<code><script>
function someFunction1(){/*...*/}
function someFunction2(){/*...*/}
...
var globalVariable1;
var globalVariable2;
...
$(function(){

$('selector1').click(function(){
    //get relevant data from various DOM elements

    //some business logic rules and validation

    //open dialog box

    //more business logic rules and more validation

    //post an ajax request

    //update the DOM
});

//many other events

//many jQuery dialogs
});
</script>
</code>```

It's a maintenance nightmare. Although I use a well designed server-side structure using DDD (application services, domain sevices, value objects,...etc.) I have had little luck structuring my client code to a better separation of concerns.

I'm not building a client-side application. I just use jQuery intensively for the client side.

How should I approach the code structure to apply DDD client-side wide?

答:
Sounds like you could use an MVVM framework ( AngularJS, Knockout, ... ), when you include jQuery along with AngularJS it'll use jQuery instead of the jQLite which AngularJS has, so you still have jQuery.

What these kind of frameworks allow you to do is define actions on elements referring to controller methods. For example AngularSJ has the ng-click directive; This as opposed to selecting something with jQuery and then adding an event handler )

Also AngularJS allows you to separate your code into controllers, services, configs, etc.
( Im only referring to AngularJS here because I haven't worked with Knockout or any of the others. )


答:
I would strongly recommend to use some kind of MV* JavaScript framework. There are a lot of them so (AngularJS, KnockoutJS, Ember, Backbone). Here is a nice review of some of the most popular ones.

Using a JS framework can sometimes be overkill for some simple pages without a lot of interactivity or if the pages relies heavy on server side. In those cases JS framework would probably not be a good fit. But if you're building something that is more complex (on the client side) and requires some interactivity (like frequent DOM manipulation or routing), the JavaScript framework is a perfect solution.

With client side frameworks you have half the job done for you:

Models that will represent your data.

Views that will update as you change your models.

Controllers that handle user input (and modify your Models).

Most of MV* frameworks also support unit testing and end-to-end testing (I love the way testing is supported in AngularJS). Unit tests on front end will ensure that your functionality doesn't break when someone changes something (e.g. some class was removed or changed and your jQuery selector can't find the element to add click event handler).

Title: Refactoring jQuery spaghetti code to use DDD

Body:
Most of my client side code ends up as a long script in one file the mostly looks like this:

```<code><script>
function someFunction1(){/*...*/}
function someFunction2(){/*...*/}
...
var globalVariable1;
var globalVariable2;
...
$(function(){

$('selector1').click(function(){
    //get relevant data from various DOM elements

    //some business logic rules and validation

    //open dialog box

    //more business logic rules and more validation

    //post an ajax request

    //update the DOM
});

//many other events

//many jQuery dialogs
});
</script>
</code>```

It's a maintenance nightmare. Although I use a well designed server-side structure using DDD (application services, domain sevices, value objects,...etc.) I have had little luck structuring my client code to a better separation of concerns.

I'm not building a client-side application. I just use jQuery intensively for the client side.

How should I approach the code structure to apply DDD client-side wide?


答:
As with all Agile processes this the purpose is: "what you get value out of".

The daily standup is typically a mechanism for ensuring communication between team members in a low-impact way, where everyone can understand where the team is with regard to the current set of tasks. So a 5 minute standup where everyone says "I did x yesterday and I'm going to do y today" is fine, as is a 15 minute one where the team decides between themselves what to work on next and updates the task board.

However, there's no need for one at all, not if you communicate these things in other ways, say using a rolling social notification system, for example.

Similarly, if you want your standup to be longer and more of a team reporting thing, then that's fine too. I'd question it, but I know some teams prefer a more directed approach to being given work. Agile can cope with all types of team after all.

The real question you should be asking is whether you are getting any value from it, and if not - what will you change it to be so you do get value. Doing the standup as prescribed by some holy book of Scrum is NOT Agile. Doing a standup that means something to your team so that you all work together better is.


问:
Is big-O really that relevant when working in industry?
In every interview I have been in, I have been quizzed on mathematical analysis of complexity, including big-O notation.

How relevant is big-O analysis to development in industry? How often do you really use it, and how necessary is it to have a honed mindset for the problem?

答:
Yes

You may not have to do formal analyses, but at least a gut understanding of the order of algorithm complexity - and how to compare two algorithms around that - is critical if you want to do non-trivial work and have it turn out well.

I've worked on two different systems that seemed fine in early development, but brought the hardware to its knees in production testing, because somebody used an O(n^2) algorithm. And in both cases, the fix was a trivial change to an O(n) algorithm.


答:
What you are describing is one way in which 'stand-ups' can fail for the team.

The best stand-ups are short because everyone understands what everyone else is doing, they explain what they achieved yesterday, what they will achieve today and flag up anything that may/did affect their ability to deliver on their promises. Other members of the team can then indicate that they can help solve each others impediments quickly, but that solutions take part outside of the stand up.

In short, They should be the glue that binds the team together.

What it sounds more like, is a status update, and you being held to account for delivery/not delivery, but the team is dysfunctional because the team are not using the stand up meetings to support each other to deliver and to remove the impediments.

In the two environments that I have seen this occur, its been caused by having a scrum master who has failed to delegate the responsibility of ensuring the team deliver on their iteration promises.  In one case it was particularly counter productive and generated an us/them attitude within the team.

Scrum is about self organising teams, where the team organises itself to solve problems quickly to deliver on their commitments


问:
What techniques are there for debugging remote client side errors?
What techniques are there for debugging remote client side errors in a web application, especially when they only affect a small subset of users?

In my case we have an app that is working well for hundreds of users, internally and externally, but a handful (12) have a specific problem with a JavaScript that prevents them from using the site.  We have screenshots of the error, have confirmed they have no server side errors, confirmed that everything is getting rendered to the browser correctly, have seen the specific error in the IE console, but still have no idea why it isn't working for these specific users.  The issue is exhibiting on different versions of IE.  We have never been able to replicate the problem here.

I'm not looking for a solution to my problem here, but rather what are the steps you would take to solve this kind of problem, and what tools there may be that might help?

答:
What you need is more "information".  You need to know from the web browser the execution flow is, what data it is receiving and so on.  And you need to know this from both the working clients and the broken clients.

You can then compare the information between working and non-working and work out where you need more detailed information, and so on.

Eventually you will get the point where you have an 'ah-ha' and know what the problem is, and can work on a fix / workaround.

One possible strategy to manage all this "information" is to have the java scripts logging their progress and forwarding this to a splunk server. In the log information have an identifier that can be used to track the progress of each execution thread, and another that uniquely identifies the web session.

This kind of approach is often implemented at the server farm end to monitor and fix server side bugs when code is distributed over many servers, but as long as its not crippling the client connection, I see no reason why it could not be used to solve your issues too.


问:
scripting support in a C# application
what is the simplest and fastest way to support simple scripting in a .Net application?
I search a lot but only find many things with practical no documentation or outdated since years.
I only need to transfer a simple .Net Object to the script and get a bool result from it.</p>

答:
Fastest and simplest?  I really hope this isn't that, but as a really last resort, you can use the .NET Emit method to create hand crafted CIL code that you generate dynamically in your program.

If your scripting requirement is really trivial, then this is probably a month or two's work.  You can work out the CIL instruction set from using a reflector to look at how the compiler translates your C# code into CIL, and then 'borrow' these code fragments.

Title: scripting support in a C# application


答:
It depends on your precise needs. Two ways I can think of:

Use a language like Python which is interoperable with C#, and call the Python script from C#. Actually, you can even make things simpler by just calling an executable, passing to it an XML or JSON data, and wait for XML or JSON response.

If you need to use C#, then compile C# on the fly, just like LINQPad does. Is it possible to dynamically compile and execute C# code fragments? is a good starting point. Loading the code in a sandbox (in a different AppDomain) is also a good idea if you need to provide enough security and don't trust the code which can be written by the user.

Title: scripting support in a C# application

Body:
what is the simplest and fastest way to support simple scripting in a .Net application?
I search a lot but only find many things with practical no documentation or outdated since years.
I only need to transfer a simple .Net Object to the script and get a bool result from it.</p>


答:
You could build a temp class and invoke a method on that

```<code>var template = @"public static class Temp
{{
  public static bool Run()
  {{
      return {0};
  }}
}}";

var script = "1 < 2";

var source = string.Format(template, script);

var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll" }, "temp.dll", true);
parameters.GenerateExecutable = false;
var results = csc.CompileAssemblyFromSource(parameters, source);
var type = results.CompiledAssembly.GetType("Temp");
var method = type.GetMethod("Run");
var result = (bool)method.Invoke(null, null);
Console.WriteLine(result);
</code>```

But you really have to trust people who write the scripts. Just add parameters to the Run method to pass your object.

Title: scripting support in a C# application

Body:
You could build a temp class and invoke a method on that

var template = @"public static class Temp
{{
  public static bool Run()
  {{
      return {0};
  }}
}}";

var script = "1 < 2";

var source = string.Format(template, script);

var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } });
var parameters = new CompilerParameters(new[] { "mscorlib.dll" }, "temp.dll", true);
parameters.GenerateExecutable = false;
var results = csc.CompileAssemblyFromSource(parameters, source);
var type = results.CompiledAssembly.GetType("Temp");
var method = type.GetMethod("Run");
var result = (bool)method.Invoke(null, null);
Console.WriteLine(result);

But you really have to trust people who write the scripts. Just add parameters to the Run method to pass your object.


问:
creating a clone of a site is good idea for project?
I am trying my hand in python, Django, JQuery.. etc to make a clone of imdb site. Currently I'm in web-development from past 10 months on same technologies. In my spare time I want to develop a side-project which may look good on resume.
I came up with an idea, to make a clone of imdb.com. But after 2 weeks of development I stopped.

reasons: its not different

Why create another imdb?

I'm not improving it?

Face it, it will be sub standard of original one.

The need for the project is to showcase my skills in above technologies but at same time I want it to be useful.

答:
What you said reminds me of a quote from John Carmack on the subject:

In the information age, the barriers [to entry into programming] just aren't there.
  The barriers are self imposed. If you want to set off and go develop some grand new
  thing, you don't need millions of dollars of capitalization. You need enough pizza and
  Diet Coke to stick in your refrigerator, a cheap PC to work on, and the dedication to
  go through with it. We slept on floors. We waded across rivers.

— John Carmack

I would say more important than the pizza, Diet Coke, and cheap PC is the dedication.  If your heart isn't into it, you'll never make a decent program.  And since making something which has already been done before is a strong demotivator, logically you should strive to do something which has never been done before.

Oddly enough, it doesn't even have to be that particularly useful since at least for me, that doesn't seem to be so important.  It just has to be something which nobody has attempted before.

Of course, on a resume, flashy is better, but flashy is not as important as getting it done, so focus on developing something you want to see finished.  You can always go back and improve on it (adding a better interface or whatever).

When you're coding every night to finish something you enjoy working on, then you'll wind up with a marvelous little project that works and is impressive.  If you quit half-way, then it doesn't matter how useful or flashy it would have been.  It didn't finish.


答:
I think the simplest way would be to use one of the .Net scripting languages that already exist, like IronPython or IronRuby.

For example, with IronPython you can write your script code in Python, execute it from your C# application and then process the results from the script.

The code could look like this:

```<code>var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("value", 43);

var code = @"
# overcomplicated just to show it's really Python
def areEqual (value1, value2):
    return value1 == value2

areEqual(value, 42)";

Console.WriteLine(engine.Execute<bool>(code, scope));
</code>```

Another option would be to use the scripting capabilities of Roslyn, but that's not production ready yet.

Title: scripting support in a C# application

Body:
I think the simplest way would be to use one of the .Net scripting languages that already exist, like IronPython or IronRuby.

For example, with IronPython you can write your script code in Python, execute it from your C# application and then process the results from the script.

The code could look like this:

var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("value", 43);

var code = @"
# overcomplicated just to show it's really Python
def areEqual (value1, value2):
    return value1 == value2

areEqual(value, 42)";

Console.WriteLine(engine.Execute<bool>(code, scope));

Another option would be to use the scripting capabilities of Roslyn, but that's not production ready yet.


答:
Isn't there something you need for yourself ? Think about it, find things you need and which don't exist yet on the market (or are expensive, or have weaknesses which make them unacceptable for you), and make those things.

Examples of my previous projects:

Something which doesn't exist: an app which can transform an ordinary screen in a tactile one by using two webcams specifically positioned in front of it.

Something which exists but is expensive: a bug tracking system.

Something which exists and is affordable, but has weaknesses: a sync tool which will work on Windows and sync files from one PC to another:

Without writing metadata files anywhere (this excludes SyncToy),

With the support for Unicode (this excludes SyncBack),

Without the 260 characters limitation for paths (this excludes nearly every sync app for Windows I know).

What's the point in making a clone of IMDB? Or Facebook? Or Google Maps?

Either your sole motivation is their success. In this case, stop right now. Their success is not due exclusively to the product itself, but the opportunities they took, their marketing scheme, and sometimes billions of dollars they invested in it. Not counting that most of those products were written by hundreds of developers, and would be slightly complicated to redo alone.

Or you're simply curious about the issues they got, or have a very specific need those sites don't fulfill well, or just for fun, then do it. Don't compare yourself to them : it's your project; it's not a clone of YouTube, but a way to see how to handle large amount of videos; it's not a clone of Twitter, but an experiment you do to see how to store small chunks of text in a way optimized for fast retrieval when they are recent, but not when they are older.

Title: creating a clone of a site is good idea for project?

Body:
I am trying my hand in python, Django, JQuery.. etc to make a clone of imdb site. Currently I'm in web-development from past 10 months on same technologies. In my spare time I want to develop a side-project which may look good on resume.
I came up with an idea, to make a clone of imdb.com. But after 2 weeks of development I stopped.

reasons: its not different

Why create another imdb?

I'm not improving it?

Face it, it will be sub standard of original one.

The need for the project is to showcase my skills in above technologies but at same time I want it to be useful.


答:
Pair programming is a skill in its self, and the benefits of pair programming can be quite widespread and varied, depending on when and how its used.

I've used it when managing a team of quite inexperienced programmers as an orientation tool when new programmers join the team. (We talk about what I am doing on the first task, as I am doing it, and then we talk about what they are doing on the second task when they are doing it, and on the third task we talk about their intended implementation and the review of their code.  - goal: code orientation and setting expectations for their work.

I have also used it as a training technique, where someone is being introduced to a new technique.  In this case, they would be introduced to the concept away from the keyboard and then a few hours or a couple of days later, we would pair program the design phase, and they would be the lead programmer doing the implementation, with me providing guidance where needed. - goal: introducing multi threaded code / async callbacks and producing something productive in a shortish period of time.

Body:
I am familiar with Agile and Pair Programming (http://en.wikipedia.org/wiki/Pair_programming).  I thought Pair Programming was used if there was a complex requirement i.e. two sets of eyes is better than one.

Is Pair Programming also used to train less experienced developers and bring them up to speed?

Also, how often is it used e.g. all the time i.e. the two developers will work together at one screen permanently or perhaps one day per week? I have read an Agile book, which talks about this concept but it does not mention frequency of use.


问:
Is Ruby on Rails supposed to have a steep learning curve or is it just me?
I'm a self-taught programmer. I've been learning RoR since October with varying intensity (sometimes all day, sometimes nothing for several weeks). Before that I knew only Java, but knew it pretty well. I've heard so much hype about RoR and how it's supposed to make you happy, productive, etc. So far it's only made me frustrated.  I learned it out of the Agile book, and I suspect part of the difficulty might have to do with my not knowing JavaScript and CSS, and having only a shaky grasp of databases and HTML. But apparently it took me much longer to complete the project in the Agile book than other people, and I still don't remember much of it. There are some things about Rails that I just can't seem to get, e.g. when to use symbols and when NOT to, or how dynamic methods are called.

Recently I was given a small Rails assignment where I'm asked to make a small change to the interface. It's taken me around 25 hours and although I've made some progress in understanding the code, I still have no idea how to proceed. I can't even ask Stack Overflow because there is so much code I'll have to provide to give context.

So my question is in the title: is RoR supposed to take a long time to learn or am I just slow? Can it be that I've been learning from the wrong book? My learning style is such that I either understand nothing or understand everything, if that makes sense.

答:
Your words, "sometimes all day, sometimes nothing for several weeks" tell me all I need to know.  If you're learning a new language AND framework (I assume that's what you're doing because you mention "Ruby on Rails" and not just "Ruby"), consistency pays off.  I have found the only way I learn and retain concepts is to study around a half-hour per day, usually at the end of the day, just before bedtime.  If i study more than a half-hour, I get fidgety and lose focus.  If I study less, I don't retain what I've learned.

Eliminate distractions - that's my best advice.  And study every single day of the week.  Before you know it, things will start to fall into place.

I didn't see any follow-up posts, so I'm wondering how you've done.  It's been 2 years, and that should certainly be plenty of time to learn to be a top-shelf web developer!


问:
How to Implement Error Handling
Even though I've programmed on a professional level for some years I still do not fully understand error handling. Although my applications work fine, the error handling isn't implemented at a professional level and is a mix and match of a number of techniques.

There is no structure behind my error handling. I'd like to learn and understand how it's implemented at a professional level. This is one area where I lack knowledge.

When should I use an exceptions and when should I return a success status, to be checked in the logic flow? Is it OK to mix exception and returning a status?

I code in C# mainly.

答:
Use exceptions for exceptional things, the things you can't reasonably expect to encounter too often, things which indicate that something goes wrong. For example, if the network is down, it is an exceptional thing for a web server. If the database is unavailable, it means that something is wrong. If the configuration file is missing, it probably means that the user messed up with it.

Don't use exceptions to handle incorrect code. In order to check the correctness of the code, you should use either the assertions, or, in .NET Framework 4 and later, Code contracts (which replace assertions and have additional, particularly valuable features).

Don't use exceptions in non-exceptional cases. The fact that the user, when asked to enter a number, entered "dog" is not so exceptional to deserve an exception.

Be careful when choosing the types of exceptions. Create your own types when needed. Carefully chose the inheritance, keeping in mind that catching parents will catch the children as well. Never throw Exception.

Don't use return codes for errors. Error codes are easily masked, ignored, forgotten. If there is a error, either handle it, or propagate it to the upper stack.

In cases where a method is expected to return a error and the error is not exceptional, use enums, never error numbers. Example:

```<code>// Note that the operation fails pretty often, since it deals with the servers which are
// frequently unavailable, and the ones which send garbage instead of the actual data.
private LoadOperationResult LoadProductsFromWeb()
{
    ...
}
</code>```

The meaning of LoadOperationResult.ServerUnavailable, LoadOperationResult.ParsingError, etc. is much more explicit than, say, remembering that code 12 means that the server is down, and code 13 — that the data cannot be parsed.

Use error codes when they refer to the common ones, known by every developer who works in the specific domain. For example, don't reinvent an enum value for HTTP 404 Not Found or HTTP 500 Internal Server Error.

Beware of booleans. Sooner or later, you will want to know not only whether a specific method succeeded or failed, but why. Exceptions and enums are much more powerful for that.

Don't catch every exception (unless you're at the very top of the stack). If you catch an exception, you should be ready to handle it. Catching everything is showing that you don't care if your code runs correctly. This may solve the "I don't want to search right now how to fix this", but will hurt you sooner or later.

In C#, never rethrow exceptions like this:

```<code>catch (SomeException ex)
{
    ...
    throw ex;
}
</code>```

because you're breaking the stack. Do this instead:

```<code>catch (SomeException)
{
    ...
    throw;
}
</code>```

Make an effort when writing exception messages. How many times I've seen something like throw Exception("wrong data") or throw Exception("shouldn't call this method in this context"). Other developers, including yourself six months later, would have no idea what data is wrong and why or why shouldn't we call some method in a context, nor which context precisely.

Don't show exception messages to the user. They are not expected for ordinary people, and often are even unreadable for developers themselves.

Don't localize exception messages. Searching the documentation for a localized message is exhausting and pointless: every message should be in English and English only.

Don't focus exclusively on exceptions and errors: logs are also extremely important.

In .NET, don't forget to include exceptions in XML documentation of the method:

```<code>/// <exception cref="MyException">Description of the exception</exception>
</code>```

Including exceptions in XML documentation makes things much easier for the person who is using the library. There is nothing more annoying than trying to guess which exception could be possibly thrown by a method and why.

In this sense¹, Java exception handling provides a stricter, better approach. It forces you to either deal with exceptions potentially thrown by the called methods, or declare in your own method that it can throw the exceptions you don't handle, making things particularly transparent.

¹ This being said, I find Java distinction between exceptions and errors pretty useless and confusing, given that the language has checked and unchecked exceptions. Luckily, .NET Framework has only exceptions, and no errors.

Title: How to Implement Error Handling

Body:
Use exceptions for exceptional things, the things you can't reasonably expect to encounter too often, things which indicate that something goes wrong. For example, if the network is down, it is an exceptional thing for a web server. If the database is unavailable, it means that something is wrong. If the configuration file is missing, it probably means that the user messed up with it.

Don't use exceptions to handle incorrect code. In order to check the correctness of the code, you should use either the assertions, or, in .NET Framework 4 and later, Code contracts (which replace assertions and have additional, particularly valuable features).

Don't use exceptions in non-exceptional cases. The fact that the user, when asked to enter a number, entered "dog" is not so exceptional to deserve an exception.

Be careful when choosing the types of exceptions. Create your own types when needed. Carefully chose the inheritance, keeping in mind that catching parents will catch the children as well. Never throw Exception.

Don't use return codes for errors. Error codes are easily masked, ignored, forgotten. If there is a error, either handle it, or propagate it to the upper stack.

In cases where a method is expected to return a error and the error is not exceptional, use enums, never error numbers. Example:

// Note that the operation fails pretty often, since it deals with the servers which are
// frequently unavailable, and the ones which send garbage instead of the actual data.
private LoadOperationResult LoadProductsFromWeb()
{
    ...
}

The meaning of LoadOperationResult.ServerUnavailable, LoadOperationResult.ParsingError, etc. is much more explicit than, say, remembering that code 12 means that the server is down, and code 13 — that the data cannot be parsed.

Use error codes when they refer to the common ones, known by every developer who works in the specific domain. For example, don't reinvent an enum value for HTTP 404 Not Found or HTTP 500 Internal Server Error.

Beware of booleans. Sooner or later, you will want to know not only whether a specific method succeeded or failed, but why. Exceptions and enums are much more powerful for that.

Don't catch every exception (unless you're at the very top of the stack). If you catch an exception, you should be ready to handle it. Catching everything is showing that you don't care if your code runs correctly. This may solve the "I don't want to search right now how to fix this", but will hurt you sooner or later.

In C#, never rethrow exceptions like this:

catch (SomeException ex)
{
    ...
    throw ex;
}

because you're breaking the stack. Do this instead:

catch (SomeException)
{
    ...
    throw;
}

Make an effort when writing exception messages. How many times I've seen something like throw Exception("wrong data") or throw Exception("shouldn't call this method in this context"). Other developers, including yourself six months later, would have no idea what data is wrong and why or why shouldn't we call some method in a context, nor which context precisely.

Don't show exception messages to the user. They are not expected for ordinary people, and often are even unreadable for developers themselves.

Don't localize exception messages. Searching the documentation for a localized message is exhausting and pointless: every message should be in English and English only.

Don't focus exclusively on exceptions and errors: logs are also extremely important.

In .NET, don't forget to include exceptions in XML documentation of the method:

/// <exception cref="MyException">Description of the exception</exception>

Including exceptions in XML documentation makes things much easier for the person who is using the library. There is nothing more annoying than trying to guess which exception could be possibly thrown by a method and why.

In this sense¹, Java exception handling provides a stricter, better approach. It forces you to either deal with exceptions potentially thrown by the called methods, or declare in your own method that it can throw the exceptions you don't handle, making things particularly transparent.

¹ This being said, I find Java distinction between exceptions and errors pretty useless and confusing, given that the language has checked and unchecked exceptions. Luckily, .NET Framework has only exceptions, and no errors.


问:
Is blocking an entire web-client due to compatibility a reasonable request?
A little bit of background, we've made an electronic POS system for registered vendors of items of a well known brand. The vendors are required to login to use the system.

Recently, IE has been giving us lots of painful maintenance problems than before. Our boss is getting worried about running into further maintenance problems, so he has asked me to find out a way to automatically install & launch chrome if they try to login with any other browsers (For the record, nearly all of the issues are related to some feature working fine on FF/Chrome/Opera/Safari but doesn't on IE).

Let us put aside the ridiculousness of running an external .exe from Javascript, which is practically impossible (And rightfully, I told him so. But he insisted it was possible, so whatever).

So my questions are:

Is this request technically viable? Is there a guaranteed way to block requests from all browsers except for allowed ones?

Is this request reasonable? IMO, From the standpoint of users, limiting accessibility does more harm than good, but maintenance issue is definitely a valid business concern.

Has there ever been a case like this where other websites explicitly blocked certain browsers?

Edit: Thanks for the answers. We're supporting IE 7+ at the moment and indeed, 7/8 were the ones that caused most of the grief. Just dropping those two will make maintenance significantly easier but my boss thinks the problem has to do with IE itself, not necessarily the versions. I'm going to try to see if I can convince him, but I have a strong feeling he's going to stick by what he thinks.

答:
The standard way to identify the client browser being used is the USER AGENT string. However, web browsers are known to lie, and a general principle of server implementation should be that you never trust the client with anything. EVER.

So in answer to point one, can you be 100% sure what client browser is being used? No. But you can make educated guesses, and validate those guesses by passing javascript to the client to test those guesses.

In point two. As a user, if a website ran a different program on my machine with no warning I would be extremely unhappy.  Redirecting the web browser to a page stating that the website was not compatible with IE, and suggesting that I point chrome / firefox would raise an eyebrow, but would be just about acceptable to me as a user.

In point 3, Yes there have been, and still are cases where websites and web applications are not compatible with certain web browsers. perhaps 10 years ago, it was common for banking websites to block clients with FireFox User agent strings, so I used to get firefox to send in Explorer UA strings for that site.  More recently, new releases of Explorer tend not to work on a wide range of sites. (hence compatibility mode in IE to allow it to work whilst everyone updates their websites).

The problem historically has been because Microsoft has been fairly poor at implementing standards.  Every attempt by microsoft to move closer to the standards breaks the web experience, because the websites present pages designed for the broken old browser.  These days, issues tend to be more to do with the JavaScript api for the bowers varying.


问:
What justifies the use of an IDE versus a standard editor?
I find myself using my text editor of choice (vim, nano, gedit, pick your poison) much more often than any IDE as of late.

After noticing my ide shortcuts getting dusty I started to think about this and wonder: what justifies use of an IDE for you opposed to a text editor?

For that matter what rationale would you have for not using an IDE and merely relying on an editor?

答:
These are my favorite features of my favorite IDE, IntelliJ, which I like using for Java, PHP, Javascript, HTML, even ActionScript.

Error checking - Like live spell check for code. Absolutely essential.

Code navigation - Ctrl+click on a function, variable, type to go to the definition. (IntelliJ is very good at this in all of the above languages)

Code completion - I use Ctrl+space constantly to help fill in the class or method name that I need.  This speeds up coding a ton, and even helps catch bugs before they happen when something you needed is not accessible from the context you are in.  IntelliJ will even help you expand acronyms - type NPE, hit Ctrl+space, and it will show "NullPointerException", "NoPageError", etc.  Hitting Alt+enter to automatically add the import is really nice too.

Code generation - Generate getters and setters, implement methods from an interface with a couple clicks.

Very good code coloring - IntelliJ not only does the standard keyword, string, variable name coloring, but also colors member variables, local variables, parameters.  In ActionScript a variable that is actually a setter/getter will be colored like a function.

Refactoring - Mistake-free renaming is the biggest. IntelliJ is very good at renaming even setters and getters or string usages.  Of course there is regex-based search and replace when you need it, and a "preserve case" option to enable you to replace "myNumber", "MyNumber" and "MYNUMBER" with "myString", "MyString" and "MYSTRING" in one operation

Version control integration - We use SVN, and my favorite IDE VC features are being able to create, delete, move classes without thinking about SVN, easily browsing history, a very good diff tool, good merging capability, and annotating files (showing line-by-line history) in the editor.

Dependency importing - When relying on a third party library that you have the source for, you can navigate to the code easily for reference, debugging, etc.

Smart typing - pasting code and having it automatically paste to the right tab position, auto completion of end-brackets, parentheses, quotes, etc.

A very good Test runner for JUnit, FlexUnit, PHPUnit

Debugging - of course. Debugs JBoss, Jetty, even Flash flawlessly.  Ctrl+click stack traces to go right to the code.

Things like the code coloring you might take for granted, but good code coloring is like peripheral vision - it allows you to focus on the important stuff without taking that split-second extra to identify the full word.

IntelliJ also even uses Ctrl+space to suggest variable names.  In Java, if you declare a new EventMessageItem variable and hit Ctrl+space, it will suggest "eventMessageItem", "eventMessage", "item", etc.

All of these things give me way more time to think about my code and architecture, and think less about fixing formatting, dealing with the file system, fixing copy-and-paste errors, switching between applications, chasing down documentation, etc. etc.  I don't know how you can say no to that kind of productivity increase.


问:
How can I organize my data flow to process a good program solution?
My main problem when trying to form a program is that while I have the tools at my disposal, I am too disorganized to properly use them to solve my problems.  Often my process is simply trial and error until the program works.

I am looking to see what others use to organize the process of writing programs.

答:
Recognizing that there's a better way than trial & error is the first step.

I usually start with paper & pencil.  I get a rough sense of what the client's asking for and sketch out the User Experience.  I need to know what the user needs to see, what they need to do, etc.  For larger projects, this would evolve into Requirements docs, Functional specifications, a Vision, etc.  I'd also identify user stories on a per-Role basis.

My next step is to look at where the data comes from, how I'm going to store it, what manipulations (if any) I need to do on it, etc.  This includes both in-memory storage and database (not every program requires a database).  Data structures are your friend.  Picking the right data organization will make the difference between a program that's a joy to use & one that's barely tolerable.

Program organization comes next - what objects do I have, how do they communicate, how do I segregate functionality so I separate stuff that changes from stuff that doesn't, how do I keep things DRY, etc.

There are some canned designs (such as model-view-controller) that can be useful.  The trick is knowing when the designs are appropriate and when they aren't so you don't suffer from hammer syndrome.

Right before I start coding I take a final look at my plan and look for things to remove.  There's a term for this -- "YAGNI".  Also, remember - you don't have to fix any features you leave out.

At this point I have the start of a plan - when I sit down at the keyboard I have an idea of what I'm trying to accomplish.

You might also want to read up on Test Driven Development - it's a very good technique, but not by itself an answer to your question.


问:
CA1819: Properties should not return arrays. Does this happen only with arrays? If yes, why?
I have a question about CA1819 msdn performance warning.

The rule is: Arrays returned by properties are not write-protected, even if the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. Specifically, they might use the property as an indexed property.

I understand the rule.

I want to know if this happens only with arrays? If yes, why?

答:
Arrays are reference types. That is when a property returns an array object it's returning a pointer/reference to it's internal array. The caller of the property can now modify that internal array (as they have a pointer to it), this is generally unwanted. To stop this you can return a copy of the internal array but now your doing a memory allocation and copy every time the property is used, and given that properties are meant to be light-weight that's not good.

This happens with any reference type that is mutable. If you have a private reference to a mutable reference type (Like a Stream, List or Dictionary) and you return that reference in a property than the caller can modify your data. If you have a value type (structs in C#) than they are always copied when they're returned from the property so the caller can't then modify your internal version of the data.


问:
can I use XML for AJAX in a website created using HTML5
I am new to web programming and just started learning XML and AJAX. I am creating a social gaming website for my college project. I am confused at the point of using XML for AJAX in HTML5. As XHTML is replaced by HTML5 so is it ok to use XML or i should choose JSON (i know nothing about JSON but it is what I found in answers on web to the question related to choice between JSON and XML). My preference is XML because it is in my syllabus but I want to make sure that XML and HTML5 will not conflict. </p>

答:
You can encode the data sent to the server in any format you want and not interfere with the web page's standards.

The idiomatic thing to do is to just use JSON these days, but that is up to you.

It's also important to note that if you use a non HTML5 tag, the police aren't going to show up at your door and, unless your professor validates your site using a tool, he probably won't notice and it will render just fine.

Certain things in your page like
 being more HTML5 compatible than
 will break XML compatibility, if that's what your asking. But the standard still leaves a clause allowing full XML compatibility in order to allow any page to comply with XML, AFAIK.  Though, from the discussion in that thread, this is explicitly for backwards compatibility purposes with the older HTML standards.

Body:
You can encode the data sent to the server in any format you want and not interfere with the web page's standards.

The idiomatic thing to do is to just use JSON these days, but that is up to you.

It's also important to note that if you use a non HTML5 tag, the police aren't going to show up at your door and, unless your professor validates your site using a tool, he probably won't notice and it will render just fine.

Certain things in your page like <br> being more HTML5 compatible than <br/> will break XML compatibility, if that's what your asking. But the standard still leaves a clause allowing full XML compatibility in order to allow any page to comply with XML, AFAIK.  Though, from the discussion in that thread, this is explicitly for backwards compatibility purposes with the older HTML standards.


答:
Well, first off, .net has introduced IReadOnlyList and IReadOnlyDictionary which address this problem for generics(which is preferable to a base array), previously you would have to had created your own interface in order to see the same performance with the same restriction.

The basic problem, and no, it's not limited to arrays, is that you want to provide a method of accessing a bunch of items without requiring that they be iterated, but you don't want the consumer of your API to be adding or deleting items -- but previously all of the built in interfaces that allow what you want, also allowed what you don't want.

The suggested solution is both inefficient (creating a clone is slow) and misleading -- the consumer gets an array that he thinks he can modify and have that effect the object that returned it.  Ie he thinks if he adds an element and then calls the property again, he will get an array with p+1 items.  He also expects that o.ItemArray.Equals(o.ItemArray).  Neither of these expectations will be true.

As a practical problem, this is no longer a problem if you can use the right version of the framework and something other than an array.

As for the performance problem...

```<code>if(o.ItemArray.Equals(o.ItemArray) || o.ItemArray.Equals(o2.ItemArray))
</code>```

Creates 4 copies of a potentially large array.

Edit in response to comment:

This is not a problem specific to Arrays. List and Dictionaries are also mutable.

```<code>IList<string> lst = new List<string>();
lst.Add("hello");
lst[0]="bye";
Console.WriteLine(lst[0]);
</code>```

And the above code sample shows the problems with mutable list as properties.  Suppose that I had a class, Greetings, which had a list of words and phrases that you would use upon meeting someone.  Hello, Hi, Hola, Hey dude, Whats up! Como esta and so forth.  So, I have a property Words, and return the above lst.  You can then immediately execute the 3rd line and change my "hello" to "bye" --for everyone that has a reference to that instance of the class.

But as I said, in 4.5, you would get around this by having your list be IReadOnlyLst and, using this...

```<code>return (IReadOnlyList<string>) lst;
</code>```

Title: CA1819: Properties should not return arrays. Does this happen only with arrays? If yes, why?

Body:
I have a question about CA1819 msdn performance warning.

The rule is: Arrays returned by properties are not write-protected, even if the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property. Specifically, they might use the property as an indexed property.

I understand the rule.

I want to know if this happens only with arrays? If yes, why?

Body:
Well, first off, .net has introduced IReadOnlyList and IReadOnlyDictionary which address this problem for generics(which is preferable to a base array), previously you would have to had created your own interface in order to see the same performance with the same restriction.

The basic problem, and no, it's not limited to arrays, is that you want to provide a method of accessing a bunch of items without requiring that they be iterated, but you don't want the consumer of your API to be adding or deleting items -- but previously all of the built in interfaces that allow what you want, also allowed what you don't want.

The suggested solution is both inefficient (creating a clone is slow) and misleading -- the consumer gets an array that he thinks he can modify and have that effect the object that returned it.  Ie he thinks if he adds an element and then calls the property again, he will get an array with p+1 items.  He also expects that o.ItemArray.Equals(o.ItemArray).  Neither of these expectations will be true.

As a practical problem, this is no longer a problem if you can use the right version of the framework and something other than an array.

As for the performance problem...

if(o.ItemArray.Equals(o.ItemArray) || o.ItemArray.Equals(o2.ItemArray))

Creates 4 copies of a potentially large array.

Edit in response to comment:

This is not a problem specific to Arrays. List and Dictionaries are also mutable.

IList<string> lst = new List<string>();
lst.Add("hello");
lst[0]="bye";
Console.WriteLine(lst[0]);

And the above code sample shows the problems with mutable list as properties.  Suppose that I had a class, Greetings, which had a list of words and phrases that you would use upon meeting someone.  Hello, Hi, Hola, Hey dude, Whats up! Como esta and so forth.  So, I have a property Words, and return the above lst.  You can then immediately execute the 3rd line and change my "hello" to "bye" --for everyone that has a reference to that instance of the class.

But as I said, in 4.5, you would get around this by having your list be IReadOnlyLst and, using this...

return (IReadOnlyList<string>) lst;


问:
Storing different algorithms and using them for demonstration
I have an app for creating simple graphs (the kind with vertices and edges) and then using different algorithms on them (BFS, DFS, topsort, Prim's etc) for demonstrating how they work.

I'm now working on porting it into a Rails app and deploying so it can be used by my university (hopefully).

Currently the graphs are stored in a SQLite db and I am planning to do some D3 magic on them.

Then to the real problem, how should I implement and store the algorithms?

I want to be able to "step" through the algorithm, showing step by step how it works on the graph. In my previous implementation, written in Java, I had an abstract Algorithm class with abstract methods like init, step and reset. But, now that we are out of the Java world and using wonderful Ruby, I have a feeling that there's a really clever and elegant way achieving the same.

I am planning to pack it into a Rails engine, just for kicks.

Here is the mentioned Java implementation: https://github.com/7SLEVIN/visualgraphalgs

答:
This sounds like a state machine to me.  You've got a graph (V,E) and a current traversal state S (been a while since my algorithms classes but I'm guessing this is a recursive stepping-through of various exploration options) including a handle to your given currently selected strategy (i.e. your graph traversal algorithm).

There's a nice ruby gem called state_machine that could give you the framework you need to move through states like Initial -> In Progress (repeat as needed) -> Completed

The key here will be figuring out a way to - from within the In Progress state - serialize the current details of your traversal so that it can be paused indefinitely while you show it off in the browser and then restarted on demand in order to execute the next step.  This is a lot like stepping through breakpoints in a debugger, except you'll likely be implementing a lot of that by hand rather than relying on a real debugger.


答:
I've seen browser detection code that tries to access various Things in javascript/the DOM and catch failures.  Based on the particular failures caught, the code then sets global variables indicating what kind of browser is in use, and then decisions can be made.

Instead of force-installing chrome, you could try telling clients to enable compatibility mode in IE, with clear directions on how to do that.  Or maybe (better) put the right doctype attribute on the HTML tag itself, which should automatically cause IE to enter the right mode.  Do a little research on IE and doctype attributes.  (Not being snarky, I'm just too rushed at the moment to do it myself, although I have in the past.)

Wait, here ya go:

http://msdn.microsoft.com/library/cc288325(v=vs.85).aspx
http://www.w3schools.com/tags/tag_doctype.asp

and here:

http://www.quirksmode.org/js/support.html

(Research is fun!)

Title: Is blocking an entire web-client due to compatibility a reasonable request?

Body:
A little bit of background, we've made an electronic POS system for registered vendors of items of a well known brand. The vendors are required to login to use the system.

Recently, IE has been giving us lots of painful maintenance problems than before. Our boss is getting worried about running into further maintenance problems, so he has asked me to find out a way to automatically install & launch chrome if they try to login with any other browsers (For the record, nearly all of the issues are related to some feature working fine on FF/Chrome/Opera/Safari but doesn't on IE).

Let us put aside the ridiculousness of running an external .exe from Javascript, which is practically impossible (And rightfully, I told him so. But he insisted it was possible, so whatever).

So my questions are:

Is this request technically viable? Is there a guaranteed way to block requests from all browsers except for allowed ones?

Is this request reasonable? IMO, From the standpoint of users, limiting accessibility does more harm than good, but maintenance issue is definitely a valid business concern.

Has there ever been a case like this where other websites explicitly blocked certain browsers?

Edit: Thanks for the answers. We're supporting IE 7+ at the moment and indeed, 7/8 were the ones that caused most of the grief. Just dropping those two will make maintenance significantly easier but my boss thinks the problem has to do with IE itself, not necessarily the versions. I'm going to try to see if I can convince him, but I have a strong feeling he's going to stick by what he thinks.