tag:blogger.com,1999:blog-32447580519014222072024-03-12T17:23:26.692-07:00TechyAnonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.comBlogger21125tag:blogger.com,1999:blog-3244758051901422207.post-73671986964583176962015-08-07T00:34:00.001-07:002015-12-25T12:38:43.057-08:00Swap ctrl and alt keys in Windows for Emacs users<h2>
<span style="color: red;">this article has been permanently moved to<a href="https://blog.xixiao.info/2015/12/23/swap-ctrl-and-alt-key/"> my new blog </a></span></h2>
Xi Xiaohttp://www.blogger.com/profile/16472665573680581983noreply@blogger.com2tag:blogger.com,1999:blog-3244758051901422207.post-85282869101476740612015-08-04T07:19:00.000-07:002015-08-10T14:17:13.966-07:00git commands fundamentals<div dir="ltr" style="text-align: left;" trbidi="on">
<div>
<br /></div>
<div>
What I have learned as Git basic commands</div>
<ul style="text-align: left;">
<li>git init</li>
<li>git log</li>
<li>git status</li>
<li>git add </li>
<li>git add -u</li>
<li>git commit -m "message for comming"</li>
<li>git diff HEAD~1..</li>
<li>git diff <#hash code>..<#hash code></li>
<li>git clean (it is to delete files from system!)</li>
<li>.gitignore</li>
<li>git log origin/master</li>
<li>git branch -r</li>
<li>git pull origin branch</li>
<li>git commit -am "commit" (no need to use "git add" as separate step)</li>
<li>git tag -a | git tag -s</li>
<li>git config --global alias.lga "log --graph --oneline --all --decorate"</li>
<li>git reflog (2nd trash bin - 30days by default only)</li>
<li>git stash | git stash list | git stash apply | git stash pop | git stash branch new_branch_for_stash(half way work, nor do want to commit, nor want to lose the modification)</li>
<li>git checkout (go to a branch or fetch latest file version)</li>
<li>git checkout master ; git merge feature1 (merge feature1 into master branch)</li>
<li>git diff --cached (compare repo and staging area)</li>
<li>git rebase (rebase the branches created from, conflicts might occur)</li>
<li>git cherry-pick (allow one commit and merge into)</li>
<li>git push origin master:new_branch (push master branch's changes up to origin's new_branch branch, ":new_branch" is optional if the branch name is the same as local branch)</li>
<li>git push origin :remote_branch_name (<b>delete remote branch</b> should be done with caution, because other people might be working on top of it)</li>
<li>git log -p -1 <file or path> or git log -p <file or path></li>
</ul>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-35821799114051986592015-08-03T11:16:00.005-07:002015-08-03T11:16:45.690-07:00linux diff command<div dir="ltr" style="text-align: left;" trbidi="on">
a good article for diff command output interpreting.<br />
referenced from: <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC11">here</a><br />
<br />
<br />
<hr />
<br />
<h1>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC10" name="SEC10"><code>diff</code> Output Formats</a></h1>
<a href="https://www.blogger.com/null" name="IDX13"></a><a href="https://www.blogger.com/null" name="IDX14"></a><br />
<code>diff</code> has several mutually exclusive options for output format. The following sections describe each format, illustrating how <code>diff</code> reports the differences between two sample input files.<br />
<h2>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC11" name="SEC11">Two Sample Input Files</a></h2>
<a href="https://www.blogger.com/null" name="IDX15"></a><a href="https://www.blogger.com/null" name="IDX16"></a><br />
Here are two sample files that we will use in numerous examples to illustrate the output of <code>diff</code> and how various options can change it.<br />
This is the file <tt>`lao'</tt>:<br />
<pre>The Way that can be told of is not the eternal Way;
The name that can be named is not the eternal name.
The Nameless is the origin of Heaven and Earth;
The Named is the mother of all things.
Therefore let there always be non-being,
so we may see their subtlety,
And let there always be being,
so we may see their outcome.
The two are the same,
But after they are produced,
they have different names.
</pre>
This is the file <tt>`tzu'</tt>:<br />
<pre>The Nameless is the origin of Heaven and Earth;
The named is the mother of all things.
Therefore let there always be non-being,
so we may see their subtlety,
And let there always be being,
so we may see their outcome.
The two are the same,
But after they are produced,
they have different names.
They both may be called deep and profound.
Deeper and more profound,
The door of all subtleties!
</pre>
In this example, the first hunk contains just the first two lines of <tt>`lao'</tt>, the second hunk contains the fourth line of <tt>`lao'</tt> opposing the second and third lines of <tt>`tzu'</tt>, and the last hunk contains just the last three lines of <tt>`tzu'</tt>.<br />
<h2>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC12" name="SEC12">Showing Differences Without Context</a></h2>
<a href="https://www.blogger.com/null" name="IDX17"></a><a href="https://www.blogger.com/null" name="IDX18"></a><br />
The "normal" <code>diff</code> output format shows each hunk of differences without any surrounding context. Sometimes such output is the clearest way to see how lines have changed, without the clutter of nearby unchanged lines (although you can get similar results with the context or unified formats by using 0 lines of context). However, this format is no longer widely used for sending out patches; for that purpose, the context format (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC16">Context Format</a>) and the unified format (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC20">Unified Format</a>) are superior. Normal format is the default for compatibility with older versions of <code>diff</code> and the Posix standard.<br />
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC13" name="SEC13">Detailed Description of Normal Format</a></h3>
The normal output format consists of one or more hunks of differences; each hunk shows one area where the files differ. Normal format hunks look like this:<br />
<pre><var>change-command</var>
< <var>from-file-line</var>
< <var>from-file-line</var>...
---
> <var>to-file-line</var>
> <var>to-file-line</var>...
</pre>
There are three types of change commands. Each consists of a line number or comma-separated range of lines in the first file, a single character indicating the kind of change to make, and a line number or comma-separated range of lines in the second file. All line numbers are the original line numbers in each file. The types of change commands are:<br />
<dl compact="">
<dt><samp>`<var>l</var>a<var>r</var>'</samp></dt>
<dd>Add the lines in range <var>r</var> of the second file after line <var>l</var> of the first file. For example, <samp>`8a12,15'</samp> means append lines 12--15 of file 2 after line 8 of file 1; or, if changing file 2 into file 1, delete lines 12--15 of file 2.</dd>
<dt><samp>`<var>f</var>c<var>t</var>'</samp></dt>
<dd>Replace the lines in range <var>f</var> of the first file with lines in range <var>t</var> of the second file. This is like a combined add and delete, but more compact. For example, <samp>`5,7c8,10'</samp> means change lines 5--7 of file 1 to read as lines 8--10 of file 2; or, if changing file 2 into file 1, change lines 8--10 of file 2 to read as lines 5--7 of file 1.</dd>
<dt><samp>`<var>r</var>d<var>l</var>'</samp></dt>
<dd>Delete the lines in range <var>r</var> from the first file; line <var>l</var> is where they would have appeared in the second file had they not been deleted. For example, <samp>`5,7d3'</samp> means delete lines 5--7 of file 1; or, if changing file 2 into file 1, append lines 5--7 of file 1 after line 3 of file 2.</dd></dl>
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC14" name="SEC14">An Example of Normal Format</a></h3>
Here is the output of the command <samp>`diff lao tzu'</samp> (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC11">Two Sample Input Files</a>, for the complete contents of the two files). Notice that it shows only the lines that are different between the two files.<br />
<pre>1,2d0
< The Way that can be told of is not the eternal Way;
< The name that can be named is not the eternal name.
4c2,3
< The Named is the mother of all things.
---
> The named is the mother of all things.
>
11a11,13
> They both may be called deep and profound.
> Deeper and more profound,
> The door of all subtleties!
</pre>
<h2>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC15" name="SEC15">Showing Differences in Their Context</a></h2>
<a href="https://www.blogger.com/null" name="IDX19"></a><a href="https://www.blogger.com/null" name="IDX20"></a><br />
Usually, when you are looking at the differences between files, you will also want to see the parts of the files near the lines that differ, to help you understand exactly what has changed. These nearby parts of the files are called the <strong>context</strong>.<br />
GNU <code>diff</code> provides two output formats that show context around the differing lines: <strong>context format</strong> and <strong>unified format</strong>. It can optionally show in which function or section of the file the differing lines are found.<br />
If you are distributing new versions of files to other people in the form of <code>diff</code> output, you should use one of the output formats that show context so that they can apply the diffs even if they have made small changes of their own to the files. <code>patch</code> can apply the diffs in this case by searching in the files for the lines of context around the differing lines; if those lines are actually a few lines away from where the diff says they are, <code>patch</code> can adjust the line numbers accordingly and still apply the diff correctly. See section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_10.html#SEC62">Applying Imperfect Patches</a>, for more information on using <code>patch</code>to apply imperfect diffs.<br />
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC16" name="SEC16">Context Format</a></h3>
The context output format shows several lines of context around the lines that differ. It is the standard format for distributing updates to source code.<br />
To select this output format, use the <samp>`-C <var>lines</var>'</samp>, <samp>`--context[=<var>lines</var>]'</samp>, or <samp>`-c'</samp> option. The argument <var>lines</var> that some of these options take is the number of lines of context to show. If you do not specify <var>lines</var>, it defaults to three. For proper operation, <code>patch</code> typically needs at least two lines of context.<br />
<h4>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC17" name="SEC17">Detailed Description of Context Format</a></h4>
The context output format starts with a two-line header, which looks like this:<br />
<pre>*** <var>from-file</var> <var>from-file-modification-time</var>
--- <var>to-file</var> <var>to-file-modification time</var>
</pre>
You can change the header's content with the <samp>`-L <var>label</var>'</samp> or <samp>`--label=<var>label</var>'</samp> option; see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC26">Showing Alternate File Names</a>.<br />
Next come one or more hunks of differences; each hunk shows one area where the files differ. Context format hunks look like this:<br />
<pre>***************
*** <var>from-file-line-range</var> ****
<var>from-file-line</var>
<var>from-file-line</var>...
--- <var>to-file-line-range</var> ----
<var>to-file-line</var>
<var>to-file-line</var>...
</pre>
The lines of context around the lines that differ start with two space characters. The lines that differ between the two files start with one of the following indicator characters, followed by a space character:<br />
<dl compact="">
<dt><samp>`!'</samp></dt>
<dd>A line that is part of a group of one or more lines that changed between the two files. There is a corresponding group of lines marked with <samp>`!'</samp> in the part of this hunk for the other file.</dd>
<dt><samp>`+'</samp></dt>
<dd>An "inserted" line in the second file that corresponds to nothing in the first file.</dd>
<dt><samp>`-'</samp></dt>
<dd>A "deleted" line in the first file that corresponds to nothing in the second file.</dd></dl>
If all of the changes in a hunk are insertions, the lines of <var>from-file</var> are omitted. If all of the changes are deletions, the lines of <var>to-file</var> are omitted.<br />
<h4>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC18" name="SEC18">An Example of Context Format</a></h4>
Here is the output of <samp>`diff -c lao tzu'</samp> (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC11">Two Sample Input Files</a>, for the complete contents of the two files). Notice that up to three lines that are not different are shown around each line that is different; they are the context lines. Also notice that the first two hunks have run together, because their contents overlap.<br />
<pre>*** lao Sat Jan 26 23:30:39 1991
--- tzu Sat Jan 26 23:30:50 1991
***************
*** 1,7 ****
- The Way that can be told of is not the eternal Way;
- The name that can be named is not the eternal name.
The Nameless is the origin of Heaven and Earth;
! The Named is the mother of all things.
Therefore let there always be non-being,
so we may see their subtlety,
And let there always be being,
--- 1,6 ----
The Nameless is the origin of Heaven and Earth;
! The named is the mother of all things.
!
Therefore let there always be non-being,
so we may see their subtlety,
And let there always be being,
***************
*** 9,11 ****
--- 8,13 ----
The two are the same,
But after they are produced,
they have different names.
+ They both may be called deep and profound.
+ Deeper and more profound,
+ The door of all subtleties!
</pre>
<h4>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC19" name="SEC19">An Example of Context Format with Less Context</a></h4>
Here is the output of <samp>`diff --context=1 lao tzu'</samp> (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC11">Two Sample Input Files</a>, for the complete contents of the two files). Notice that at most one context line is reported here.<br />
<pre>*** lao Sat Jan 26 23:30:39 1991
--- tzu Sat Jan 26 23:30:50 1991
***************
*** 1,5 ****
- The Way that can be told of is not the eternal Way;
- The name that can be named is not the eternal name.
The Nameless is the origin of Heaven and Earth;
! The Named is the mother of all things.
Therefore let there always be non-being,
--- 1,4 ----
The Nameless is the origin of Heaven and Earth;
! The named is the mother of all things.
!
Therefore let there always be non-being,
***************
*** 11 ****
--- 10,13 ----
they have different names.
+ They both may be called deep and profound.
+ Deeper and more profound,
+ The door of all subtleties!
</pre>
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC20" name="SEC20">Unified Format</a></h3>
<a href="https://www.blogger.com/null" name="IDX21"></a><a href="https://www.blogger.com/null" name="IDX22"></a><br />
The unified output format is a variation on the context format that is more compact because it omits redundant context lines. To select this output format, use the <samp>`-U <var>lines</var>'</samp>, <samp>`--unified[=<var>lines</var>]'</samp>, or <samp>`-u'</samp> option. The argument <var>lines</var> is the number of lines of context to show. When it is not given, it defaults to three.<br />
At present, only GNU <code>diff</code> can produce this format and only GNU <code>patch</code> can automatically apply diffs in this format. For proper operation, <code>patch</code> typically needs at least two lines of context.<br />
<h4>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC21" name="SEC21">Detailed Description of Unified Format</a></h4>
The unified output format starts with a two-line header, which looks like this:<br />
<pre>--- <var>from-file</var> <var>from-file-modification-time</var>
+++ <var>to-file</var> <var>to-file-modification-time</var>
</pre>
You can change the header's content with the <samp>`-L <var>label</var>'</samp> or <samp>`--label=<var>label</var>'</samp> option; see See section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC26">Showing Alternate File Names</a>.<br />
Next come one or more hunks of differences; each hunk shows one area where the files differ. Unified format hunks look like this:<br />
<pre>@@ <var>from-file-range</var> <var>to-file-range</var> @@
<var>line-from-either-file</var>
<var>line-from-either-file</var>...
</pre>
The lines common to both files begin with a space character. The lines that actually differ between the two files have one of the following indicator characters in the left column:<br />
<dl compact="">
<dt><samp>`+'</samp></dt>
<dd>A line was added here to the first file.</dd>
<dt><samp>`-'</samp></dt>
<dd>A line was removed here from the first file.</dd></dl>
<h4>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC22" name="SEC22">An Example of Unified Format</a></h4>
Here is the output of the command <samp>`diff -u lao tzu'</samp> (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC11">Two Sample Input Files</a>, for the complete contents of the two files):<br />
<pre>--- lao Sat Jan 26 23:30:39 1991
+++ tzu Sat Jan 26 23:30:50 1991
@@ -1,7 +1,6 @@
-The Way that can be told of is not the eternal Way;
-The name that can be named is not the eternal name.
The Nameless is the origin of Heaven and Earth;
-The Named is the mother of all things.
+The named is the mother of all things.
+
Therefore let there always be non-being,
so we may see their subtlety,
And let there always be being,
@@ -9,3 +8,6 @@
The two are the same,
But after they are produced,
they have different names.
+They both may be called deep and profound.
+Deeper and more profound,
+The door of all subtleties!
</pre>
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC23" name="SEC23">Showing Which Sections Differences Are in</a></h3>
<a href="https://www.blogger.com/null" name="IDX23"></a><a href="https://www.blogger.com/null" name="IDX24"></a><br />
Sometimes you might want to know which part of the files each change falls in. If the files are source code, this could mean which function was changed. If the files are documents, it could mean which chapter or appendix was changed. GNU <code>diff</code> can show this by displaying the nearest section heading line that precedes the differing lines. Which lines are "section headings" is determined by a regular expression.<br />
<h4>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC24" name="SEC24">Showing Lines That Match Regular Expressions</a></h4>
<a href="https://www.blogger.com/null" name="IDX25"></a><a href="https://www.blogger.com/null" name="IDX26"></a><br />
To show in which sections differences occur for files that are not source code for C or similar languages, use the <samp>`-F <var>regexp</var>'</samp> or <samp>`--show-function-line=<var>regexp</var>'</samp> option. <code>diff</code> considers lines that match the argument <var>regexp</var> to be the beginning of a section of the file. Here are suggested regular expressions for some common languages:<br />
<dl compact="">
<dt><samp>`^[A-Za-z_]'</samp></dt>
<dd>C, C++, Prolog</dd>
<dt><samp>`^('</samp></dt>
<dd>Lisp</dd>
<dt><samp>`^@\(chapter\|appendix\|unnumbered\|chapheading\)'</samp></dt>
<dd>Texinfo</dd></dl>
This option does not automatically select an output format; in order to use it, you must select the context format (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC16">Context Format</a>) or unified format (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC20">Unified Format</a>). In other output formats it has no effect.<br />
The <samp>`-F'</samp> and <samp>`--show-function-line'</samp> options find the nearest unchanged line that precedes each hunk of differences and matches the given regular expression. Then they add that line to the end of the line of asterisks in the context format, or to the <samp>`@@'</samp> line in unified format. If no matching line exists, they leave the output for that hunk unchanged. If that line is more than 40 characters long, they output only the first 40 characters. You can specify more than one regular expression for such lines; <code>diff</code> tries to match each line against each regular expression, starting with the last one given. This means that you can use <samp>`-p'</samp> and <samp>`-F'</samp> together, if you wish.<br />
<h4>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC25" name="SEC25">Showing C Function Headings</a></h4>
<a href="https://www.blogger.com/null" name="IDX27"></a><a href="https://www.blogger.com/null" name="IDX28"></a><br />
To show in which functions differences occur for C and similar languages, you can use the <samp>`-p'</samp> or <samp>`--show-c-function'</samp> option. This option automatically defaults to the context output format (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC16">Context Format</a>), with the default number of lines of context. You can override that number with <samp>`-C <var>lines</var>'</samp> elsewhere in the command line. You can override both the format and the number with <samp>`-U <var>lines</var>'</samp> elsewhere in the command line.<br />
The <samp>`-p'</samp> and <samp>`--show-c-function'</samp> options are equivalent to <samp>`-F'^[_a-zA-Z$]''</samp> if the unified format is specified, otherwise <samp>`-c -F'^[_a-zA-Z$]''</samp> (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC24">Showing Lines That Match Regular Expressions</a>). GNU <code>diff</code> provides them for the sake of convenience.<br />
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC26" name="SEC26">Showing Alternate File Names</a></h3>
<a href="https://www.blogger.com/null" name="IDX29"></a><a href="https://www.blogger.com/null" name="IDX30"></a><br />
If you are comparing two files that have meaningless or uninformative names, you might want <code>diff</code> to show alternate names in the header of the context and unified output formats. To do this, use the <samp>`-L <var>label</var>'</samp> or <samp>`--label=<var>label</var>'</samp> option. The first time you give this option, its argument replaces the name and date of the first file in the header; the second time, its argument replaces the name and date of the second file. If you give this option more than twice, <code>diff</code> reports an error. The <samp>`-L'</samp> option does not affect the file names in the <code>pr</code> header when the <samp>`-l'</samp> or <samp>`--paginate'</samp>option is used (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_5.html#SEC44">Paginating <code>diff</code> Output</a>).<br />
Here are the first two lines of the output from <samp>`diff -C2 -Loriginal -Lmodified lao tzu'</samp>:<br />
<pre>*** original
--- modified
</pre>
<h2>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC27" name="SEC27">Showing Differences Side by Side</a></h2>
<a href="https://www.blogger.com/null" name="IDX31"></a><a href="https://www.blogger.com/null" name="IDX32"></a><a href="https://www.blogger.com/null" name="IDX33"></a><br />
<code>diff</code> can produce a side by side difference listing of two files. The files are listed in two columns with a gutter between them. The gutter contains one of the following markers:<br />
<dl compact="">
<dt>white space</dt>
<dd>The corresponding lines are in common. That is, either the lines are identical, or the difference is ignored because of one of the <samp>`--ignore'</samp> options (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_2.html#SEC4">Suppressing Differences in Blank and Tab Spacing</a>).</dd>
<dt><samp>`|'</samp></dt>
<dd>The corresponding lines differ, and they are either both complete or both incomplete.</dd>
<dt><samp>`<'</samp></dt>
<dd>The files differ and only the first file contains the line.</dd>
<dt><samp>`>'</samp></dt>
<dd>The files differ and only the second file contains the line.</dd>
<dt><samp>`('</samp></dt>
<dd>Only the first file contains the line, but the difference is ignored.</dd>
<dt><samp>`)'</samp></dt>
<dd>Only the second file contains the line, but the difference is ignored.</dd>
<dt><samp>`\'</samp></dt>
<dd>The corresponding lines differ, and only the first line is incomplete.</dd>
<dt><samp>`/'</samp></dt>
<dd>The corresponding lines differ, and only the second line is incomplete.</dd></dl>
Normally, an output line is incomplete if and only if the lines that it contains are incomplete; See section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_17.html#SEC83">Incomplete Lines</a>. However, when an output line represents two differing lines, one might be incomplete while the other is not. In this case, the output line is complete, but its the gutter is marked <samp>`\'</samp> if the first line is incomplete, <samp>`/'</samp> if the second line is.<br />
Side by side format is sometimes easiest to read, but it has limitations. It generates much wider output than usual, and truncates lines that are too long to fit. Also, it relies on lining up output more heavily than usual, so its output looks particularly bad if you use varying width fonts, nonstandard tab stops, or nonprinting characters.<br />
You can use the <code>sdiff</code> command to interactively merge side by side differences. See section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_9.html#SEC57">Interactive Merging with <code>sdiff</code></a>, for more information on merging files.<br />
<h2>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC28" name="SEC28">Controlling Side by Side Format</a></h2>
<a href="https://www.blogger.com/null" name="IDX34"></a><br />
The <samp>`-y'</samp> or <samp>`--side-by-side'</samp> option selects side by side format. Because side by side output lines contain two input lines, they are wider than usual. They are normally 130 columns, which can fit onto a traditional printer line. You can set the length of output lines with the <samp>`-W <var>columns</var>'</samp> or<samp>`--width=<var>columns</var>'</samp> option. The output line is split into two halves of equal length, separated by a small gutter to mark differences; the right half is aligned to a tab stop so that tabs line up. Input lines that are too long to fit in half of an output line are truncated for output.<br />
The <samp>`--left-column'</samp> option prints only the left column of two common lines. The <samp>`--suppress-common-lines'</samp> option suppresses common lines entirely.<br />
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC29" name="SEC29">An Example of Side by Side Format</a></h3>
Here is the output of the command <samp>`diff -y -W 72 lao tzu'</samp> (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC11">Two Sample Input Files</a>, for the complete contents of the two files).<br />
<pre>The Way that can be told of is n <
The name that can be named is no <
The Nameless is the origin of He The Nameless is the origin of He
The Named is the mother of all t | The named is the mother of all t
>
Therefore let there always be no Therefore let there always be no
so we may see their subtlety, so we may see their subtlety,
And let there always be being, And let there always be being,
so we may see their outcome. so we may see their outcome.
The two are the same, The two are the same,
But after they are produced, But after they are produced,
they have different names. they have different names.
> They both may be called deep and
> Deeper and more profound,
> The door of all subtleties!
</pre>
<h2>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC30" name="SEC30">Making Edit Scripts</a></h2>
<a href="https://www.blogger.com/null" name="IDX35"></a><br />
Several output modes produce command scripts for editing <var>from-file</var> to produce <var>to-file</var>.<br />
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC31" name="SEC31"><code>ed</code> Scripts</a></h3>
<a href="https://www.blogger.com/null" name="IDX36"></a><br />
<code>diff</code> can produce commands that direct the <code>ed</code> text editor to change the first file into the second file. Long ago, this was the only output mode that was suitable for editing one file into another automatically; today, with <code>patch</code>, it is almost obsolete. Use the <samp>`-e'</samp> or <samp>`--ed'</samp> option to select this output format.<br />
Like the normal format (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC12">Showing Differences Without Context</a>), this output format does not show any context; unlike the normal format, it does not include the information necessary to apply the diff in reverse (to produce the first file if all you have is the second file and the diff).<br />
If the file <tt>`d'</tt> contains the output of <samp>`diff -e old new'</samp>, then the command <samp>`(cat d && echo w) | ed - old'</samp> edits <tt>`old'</tt> to make it a copy of <tt>`new'</tt>. More generally, if <tt>`d1'</tt>, <tt>`d2'</tt>, ..., <tt>`dN'</tt> contain the outputs of <samp>`diff -e old new1'</samp>, <samp>`diff -e new1 new2'</samp>, ..., <samp>`diff -e newN-1 newN'</samp>, respectively, then the command <samp>`(cat d1 d2 ... dN && echo w) | ed - old'</samp> edits <tt>`old'</tt> to make it a copy of <tt>`newN'</tt>.<br />
<h4>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC32" name="SEC32">Detailed Description of <code>ed</code> Format</a></h4>
The <code>ed</code> output format consists of one or more hunks of differences. The changes closest to the ends of the files come first so that commands that change the number of lines do not affect how <code>ed</code> interprets line numbers in succeeding commands. <code>ed</code> format hunks look like this:<br />
<pre><var>change-command</var>
<var>to-file-line</var>
<var>to-file-line</var>...
.
</pre>
Because <code>ed</code> uses a single period on a line to indicate the end of input, GNU <code>diff</code> protects lines of changes that contain a single period on a line by writing two periods instead, then writing a subsequent <code>ed</code> command to change the two periods into one. The <code>ed</code> format cannot represent an incomplete line, so if the second file ends in a changed incomplete line, <code>diff</code> reports an error and then pretends that a newline was appended.<br />
There are three types of change commands. Each consists of a line number or comma-separated range of lines in the first file and a single character indicating the kind of change to make. All line numbers are the original line numbers in the file. The types of change commands are:<br />
<dl compact="">
<dt><samp>`<var>l</var>a'</samp></dt>
<dd>Add text from the second file after line <var>l</var> in the first file. For example, <samp>`8a'</samp> means to add the following lines after line 8 of file 1.</dd>
<dt><samp>`<var>r</var>c'</samp></dt>
<dd>Replace the lines in range <var>r</var> in the first file with the following lines. Like a combined add and delete, but more compact. For example, <samp>`5,7c'</samp> means change lines 5--7 of file 1 to read as the text file 2.</dd>
<dt><samp>`<var>r</var>d'</samp></dt>
<dd>Delete the lines in range <var>r</var> from the first file. For example, <samp>`5,7d'</samp> means delete lines 5--7 of file 1.</dd></dl>
<h4>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC33" name="SEC33">Example <code>ed</code> Script</a></h4>
Here is the output of <samp>`diff -e lao tzu'</samp> (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC11">Two Sample Input Files</a>, for the complete contents of the two files):<br />
<pre>11a
They both may be called deep and profound.
Deeper and more profound,
The door of all subtleties!
.
4c
The named is the mother of all things.
.
1,2d
</pre>
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC34" name="SEC34">Forward <code>ed</code> Scripts</a></h3>
<a href="https://www.blogger.com/null" name="IDX37"></a><br />
<code>diff</code> can produce output that is like an <code>ed</code> script, but with hunks in forward (front to back) order. The format of the commands is also changed slightly: command characters precede the lines they modify, spaces separate line numbers in ranges, and no attempt is made to disambiguate hunk lines consisting of a single period. Like <code>ed</code> format, forward <code>ed</code> format cannot represent incomplete lines.<br />
Forward <code>ed</code> format is not very useful, because neither <code>ed</code> nor <code>patch</code> can apply diffs in this format. It exists mainly for compatibility with older versions of <code>diff</code>. Use the <samp>`-f'</samp> or <samp>`--forward-ed'</samp> option to select it.<br />
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC35" name="SEC35">RCS Scripts</a></h3>
<a href="https://www.blogger.com/null" name="IDX38"></a><br />
The RCS output format is designed specifically for use by the Revision Control System, which is a set of free programs used for organizing different versions and systems of files. Use the <samp>`-n'</samp> or <samp>`--rcs'</samp> option to select this output format. It is like the forward <code>ed</code> format (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC34">Forward<code>ed</code> Scripts</a>), but it can represent arbitrary changes to the contents of a file because it avoids the forward <code>ed</code> format's problems with lines consisting of a single period and with incomplete lines. Instead of ending text sections with a line consisting of a single period, each command specifies the number of lines it affects; a combination of the <samp>`a'</samp> and <samp>`d'</samp> commands are used instead of <samp>`c'</samp>. Also, if the second file ends in a changed incomplete line, then the output also ends in an incomplete line.<br />
Here is the output of <samp>`diff -n lao tzu'</samp> (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC11">Two Sample Input Files</a>, for the complete contents of the two files):<br />
<pre>d1 2
d4 1
a4 2
The named is the mother of all things.
a11 3
They both may be called deep and profound.
Deeper and more profound,
The door of all subtleties!
</pre>
<h2>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC36" name="SEC36">Merging Files with If-then-else</a></h2>
<a href="https://www.blogger.com/null" name="IDX39"></a><a href="https://www.blogger.com/null" name="IDX40"></a><a href="https://www.blogger.com/null" name="IDX41"></a><a href="https://www.blogger.com/null" name="IDX42"></a><br />
You can use <code>diff</code> to merge two files of C source code. The output of <code>diff</code> in this format contains all the lines of both files. Lines common to both files are output just once; the differing parts are separated by the C preprocessor directives <code>#ifdef <var>name</var></code> or <code>#ifndef <var>name</var></code>, <code>#else</code>, and <code>#endif</code>. When compiling the output, you select which version to use by either defining or leaving undefined the macro <var>name</var>.<br />
To merge two files, use <code>diff</code> with the <samp>`-D <var>name</var>'</samp> or <samp>`--ifdef=<var>name</var>'</samp> option. The argument <var>name</var> is the C preprocessor identifier to use in the <code>#ifdef</code> and <code>#ifndef</code> directives.<br />
For example, if you change an instance of <code>wait (&s)</code> to <code>waitpid (-1, &s, 0)</code> and then merge the old and new files with the <samp>`--ifdef=HAVE_WAITPID'</samp> option, then the affected part of your code might look like this:<br />
<pre> do {
#ifndef HAVE_WAITPID
if ((w = wait (&s)) < 0 && errno != EINTR)
#else /* HAVE_WAITPID */
if ((w = waitpid (-1, &s, 0)) < 0 && errno != EINTR)
#endif /* HAVE_WAITPID */
return w;
} while (w != child);
</pre>
You can specify formats for languages other than C by using line group formats and line formats, as described in the next sections.<br />
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC37" name="SEC37">Line Group Formats</a></h3>
<a href="https://www.blogger.com/null" name="IDX43"></a><a href="https://www.blogger.com/null" name="IDX44"></a><br />
Line group formats let you specify formats suitable for many applications that allow if-then-else input, including programming languages and text formatting languages. A line group format specifies the output format for a contiguous group of similar lines.<br />
For example, the following command compares the TeX files <tt>`old'</tt> and <tt>`new'</tt>, and outputs a merged file in which old regions are surrounded by <samp>`\begin{em}'</samp>-<samp>`\end{em}'</samp> lines, and new regions are surrounded by <samp>`\begin{bf}'</samp>-<samp>`\end{bf}'</samp> lines.<br />
<pre>diff \
--old-group-format='\begin{em}
%<\end{em}
' \
--new-group-format='\begin{bf}
%>\end{bf}
' \
old new
</pre>
The following command is equivalent to the above example, but it is a little more verbose, because it spells out the default line group formats.<br />
<pre>diff \
--old-group-format='\begin{em}
%<\end{em}
' \
--new-group-format='\begin{bf}
%>\end{bf}
' \
--unchanged-group-format='%=' \
--changed-group-format='\begin{em}
%<\end{em}
\begin{bf}
%>\end{bf}
' \
old new
</pre>
Here is a more advanced example, which outputs a diff listing with headers containing line numbers in a "plain English" style.<br />
<pre>diff \
--unchanged-group-format=" \
--old-group-format='-------- %dn line%(n=1?:s) deleted at %df:
%<' \
--new-group-format='-------- %dN line%(N=1?:s) added after %de:
%>' \
--changed-group-format='-------- %dn line%(n=1?:s) changed at %df:
%<-------- to:
%>' \
old new
</pre>
To specify a line group format, use <code>diff</code> with one of the options listed below. You can specify up to four line group formats, one for each kind of line group. You should quote <var>format</var>, because it typically contains shell metacharacters.<br />
<dl compact="">
<dt><samp>`--old-group-format=<var>format</var>'</samp></dt>
<dd>These line groups are hunks containing only lines from the first file. The default old group format is the same as the changed group format if it is specified; otherwise it is a format that outputs the line group as-is.</dd>
<dt><samp>`--new-group-format=<var>format</var>'</samp></dt>
<dd>These line groups are hunks containing only lines from the second file. The default new group format is same as the the changed group format if it is specified; otherwise it is a format that outputs the line group as-is.</dd>
<dt><samp>`--changed-group-format=<var>format</var>'</samp></dt>
<dd>These line groups are hunks containing lines from both files. The default changed group format is the concatenation of the old and new group formats.</dd>
<dt><samp>`--unchanged-group-format=<var>format</var>'</samp></dt>
<dd>These line groups contain lines common to both files. The default unchanged group format is a format that outputs the line group as-is.</dd></dl>
In a line group format, ordinary characters represent themselves; conversion specifications start with <samp>`%'</samp> and have one of the following forms.<br />
<dl compact="">
<dt><samp>`%<'</samp></dt>
<dd>stands for the lines from the first file, including the trailing newline. Each line is formatted according to the old line format (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC38">Line Formats</a>).</dd>
<dt><samp>`%>'</samp></dt>
<dd>stands for the lines from the second file, including the trailing newline. Each line is formatted according to the new line format.</dd>
<dt><samp>`%='</samp></dt>
<dd>stands for the lines common to both files, including the trailing newline. Each line is formatted according to the unchanged line format.</dd>
<dt><samp>`%%'</samp></dt>
<dd>stands for <samp>`%'</samp>.</dd>
<dt><samp>`%c'<var>C</var>''</samp></dt>
<dd>where <var>C</var> is a single character, stands for <var>C</var>. <var>C</var> may not be a backslash or an apostrophe. For example, <samp>`%c':''</samp> stands for a colon, even inside the then-part of an if-then-else format, which a colon would normally terminate.</dd>
<dt><samp>`%c'\<var>O</var>''</samp></dt>
<dd>where <var>O</var> is a string of 1, 2, or 3 octal digits, stands for the character with octal code <var>O</var>. For example, <samp>`%c'\0''</samp> stands for a null character.</dd>
<dt><samp>`<var>F</var><var>n</var>'</samp></dt>
<dd>where <var>F</var> is a <code>printf</code> conversion specification and <var>n</var> is one of the following letters, stands for <var>n</var>'s value formatted with <var>F</var>.
<dl compact="">
<dt><samp>`e'</samp></dt>
<dd>The line number of the line just before the group in the old file.</dd>
<dt><samp>`f'</samp></dt>
<dd>The line number of the first line in the group in the old file; equals <var>e</var> + 1.</dd>
<dt><samp>`l'</samp></dt>
<dd>The line number of the last line in the group in the old file.</dd>
<dt><samp>`m'</samp></dt>
<dd>The line number of the line just after the group in the old file; equals <var>l</var> + 1.</dd>
<dt><samp>`n'</samp></dt>
<dd>The number of lines in the group in the old file; equals <var>l</var> - <var>f</var> + 1.</dd>
<dt><samp>`E, F, L, M, N'</samp></dt>
<dd>Likewise, for lines in the new file.</dd></dl>
The <code>printf</code> conversion specification can be <samp>`%d'</samp>, <samp>`%o'</samp>, <samp>`%x'</samp>, or <samp>`%X'</samp>, specifying decimal, octal, lower case hexadecimal, or upper case hexadecimal output respectively. After the <samp>`%'</samp> the following options can appear in sequence: a <samp>`-'</samp> specifying left-justification; an integer specifying the minimum field width; and a period followed by an optional integer specifying the minimum number of digits. For example, <samp>`%5dN'</samp> prints the number of new lines in the group in a field of width 5 characters, using the <code>printf</code> format <code>"%5d"</code>.</dd>
<dt><samp>`(<var>A</var>=<var>B</var>?<var>T</var>:<var>E</var>)'</samp></dt>
<dd>If <var>A</var> equals <var>B</var> then <var>T</var> else <var>E</var>. <var>A</var> and <var>B</var> are each either a decimal constant or a single letter interpreted as above. This format spec is equivalent to <var>T</var> if <var>A</var>'s value equals <var>B</var>'s; otherwise it is equivalent to <var>E</var>. For example, <samp>`%(N=0?no:%dN) line%(N=1?:s)'</samp> is equivalent to <samp>`no lines'</samp> if <var>N</var> (the number of lines in the group in the the new file) is 0, to <samp>`1 line'</samp> if <var>N</var> is 1, and to <samp>`%dN lines'</samp> otherwise.</dd></dl>
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC38" name="SEC38">Line Formats</a></h3>
<a href="https://www.blogger.com/null" name="IDX45"></a><br />
Line formats control how each line taken from an input file is output as part of a line group in if-then-else format.<br />
For example, the following command outputs text with a one-column change indicator to the left of the text. The first column of output is <samp>`-'</samp> for deleted lines, <samp>`|'</samp> for added lines, and a space for unchanged lines. The formats contain newline characters where newlines are desired on output.<br />
<pre>diff \
--old-line-format='-%l
' \
--new-line-format='|%l
' \
--unchanged-line-format=' %l
' \
old new
</pre>
To specify a line format, use one of the following options. You should quote <var>format</var>, since it often contains shell metacharacters.<br />
<dl compact="">
<dt><samp>`--old-line-format=<var>format</var>'</samp></dt>
<dd>formats lines just from the first file.</dd>
<dt><samp>`--new-line-format=<var>format</var>'</samp></dt>
<dd>formats lines just from the second file.</dd>
<dt><samp>`--unchanged-line-format=<var>format</var>'</samp></dt>
<dd>formats lines common to both files.</dd>
<dt><samp>`--line-format=<var>format</var>'</samp></dt>
<dd>formats all lines; in effect, it sets all three above options simultaneously.</dd></dl>
In a line format, ordinary characters represent themselves; conversion specifications start with <samp>`%'</samp> and have one of the following forms.<br />
<dl compact="">
<dt><samp>`%l'</samp></dt>
<dd>stands for the the contents of the line, not counting its trailing newline (if any). This format ignores whether the line is incomplete; See section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_17.html#SEC83">Incomplete Lines</a>.</dd>
<dt><samp>`%L'</samp></dt>
<dd>stands for the the contents of the line, including its trailing newline (if any). If a line is incomplete, this format preserves its incompleteness.</dd>
<dt><samp>`%%'</samp></dt>
<dd>stands for <samp>`%'</samp>.</dd>
<dt><samp>`%c'<var>C</var>''</samp></dt>
<dd>where <var>C</var> is a single character, stands for <var>C</var>. <var>C</var> may not be a backslash or an apostrophe. For example, <samp>`%c':''</samp> stands for a colon.</dd>
<dt><samp>`%c'\<var>O</var>''</samp></dt>
<dd>where <var>O</var> is a string of 1, 2, or 3 octal digits, stands for the character with octal code <var>O</var>. For example, <samp>`%c'\0''</samp> stands for a null character.</dd>
<dt><samp>`<var>F</var>n'</samp></dt>
<dd>where <var>F</var> is a <code>printf</code> conversion specification, stands for the line number formatted with <var>F</var>. For example, <samp>`%.5dn'</samp> prints the line number using the <code>printf</code> format <code>"%.5d"</code>. See section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC37">Line Group Formats</a>, for more about printf conversion specifications.</dd></dl>
The default line format is <samp>`%l'</samp> followed by a newline character.<br />
If the input contains tab characters and it is important that they line up on output, you should ensure that <samp>`%l'</samp> or <samp>`%L'</samp> in a line format is just after a tab stop (e.g. by preceding <samp>`%l'</samp> or <samp>`%L'</samp> with a tab character), or you should use the <samp>`-t'</samp> or <samp>`--expand-tabs'</samp> option.<br />
Taken together, the line and line group formats let you specify many different formats. For example, the following command uses a format similar to <code>diff</code>'s normal format. You can tailor this command to get fine control over <code>diff</code>'s output.<br />
<pre>diff \
--old-line-format='< %l
' \
--new-line-format='> %l
' \
--old-group-format='%df%(f=l?:,%dl)d%dE
%<' \
--new-group-format='%dea%dF%(F=L?:,%dL)
%>' \
--changed-group-format='%df%(f=l?:,%dl)c%dF%(F=L?:,%dL)
%<---
%>' \
--unchanged-group-format=" \
old new
</pre>
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC39" name="SEC39">Detailed Description of If-then-else Format</a></h3>
For lines common to both files, <code>diff</code> uses the unchanged line group format. For each hunk of differences in the merged output format, if the hunk contains only lines from the first file, <code>diff</code> uses the old line group format; if the hunk contains only lines from the second file, <code>diff</code> uses the new group format; otherwise, <code>diff</code> uses the changed group format.<br />
The old, new, and unchanged line formats specify the output format of lines from the first file, lines from the second file, and lines common to both files, respectively.<br />
The option <samp>`--ifdef=<var>name</var>'</samp> is equivalent to the following sequence of options using shell syntax:<br />
<pre>--old-group-format='#ifndef <var>name</var>
%<#endif /* not <var>name</var> */
' \
--new-group-format='#ifdef <var>name</var>
%>#endif /* <var>name</var> */
' \
--unchanged-group-format='%=' \
--changed-group-format='#ifndef <var>name</var>
%<#else /* <var>name</var> */
%>#endif /* <var>name</var> */
'
</pre>
You should carefully check the <code>diff</code> output for proper nesting. For example, when using the the <samp>`-D <var>name</var>'</samp> or <samp>`--ifdef=<var>name</var>'</samp> option, you should check that if the differing lines contain any of the C preprocessor directives <samp>`#ifdef'</samp>, <samp>`#ifndef'</samp>, <samp>`#else'</samp>, <samp>`#elif'</samp>, or <samp>`#endif'</samp>, they are nested properly and match. If they don't, you must make corrections manually. It is a good idea to carefully check the resulting code anyway to make sure that it really does what you want it to; depending on how the input files were produced, the output might contain duplicate or otherwise incorrect code.<br />
The <code>patch</code> <samp>`-D <var>name</var>'</samp> option behaves just like the <code>diff</code> <samp>`-D <var>name</var>'</samp> option, except it operates on a file and a diff to produce a merged file; See section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_15.html#SEC80">Options to <code>patch</code></a>.<br />
<h3>
<a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html#TOC40" name="SEC40">An Example of If-then-else Format</a></h3>
Here is the output of <samp>`diff -DTWO lao tzu'</samp> (see section <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_3.html#SEC11">Two Sample Input Files</a>, for the complete contents of the two files):<br />
<pre>#ifndef TWO
The Way that can be told of is not the eternal Way;
The name that can be named is not the eternal name.
#endif /* not TWO */
The Nameless is the origin of Heaven and Earth;
#ifndef TWO
The Named is the mother of all things.
#else /* TWO */
The named is the mother of all things.
#endif /* TWO */
Therefore let there always be non-being,
so we may see their subtlety,
And let there always be being,
so we may see their outcome.
The two are the same,
But after they are produced,
they have different names.
#ifdef TWO
They both may be called deep and profound.
Deeper and more profound,
The door of all subtleties!
#endif /* TWO */
</pre>
<br />
<hr />
Go to the <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_1.html">first</a>, <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_2.html">previous</a>, <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_4.html">next</a>, <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_19.html">last</a> section, <a href="http://www.chemie.fu-berlin.de/chemnet/use/info/diff/diff_toc.html">table of contents</a>.</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-40874485738270577082015-07-29T03:42:00.002-07:002015-07-29T03:42:30.947-07:00emacs users ergonomic concern<div dir="ltr" style="text-align: left;" trbidi="on">
Emacs users are heavy function/modifier key users. I have followed originally the general idea to swap left ctrl with caplock, but the pinky finger really gets sore after days. Now by article from Xah Lee (http://ergoemacs.org/emacs/emacs_pinky.html), I realize that I need a ergo keyboard as well as swap ctrl with alt.<br />
<br />
It is annoying to swtich function key at the time that I am already used to the original positions, but for healthy concideration, it ought to be good for long run!<br />
<br />
I am now looking for good keyboards and try to get used to ctrl-alt swapped layout.<br />
<br />
Happy emacsing!</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-28803930485552981512015-07-25T13:16:00.001-07:002015-07-25T13:16:10.429-07:00Officially, I am entitled as an Emacs beginner :)<div dir="ltr" style="text-align: left;" trbidi="on">
I have studied emacs for couple of weeks and spent numerous time tinkering it. So much fun to learn such amazing text editing tool :D.<br />
<br />
until today, I found out that people should rebind cap-lock key to ctrl to ease the left hand muscles! I have used by-default ctrl key for these days and didn't find it difficult to use after several try days.<br />
<br />
now I have to reshape the ctrl key memory in head, but surely it will take little time!<br />
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-61534966995481429392015-07-18T12:19:00.001-07:002015-07-18T13:33:17.776-07:00C# IDisposable best practice<div dir="ltr" style="text-align: left;" trbidi="on">
<h3 style="text-align: left;">
General Information</h3>
<ul style="text-align: left;">
<li>.net managed code talks to and uses external resources, that needs to implement IDisposable interface</li>
<li>GC(Garbage Collector) tries best to clean memory when using external resources, such as SQLconnection, without IDisposable. Thus, it is impossible to detect when app will fail.</li>
<li>GC is triggered when the memory threshold is reached.</li>
</ul>
<div>
<br /></div>
<h3 style="text-align: left;">
Managed resources v.s. unmanaged resources</h3>
<div>
<br /></div>
Managed resources basically means "managed memory" that is managed by the garbage collector. When you no longer have any references to a managed object (which uses managed memory), the garbage collector will (eventually) release that memory for you.<br />
<br />
Unmanaged resources are then everything that the garbage collector does not know about. For example:<br />
Open files<br />
Open network connections<br />
Unmanaged memory<br />
In XNA: vertex buffers, index buffers, textures, etc.<br />
<br />
Normally you want to release those unmanaged resources before you lose all the references you have to the object managing them. You do this by calling Dispose on that object, or (in C#) using the using statement which will handle calling Dispose for you.<br />
<br />
If you neglect to Dispose of your unmanaged resources correctly, the garbage collector will eventually handle it for you when the object containing that resource is garbage collected (this is "finalization"). But because the garbage collector doesn't know about the unmanaged resources, it can't tell how badly it needs to release them - so it's possible for your program to perform poorly or run out of resources entirely.<br />
<br />
If you implement a class yourself that handles unmanaged resources, it is up to you to implement Dispose and Finalize correctly.<br />
<h3 style="text-align: left;">
Best Practices</h3>
<ul style="text-align: left;">
<li><b>best practice #1</b>: Dispose of IDisposable objects as soon as you can. </li>
<li>Implementing IDisposable code pattern as:</li>
<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> private bool _disposed;
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Clear all property values that maybe have been set
// when the class was instantiated
id = 0;
name = String.Empty;
pass = String.Empty;
}
// Indicate that the instance has been disposed.
_disposed = true;
}
}
</code></pre>
<li><b>best practice #2</b>: If you use IDisposable objects (e.g. SQLConnection _connection) as instance fields, implement IDisposable.</li>
<li><b>best practice #3</b>: allow Dispose() to be called multiple times and do not throw exceptions (last 3 lines in the code sample below)</li>
<pre style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: 1px dashed rgb(204, 204, 204); height: auto; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="background-color: #f0f0f0; color: black; font-family: arial; font-size: 12px; line-height: 20px; word-wrap: normal;"> public class DatabaseState : IDisposable
{
private SqlConnection _connection;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(disposing && _connection != null)
{ _connection.Dispose();
_connection = null;
}
} </code><span style="word-wrap: normal;"> </span></pre>
<li><b>best practice #4 </b>implement IDisposable to support disposing resources in a class heraychy.</li>
<li><b>best practice #5 </b>if you use unmanaged resources, declare a finalizer which cleans them up.</li>
<li><b>best practice #6: </b>Visual Studio using code analysis CA2000 (not enabled by default) to check this issue.</li>
<li><b>best practice #7: </b>if your class implements an interface and use IDisposable fields, extend the interface from IDisposable rather than the implementing class. <b>This conflicts with OO Design.</b></li>
<li><b>best practice #8: </b>if you implement IDisposable, do not implement it explicitly.</li>
</ul>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-37620080041123999722015-07-17T13:21:00.000-07:002015-07-17T13:21:55.272-07:00C# Generic study<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<h3 style="text-align: left;">
Generic Constraints</h3>
<div>
Generic Constraints is used when T in the class needs to have specific characteristics/methods that object type doesn't have (object type has only "toString" and "hasHashCode" methods).</div>
<ul style="text-align: left;">
<li>"where" keyword can be used to constrain the generic type, for example: </li>
<ul>
<li>public class SqlRepository<T> : IRepository<T> where T : class</li>
</ul>
<li>we can create a new interface with such method and use "where" keyword to constrain T. for example:</li>
<ul>
<li>public interface IEntity {bool IsValid()} so that "where T : IEntity" will allow "T.IsValid()".</li>
<li>Note. usually we do not need to define own interface, check in advance if .net framework already has such!</li>
</ul>
<li>default(T) will assign default value to T. if T is class -> null; if T is struct -> 0</li>
<li>where T : new() -> T has a default constructor so that T can be instantiated in code, for example:</li>
<ul>
<li>public T CreateNewT() {T t = new T(); return t;}</li>
</ul>
<li>constraints is preferable to be implemented in concrete class instead of in interface</li>
<li>Covariant V.S. Contravariant</li>
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4jSoyzPHJOZzqWOjvGCSjjF8JW-FsuIpBQjJbMwUfO-jdVeJG7ypN-QCDbiC87CSZtxWndeXEx8FN7OIIZnzN_smogCAxkDw-cjqQh-eP-jJfBhtX351oCInviMPheEedZGlqcYj2FTKQ/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public interface IReadOnlyRepository<out T> : IDisposable
{
T FindById(int id);
IQueryable<T> FindAll();
}
public interface IWriteOnlyRepository<in T> : IDisposable
{
void Add(T newEntity);
void Delete(T entity);
int Commit();
}
public interface IRepository<T> : IReadOnlyRepository<T>, IWriteOnlyRepository<T>
{
} </code></pre>
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4jSoyzPHJOZzqWOjvGCSjjF8JW-FsuIpBQjJbMwUfO-jdVeJG7ypN-QCDbiC87CSZtxWndeXEx8FN7OIIZnzN_smogCAxkDw-cjqQh-eP-jJfBhtX351oCInviMPheEedZGlqcYj2FTKQ/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> using (IRepository<Employee> employeeRepository
= new SqlRepository<Employee>(new EmployeeDb()))
{
AddManagers(employeeRepository);
DumpPeople(employeeRepository);
}
</code></pre>
<li>Reflection in C# (for Generic part) // ToDo</li>
</ul>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-46176702384884855002015-07-16T11:53:00.001-07:002015-07-16T11:57:43.041-07:00Study HashSet and SortedList generics and remove generics in code of business logic<div dir="ltr" style="text-align: left;" trbidi="on">
Note. This lesson is learned from Scott Allen C# Generic videos in Pluralsight.<br />
<h3 style="text-align: left;">
1) Hashset (how to remove object duplicates)</h3>
<br />
HashSet type is supposed to identify duplicates and guarantee the uniqueness of stored objects, while the uniqueness/equality comparison shall be defined by the code.<br />
<br />
HashSet has one construction that accepts a IEqualityComparer interface.<br />
<br />
var departments = new SortedDictionary<string, HashSet<Employee>>();<br />
Departments.Add("Sales", new HashSet<Employee>(<b>new EmployeeComparer()</b>);<br />
departments["Sales"].Add(new Employee{Name = "Joy" });<br />
departments["Sales"].Add(new Employee{Name = "Joy" });<br />
departments["Sales"].Add(new Employee{Name = "Joy" });<br />
<br />
<h3 style="text-align: left;">
2) SortedSet (how to sort objects)</h3>
//SortedSet is similar, needs to implement IComparer<> interface<br />
new SortedSet<Employee>(<b>new EmployeeComparer()</b>);<br />
<br />
<br />
public class EmployeeComparer : <b>IEqualityComparer</b><Employee>,<b> IComparer</b><Employee><br />
{<br />
Equals ();<br />
GetHashCode ();<br />
}<br />
<br />
<h3 style="text-align: left;">
3) Cleaner code - hide those fussy "new", "generic" keywords by create a new class to inherit</h3>
<br />
<br />
<br />
<br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4jSoyzPHJOZzqWOjvGCSjjF8JW-FsuIpBQjJbMwUfO-jdVeJG7ypN-QCDbiC87CSZtxWndeXEx8FN7OIIZnzN_smogCAxkDw-cjqQh-eP-jJfBhtX351oCInviMPheEedZGlqcYj2FTKQ/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
namespace Employees
{
public class Employee
{
public string Name { get; set; }
}
public class EmployeeComparer : IEqualityComparer<Employee>, IComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
return string.Equals(x.Name, y.Name);
}
public int GetHashCode(Employee obj)
{
return obj.Name.GetHashCode();
}
public int Compare(Employee x, Employee y)
{
return string.Compare(x.Name, y.Name);
}
}
public class DepartmentCollection : SortedDictionary<string, HashSet<Employee>>
{
public DepartmentCollection Add(string departmentName, Employee employee)
{
if (!ContainsKey(departmentName)) {
this.Add(departmentName, new HashSet<Employee>(new EmployeeComparer()));
}
this[departmentName].Add(employee);
return this;
}
}
class Program
{
static void Main(string[] args)
{
var departments = new DepartmentCollection();
departments.Add("Sales", new Employee { Name = "Xi" })
.Add("Sales", new Employee { Name = "Xi" })
.Add("Sales", new Employee { Name = "Liu" });
departments.Add("Engineers", new Employee { Name = "Jin" })
.Add("Engineers", new Employee { Name = "Jin" })
.Add("Engineers", new Employee { Name = "Jin" });
foreach (var item in departments)
{
Console.WriteLine(item.Key);
foreach (var employee in item.Value)
{
Console.WriteLine("\t" + employee.Name);
}
}
Console.ReadLine();
}
}
}
</code></pre>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-58826418839048550342015-07-13T12:39:00.001-07:002015-07-13T12:40:09.122-07:00[book read] Win Friends influence people <div dir="ltr" style="text-align: left;" trbidi="on">
This is a <b>mind blowing</b> book for me!<br />
<br />
In order to get the most out of this book:<br />
<br />
<ul style="text-align: left;">
<li>Develop a deep, driving desire to master the principles of human relations</li>
<li>Read each chapter twice before going on to the next one</li>
<li>Stop frequently to ask self how you can apply each suggestion</li>
<li>Underscore each important idea</li>
<li>Review this book each month :)</li>
<li>Apply these principles at every opportunity!</li>
<li>make a lovely game out of the learning</li>
<li>Check up each week on the progress you are making. Ask yourself what mistakes you have made, what improvement, what lessons you have learned for the future</li>
<li>Keep notes</li>
</ul>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<b>Summary of the book</b><br />
<br />
<ol style="text-align: left;">
<li>Don't criticize, condemn or complain</li>
<li>Give honest and sincere appreciation</li>
<li>Arouse in the other person an eager want</li>
</ol>
<div>
<br /></div>
<div>
<b>Six ways to make people like you</b></div>
<ol style="text-align: left;">
<li>Become genuinely interested in other people</li>
<li>Smile</li>
<li>Remember that a person's name is to that person the sweetest and most important sound in any language</li>
<li>Be a good listener. Encourage others to talk about themselves</li>
<li>Talk in terms of the other person's interests</li>
<li>Make the other person feel important and do it sincerely</li>
</ol>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-54221696019142033172015-07-05T22:55:00.000-07:002015-07-05T22:55:20.946-07:00C# in a Nutshell Chapter 15 - Streams and I/O<div dir="ltr" style="text-align: left;" trbidi="on">
The .NET stream architecture centers on three concepts: backing stores, decorators, and adapters.<br />
<br />
<b>Backing store streams</b><br />
These are hard-wired to a particular type of backing store, such as FileStream or NetworkStream<br />
<br />
<b>Decorator streams</b><br />
These feed off another stream, transforming the data in some way, such as DeflateStream or CryptoStream<br />
<br />
<b>Adapters</b><br />
Both backing store and decorator streams deal exclusively in bytes. Although this is flexible and efficient, applications often work at higher levels such as text or XML. Adapters<b> </b>bridge this gap by wrapping a stream in a class with specialized methods typed to a particular format. For example, a text reader exposes a ReadLine method; an XML writer exposes a WriteAttributes method.<br />
<br />
An adapter wraps a stream, just like a decorator. Unlike a decorator, however, an adapter is not itself a stream; it typically hides the byte-oriented methods completely.<br />
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<br />
<b>To summarize,</b> backing store streams provide the raw data; decorator streams provide transparent binary transformations such as encryption; adapters offer typed methods for dealing in higher-level types such as strings and XML. To compose a chain, you simply pass one object into another’s constructor.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhNqLCY7amvmHVLh9itk4pHhmSUhiRDPOxyi4XoVnMbvesMugmKQrkwl_ucEq8NpGehentwsMlTP9Ni1Tc9qehrqkO7m8W3p1HlAr400o4yrghowuHuQJW7y4kNjKMcQ63WQID95lRYWgg/s1600/1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em; text-align: center;"><img border="0" height="207" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhNqLCY7amvmHVLh9itk4pHhmSUhiRDPOxyi4XoVnMbvesMugmKQrkwl_ucEq8NpGehentwsMlTP9Ni1Tc9qehrqkO7m8W3p1HlAr400o4yrghowuHuQJW7y4kNjKMcQ63WQID95lRYWgg/s320/1.png" width="320" /></a><br />
<br />
<br />
<h3 style="text-align: left;">
Stream Class</h3>
<div>
<div>
using System;</div>
<div>
using System.IO;</div>
<div>
class Program</div>
<div>
{</div>
<div>
static void Main()</div>
<div>
{</div>
<div>
// Create a file called test.txt in the current directory:</div>
<div>
using (Stream s = new FileStream ("test.txt", FileMode.Create))</div>
<div>
{</div>
<div>
Console.WriteLine (s.CanRead);</div>
<div>
// True</div>
<div>
Console.WriteLine (s.CanWrite);</div>
<div>
// True</div>
<div>
Console.WriteLine (s.CanSeek);</div>
<div>
// True</div>
<div>
<br /></div>
<div>
s.WriteByte (101);</div>
<div>
s.WriteByte (102);</div>
<div>
byte[] block = { 1, 2, 3, 4, 5 };</div>
<div>
s.Write (block, 0, block.Length); // Write block of 5 bytes</div>
<div>
Console.WriteLine (s.Length);</div>
<div>
Console.WriteLine (s.Position);</div>
<div>
s.Position = 0; // 7</div>
<div>
// 7</div>
<div>
// Move back to the start</div>
<div>
Console.WriteLine (s.ReadByte());</div>
<div>
Console.WriteLine (s.ReadByte()); // 101</div>
<div>
// 102</div>
<div>
// Read from the stream back into the block array:</div>
<div>
Console.WriteLine (s.Read (block, 0, block.Length)); // 5</div>
<div>
// Assuming the last Read returned 5, we'll be at</div>
<div>
// the end of the file, so Read will now return 0:</div>
<div>
Console.WriteLine (s.Read (block, 0, block.Length)); // 0</div>
</div>
<div>
<div>
}</div>
<div>
}</div>
<div>
}</div>
</div>
<div>
<br /></div>
<div>
<br />
<h3 style="text-align: left;">
Reading and Writing</h3>
</div>
<div>
A stream may support reading, writing, or both. If CanWrite returns false , the stream is read-only; if CanRead returns false , the stream is write-only.<br />
<br />
With Read , you can be certain you’ve reached the end of the stream <b>only when the method returns 0</b> . So, if you have a 1,000 byte stream, the following code may fail to read it all into memory:</div>
<div>
<br />
// Assuming s is a stream:<br />
byte[] data = new byte [1000];<br />
s.Read (data, 0, data.Length);<br />
<br />
The Read method could read anywhere from 1 to 1,000 bytes, leaving the balance of the stream unread.<br />
<br />
Here’s the correct way to read a 1,000-byte stream:<br />
<br />
byte[] data = new byte [1000];<br />
// bytesRead will always end up at 1000, unless the stream is itself smaller in length:<br />
int bytesRead = 0;<br />
int chunkSize = 1;<br />
while (bytesRead < data.Length && chunkSize > 0)<br />
bytesRead += chunkSize = s.Read (data, bytesRead, data.Length - bytesRead);</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
Fortunately, the BinaryReader type provides a simpler way to achieve the same result:<br />
<br />
byte[] data = new BinaryReader (s).ReadBytes (1000);<br />
<br />
If the stream is less than 1,000 bytes long, the byte array returned reflects the actual stream size. If the stream is seekable, you can read its entire contents by replacing 1000 with (int)s.Length .</div>
<div>
<h3 style="text-align: left;">
<br />Seeking</h3>
</div>
<div>
A stream is seekable if CanSeek returns true . With a seekable stream (such as a file stream), you can query or modify its Length (by calling SetLength ), and at any time change the Position at which you’re reading or writing. The Position property is relative to the beginning of the stream; the Seek method, however, allows you to move relative to the current position or the end of the stream.</div>
<div>
<br /></div>
<div>
With a nonseekable stream (such as an encryption stream), the only way to determine its length is to read it right through. Furthermore, if you need to reread a previous section, you must close the stream and start afresh with a new one.</div>
<div>
<br /></div>
<div>
<h3 style="text-align: left;">
Closing and Flush</h3>
Streams must be disposed after use to release underlying resources such as file and socket handles. A simple way to guarantee this is by instantiating streams within <b>using blocks.</b></div>
<div>
<br /></div>
<div>
In general, streams follow standard disposal semantics:<br />
<br />
<ul style="text-align: left;">
<li>Dispose and Close are identical in function.</li>
<li>Disposing or closing a stream repeatedly causes no error.</li>
</ul>
</div>
<div>
Closing a decorator stream closes both the decorator and its backing store stream. With a chain of decorators, closing the outermost decorator (at the head of the chain) closes the whole lot.</div>
<div>
<br /></div>
<div>
Some streams internally buffer data to and from the backing store to lessen round tripping and so improve performance (file streams are a good example of this). This means data you write to a stream may not hit the backing store immediately; it can be delayed as the buffer fills up. The Flush method forces any internally buffered data to be written immediately. <b>Flush is called automatically when a stream is closed, </b>so you never need to do the following: s.Flush(); s.Close();</div>
<div>
<br /></div>
<div>
<h3 style="text-align: left;">
Timeouts</h3>
A stream supports read and write timeouts if CanTimeout returns true . Network streams support timeouts; file and memory streams do not. For streams that support timeouts, the ReadTimeout and WriteTimeout properties determine the desired timeout in milliseconds, where 0 means no timeout. The Read and Write methods indicate that a timeout has occurred by throwing an exception.</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<h3 style="text-align: left;">
Backing Store Streams</h3>
</div>
<div>
<h3 style="text-align: left;">
<b>FileStream</b></h3>
</div>
<div>
<br /></div>
<div>
The simplest way to instantiate a FileStream is to use one of the following <b>static </b><b>methods</b> on the File class:<br />
<br />
FileStream fs1 = File.<b>OpenRead</b> ("readme.bin"); // Read-only<br />
FileStream fs2 = File.<b>OpenWrite</b> (@"c:\temp\writeme.tmp"); // Write-only<br />
FileStream fs3 = File.<b>Create </b>(@"c:\temp\writeme.tmp"); // Read/write<br />
<br />
<br />
<b>OpenWrite</b> and <b>Create</b> differ in behavior if the file already exists. <b>Create</b> truncates any existing content; <b>OpenWrite</b> leaves existing content intact with the stream positioned at zero. If you write fewer bytes than were previously in the file, <b>OpenWrite</b> leaves you with a mixture of old and new content.</div>
<div>
<br /></div>
<div>
<b>Instantiate</b> <b>a FileStream is also possible</b>. The following opens an existing file for read/write access without overwriting it:<br />
<br />
var fs = new FileStream ("readwrite.tmp", FileMode.Open);</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<h3 style="text-align: left;">
<b>File Class</b></h3>
<br />
The following static methods read an entire file into memory in one step:<br />
• File.ReadAllText (returns a string)<br />
• File.ReadAllLines (returns an array of strings)<br />
• File.ReadAllBytes (returns a byte array)<br />
The following static methods write an entire file in one step:<br />
• File.WriteAllText<br />
• File.WriteAllLines<br />
• File.WriteAllBytes<br />
• File.AppendAllText (great for appending to a log file)<br />
<br />
There’s also a static method called File.ReadLines : this is like ReadAllLines except that it returns a lazily-evaluated IEnumerable<string> . This is more efficient because it doesn’t load the entire file into memory at once. LINQ is ideal for consuming the results: the following calculates the number of lines greater than 80 characters in length:<br />
int longLines = File.ReadLines ("filePath").Count (l => l.Length > 80);<br />
<br />
<h3 style="text-align: left;">
<b>File Mode</b></h3>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgw9uHaMUnYpf7hx2S_REmyTI_YCORvSTCuE294Mw-imZYcUAVIyQQRWPiRE9aGhFGMViAHWA-aFonGmTh-uB4zPU3xq0OOzXKgq1u3FUEFzV_uNqZE3_cwB1NeM6q4PKb0GKm4c-FIhY0/s1600/2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="234" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgw9uHaMUnYpf7hx2S_REmyTI_YCORvSTCuE294Mw-imZYcUAVIyQQRWPiRE9aGhFGMViAHWA-aFonGmTh-uB4zPU3xq0OOzXKgq1u3FUEFzV_uNqZE3_cwB1NeM6q4PKb0GKm4c-FIhY0/s320/2.png" width="320" /></a></div>
<br />
<br />
<b><br /></b>
<br />
<h3 style="text-align: left;">
<b>MemoryStream</b></h3>
<br />
Closing and flushing a MemoryStream is optional. If you close a MemoryStream , you can no longer read or write to it, but you are still permitted to call ToArray to obtain the underlying data.<br />
Flush does absolutely nothing on a memory stream.<br />
<br />
<h3 style="text-align: left;">
<b>PipeStream</b></h3>
<br />
PipeStream was introduced in Framework 3.5. It provides a simple means by which one process can communicate with another through the Windows pipes protocol.<br />
There are two kinds of pipe:<br />
<br />
<ol style="text-align: left;">
<li>Anonymous pipe: Allows one-way communication between a parent and child process on the same computer.</li>
<li>Named pipe: Allows two-way communication between arbitrary processes on the same computer—or different computers across a Windows network.</li>
</ol>
<br />
PipeStream is an abstract class with four concrete subtypes. Two are used for anonymous pipes and the other two for named pipes:<br />
<br />
<ol style="text-align: left;">
<li>AnonymousPipeServerStream and AnonymousPipeClientStream</li>
<li>NamedPipeServerStream and NamedPipeClientStream</li>
</ol>
<br />
<h3 style="text-align: left;">
<b>BufferedStream</b></h3>
<br />
BufferedStream decorates, or wraps, another stream with buffering capability.<br />
Buffering improves performance by reducing round trips to the backing store. Here’s how we wrap a FileStream in a 20 KB BufferedStream :<br />
<br />
// Write 100K to a file:<br />
File.WriteAllBytes ("myFile.bin", new byte [100000]);<br />
using (FileStream fs = File.OpenRead ("myFile.bin"))<br />
using (BufferedStream bs = new BufferedStream (fs, 20000))<br />
{<br />
bs.ReadByte();<br />
Console.WriteLine (fs.Position);<br />
// 20000<br />
}<br />
<br />
In this example, the underlying stream advances 20,000 bytes after reading just 1 byte, thanks to the read-ahead buffering. We could call ReadByte another 19,999 times before the FileStream would be hit again.<br />
<br />
Coupling a BufferedStream to a FileStream , as in this example, is of limited value because FileStream already has built-in buffering. Its only use might be in enlarging the buffer on an already constructed FileStream .<br />
Closing a BufferedStream automatically closes the underlying backing store stream.<br />
<br />
<h3 style="text-align: left;">
<b>Stream Adapters</b></h3>
<br />
A Stream deals only in bytes; to read or write data types such as strings, integers, or XML elements, you must plug in an adapter.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPq7C8tN5EZzUeNPYpiuxihYExfC9SCFqNUI3VG-ryoX6wR7bg5lRk7mHdBBG3z14yUcD6ia2Ays3XFadsbDcfEiYvkQTr_4p-vEAD-WXeOLF7wbVw7uhDhWe0MRnmsVwTg0GBwnGcj68/s1600/3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="171" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhPq7C8tN5EZzUeNPYpiuxihYExfC9SCFqNUI3VG-ryoX6wR7bg5lRk7mHdBBG3z14yUcD6ia2Ays3XFadsbDcfEiYvkQTr_4p-vEAD-WXeOLF7wbVw7uhDhWe0MRnmsVwTg0GBwnGcj68/s320/3.png" width="320" /></a></div>
<br />
<br />
<h3 style="text-align: left;">
<b>Text Adapters</b></h3>
<b><br /></b>
<b>TextReader</b> and <b>TextWriter</b> are the abstract base classes for adapters that deal exclusively with characters and strings.<br />
<br />
using (FileStream fs = File.Create ("test.txt"))<br />
using (TextWriter writer = new StreamWriter (fs))<br />
{<br />
writer.WriteLine ("Line1");<br />
writer.WriteLine ("Line2");<br />
}<br />
using (FileStream fs = File.OpenRead ("test.txt"))<br />
using (TextReader reader = new StreamReader (fs))<br />
{<br />
Console.WriteLine (reader.ReadLine()); // Line1<br />
Console.WriteLine (reader.ReadLine()); // Line2<br />
}<br />
<br />
Because text adapters are so often coupled with files, the File class provides the static methods CreateText , AppendText , and OpenText to <b>shortcut</b> the process:<br />
<br />
using (TextWriter writer = File.CreateText ("test.txt"))<br />
{<br />
writer.WriteLine ("Line1");<br />
writer.WriteLine ("Line2");<br />
}<br />
using (TextWriter writer = File.AppendText ("test.txt"))<br />
writer.WriteLine ("Line3");<br />
using (TextReader reader = File.OpenText ("test.txt"))<br />
while (reader.Peek() > −1)<br />
Console.WriteLine (reader.ReadLine());<br />
<br />
This also illustrates how to test for the end of a file (viz. <b>reader.Peek()</b> ). Another option is to read until reader.ReadLine returns null.<br />
<br />
You can also read and write other types such as integers, but because TextWriter invokes ToString on your type, you must parse a string when reading it back:<br />
<br />
using (TextWriter w = File.CreateText ("data.txt"))<br />
{<br />
w.WriteLine (123);<br />
// Writes "123"<br />
w.WriteLine (true);<br />
// Writes the word "true"<br />
}<br />
using (TextReader r = File.OpenText ("data.txt"))<br />
{<br />
int myInt = int.Parse (r.ReadLine());<br />
// myInt == 123<br />
bool yes = bool.Parse (r.ReadLine());<br />
// yes == true<br />
}<br />
<br />
<h3 style="text-align: left;">
<b>Character encodings</b></h3>
<br />
TextReader and TextWriter are by themselves just abstract classes with no connection to a stream or backing store. The <b>StreamReader</b> and <b>StreamWriter</b> types, however, are connected to an underlying byte-oriented stream, so they must convert between characters and bytes. They do so through an Encoding class from the System.Text namespace, which you choose when constructing the StreamReader or StreamWriter . If you choose none, the <b>default</b> <b>UTF-8 </b>encoding is used.<br />
<br />
<h3 style="text-align: left;">
<b>StringReader and StringWriter</b></h3>
<br />
The StringReader and StringWriter adapters don’t wrap a stream at all; instead, they use a string or StringBuilder as the underlying data source. This means no byte translation is required—in fact, the classes do nothing you couldn’t easily achieve with a string or StringBuilder coupled with an index variable. Their advantage, though, is that they share a base class with StreamReader / StreamWriter . For instance, suppose we have a string containing XML and want to parse it with an XmlReader .<br />
The XmlReader.Create method accepts one of the following:<br />
<br />
<ol style="text-align: left;">
<li>A URI</li>
<li>A Stream</li>
<li>A TextReader</li>
</ol>
<br />
So, how do we XML-parse our string? Because StringReader is a subclass of TextReader , we’re in luck. We can instantiate and pass in a StringReader as follows:<br />
<br />
XmlReader r = XmlReader.Create (new StringReader (myString));<br />
<br />
<h3 style="text-align: left;">
<br /><b>Binary Adapters</b></h3>
<b><br /></b>
<b>BinaryReader</b> and <b>BinaryWriter</b> read and write native data types: bool , byte , char ,<br />
decimal , float , double , short , int , long , sbyte , ushort , uint , and ulong , as well as<br />
<br />
string s and arrays of the primitive data types.<br />
<br />
<b>BinaryReader</b> can also read into byte arrays. The following reads the entire contents<br />
of a seekable stream:<br />
<br />
byte[] data = new BinaryReader (s).ReadBytes ((int) s.Length);<br />
<br />
This is more convenient than reading directly from a stream, because it doesn't require a loop to ensure that all data has been read.<br />
<br />
<br />
<h3 style="text-align: left;">
Compression Streams</h3>
<div>
<div>
Two general-purpose compression streams are provided in the System.IO.Compression namespace: <b>DeflateStream</b> and <b>GZipStream.</b></div>
</div>
<div>
<b><br /></b></div>
DeflateStream and GZipStream are decorators; they compress or decompress data from another stream that you supply in construction. In the following example, we compress and decompress a series of bytes, using a FileStream as the backing store:<br />
<br />
using (Stream s = File.OpenRead ("compressed.bin"))<br />
using (Stream ds = new DeflateStream (s, CompressionMode.Decompress))<br />
for (byte i = 0; i < 100; i++)<br />
Console.WriteLine (ds.ReadByte());<br />
// Writes 0 to 99<br />
<br />
Even with the smaller of the two algorithms, the compressed file is 241 bytes long: more than double the original! Compression works poorly with “dense,” nonrepetitive binary filesdata!<br />
<br />
In the next example, we compress and decompress a text stream composed of 1,000 words chosen randomly from a small sentence. This also demonstrates chaining a backing store stream, a decorator<br />
stream, and an adapter (as depicted at the start of the chapter in Figure 15-1), and the use asynchronous methods:<br />
<br />
string[] words = "The quick brown fox jumps over the lazy dog".Split();<br />
Random rand = new Random();<br />
using (Stream s = File.Create ("compressed.bin"))<br />
using (Stream ds = new DeflateStream (s, CompressionMode.Compress))<br />
using (TextWriter w = new StreamWriter (ds))<br />
for (int i = 0; i < 1000; i++)<br />
await w.WriteAsync (words [rand.Next (words.Length)] + " ");<br />
Console.WriteLine (new FileInfo ("compressed.bin").Length);<br />
// 1073<br />
using (Stream s = File.OpenRead ("compressed.bin"))<br />
using (Stream ds = new DeflateStream (s, CompressionMode.Decompress))<br />
using (TextReader r = new StreamReader (ds))<br />
Console.Write (await r.ReadToEndAsync()); // Output;<br />
<br />
In this case, DeflateStream compresses efficiently to 1,073 bytes—slightly more than 1 byte per word.<br />
<br />
<b>Compressing in memory</b><br />
<br />
Sometimes you need to compress entirely in memory. Here’s how to use a <b>Memory Stream</b> for this purpose:<br />
<br />
byte[] data = new byte[1000];<br />
// We can expect a good compression<br />
// ratio from an empty array!<br />
var ms = new MemoryStream();<br />
using (Stream ds = new DeflateStream (ms, CompressionMode.Compress))<br />
ds.Write (data, 0, data.Length);<br />
byte[] compressed = ms.ToArray();<br />
Console.WriteLine (compressed.Length);<br />
// 113<br />
// Decompress back to the data array:<br />
ms = new MemoryStream (compressed);<br />
using (Stream ds = new DeflateStream (ms, CompressionMode.Decompress))<br />
for (int i = 0; i < 1000; i += ds.Read (data, i, 1000 - i));<br />
<br />
The using statement around the DeflateStream closes it in a textbook fashion, flushing any unwritten buffers in the process. This also closes the MemoryStream it wraps —meaning <b>we must then call ToArray</b> to extract its data.<br />
<br />
<h3 style="text-align: left;">
Working with Zip Files</h3>
new feature in Framework 4.5 - <b>ZipArchive</b> and <b>ZipFile</b> classes<br />
<br />
ZipFile is a static helper class for ZipArchive;<br />
<br />
ZipFile ’s <b>CreateFromDirectory</b> method adds all the files in a specified directory into a zip file:<br />
ZipFile.CreateFromDirectory (@"d:\MyFolder", @"d:\compressed.zip");<br />
<br />
whereas <b>ExtractToDirectory</b> does the opposite and extracts a zip file to a directory:<br />
ZipFile.ExtractToDirectory (@"d:\compressed.zip", @"d:\MyFolder");<br />
<br />
<h3 style="text-align: left;">
File and Directory Operations</h3>
<b>FileInfo</b> offers an easier way to change a file’s read-only flag:<br />
new FileInfo (@"c:\temp\test.txt").IsReadOnly = false;<br />
<br />
<br />
Here are all the members of the <b>FileAttribute</b> <b>enum</b> that <b>GetAttributes</b> returns:<br />
<br />
<i>Archive, Compressed, Device, Directory, Encrypted, Hidden, Normal, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, Temporary</i><br />
<br />
<b>File security</b><br />
<br />
The <b>GetAccessControl</b> and <b>SetAccessControl</b> methods allow you to query and change the operating system permissions assigned to users and roles via a FileSecurity object (namespace System.Security.AccessControl ). You can also pass a <b>FileSecurity</b> object to a <b>FileStream</b> ’s constructor to specify permissions when creating a new file.<br />
<br />
In this example, we list a file’s existing permissions, and then assign execution permission to the “Users” group:<br />
<br />
FileSecurity sec = File.GetAccessControl (@"d:\test.txt");<br />
AuthorizationRuleCollection rules = sec.GetAccessRules (true, true,<br />
typeof (NTAccount));<br />
foreach (FileSystemAccessRule rule in rules)<br />
{<br />
Console.WriteLine (rule.AccessControlType); // Allow or Deny<br />
Console.WriteLine (rule.FileSystemRights); // e.g., FullControl<br />
Console.WriteLine (rule.IdentityReference.Value); // e.g., MyDomain/Joe<br />
}<br />
var sid = new SecurityIdentifier (WellKnownSidType.BuiltinUsersSid, null);<br />
string usersAccount = sid.Translate (typeof (NTAccount)).ToString();<br />
FileSystemAccessRule newRule = new FileSystemAccessRule<br />
(usersAccount, FileSystemRights.ExecuteFile, AccessControlType.Allow);<br />
sec.AddAccessRule (newRule);<br />
File.SetAccessControl (@"d:\test.txt", sec);<br />
<h3 style="text-align: left;">
<br />The Directory Class</h3>
he static Directory class provides a set of methods analogous to those in the File class—for checking whether a directory exists ( <b>Exists</b> ), moving a directory ( <b>Move</b> ), deleting a directory ( <b>Delete</b> ), getting/setting times of creation or last access, and getting/setting security permissions. Furthermore, Directory exposes the following static methods:<br />
<br />
string GetCurrentDirectory ();<br />
void<br />
SetCurrentDirectory (string path);<br />
DirectoryInfo CreateDirectory (string path);<br />
DirectoryInfo GetParent<br />
(string path);<br />
string<br />
GetDirectoryRoot (string path);<br />
string[] GetLogicalDrives();<br />
// The following methods all return full paths:<br />
string[] GetFiles<br />
(string path);<br />
string[] GetDirectories<br />
(string path);<br />
string[] GetFileSystemEntries (string path);<br />
IEnumerable<string> EnumerateFiles (string path);<br />
IEnumerable<string> EnumerateDirectories (string path);<br />
IEnumerable<string> EnumerateFileSystemEntries (string path);<br />
<br />
<h3 style="text-align: left;">
FileInfo and DirectoryInfo</h3>
The static methods on <b>File</b> and <b>Directory</b> are convenient for executing a single file or directory operation. If you need to call a series of methods in a row, the FileInfo and DirectoryInfo classes provide an object model that makes the job easier.<br />
<br />
<b>FileInfo</b> offers most of the File ’s static methods in <b>instance form</b>—with some additional properties such as Extension , Length , IsReadOnly , and Directory —for returning a DirectoryInfo object. For example:<br />
<br />
FileInfo fi = new FileInfo (@"c:\temp\FileInfo.txt");<br />
Console.WriteLine (fi.Exists); // false<br />
using (TextWriter w = fi.CreateText())<br />
w.Write ("Some text");<br />
Console.WriteLine (fi.Exists); // false (still)<br />
fi.Refresh();<br />
Console.WriteLine (fi.Exists); // true<br />
<br />
(fi.Name); // FileInfo.txt<br />
(fi.FullName); //c:\temp\FileInfo.txt<br />
(fi.DirectoryName); //c:\temp<br />
(fi.Directory.Name); //temp<br />
(fi.Extension); // .txt<br />
(fi.Length); // 9<br />
<br />
fi.Encrypt();<br />
fi.Attributes ^= FileAttributes.Hidden; //(toggle hidden flag)<br />
fi.IsReadOnly = true;<br />
Console.WriteLine (fi.Attributes); // ReadOnly,Archive,Hidden,Encrypted<br />
Console.WriteLine (fi.CreationTime);<br />
<br />
fi.MoveTo (@"c:\temp\FileInfoX.txt");<br />
DirectoryInfo di = fi.Directory;<br />
Console.WriteLine (di.Name); // temp<br />
Console.WriteLine (di.FullName); // c:\temp<br />
Console.WriteLine (di.Parent.FullName); // c:\<br />
di.CreateSubdirectory ("SubFolder");<br />
<br />
Here’s how to use DirectoryInfo to enumerate files and subdirectories:<br />
<br />
DirectoryInfo di = new DirectoryInfo (@"e:\photos");<br />
foreach (FileInfo fi in di.GetFiles ("*.jpg"))<br />
Console.WriteLine (fi.Name);<br />
foreach (DirectoryInfo subDir in di.GetDirectories())<br />
Console.WriteLine (subDir.FullName);<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br /></div>
<div>
<br /></div>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-47592651034858286012015-07-04T11:27:00.001-07:002015-07-04T11:27:40.238-07:00C# in Nutshell Chapter 13 - Diagnostics and Code Contracts<div dir="ltr" style="text-align: left;" trbidi="on">
<h3 style="text-align: left;">
Conditional Attribute</h3>
<div>
<div>
The Conditional attribute instructs the compiler to ignore any calls to a particular class or method, if the specified symbol has not been defined.</div>
</div>
<div>
<br /></div>
<div>
<div>
static void Main()</div>
<div>
{</div>
<div>
WriteLine();</div>
<div>
Console.ReadLine();</div>
<div>
}</div>
<div>
<br /></div>
<div>
[Conditional("TESTMODE")]</div>
<div>
public static void WriteLine() { Console.WriteLine("HelloWorld"); }</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
In Visual Stuido project property -> Build -> Optional compiling symbol to set it</div>
<div>
<br /></div>
<div>
<div>
The Conditional attribute is ignored at runtime—it’s purely an instruction to the compiler.</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
Debug and Trace Classes</h3>
<div>
<br /></div>
<h3 style="text-align: left;">
Code Contracts</h3>
<div>
<div>
public static bool AddIfNotPresent<T> (IList<T> list, T item)</div>
<div>
{</div>
<div>
Contract.Requires (list != null); // Precondition</div>
<div>
Contract.Requires (!list.IsReadOnly); // Precondition</div>
<div>
Contract.Ensures (list.Contains (item)); // Postcondition</div>
<div>
if (list.Contains(item)) return false;</div>
<div>
list.Add (item);</div>
<div>
return true;</div>
<div>
}</div>
<div>
<br /></div>
<div>
The preconditions are defined by Contract.Requires and are verified when the method starts. The postcondition is defined by Contract.Ensures and is verified not where it appears in the code, but when the method exits. Preconditions and postconditions act like assertions and, in this case, detect the following errors:</div>
<div>
<ul style="text-align: left;">
<li>A bug in the method whereby we forgot to add the item to the list</li>
<li>A bug in the method whereby we forgot to add the item to the list</li>
</ul>
</div>
</div>
<div>
<div>
Preconditions and postconditions must appear at the start of the method. </div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
Windows Eventlog</h3>
<div>
<div>
To write to a Windows event log:</div>
<div>
1. Choose one of the three event logs (usually Application).</div>
<div>
2. Decide on a source name and create it if necessary.</div>
<div>
3. Call EventLog.WriteEntry with the log name, source name, and message data.</div>
<div>
<br /></div>
<div>
The source name is an easily identifiable name for your application. You must register a source name before you use it—the CreateEventSource method performs this function. You can then call WriteEntry :</div>
<div>
const string SourceName = "MyCompany.WidgetServer";</div>
<div>
// CreateEventSource requires administrative permissions, so this would</div>
<div>
// typically be done in application setup.</div>
<div>
if (!EventLog.SourceExists (SourceName))</div>
<div>
EventLog.CreateEventSource (SourceName, "Application");</div>
<div>
EventLog.WriteEntry (SourceName, "Service started; using configuration file=...", EventLogEntryType.Information);</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
The Stopwatch Class</h3>
<div>
<div>
The Elapsed property returns the elapsed interval as a <b>TimeSpan</b> :</div>
<div>
<br /></div>
<div>
Stopwatch s = Stopwatch.StartNew();</div>
<div>
System.IO.File.WriteAllText ("test.txt", new string ('*', 30000000));</div>
<div>
Console.WriteLine (s.Elapsed); // 00:00:01.4322661</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
<br /></h3>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-78426000200352672652015-07-04T04:08:00.000-07:002015-07-04T04:08:57.200-07:00C# in Nutshell Chapter 8 - LINQ<div dir="ltr" style="text-align: left;" trbidi="on">
<h3 style="text-align: left;">
LINQ</h3>
<div>
<div>
A query operator never alters the input sequence; instead, it returns a new sequence. This is consistent with the functional programming paradigm, from which LINQ was inspired.</div>
</div>
<div>
<br /></div>
<div>
string[] s = {"Dirk", "Xi", "Auli", "Jouni"};</div>
<div>
IEnumerable<string> items = s.where (n => n.length >=4);</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<b>Sequence Operators </b></div>
<div>
s.OrderBy()</div>
<div>
s.Select()</div>
<div>
s.Take()</div>
<div>
s.Skip()</div>
<div>
s.Reverse()</div>
<div>
<br /></div>
<div>
<b>Element Operators</b></div>
<div>
s.First()</div>
<div>
s.Last()</div>
<div>
s.ElementAt()</div>
<div>
<br /></div>
<div>
<b>Aggregation Operators</b></div>
<div>
s.Count();</div>
<div>
s.Min();</div>
<div>
<br /></div>
<div>
<b>Quantifiers </b>(return a bool)</div>
<div>
s.Contains()</div>
<div>
s.Any()\</div>
<div>
<br /></div>
<div>
<b>Other Operators</b></div>
<div>
<br /></div>
<div>
<div>
int[] seq1 = { 1, 2, 3 };</div>
<div>
int[] seq2 = { 3, 4, 5 };</div>
<div>
IEnumerable<int> concat = seq1.Concat (seq2); // { 1, 2, 3, 3, 4, 5 }</div>
<div>
IEnumerable<int> union = seq1.Union (seq2); // { 1, 2, 3, 4, 5 }</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<b>Query Expression</b></div>
<div>
<b><br /></b></div>
<div>
<div>
Query expressions always start with a <b>from</b> clause and end with either a <b>select </b>or</div>
<div>
<b>group</b> clause. The from clause declares a range variable (in this case, n), which you</div>
<div>
can think of as traversing the input sequence—rather like foreach.</div>
</div>
<div>
<br /></div>
<div>
<div>
IEnumerable<string> query =</div>
<div>
from n in names</div>
<div>
where n.Contains ("a") // Filter elements</div>
<div>
orderby n.Length // Sort elements</div>
<div>
select n.ToUpper(); // Translate each element (project)</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
The Into Keyword</h3>
<div>
<div>
The into keyword lets you “continue” a query after a projection and is a shortcut</div>
<div>
for progressively querying.</div>
</div>
<div>
<div>
The <b>only place </b>you can use into is after a <b>select </b>or <b>group </b>clause. into “restarts” a</div>
<div>
query, allowing you to introduce fresh <b>where</b>, <b>orderby</b>, and <b>select </b>clauses.</div>
</div>
<div>
<br /></div>
<div>
<div>
IEnumerable<string> query =</div>
<div>
from n in names</div>
<div>
select n.Replace ("a", "").Replace ("e", "").Replace ("i", "")</div>
<div>
.Replace ("o", "").Replace ("u", "")</div>
<div>
<b>into </b>noVowel</div>
<div>
where noVowel.Length > 2 orderby noVowel select noVowel;</div>
</div>
<div>
<br /></div>
<div>
Otherwise, we need to write</div>
<div>
<br /></div>
<div>
<div>
IEnumerable<string> query =</div>
<div>
from n in names</div>
<div>
select n.Replace ("a", "").Replace ("e", "").Replace ("i", "")</div>
<div>
.Replace ("o", "").Replace ("u", "");</div>
<div>
query = from n in query where n.Length > 2 orderby n select n;</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<b>Scoping rules</b></div>
<div>
<div>
All range variables are out of scope following an <b>into</b> keyword. The following will not compile:</div>
<div>
var query =</div>
<div>
from n1 in names</div>
<div>
select n1.ToUpper()</div>
<div>
into n2 // Only n2 is visible from here on.</div>
<div>
where n1.Contains ("x") // Illegal: n1 is not in scope.</div>
<div>
select n2;</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
Projection Strategies</h3>
<div>
<b>Object Initializers</b></div>
<div>
<b><br /></b></div>
<div>
<div>
class TempProjectionItem</div>
<div>
{</div>
<div>
public string Original; // Original name</div>
<div>
public string Vowelless; // Vowel-stripped name</div>
<div>
}</div>
</div>
<div>
<br /></div>
<div>
string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };</div>
<div>
<br /></div>
<div>
<div>
IEnumerable<TempProjectionItem> temp =</div>
<div>
from n in names select new TempProjectionItem</div>
</div>
<div>
<div>
{</div>
<div>
Original = n,</div>
<div>
Vowelless = n.Replace ("a", "").Replace ("e", "").Replace ("i", "")</div>
<div>
.Replace ("o", "").Replace ("u", "")</div>
<div>
};</div>
</div>
<div>
<br /></div>
<div>
<b><br /></b></div>
<div>
<b>Anonymous Types</b></div>
<div>
<div>
We can eliminate the TempProjectionItem class in our previous</div>
<div>
example with anonymous types:</div>
</div>
<div>
<br /></div>
<div>
<div>
var intermediate = from n in names</div>
<div>
select new</div>
<div>
{</div>
<div>
Original = n,</div>
<div>
Vowelless = n.Replace ("a", "").Replace ("e", "").Replace ("i", "")</div>
<div>
.Replace ("o", "").Replace ("u", "")</div>
<div>
};</div>
<div>
IEnumerable<string> query = from item in intermediate</div>
<div>
where item.Vowelless.Length > 2</div>
<div>
select item.Original;</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<b>Let Keyword</b></div>
<div>
<b><br /></b></div>
<div>
<div>
string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };</div>
<div>
IEnumerable<string> query =</div>
<div>
from n in names</div>
<div>
let vowelless = n.Replace ("a", "").Replace ("e", "").Replace ("i", "") .Replace ("o", "").Replace ("u", "")</div>
<div>
where vowelless.Length > 2 orderby vowelless</div>
<div>
select n; // Thanks to let, n is still in scope.</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
Interpreted Queries</h3>
<div>
<div>
LINQ provides two parallel architectures: local queries for local object collections, and <b>interpreted queries for remote data sources</b>.</div>
</div>
<div>
<br /></div>
<div>
Interpreted queries operate over sequences that implement <b>IQueryable<T>.</b></div>
<div>
<b><br /></b></div>
<div>
<b><br /></b></div>
<div>
<b>combined interpreted and local queries</b><br />
<b><br /></b>
<b><br /></b></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-64643322335131823922015-07-03T03:59:00.000-07:002015-07-03T04:00:50.023-07:00C# in Nutshell Chapter 7 - Collections<div dir="ltr" style="text-align: left;" trbidi="on">
<h3 style="text-align: left;">
Enumerator and Enumerable</h3>
<div>
IEnumerable can be thought of as “IEnumeratorProvider”</div>
<div>
<div>
string s = "Hello";</div>
<div>
// Because string implements IEnumerable, we can call GetEnumerator():</div>
<div>
IEnumerator rator = s.GetEnumerator();</div>
<div>
while (rator.MoveNext())</div>
<div>
{</div>
<div>
char c = (char) rator.Current;</div>
<div>
Console.Write (c + ".");</div>
<div>
}</div>
<div>
// Output: H.e.l.l.o.</div>
</div>
<div>
<br /></div>
<div>
<div>
Fortunately, you rarely need to write this sort of code, thanks to the foreach statement.</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<div>
IEnumerable<T> (and IEnumerable)</div>
<div>
Provides minimum functionality (enumeration only)</div>
<div>
<br /></div>
<div>
ICollection<T> (and ICollection)</div>
<div>
Provides medium functionality (e.g., the Count property)</div>
<div>
<br /></div>
<div>
IList <T>/IDictionary <K,V> and their nongeneric versions</div>
<div>
Provide maximum functionality (including “random” access by index/key)</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
ICollection<T> and ICollection</h3>
<div>
<div>
ICollection<T> is the standard interface for countable collections of objects. </div>
<div>
<br /></div>
<div>
It provides the ability to determine the size of a collection (Count), determine whether an item exists in the collection (Contains), copy the collection into an array (ToArray), and determine whether the collection is read-only (IsReadOnly). For writable collections, you can also Add, Remove, and Clear items from the collection. And since it extends IEnumerable<T>, it can also be traversed via the foreach statement.</div>
</div>
<div>
<br /></div>
<div>
<div>
The nongeneric ICollection is similar in providing a countable collection, but doesn’t provide functionality for altering the list or checking for element membership:</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
IList<T> and IList</h3>
<div>
IList<T> is the standard interface for collections indexable by position.</div>
<div>
<br /></div>
<div>
<div>
In addition to the functionality inherited from ICollection<T> and IEnumerable<T>, it provides the ability to read or write an element by position (via an indexer) and insert/remove by position:</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
IReadOnlyList<T></h3>
<div>
<div>
In order to interoperate with read-only Windows Runtime collections, Framework 4.5 introduces a new collection interface called IReadOnlyList<T>.</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-46568316335371255592015-07-03T02:21:00.000-07:002015-07-03T02:21:48.730-07:00C# in Nutshell Chapter 6 - Framework Fundamentals<div dir="ltr" style="text-align: left;" trbidi="on">
<h3 style="text-align: left;">
String</h3>
<div>
<div>
The static string.<b>IsNullOrEmpty</b> method is a useful shortcut for testing whether a given string is either null or empty.</div>
</div>
<div>
<br /></div>
string empty = string.<b>Empty</b><br />
"abc".<b>Contains</b>("a")<br />
"abc".<b>EndsWith</b>("a")<br />
"abc".<b>IndexOf</b>("a") // return 0;<br />
"abcdef".<b>StartsWith </b>("abc", StringComparison.InvariantCultureIgnoreCase)<br />
"abcde".<b>IndexOf </b>("CD", StringComparison.CurrentCultureIgnoreCase); // 2<br />
<br />
<b>LastIndexOf</b> is like IndexOf, but works backward through the string.<br />
<br />
<b>IndexOfAny</b> returns the first matching position of any one of a set of characters<br />
<br />
Console.Write ("ab,cd ef".IndexOfAny (new char[] {' ', ','} )); // 2<br />
Console.Write ("pas5w0rd".IndexOfAny ("0123456789".ToCharArray() )); // 3<br />
<br />
<b>LastIndexOfAny </b>does the same in the reverse direction.<br />
<br />
<h3 style="text-align: left;">
Manipulating strings</h3>
<div>
<div>
string left3 = "12345".Substring (0, 3); // left3 = "123";</div>
<div>
string mid3 = "12345".Substring (1, 3); // mid3 = "234";</div>
</div>
<div>
string end3 = "12345".Substring (2); // end3 = "345";</div>
<div>
<br /></div>
<div>
<div>
string s1 = "helloworld".Insert (5, ", "); // s1 = "hello, world"</div>
<div>
string s2 = s1.Remove (5, 2); // s2 = "helloworld";</div>
</div>
<div>
<br /></div>
<div>
<div>
PadLeft and PadRight pad a string to a given length with a specified character (or a space if unspecified). If the input string is longer than the padding length, the original string is returned</div>
<div>
unchanged.</div>
<div>
<br /></div>
<div>
Console.WriteLine ("12345".PadLeft (9, '*')); // ****12345</div>
<div>
Console.WriteLine ("12345".PadLeft (9)); // 12345</div>
<div>
<br /></div>
<div>
<div>
<b>TrimStart</b> and <b>TrimEnd </b>remove specified characters from the beginning or end of a string; <b>Trim </b>does both. By default, these functions remove whitespace characters (including spaces, tabs, new lines, and Unicode variations of these): </div>
<div>
<br /></div>
<div>
Console.WriteLine (" abc \t\r\n ".Trim().Length); // 3</div>
</div>
<div>
<br /></div>
<div>
<div>
<b>Replace </b>replaces all (non-overlapping) occurrences of a particular character or substring:</div>
<div>
<br /></div>
<div>
Console.WriteLine ("to be done".Replace (" ", " | ") ); // to | be | done</div>
<div>
Console.WriteLine ("to be done".Replace (" ", "") ); // tobedone</div>
</div>
<div>
<br /></div>
<div>
<b>ToUpper() ToLower() ToUpperInvariant() ToLowerInvariant()</b></div>
<div>
<b><br /></b></div>
<div>
<b><br /></b></div>
<div>
<div>
string[] words = "The quick brown fox".Split();</div>
<div>
string together = string.Join (" ", words); // The static Join method does the reverse of Split</div>
</div>
<div>
<br /></div>
<div>
<div>
The static <b>Concat </b>method is similar to Join but accepts only a params string array and applies no separator. Concat is exactly equivalent to the + operator.</div>
</div>
<div>
<br /></div>
<div>
<div>
string sentence = string.Concat ("The", " quick", " brown", " fox");</div>
<div>
string sameSentence = "The" + " quick" + " brown" + " fox";</div>
</div>
<div>
<br /></div>
<div>
<b>string.Format</b></div>
<div>
<b><br /></b></div>
<div>
<div>
string composite = "It's {0} degrees in {1} on this {2} morning";</div>
<div>
string s = string.Format (composite, 35, "Perth", DateTime.Now.DayOfWeek);</div>
<div>
// s == "It's 35 degrees in Perth on this Friday morning"</div>
</div>
<div>
<br /></div>
<div>
<div>
Each number in curly braces is called a format item. The number corresponds to the argument position and is optionally followed by:</div>
<div>
<ul style="text-align: left;">
<li>A comma and a minimum width to apply</li>
<li>A colon and a format string</li>
</ul>
</div>
<div>
The minimum width is useful for aligning columns. If the value is negative, the data is left-aligned; otherwise, it’s right-aligned. For example:</div>
<div>
<br /></div>
<div>
string composite = "Name={0,-20} Credit Limit={1,15:C}";</div>
<div>
Console.WriteLine (string.Format (composite, "Mary", 500));</div>
<div>
Console.WriteLine (string.Format (composite, "Elizabeth", 20000));</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
The equivalent without using string.Format is this:</div>
<div>
string s = "Name=" + "Mary".PadRight (20) + " Credit Limit=" + 500.ToString ("C").PadLeft (15);</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
<b>Comparing Strings</b></h3>
<div>
<div>
There are two basic algorithms for string comparison: ordinal and culture-sensitive. Ordinal comparisons interpret characters simply as numbers (according to their numeric Unicode value); culture-sensitive comparisons interpret characters with reference to a particular alphabet. There are two special cultures: the “current culture,” which is based on settings picked up from the computer’s control panel, and the “invariant culture,” which is the same on every computer (and closely matches</div>
<div>
American culture).</div>
</div>
<div>
<b><br /></b></div>
<div>
<div>
Despite ordinal’s limitations, <b>string’s == operator</b> always performs ordinal case sensitive comparison.The same goes for the instance version of <b>string.Equals</b> when called without arguments; this defines the “default” equality comparison behavior for the string type.</div>
</div>
<div>
<br /></div>
<div>
<div>
The following methods allow culture-aware or case-insensitive comparisons:</div>
<div>
<ul style="text-align: left;">
<li>public bool Equals(string value, StringComparison comparisonType);</li>
<li>public static bool Equals (string a, string b, StringComparison comparisonType);</li>
</ul>
</div>
<div>
<br /></div>
<div>
The static version is advantageous in that it still works if one or both of the strings are null. StringComparison is an enum defined as follows:</div>
<div>
<br /></div>
<div>
public enum StringComparison</div>
<div>
{</div>
<div>
CurrentCulture, // Case-sensitive</div>
<div>
CurrentCultureIgnoreCase,</div>
<div>
InvariantCulture, // Case-sensitive</div>
<div>
InvariantCultureIgnoreCase,</div>
<div>
Ordinal, // Case-sensitive</div>
<div>
<div>
OrdinalIgnoreCase</div>
<div>
}</div>
</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
String order comparison</h3>
<div>
<div>
String’s CompareTo instance method performs culture-sensitive, case-sensitive order comparison. Unlike the == operator, CompareTo does not use ordinal comparison: for ordering, a culture-sensitive algorithm is much more useful. Here’s the method’s definition:</div>
<div>
<br /></div>
<div>
public int CompareTo (string strB);</div>
</div>
<div>
<br /></div>
<div>
<div>
For other kinds of comparison, you can call the static <b>Compare </b>and <b>CompareOrdinal</b></div>
<div>
methods:</div>
<div>
<ol style="text-align: left;">
<li>public static int Compare (string strA, string strB, StringComparison comparisonType);</li>
<li>public static int Compare (string strA, string strB, bool ignoreCase, CultureInfo culture);</li>
<li>public static int Compare (string strA, string strB, bool ignoreCase);</li>
<li>public static int CompareOrdinal (string strA, string strB);</li>
</ol>
</div>
<div>
<br /></div>
</div>
<div>
<div>
Console.WriteLine ("Boston".CompareTo ("Austin")); // 1</div>
<div>
Console.WriteLine ("Boston".CompareTo ("Boston")); // 0</div>
<div>
Console.WriteLine ("Boston".CompareTo ("Chicago")); // −1</div>
</div>
<div>
<div>
Console.WriteLine ("ṻ".CompareTo ("ǖ")); // 0</div>
<div>
Console.WriteLine ("foo".CompareTo ("FOO")); // −1</div>
</div>
<div>
<br /></div>
<div>
<div>
By supplying a CultureInfo object, you can plug in any alphabet:</div>
<div>
// CultureInfo is defined in the System.Globalization namespace</div>
<div>
<br /></div>
<div>
CultureInfo german = CultureInfo.GetCultureInfo ("de-DE");</div>
<div>
int i = string.Compare ("Müller", "Muller", false, german);</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
<br />StringBuilder</h3>
<div>
<div>
The StringBuilder class (System.Text namespace) represents a mutable (editable) string. With a StringBuilder, you can Append, Insert, Remove, and Replace substrings without replacing the whole StringBuilder.</div>
</div>
<div>
<br /></div>
<div>
<div>
StringBuilder’s constructor optionally accepts an initial string value, as well as a starting size for its internal capacity (default is 16 characters). If you go above this, StringBuilder automatically resizes its internal structures to accommodate (at a slight performance cost) up to its maximum capacity (default is int.MaxValue). A popular use of StringBuilder is to build up a long string by repeatedly calling Append.</div>
</div>
<div>
<br /></div>
<div>
<div>
StringBuilder sb = new StringBuilder();</div>
<div>
for (int i = 0; i < 50; i++) sb.Append (i + ",");</div>
<div>
Console.WriteLine (sb.ToString())</div>
</div>
<div>
<br /></div>
<div>
<div>
In our example above, the expression i + "," means that we’re still repeatedly concatenating strings. However, this incurs only a small performance cost in that the strings in question are small</div>
<div>
and don’t grow with each loop iteration. For maximum performance, however, we could change the loop body to this: <b>{ sb.Append (i.ToString()); sb.Append (","); }</b></div>
</div>
<div>
<b><br /></b></div>
<div>
Methods: <b>AppendLine, AppendFormat, Remove, Insert, Replace</b><br />
<b><br /></b>
<br />
<h3 style="text-align: left;">
<b>Encoding object</b></h3>
</div>
<div>
<b><br /></b></div>
<div>
Encoding utf8 = Encoding.GetEncoding ("utf-8");<br />
<br />
Encoding chinese = Encoding.GetEncoding ("GB18030");<br />
<br />
The most common encodings can also be obtained through dedicated static prop-<br />
erties on Encoding:<br />
<br />
<ol style="text-align: left;">
<li>Encoding.UTF8</li>
<li>Encoding.Unicode</li>
<li>Encoding.UTF32</li>
<li>Encoding.ASCII</li>
</ol>
<div>
Encoding.GetEncodings()</div>
<div>
<br /></div>
<br />
<div>
foreach (EncodingInfo info in Encoding.GetEncodings())</div>
<div>
Console.WriteLine (info.Name);</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
Dates and Times<b><br /></b></h3>
<div>
<b>TimeSpan</b></div>
<div>
<br /></div>
<div>
A TimeSpan represents an interval of time—or a time of the day<br />
<br />
Constructors:<br />
<br />
<ol style="text-align: left;">
<li>public TimeSpan (int hours, int minutes, int seconds);</li>
<li>public TimeSpan (int days, int hours, int minutes, int seconds);</li>
<li>public TimeSpan (int days, int hours, int minutes, int seconds, int milliseconds);</li>
<li>public TimeSpan (long ticks); // Each tick = 100ns</li>
</ol>
</div>
<div>
Or more convenient to use static <b>From... </b>method:<br />
<br />
<ul style="text-align: left;">
<li>public static TimeSpan FromDays (double value);</li>
<li>public static TimeSpan FromHours (double value);</li>
<li>public static TimeSpan FromMinutes (double value);</li>
<li>public static TimeSpan FromSeconds (double value);</li>
<li>public static TimeSpan FromMilliseconds (double value);</li>
</ul>
</div>
<div>
For example:<br />
Console.WriteLine (new TimeSpan (2, 30, 0)); // 02:30:00<br />
Console.WriteLine (TimeSpan.FromHours (2.5)); // 02:30:00<br />
Console.WriteLine (TimeSpan.FromHours (−2.5)); // −02:30:00<br />
<br />
<br />
TimeSpan overloads the + and - operators:<br />
<br />
TimeSpan.FromHours(2) + TimeSpan.FromMinutes(30);</div>
<div>
TimeSpan.FromDays(10) - TimeSpan.FromSeconds(1); // 9.23:59:59<br />
<br /></div>
<div>
TimeSpan can also be used to represent the time of the day (the elapsed time since midnight). To obtain the current time of day, call <b>DateTime.Now.TimeOfDay</b> .</div>
<div>
<br /></div>
<div>
<h3 style="text-align: left;">
<br />DateTime and DateTimeOffset</h3>
</div>
<div>
<div>
A DateTime incorporates a <b>three-state flag</b> indicating whether the DateTime is relative to:</div>
<div>
<ul style="text-align: left;">
<li>The local time on the current computer</li>
<li>UTC (the modern equivalent of Greenwich Mean Time)</li>
<li>Unspecified</li>
</ul>
</div>
</div>
<div>
<div>
A DateTimeOffset is more specific—it stores the offset from UTC as a TimeSpan:</div>
<div>
<br /></div>
<div>
July 01 2007 03:00:00 −06:00</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<div>
This influences <b>equality comparisons,</b> which is the main factor in choosing between DateTime and DateTimeOffset. Specifically:</div>
<div>
<ul style="text-align: left;">
<li>DateTime ignores the three-state flag in comparisons and considers two values equal if they have the same year, month, day, hour, minute, and so on.</li>
<li>DateTimeOffset considers two values equal if they refer to the same point in time.</li>
</ul>
<div>
<div>
DateTime dt1 = new DateTime (2000, 1, 1, 10, 20, 30, DateTimeKind.Local);</div>
<div>
DateTime dt2 = new DateTime (2000, 1, 1, 10, 20, 30, DateTimeKind.Utc);</div>
<div>
Console.WriteLine (dt1 == dt2);</div>
<div>
DateTime local = DateTime.Now; // True</div>
<div>
DateTime utc = local.ToUniversalTime();</div>
<div>
Console.WriteLine (local == utc); // False</div>
<div>
<br /></div>
</div>
</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
DateTime considers the following two values different, whereas DateTimeOffset<br />
considers them equal:<br />
July 01 2007 09:00:00 +00:00 (GMT)<br />
July 01 2007 03:00:00 −06:00 (local time, Central America)</div>
<div>
<br />
<b>Convert from DateTime to DateTimeOffset</b><br />
<br /></div>
<div>
You can construct a DateTimeOffset from an existing DateTime either by using these<br />
constructors:<br />
<br />
<div style="text-align: left;">
public DateTimeOffset (DateTime dateTime);</div>
<div style="text-align: left;">
public DateTimeOffset (DateTime dateTime, TimeSpan offset);</div>
</div>
<div>
<br /></div>
<div>
or with an implicit cast. The implicit cast from DateTime to DateTimeOffset is handy because most of the .NET Framework supports DateTime—not DateTimeOffset.<br />
<br />
DateTimeOffset dt = new DateTime (2000, 2, 3);</div>
<div>
<br />
If you don’t specify an offset, it’s inferred from the DateTime value using these rules:<br />
<br />
<ul style="text-align: left;">
<li>If the DateTime has a DateTimeKind of Utc, the offset is zero.</li>
<li>If the DateTime has a DateTimeKind of Local or Unspecified (the default), the offset is taken from the current local time zone.</li>
</ul>
<div>
<br /></div>
</div>
<div>
<b>Convert from DateTimeOffset to DateTime</b></div>
<div>
<br /></div>
<div>
DateTimeOffset provides three properties that return values of type DateTime :<br />
<br />
<ol style="text-align: left;">
<li>The UtcDateTime property returns a DateTime in UTC time.</li>
<li>The LocalDateTime property returns a DateTime in the current local time zone (converting it if necessary).</li>
<li>The DateTime property returns a DateTime in whatever zone it was specified, with a Kind of Unspecified (i.e., it returns the UTC time plus the offset).</li>
</ol>
</div>
<div>
<br /></div>
<div>
TimeZone and TimeZoneInfo<br />
<br />
TimeZoneInfo was introduced in Framework 3.5. </div>
<div>
The biggest difference between the two types is that TimeZone lets you access only the current local time zone, whereas TimeZoneInfo provides access to all the world’s time zones. Further, TimeZoneInfo exposes a richer (although at times, more awkward) rules-based model for describing daylight saving time.</div>
<div>
<br /></div>
<div>
<br />
<h3 style="text-align: left;">
Tuples</h3>
</div>
<div>
Framework 4.0 introduced a new set of generic classes for holding a set of differently<br />
typed elements. These are called tuples.<br />
<br /></div>
<div>
You can instantiate a tuple either via its constructor or via the static helper method Tuple.Create:<br />
<br />
var t = new Tuple<int,string> (123, "Hello");<br />
Tuple<int,string> t = Tuple.Create (123, "Hello");</div>
<div>
<br />
You can then access the properties as follows (notice that each is statically typed):<br />
<br /></div>
<div>
Console.WriteLine (t.Item1 * 2); // 246<br />
Console.WriteLine (t.Item2.ToUpper()); // HELLO<br />
<br />
Tuples are convenient in returning more than one value from a method—or creating<br />
collections of value pairs (we’ll cover collections in the following chapter).<br />
<br />
An alternative to tuples is to use an object array. However, you then lose static type<br />
safety, incur the cost of boxing/unboxing for value types, and require clumsy casts<br />
that cannot be validated by the compiler:<br />
<br />
object[] items = { 123, "Hello" };<br />
Console.WriteLine ( ((int) items[0]) * 2) ;<br />
Console.WriteLine ( ((string) items[1]).ToUpper() );<br />
<br />
Comparing Tuples:<br />
<br />
var t1 = Tuple.Create (123, "Hello");<br />
var t2 = Tuple.Create (123, "Hello");<br />
Console.WriteLine (t1 == t2); // False<br />
Console.WriteLine (t1.Equals (t2)); // True<br />
<br />
<h3 style="text-align: left;">
Guid</h3>
The static Guid.NewGuid method generates a unique Guid:<br />
<br />
Guid g = Guid.NewGuid ();<br />
Console.WriteLine (g.ToString()); // 0d57629c-7d6e-4847-97cb-9e2fc25083fe<br />
<br />
To instantiate an existing value, you use one of the constructors. The two most useful constructors are:<br />
<br />
public Guid (byte[] b); // Accepts a 16-byte array<br />
public Guid (string g); // Accepts a formatted string<br />
<br />
Being a struct, a Guid honors value-type semantics; hence, the equality operator works.<br />
The static Guid.Empty property returns an empty Guid (all zeros). This is often used in place of null .</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<h3 style="text-align: left;">
Equality Comparison</h3>
</div>
<div>
There are three standard protocols that types can implement for equality comparison:<br />
<br />
<ol style="text-align: left;">
<li>The == and != operators</li>
<li>The virtual Equals method in object</li>
<li>The IEquatable<T> interface</li>
</ol>
<br />
</div>
<div>
<br />
<br />
1.<br />
Because object is a class (and so a reference type), object’s == operator uses referential equality to compare x and y. The result is false, because x and y each refer to different boxed objects on the heap. "==" and "!=" are operators, i.e. static and resolved at compiling time.<br />
<br />
int x = 5, y = 5;<br />
<br />
Console.WriteLine (x == y); // True<br />
<br />
object x = 5, y = 5;<br />
Console.WriteLine (x == y); // False<br />
<br />
<br />
2.<br />
Object.Equals method is resolved at runtime - according to the object's actual type. In this example below, it calls Int32’s Equals method, which applies value equality to the operands, returning true. With reference types, Equals performs referential equality comparison by default; with structs, Equals performs structural comparison by calling Equals on each of its fields.<br />
<br />
object x = 5, y = 5;<br />
Console.WriteLine (x.Equals (y)); // True<br />
<br />
Occasionally, you need to force referential equality comparison. The static object.<b>ReferenceEquals</b> method<br />
<br />
<br />
3.<br />
Since the Equals method has a parameter of type Object, a cast will be needed in order to be able to access class specific members. Tus A consequence of calling object.Equals is that it forces boxing on value types. This is undesirable in highly performance-sensitive scenarios because boxing is relatively expensive compared to the actual comparison.<br />
<br />
The idea is that IEquatable<T>, when implemented, gives the same result as calling object’s virtual Equals method—but more quickly. Most basic .NET types implement IEquatable<T>. You can use IEquatable<T> as a constraint in a generic type:<br />
<br />
class Test<T> where T : IEquatable<T><br />
{<br />
public bool IsEqual (T a, T b)<br />
{<br />
return a.Equals (b); // No boxing with generic T<br />
}<br />
}</div>
<div>
<br />
If we remove the generic constraint, the class would still compile, but a.Equals(b) would instead bind to the slower object.Equals (slower assuming T was a value type).<br />
<br />
<b>Note</b>. the runtime will use the IEquatable.Equals method <b>only </b>if you pass an object with the <b>same </b>type as defined in the interface implementation; otherwise, it will use the Object.Equals method.<br />
Therefore, in order to align the same result of both interface and object equals() method, we need to do both work: http://www.codeproject.com/Articles/20592/Implementing-IEquatable-Properly/<br />
<br />
<h3 style="text-align: left;">
<br />Order Comparison</h3>
</div>
<div>
The basic protocols for determining the order of objects:<br />
<br />
<ul style="text-align: left;">
<li>The IComparable interfaces (IComparable and IComparable<T>)</li>
<li>The > and < operators</li>
</ul>
<br />
</div>
<div>
The IComparable interfaces are defined as follows:<br />
<br />
<ul style="text-align: left;">
<li>public interface IComparable { int CompareTo (object other); }</li>
<li>public interface IComparable<in T> { int CompareTo (T other); }</li>
</ul>
<br />
</div>
<div>
<b><br /></b></div>
<div>
<b><br /></b></div>
<div>
<b><br /></b></div>
<div>
<b><br /></b></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-21648138159372285002015-07-01T04:15:00.001-07:002015-07-03T02:22:03.420-07:00C# in Nutshell Chapter 4 Advanced C#<div dir="ltr" style="text-align: left;" trbidi="on">
<h3 style="text-align: left;">
Delegates</h3>
<div>
A delegate is an object that knows how to call a method.</div>
<div>
<br /></div>
<div>
<div>
delegate int Transformer (int x);</div>
<div>
class Test</div>
<div>
{</div>
<div>
static void Main()</div>
<div>
{</div>
<div>
Transformer t = Square; // Create delegate instance</div>
<div>
int result = t(3); // Invoke delegate</div>
<div>
Console.WriteLine (result); // 9</div>
<div>
}</div>
</div>
<div>
<div>
static int Square (int x) { return x * x; }</div>
<div>
}</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
plug-in methods with Delegates </h3>
<div>
<div>
public delegate int Transformer (int x);</div>
<div>
class Util</div>
<div>
{</div>
<div>
public static void Transform (int[] values, Transformer t)</div>
<div>
{</div>
<div>
for (int i = 0; i < values.Length; i++)</div>
<div>
values[i] = t (values[i]);</div>
<div>
}</div>
<div>
}</div>
<div>
class Test</div>
<div>
{</div>
</div>
<div>
<div>
static void Main()</div>
<div>
{</div>
<div>
int[] values = { 1, 2, 3 };</div>
<div>
Util.Transform (values, Square); // Hook in the Square method</div>
<div>
foreach (int i in values)</div>
<div>
Console.Write (i + " "); // 1 4 9</div>
<div>
}</div>
<div>
<br /></div>
<div>
static int Square (int x) { return x * x; }</div>
<div>
}<br />
<br />
<h3 style="text-align: left;">
Multicast Delegates</h3>
All delegate instances have multicast capability. This means that a delegate instance<br />
can reference not just a single target method, but also a list of target methods. The<br />
+ and += operators combine delegate instances. For example:<br />
<br />
SomeDelegate d = SomeMethod1;<br />
d += SomeMethod2;<br />
<br />
Note. Delegates are immutable, so when you call += or −=, you’re in fact creating a new delegate instance and assigning it to the existing variable.<br />
<br />
If a multicast delegate has a nonvoid return type, the caller receives the return value from the last method to be invoked. The preceding methods are still called, but their return values are discarded.<br />
<br />
Multicast example:<br />
<br />
class Test<br />
{<br />
static void Main()<br />
{<br />
ProgressReporter p = WriteProgressToConsole;<br />
p += WriteProgressToFile;<br />
Util.HardWork (p);<br />
}<br />
static void WriteProgressToConsole (int percentComplete)<br />
{<br />
Console.WriteLine (percentComplete);<br />
}<br />
static void WriteProgressToFile (int percentComplete)<br />
{<br />
System.IO.File.WriteAllText ("progress.txt",<br />
percentComplete.ToString());<br />
}<br />
}<br />
<br />
<br />
<h3 style="text-align: left;">
Delegate v.s Interface</h3>
A problem that can be solved with a delegate can also be solved with an interface.<br />
<br />
A delegate design may be a better choice than an interface design if one or more of<br />
these conditions are true:<br />
• The interface defines only a single method.<br />
• Multicast capability is needed.<br />
• The subscriber needs to implement the interface multiple times.<br />
<br />
<br />
<h3 style="text-align: left;">
Delegate Parameter compatibility</h3>
When you call a method, you can supply arguments that have more specific types<br />
than the parameters of that method. This is ordinary polymorphic behavior. For<br />
exactly the same reason, a delegate can have more specific parameter types than its<br />
method target. This is called contravariance.<br />
<br />
<h3 style="text-align: left;">
Delegate Return type compatibility</h3>
<div>
<div>
If you call a method, you may get back a type that is more specific than what you</div>
<div>
asked for. This is ordinary polymorphic behavior. For exactly the same reason, a</div>
<div>
delegate target method may return a more specific type than described by the delegate.</div>
<div>
This is called covariance.</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
Events in Delegates</h3>
<div>
<div>
The main purpose of events is to prevent subscribers from interfering with each other.</div>
</div>
<div>
For example below, if we remove the event keyword from our example so that PriceChanged becomes an ordinary delegate field, our example would give the same results. However, Stock</div>
<div>
would be less robust, in that subscribers could do the following things to interfere</div>
<div>
with each other:</div>
<div>
<ol style="text-align: left;">
<li>Replace other subscribers by reassigning PriceChanged (instead of using the += operator).</li>
<li>Clear all subscribers (by setting PriceChanged to null).</li>
<li>Broadcast to other subscribers by invoking the delegate.</li>
</ol>
</div>
<div>
<div>
Code within the Stock type has full access to PriceChanged and can treat it as a delegate. Code outside of Stock can only perform += and −= operations on the PriceChanged event.</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<div>
public delegate void PriceChangedHandler (decimal oldPrice, decimal newPrice);</div>
<div>
<br /></div>
<div>
public class Stock</div>
<div>
{</div>
<div>
string symbol;</div>
<div>
decimal price;</div>
<div>
public Stock (string symbol) { this.symbol = symbol; }</div>
<div>
public event PriceChangedHandler PriceChanged;</div>
<div>
public decimal Price</div>
<div>
{</div>
<div>
get { return price; }</div>
<div>
set</div>
<div>
{</div>
<div>
if (price == value) return; // Exit if nothing has changed</div>
<div>
decimal oldPrice = price;</div>
<div>
price = value;</div>
<div>
if (PriceChanged != null) // If invocation list not</div>
<div>
PriceChanged (oldPrice, price); // empty, fire event.</div>
</div>
<div>
}</div>
<div>
}</div>
<div>
}</div>
<div>
<br /></div>
<h3 style="text-align: left;">
throw v.s. throw ex</h3>
<div>
<div>
try { ... }</div>
<div>
catch (Exception ex)</div>
<div>
{</div>
<div>
// Log error</div>
<div>
...</div>
<div>
throw; // Rethrow same exception</div>
<div>
}</div>
</div>
<div>
<br /></div>
<div>
<div>
If we replaced throw with throw ex, the example would still work, but the StackTrace property of the newly propagated exception would no longer reflect the original error.</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
Preprocessor Directives</h3>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br /></div>
</div>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-41886411956348492982015-06-30T22:59:00.000-07:002015-07-03T02:22:16.127-07:00C# Nutshell Chapter 3 Creating Types in C#<div dir="ltr" style="text-align: left;" trbidi="on">
<h3 style="text-align: left;">
Object Initializers</h3>
<div>
<div>
To simplify object initialization, any accessible fields or properties of an object can</div>
<div>
be set via an object initializer directly after construction.</div>
</div>
<div>
<br /></div>
<div>
<div>
public class Bunny</div>
<div>
{</div>
<div>
public string Name;</div>
<div>
public bool LikesCarrots;</div>
<div>
public bool LikesHumans;</div>
<div>
public Bunny () {}</div>
<div>
public Bunny (string n) { Name = n; }</div>
<div>
}</div>
</div>
<div>
<br /></div>
<div>
<div>
// Note parameterless constructors can omit empty parentheses</div>
<div>
Bunny b1 = new Bunny { Name="Bo", LikesCarrots=true, LikesHumans=false };</div>
<div>
Bunny b2 = new Bunny ("Bo") { LikesCarrots=true, LikesHumans=false };</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
Properties</h3>
<div>
<div>
Properties look like fields from the outside, but internally they contain logic, like</div>
<div>
methods do.</div>
</div>
<div>
<div>
A property is declared like a field, but with a get/set block added. Here’s how to</div>
<div>
implement CurrentPrice as a property:</div>
<div>
public class Stock</div>
<div>
{</div>
<div>
decimal currentPrice; // The private "backing" field</div>
<div>
public decimal CurrentPrice // The public property</div>
<div>
{</div>
<div>
get { return currentPrice; } set { currentPrice = value; }</div>
<div>
}</div>
<div>
}</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
Const v.s. static readonly</h3>
<div>
<div>
A static readonly field is also advantageous when exposing to</div>
<div>
other assemblies a value that might change in a later version.</div>
<div>
For instance, suppose assembly X exposes a constant as follows:</div>
<div>
public const decimal ProgramVersion = 2.3;</div>
<div>
If assembly Y references X and uses this constant, the value 2.3</div>
<div>
will be baked into assembly Y when compiled. This means that</div>
<div>
if X is later recompiled with the constant set to 2.4, Y will still</div>
<div>
use the old value of 2.3 until Y is recompiled. A static</div>
<div>
readonly field avoids this problem.</div>
<div>
Another way of looking at this is that any value that might</div>
<div>
change in the future is not constant by definition, and so should</div>
<div>
not be represented as one.</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
Structs</h3>
<div>
<div>
A struct is similar to a class, with the following key differences:</div>
<div>
<ul style="text-align: left;">
<li>• A struct is a value type, whereas a class is a reference type.</li>
<li>• A struct does not support inheritance (other than implicitly deriving from object, or more precisely, System.ValueType).</li>
</ul>
</div>
<div>
<br /></div>
<div>
A struct can have all the members a class can, except the following:</div>
<div>
<ul style="text-align: left;">
<li>• A parameterless constructor</li>
<li>• A finalizer</li>
<li>• Virtual members</li>
</ul>
</div>
</div>
<div>
<div>
public struct Point</div>
<div>
{</div>
<div>
int x = 1; // Illegal: cannot initialize field</div>
<div>
int y;</div>
<div>
public Point() {} // Illegal: cannot have</div>
<div>
// parameterless constructor</div>
<div>
public Point (int x) {this.x = x;} // Illegal: must assign field y</div>
<div>
}</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
Class Access Modifiers</h3>
<div>
<div>
<b>public</b></div>
<div>
Fully accessible. This is the implicit accessibility for members of an enum or</div>
<div>
interface.</div>
<div>
<b>internal</b></div>
<div>
Accessible only within containing assembly or friend assemblies. This is the</div>
<div>
default accessibility for non-nested types.</div>
<div>
<b>private</b></div>
<div>
Accessible only within containing type. This is the default accessibility for</div>
<div>
members of a class or struct.</div>
<div>
<b>protected</b></div>
<div>
Accessible only within containing type or subclasses.</div>
</div>
<div>
<br /></div>
<div>
<div>
<i>Class2 is accessible from outside its assembly; Class1 is not:</i></div>
<div>
<br /></div>
<div>
class Class1 {} // Class1 is internal (default)</div>
<div>
public class Class2 {}</div>
<div>
<br /></div>
<div>
<i>ClassB exposes field x to other types in the same assembly; ClassA does not:</i></div>
<div>
<br /></div>
<div>
class ClassA { int x; } // x is private (default)</div>
<div>
class ClassB { internal int x; }</div>
<div>
<br /></div>
<div>
<i>Functions within Subclass can call Bar but not Foo:</i></div>
<div>
<i><br /></i></div>
<div>
class BaseClass</div>
<div>
{</div>
<div>
void Foo() {} // Foo is private (default)</div>
<div>
protected void Bar() {}</div>
<div>
}</div>
<div>
class Subclass : BaseClass</div>
<div>
{</div>
<div>
void Test1() { Foo(); } // Error - cannot access Foo</div>
<div>
void Test2() { Bar(); } // OK</div>
<div>
}</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
Constructors and Inheritance</h3>
<div>
<div>
A subclass must declare its own constructors. The base class’s constructors are</div>
<div>
accessible to the derived class, but are never automatically inherited.</div>
</div>
<div>
<br /></div>
<div>
<div>
public class Baseclass</div>
<div>
{</div>
<div>
public int X;</div>
<div>
public Baseclass () { }</div>
<div>
public Baseclass (int x) { this.X = x; }</div>
<div>
}</div>
<div>
public class Subclass : Baseclass { }</div>
<div>
//<b>the following is illegal:</b></div>
<div>
Subclass s = new Subclass (123);</div>
</div>
<div>
<br /></div>
<div>
<div>
Subclass must hence “redefine” any constructors it wants to expose. In doing so,</div>
<div>
however, it can call any of the base class’s constructors with the base keyword:</div>
<div>
public class Subclass : Baseclass</div>
<div>
{</div>
<div>
public Subclass (int x) : base (x) { }</div>
<div>
}</div>
</div>
<div>
<br /></div>
<div>
<div>
If a constructor in a subclass omits the base keyword, the base type’s parameterless constructor is implicitly called. If the base class has no accessible parameterless constructor, subclasses are forced to use the base keyword in their constructors.</div>
</div>
<div>
<br /></div>
<div>
<div>
public class BaseClass</div>
<div>
{</div>
<div>
public int X;</div>
<div>
public BaseClass() { X = 1; } //without this, subclass has to use 'base' keyword</div>
<div>
}</div>
<div>
public class Subclass : BaseClass</div>
<div>
{</div>
<div>
public Subclass() { Console.WriteLine (X); } // 1</div>
<div>
}</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
Using Interface or Superclass</h3>
<div>
<div>
As a guideline:</div>
<div>
• Use classes and subclasses for types that naturally share an implementation.</div>
<div>
• Use interfaces for types that have independent implementations.</div>
<div>
Consider the following classes:</div>
<div>
abstract class Animal {}</div>
<div>
abstract class Bird : Animal {}</div>
<div>
abstract class Insect : Animal {}</div>
<div>
abstract class FlyingCreature : Animal {}</div>
<div>
abstract class Carnivore : Animal {}</div>
<div>
// Concrete classes:</div>
<div>
class Ostrich : Bird {}</div>
<div>
class Eagle : Bird, FlyingCreature, Carnivore {} // Illegal</div>
<div>
class Bee : Insect, FlyingCreature {} // Illegal</div>
<div>
class Flea : Insect, Carnivore {} // Illegal</div>
<div>
<br /></div>
<div>
The Eagle, Bee, and Flea classes do not compile because inheriting from multiple</div>
<div>
classes is prohibited. To resolve this, we must convert some of the types to interfaces.</div>
<div>
The question then arises, which types? Following our general rule, we could</div>
<div>
say that</div>
<div>
<b>insects share an implementation, and birds share an implementation, so</b></div>
<div>
<b>they remain classes. In contrast, flying creatures have independent mechanisms</b></div>
<div>
<b>for flying, and carnivores have independent strategies for eating animals,</b> </div>
<div>
so we</div>
<div>
would convert FlyingCreature and Carnivore to interfaces:</div>
<div>
interface IFlyingCreature {}</div>
<div>
interface ICarnivore {}</div>
</div>
<div>
<br /></div>
<h3 style="text-align: left;">
<br />Enum initialization</h3>
<div>
It is different from other type initialization. </div>
<div>
<br /></div>
<div>
public enum BorderSide { Left, Right, Top, Bottom }</div>
<div>
<div>
BorderSide topSide = BorderSide.Top;</div>
<div>
bool isTop = (topSide == BorderSide.Top); // true</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<h3 style="text-align: left;">
Enum Operator Type-safety Issues</h3>
<div>
<div>
Since an enum can be cast to and from its underlying integral type, the actual value</div>
<div>
it may have may fall outside the bounds of a legal enum member</div>
</div>
<div>
<br /></div>
<div>
<div>
BorderSide b = BorderSide.Bottom;</div>
<div>
b++; // No errors</div>
</div>
<div>
<br /></div>
<div>
An invalid BorderSide would break the following code:</div>
<div>
<br /></div>
<div>
<div>
void Draw (BorderSide side)</div>
<div>
{</div>
<div>
if (side == BorderSide.Left) {...}</div>
<div>
else if (side == BorderSide.Right) {...}</div>
<div>
else if (side == BorderSide.Top) {...}</div>
<div>
else {...} // Assume BorderSide.Bottom</div>
<div>
}</div>
</div>
<div>
<br /></div>
<div>
<div>
One solution is to add another else clause:</div>
<div>
...</div>
<div>
else if (side == BorderSide.Bottom) ...</div>
<div>
else throw new ArgumentException ("Invalid BorderSide: " + side, "side");</div>
<div>
<br /></div>
<div>
Another workaround is to explicitly check an enum value for validity. The static</div>
<div>
Enum.IsDefined method does this job:</div>
<div>
<br /></div>
<div>
BorderSide side = (BorderSide) 12345;</div>
<div>
Console.WriteLine (Enum.IsDefined (typeof (BorderSide), side)); // False</div>
</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-64935239089288118102015-06-29T06:40:00.000-07:002015-07-03T02:22:25.228-07:00C# Nutshell Chapter 1-2 Basics<div dir="ltr" style="text-align: left;" trbidi="on">
<h3 style="text-align: left;">
<b>"==" makes a compile-time decision</b></h3>
int x = 1;<br />
int y = 1;<br />
x == y // true<br />
<br />
object x = 1;<br />
object y = 1;<br />
x == y // false; referential equality from object's == operator<br />
<br />
<h3 style="text-align: left;">
<b>"Equals" is resolved at runtime, according to the object's actual type</b></h3>
object x = 1;<br />
object y = 1;<br />
x.Equals(y); //true<br />
<b><br /></b>
<br />
<h3 style="text-align: left;">
<b>object class static helper method providing null-safe equality comparision</b></h3>
object x = 3, y = 3;<br />
Console.WriteLine (object.Equals (x, y)); // True<br />
x = null;<br />
Console.WriteLine (object.Equals (x, y)); // False<br />
y = null;<br />
Console.WriteLine (object.Equals (x, y)); // True<br />
<br />
<h3 style="text-align: left;">
<b>implicitly assigned default value</b></h3>
static void Main()<br />
{<br />
int x;<br />
Console.WriteLine (x); // Compile-time error<br />
}<br />
<br />
<br />
class Test<br />
{<br />
static int x;<br />
static void Main() { Console.WriteLine (x); } // 0<br />
}<br />
<br />
<h3 style="text-align: left;">
<b>"ref" and "out" keywords</b></h3>
<br />
<ul style="text-align: left;">
<li>"ref" - pass in as reference rather than value</li>
<li>"out" - no need to be assigned before going into the function, but must be assigned before comes out of the function. </li>
<li>both "ef"and "out" are passed in by <b>reference</b></li>
</ul>
<br />
<h3 style="text-align: left;">
"params" modifier</h3>
<div>
<div>
The params parameter modifier may be specified on the last parameter of a method</div>
<div>
so that the method accepts any number of parameters of a particular type.</div>
</div>
<div>
<br /></div>
static int Sum (int a, int b, params int[] ints)<br />
{<br />
Console.WriteLine(a);<br />
Console.WriteLine(b);<br />
int sum = 0;<br />
for (int i = 0; i < ints.Length; i++)<br />
sum += ints[i]; // Increase sum by ints[i]<br />
return sum;<br />
}<br />
<br />
<h3 style="text-align: left;">
Optional parameters</h3>
void Foo (int x = 23) { Console.WriteLine (x); }<br />
Foo(); // 23<br />
<br />
Mandatory parameters must occur before optional parameters in both the method declaration and the method call public method that’s called from another assembly requires recompilation of both assemblies.<br />
<br />
void Foo (int x = 0, int y = 0) { Console.WriteLine (x + ", " + y); }<br />
void Test()<br />
{<br />
Foo(1); // 1, 0<br />
}<br />
<br />
<h3 style="text-align: left;">
Named arguments</h3>
Rather than identifying an argument by position, you can identify an argument by<br />
name.<br />
<br />
void Foo (int x, int y) { Console.WriteLine (x + ", " + y); }<br />
void Test()<br />
{<br />
Foo (y:2, x:1); // 1, 2<br />
}<br />
<br />
Named arguments are particularly useful in conjunction with optional parameters.<br />
For instance, consider the following method:<br />
void Bar (int a = 0, int b = 0, int c = 0, int d = 0) { ... }<br />
We can call this supplying only a value for d as follows:<br />
Bar (d:3);<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br /></div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-46540440693728642862015-01-23T05:56:00.001-08:002015-01-23T05:59:28.273-08:00Finding closet pair<div dir="ltr" style="text-align: left;" trbidi="on">
<b>Challenge</b><br />
<div>
<br /></div>
<div>
Assuming multiple points in a 2D dimension, what is the pair of points with <b>closest distance</b>? </div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<b>Naive brute-force solution</b></div>
<div>
<br /></div>
<div>
Double loop through all points in the scope and find the closest pair will cost O(n^2). However, we can improve and reduce the operational time to O(nlogn) as a smart algorithm demonstrates below.<br />
<br /></div>
<div>
<br /></div>
<div>
<b>O(nlogn) for closest pair</b></div>
<div>
<b><br /></b></div>
<div>
note that this is not the details for this algorithm, only the essentials/magics used in it.</div>
<div>
<br /></div>
<div>
Essentials:</div>
<div>
<ol style="text-align: left;">
<li>Sort points by x-cooridnate and y-cooridnate respectively and store in two arrays => Px, Py. This step will have running time of O(nlogn) with mergesort, which we discussed in one previous blog, or quick sort.</li>
<li>utilizing "divide and conquer paradigm" and construct recursive function as below:</li>
<li>split points by half => find the closest pair in left half => find the closest pair in right half => find the closest pair with 1 point in left half and 1 point in right half. here the last step, i.e.split_counting, is the difficulty.</li>
<li>By first observing the split_counting step, it has running time of O(n^2), because all points are possible candidates. however, by proof we see that<b> only the subsequent 7 points</b> in Py array can make a closest pair, which is:</li>
<ol>
<li>for i = 0, i in Py</li>
<ol>
<li>for j = i + 1, j in [i ... i + 7]</li>
<ol>
<li>count_cloest_pair(Pi, Pj)</li>
</ol>
</ol>
</ol>
<li>in the nested loop above, it has running time of O(n) only! this is the beauty of this algorithm.</li>
</ol>
</div>
<div>
<br /></div>
<div>
for this algorithm details and the mathematics proof, please google "closest pair algorithm".</div>
<div>
<br /></div>
<div>
<br /></div>
<div>
<br /></div>
</div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-42065777179532101072015-01-23T05:30:00.000-08:002015-01-23T05:30:57.231-08:00why study algorithm - quotation<div dir="ltr" style="text-align: left;" trbidi="on">
<span style="background-color: white; color: #221e1f; font-family: Verdana, arial, helvetica, sans-serif; font-size: 14px; font-style: italic; line-height: 19.6000003814697px; text-align: -webkit-center;">People who analyze algorithms have double happiness. First of all they experience the sheer beauty of elegant mathematical patterns that surround elegant computational procedures. Then they receive a practical payoff when their theories make it possible to get other jobs done more quickly and more economically. </span><b style="background-color: white; color: #221e1f; font-family: Verdana, arial, helvetica, sans-serif; font-size: 14px; font-style: italic; line-height: 19.6000003814697px; text-align: -webkit-center;">D. E. Knuth</b></div>
Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-80112122875168672862015-01-16T01:36:00.000-08:002015-01-19T05:03:24.338-08:00Mergesort used in inversion counting<div dir="ltr" style="text-align: left;" trbidi="on">
<i>Note. In order to understand the inversion counting method in this blog, you need to be familiar with mergesort algorithm first. Especially the "divide and conquer paradigm" concept applied in mergesort.</i><br />
<i><br /></i>
I have explained that mergesort can be done in O(n*log(n)) in previous blog <a href="http://xixiao001.blogspot.fi/2015/01/mergesort-study.html">here</a><br />
<i><br /></i>
<b>What is inversion</b><br />
<b><br /></b>
given an array A with length n, the number of inversion in this array equals to number of pairs (A[i], A[j]) with i < j and A[i] > A[j].<br />
<br />
example: array = {1,3,5,2,4,6}, the inversions are (5,2) (5,4) (3,2)<br />
<br />
<b>Why study inversion</b><br />
<b><br /></b>
for example: to study the similarity of movie taste for two people.<br />
identify 6 movies and give them to the two to rank according to their favors.<br />
input result from 1st person as array A and result from 2nd person as array B, then calculate the number of inversions to quantify their movie favor differences.<br />
<br />
<b>The design of inversion counting </b><br />
1.<br />
it uses <i>"divide and conquer paradigm" </i>and algorithm as below:<br />
<br />
count_inversion (array A)<br />
count_inversion (left half of A i,j < n/2)<br />
count_inversion (right half of A i,j > n/2)<br />
count_split_inversion (i < n/2 < j)<br />
<br />
at each level of count method, the operation carried out is "count_split_inversion". <b>The key challenge </b>is to make sure "count_split_inversion" method can be done in O(n) so that inversion counting can be done with O(nlog(n)).<br />
<br />
2, <b> </b>(brilliant idea!)<br />
Piggyback on mergesort!<br />
<br />
<b>sort_and_</b>count_inversion (array A)<br />
<b>sort_and_</b>count_inversion (left half of A i,j < n/2)<br />
<b>sort_and_</b>count_inversion (right half of A i,j > n/2)<br />
<b>merge_and</b>_count_split_inversion (i < n/2 < j)<br />
<br />
The reason to add mergesort, which has O(nlog(n)) is that it will reduce the inversion count complexity from O(n^2) to O(nlog(n)), and we will see as below:<br />
<br />
when do merge_and_count_split_inversion from "sorted left half A" and "sorted right half A", items are copied from them to an empty array (same as in mergesort). Now we can claim that: whenever we compare A[i] and A[j] if we found A[i] > A[j] (i<n/2<j) in this step , an inversion is found. this step is O(n).<br />
<br />
Therefore, the computational complexity at each level is O(n) and the total complexity is O(nlog(n)).<br />
<br />
<b>C# Implementation</b><br />
<pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4jSoyzPHJOZzqWOjvGCSjjF8JW-FsuIpBQjJbMwUfO-jdVeJG7ypN-QCDbiC87CSZtxWndeXEx8FN7OIIZnzN_smogCAxkDw-cjqQh-eP-jJfBhtX351oCInviMPheEedZGlqcYj2FTKQ/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> using System;
using System.Linq;
namespace InversionCount
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("please give a integer for the size of array, system will generate internal values and do sorting for you");
int size = int.Parse(Console.ReadLine());
int[] count = new int[size];
RandomizeArray(ref count);
SortAndCountInversion(count);
Console.ReadLine();
}
public static int[] SortAndCountInversion(int[] A)
{
if (A.Length == 1)
return A;
int size = A.Length;
int halfSize = A.Length / 2;
int[] A1 = new int[halfSize];
int[] A2 = new int[A.Length - halfSize];
Split<int>(A, halfSize, out A1, out A2);
int[] ResultA = SortAndCountInversion(A1);
int[] ResultB = SortAndCountInversion(A2);
return MergeAndCoutInversion(ResultA, ResultB);
}
private static int[] MergeAndCoutInversion(int[] ResultA, int[] ResultB)
{
int resultSize = ResultA.Length + ResultB.Length;
int[] resultArray = new int[resultSize];
int i = 0, j = 0;
for (int k = 0; k < resultSize; k++)
{
if (i == ResultA.Length)
resultArray[k] = ResultB[j++];
else if (j == ResultB.Length)
resultArray[k] = ResultA[i++];
else if (ResultA[i] <= ResultB[j])
resultArray[k] = ResultA[i++];
else if (ResultA[i] > ResultB[j])
{
for (int s = i; s < ResultA.Length; s++)
{
Console.WriteLine("{0} - {1}", ResultA[s], ResultB[j]);
}
resultArray[k] = ResultB[j++];
}
else
{
Console.WriteLine("odd!");
}
}
return resultArray;
}
public static void Split<T>(T[] array, int index, out T[] first, out T[] second)
{
first = array.Take(index).ToArray();
second = array.Skip(index).ToArray();
}
private static void RandomizeArray(ref int[] count)
{
int size = count.Length;
Random random = new Random();
int randomInt;
for (int i = 0; i < size; i++)
{
randomInt = random.Next(0, size);
count[i] = randomInt;
}
}
}
}
</code></pre>
<br />
<br />
<br />
<br />
<br />
<br />
<br /></div>Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0tag:blogger.com,1999:blog-3244758051901422207.post-53861299421842430502015-01-15T01:32:00.002-08:002015-01-16T06:39:50.382-08:00MergeSort study<div dir="ltr" style="text-align: left;" trbidi="on">
<b>MergeSort algorithm learning notes:</b><br />
<div>
<br /></div>
<div>
I am studying algorithm course in coursera to sharpen my CS understanding.</div>
<div>
<br /></div>
<div>
Karatsuba algorithm (KA) is the first algorithm in this course opened my eyes. I never thought of any faster algorithm can do better/faster than the grade 3 learned calculating algorithm. I plan to implement KA in another thread in C# and post it here.</div>
<div>
<br /></div>
<div>
Back to track, this thread is about MergeSort algorithm (MA). Teacher Tim Roughgarden introduced the MA with a simple example and illustrate further step by step why MA is faster than most of other O(n2) algorithm. </div>
<div>
<br /></div>
<div>
<u>Here is MA's sorting complexity explanation:</u></div>
<div>
<br /></div>
<div>
<ul style="text-align: left;">
<li>Each level of MA calculation has maxi. <i>6j</i> operations, given that <i>j</i> is the number of items in the current level array input in each recursive call). </li>
<li>MA has sum of <i>log2(n) + 1</i> levels (assume original level is level 0)</li>
<li>At any given level <i>j</i>, there are <i>2^j (2pwoer j)</i> number of recursive calls</li>
<li>At any given level <i>j</i>, each recursive call has array size <i>n/</i><i>2^j</i></li>
</ul>
<div>
We find out that the operations at any given level j is <i>2^j</i> * (6 *n/<i>2^j</i>) = 6n (<b>astonishingly independent of j ! isn't this cool!?</b>)<br />
<br /></div>
</div>
<div>
Finally, 6n (log2(n) + 1) is the total operations in MA.<br />
<br />
In summary, the reason Mergesort is fast is that its operations in each call is constant 6n and the level of recursive call is log2(n), which is flatter than f(n) = n. The drawback for mergesort is that it requires extra space to store the items when aggregating back from the left and right sub-streams.<br />
<br />
<br />
<b>C# implementation</b><br />
<pre style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;;background-image:URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4jSoyzPHJOZzqWOjvGCSjjF8JW-FsuIpBQjJbMwUfO-jdVeJG7ypN-QCDbiC87CSZtxWndeXEx8FN7OIIZnzN_smogCAxkDw-cjqQh-eP-jJfBhtX351oCInviMPheEedZGlqcYj2FTKQ/s320/codebg.gif);padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;"> using System;
using System.Linq;
namespace Mergesort
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("please give a integer for the size of array, system will generate internal values and do sorting for you");
int size = int.Parse(Console.ReadLine());
Random random = new Random();
int randomInt;
int[] count = new int[size];
for (int i = 0; i < size; i++)
{
randomInt = random.Next(0, size);
count[i] = randomInt;
}
int[] countResult = Mergesort(count);
foreach (int i in countResult)
{ Console.WriteLine(i); }
Console.ReadLine();
}
public static int[] Mergesort(int[] A)
{
if (A.Length == 1)
return A;
int size = A.Length;
int halfSize = A.Length / 2;
int[] A1 = new int[halfSize];
int[] A2 = new int[A.Length - halfSize];
Split<int>(A, halfSize, out A1, out A2);
int[] ResultA = Mergesort(A1);
int[] ResultB = Mergesort(A2);
return MergeTwoArray(ResultA, ResultB);
}
private static int[] MergeTwoArray(int[] ResultA, int[] ResultB)
{
int resultSize = ResultA.Length + ResultB.Length;
int[] resultArray = new int[resultSize];
int i = 0, j = 0;
for (int k = 0; k < resultSize; k++)
{
if (i == ResultA.Length)
resultArray[k] = ResultB[j++];
else if (j == ResultB.Length)
resultArray[k] = ResultA[i++];
else if (ResultA[i] <= ResultB[j])
resultArray[k] = ResultA[i++];
else
resultArray[k] = ResultB[j++];
}
return resultArray;
}
public static void Split<T>(T[] array, int index, out T[] first, out T[] second)
{
first = array.Take(index).ToArray();
second = array.Skip(index).ToArray();
}
}
}
</code></pre>
<b><br /></b>
<b><br /></b>
<div class="line number1 index0 alt2" style="background: none white !important; border-radius: 0px !important; border: 0px !important; bottom: auto !important; box-sizing: content-box !important; color: #cccccc; float: none !important; font-family: Consolas, 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace; font-size: 15px; height: auto !important; left: auto !important; line-height: 16.3350009918213px; margin: 0px !important; min-height: inherit !important; outline: 0px !important; overflow: visible !important; padding: 0px 1em !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; white-space: pre !important; width: auto !important;">
<br /></div>
</div>
<div>
<br /></div>
<div>
<br /></div>
</div>Anonymoushttp://www.blogger.com/profile/14238545552980844419noreply@blogger.com0