вторник, 27 ноября 2012 г.

Git вместе с Eclipse (EGit) - Урок

Версия 2.9

Урок описывает использование EGit, плагин Eclipse для использования распределенной системы контроля версий Git. Это руководство основан на Eclipse 4.2 (Juno)

1. Что такое EGit

EGit является представителем Eclipse Team для распределенной системы контроля версий Git. EGit позволяет выполнять команды Git из Eclipse IDE.
EGit основан на библиотеке JGit. JGit - библиотека, которая реализует функциональность Git на Java.

2. Консольный Git

Это руководство описывает использование EGit. Если вам нужно выучить использование консольного Git, вы можете использовать Git Tutorial как справочник.

3. Установка EGit

Большинство пакетов Eclipse 4.2 с Eclipse.org содержат EGit по умолчанию. В этом случае дополнительная установка не нужна.
Если EGit пропущен в вашей инсталляции Eclipse, вы можете установить его через Eclipse Update Manager через: Help → Install new Software. EGit может быть установлен по следующей URL: http://download.eclipse.org/egit/updates

Installing EGit

4. Первые шаги с EGit

Следующий раздел объясняет как создать репозиторий для одного проекта и повазывает как сделать "checkout" для существующего проекта из удаленного репозитория.

4.1. Put a new project under version control

Create a new Java project called de.vogella.git.first in Eclipse. Create the de.vogella.git.first package and the following class.
package de.vogella.git.first;

public class GitTest {
  public static void main(String[] args) {
    System.out.println("Git is fun");
  }
} 
Right click on your project, select Team → Share Project → Git. On the next dialog press the Create button.
Git repository creation wizard - Step 1
EGit will propose an directory outside your workspace. Enter your project name as Name for your local Git repository. Select the Finish button.
Git repository creation wizard - Step 2
The wizard shows you the settings for your local Git repository. Select the Finish button to put your repository under Git version control.
Git repository creation wizard - Step 3
You have created a local Git repository. The git repository is in this case directly stored in the specified folder in a .gitfolder. The following screenshot shows the directory structure based on the tree -a command.
Git repository creation result

4.2. Setup Gitignore

Create a .gitignore file in your project with the following content.
bin
.metadata 
All files and directories which apply to the pattern described in this file will be ignored by Git. In this example all files in the bin and the .metadata directory will be ignored.

4.3. Initial commit

The Git Staging View allows to stage changes and to commit them.
Open the Git Staging View via the menu Window → Show View → Other → Git → Git Staging.
Mark all files which have changed on drag them into the Staged Changes area.
Git Staging View - Add to staging index
Write a descriptive commmit message and press the Commit button which is hightlighted in the following screenshot.
Git Staging View - Commit
Now the first version of your Java project is under version control.

4.4. Making changes and commiting them

Change the System.out.println message in your GitTest class.
package de.vogella.git.first;

public class GitTest {
  public static void main(String[] args) {
    System.out.println("Git is cool");
  }
} 
Drag the file which you have changed into the Staged Changes area, write a good commit message and press the commit button.
Git Staging View - Add to staging index
This change will now be in your local Git repository.

4.5. Show changes

Open the Git repository view via the following menu entries: Window → Show View → Other → Git → Git Staging.
Select your project, right click on it and select Show in → History to see the timeline of changes.
If you select a commit you see the commit message and the involved files.
History View
Via right mouse click on an individual file you can compare this file with its ancestor (the commit before that) or with the current version in the workspace.

5. Commit messages

5.1. Importance of Git commit messages

The commit message describes the changes done by a commit and is used as the first point of checking the history of a Git repository.
A commit message should therefore be descriptive and informative without repeating the code changes.

5.2. Guidelines for useful commit messages

A commit message should have a header and a body. The header should be less than 50 characters and the body should wrap its text at 72 so that the commit messages is displayed well on the command line. The body should be separated by the header with an empty line.
The body should contain the reason why the change was made.
The commit message should be in present tense, e.g. "Add better error handling" instead of "Added better error handling".

5.3. Example

The following can serve as an example for a commit message.
Short summary (less than 50 characters)

Detailed explanation, if required, line break at around 72 characters
more stuff to describe... 

6. Repository view

EGit has a Git repository view which allow you to browse your repositories, checkout projects and manage your branches.

7. Clone existing project

EGit allows to clone an existing Git repository.
Select File → Import → Git → Project from Git.
Importing projects via EGit
Select URI in the next dialog.
URI selected in EGit
Press clone and enter the URL to your Git repository. Git supports several protocols, e.g. git:// and https://. You only have to paste the URL to the first line of the dialog, the rest will be filled out automatically.
Please note that some proxy servers block the git:// protocol. If you face issues, please try to use the https://protocol.
For example the following URI can be used to clone the example projects of the Eclipse 4 application development book: git@github.com:vogella/eclipse4book.git
URI entered in the dialog
After pressing next the system will allow you to import the existing branches. You should select at least master as this is typically the main development branch.
URI entered in the dialog
The next dialog allows you to specify where the project should be copied to and which branch should be initially selected.
Define target directory for Git repository
After the Git repository is cloned, EGit opens an additional import dialog which allows to import the Eclipse projects from the Git repository.
Importing projects
Once this dialog is completed, you have checked out (cloned) the projects into a local Git repository and you can use Git operation on these projects.

8. Использование EGit

8.1. Базовые операции

Once you have placed a project under version control you can start using team operations on your project. The team operations are available via right mouse click on your project. You can:
  • Select Team → Add, on the project node to add all files to version control.
  • Select "Team" -> "Commit", to commit your changes to the local Git repository.
  • Select "Team" -> "Push" to push your change to a remote Git repository (see the GitHub chapter).
  • "Team" -> "Tag" allows you to create and manage tags.

8.2. Слияние

EGit supports merging of branches to add the changes of one branch into another if this branch has not been changed. Select your project and Team → Merge to start the merge dialog.

8.3. Разрешение конфликтов слияния

If you pull in changes or merge a branch and you have conflicting changes, EGit will highlight the affected files. EGit also supports the resolution of these merge conflicts.
Right click on a file with merge conflicts and select Team → Merge Tool.
This opens a dialog, asking you which merge mode you would like to use. The easiest way to see the conflicting changes is to use the Use HEAD (the last local version) of conflicting files as merge mode. This way you see the original changes on the left side and the conflicting changes on the right side.
Selecting the merge model
You can manually edit the text on the left side or use the Copy current change from right to left button to copy the conflicting changes from right to left.
Seeing merge conflicts
Copy changes from right to left
Once you have manually merged the changes, select Team → Add from the context menu of the resource to mark the conflicts as resolved and commit the merge resolution via Team → Commit.

8.4. Git amend

Git amend allows to adjust the last commit. For example you can change the commit message. The Git Staging view allows to perform the Git amend command via the the highlighted button in the following screenshot.
Git amend in the Git Staging view

8.5. View the resource history

Select a resource and select Show in (Alt+Shift+W) -> History to see the commit history of this resource.

9. Ветвление

9.1. Что такое ветки?

Git allows you to create branches, e.g. independent copies of the source code which can be changed independently from each other. The default branch is called master.
Git allows you to create branches very fast and cheaply in terms of resource consumption. Developers are encouraged to use branches frequently.

9.2. Switch Branches

Right-click your project and select Team → Branch to create new branches or to switch between existing branches.

10. Blame annotations

EGit allows to add annotations to see which line was changed by whom and which commit. To enable this, right click on your file and select Team → Show Annotations.
Afterwards you can place the mouse on the left side of the editor and a popup will show the commit information.

11. Stash support for uncommited changes

11.1. Stash to save uncommitted changes

Git provides the stash command which allows to save the current uncommmitted changes and checkout the last committed revision.
This allows you to pull in the latest changes or to develop an urgent fix. Afterwards you can restore the stashed changes, which will reapply the changes to the current version of the source code.
In general using the stash command should be the exception in using Git. Typically you would create new branches for new features and switch between branches.

11.2. Stash via the Git repository view

Stashing is available in the Git repository View.
Stash changes in EGit
Stash changes in EGit
Stash changes in EGit

12. Git repository for multiple projects

12.1. Create a new repository

Eclipse allows to work with projects which are not included in the workspace.
To put several Eclipse projects into the same Git repository you can create a folder inside or outside your workspace and create the projects inside this folder. You can create a Git repository for this folder and all projects in this folder will be handled by the same repository. The best practice is to put the Git repository outsite of the Eclipse workspace.
You can import these projects into your workspace via File → Import → Git → Projects from Git
Import project from Git repository

12.2. Добавление проекта в существующий Git репозиторий

To add a new Eclipse project to an existing Git repository, select the project, right click on it and select Team → Share→ Git and select the existing Git repository.
Adding a project to an existing Git repository
EGit moves the projects to the repository and imports the project automatically into your workspace.

13. Tutorial: Create Git repository for multiple projects

Create two Java projects called de.vogella.egit.multi.java1 and de.vogella.egit.multi.java2. Do not use the default location (which would be the workspace) but use a subfolder called gitmulti.
Create at least on Java class in each project. Git is not able to save empty folders.
Afterwards select both projects, right click on them and select Team → Share → Git.
You create a new Git repository which contains both projects.

14. Использование EGit с Github

14.1. Github

Github is a popular hosting provider for Git projects and if you repository is public to everyone Github hosting is free. To use GitHub create an account on the Github Website. During the sign-up you will be asked to provide a "passphase". This "passphase" is later needed to push to Github from your local repository.

14.2. Create Repository in Github

Create a new repository on Github, e.g. "de.vogella.git.github".
After creation of your new repository Github tells you what to do if you would inport via the command line. As we are going to use EGit we can ignore this information.

14.3. Push проекта на Github

Create a new project "de.vogella.git.github" and put it under version control. Right-mouse click on your project and select "Team" -> "Push". A dialog pops up. Maintain the following data. Adjust the hightlighted line so that you are using your user and your project name.
git+ssh://git@github.com/vogella/de.vogella.git.github 
Maintain your passphase which you maintained during the Github setup.
Select your branch (you should currently only have master if you followed my tutorial), press "Add all branches spec" and select next.
Нажмите finish.
If you now select your github Dashboard and then your project you should see the commited files.

14.4. Clone repository from Github

Use the same URI you use to push to Github to clone the project into another workspace.

15. Интеграция Mylyn с Github

Eclipse Mylyn is a productively tool for programmers. There is a GitHub connector for Mylyn available, please seehttp://wiki.eclipse.org/EGit/GitHub/UserGuide for details. .

16. Hacking EGit - Getting the source code

EGit is self-hosted on git://egit.eclipse.org. You can clone the EGit code from the repository using EGit using the following URL git://egit.eclipse.org/jgit.git and git://egit.eclipse.org/egit.git.
You also need some libraries from Orbit. See Libraries from Orbit for getting these libraries.

17. Вопросы и обсуждение

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.com Google Group. I have created a short list how to create good questions which might also help you.

18. Ссылки и литература

18.2. vogella Resources

vogella Training Android and Eclipse Training from the vogella team
Android Tutorial Introduction to Android Programming
GWT Tutorial Program in Java and compile to JavaScript and HTML
Eclipse RCP Tutorial Create native applications in Java
JUnit Tutorial Test your application
Git Tutorial Put everything you have under distributed version control system

пятница, 23 ноября 2012 г.

Math render in Blogger

Sorry for my bad english.
I use MathJax, because it gives me perfect font quality (even exporting page as PDF file gives you perfect result). Downside is the low speed of rendering really big posts.

How to use

Add this lines to your post (in HTML mode):
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({ TeX: { extensions: ["color.js"] }});
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript">
</script>

Then surround math code by $ if you want inline math:
---> Do wou now formula $E=mc^{2}$?
Or by $$, if you want stand-alone math: $$E=mc^{2}$$
$E=mc^{2}$ - inline
$$E=mc^{2}$$ - stand-alone

That's all. Now you have math in your blog.

Configuration

Without this code math cannot be rendered at all.
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript">
</script>


This code gives you inline math:
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
</script>



This code includes color.js extension.

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({ TeX: { extensions: ["color.js"] }});
</script>
I need colors.js extension, because I use Lyx as the main math editor. By default, MathJax color formula in TeX mode, not LaTeX. Feel different, this code

{\color{blue}x_{1}+\cfrac{a_{12}}{a_{11}}x_{2}+\cfrac{a_{13}}{a_{11}}x_{3}+\cfrac{a_{14}}{a_{11}}x_{4}+...+\cfrac{a_{1n}}{a_{11}}x_{n}=\cfrac{b_{1}}{a_{11}}}

in LaTeX mode (with color.js) looks like:
$${\color{blue}x_{1}+\cfrac{a_{12}}{a_{11}}x_{2}+\cfrac{a_{13}}{a_{11}}x_{3}+\cfrac{a_{14}}{a_{11}}x_{4}+...+\cfrac{a_{1n}}{a_{11}}x_{n}=\cfrac{b_{1}}{a_{11}}}$$

but by default:
$${\color{blue}x}_{1}+\cfrac{a_{12}}{a_{11}}x_{2}+\cfrac{a_{13}}{a_{11}}x_{3}+\cfrac{a_{14}}{a_{11}}x_{4}+...+\cfrac{a_{1n}}{a_{11}}x_{n}=\cfrac{b_{1}}{a_{11}}$$

четверг, 22 ноября 2012 г.

Syntax Highliting in Blogger for Dynamic View Template


I use alexgorbatchev syntax highliter. It is a full guide to configure it for your blog. Sorry for my bad english.

How to create post with highlited code (Install CSS first):

It's ugly, but if you use Dynamic View in Blogger, you should add this code for each post in your blog (example for C++):
<!-- (1) This code should be at the beginning of the page -->
<style type="text/css">
    .height_600px_class {height: 600px;}
    .overflow_y_hidden_class {overflow-y: hidden !important;}
</style>





<!-- (2) This code must be situated after code (1) -->
<pre class="brush:cpp; class-name:'overflow_y_hidden_class'" style="height:400px; overflow:hidden;">
#include <iostream>

using namespace std;

int main()
{
    cout<<"Hello World!"<<endl;
}
</pre>


<!-- (3) This code should be situated at the end of the page -->
<script src="http://syntaxhighliter.narod2.ru/highlightLoader.js" type="text/javascript"></script>

Blogger's strange behavior

It looks very strange, but you can add the code snippets (1) and (3) only at one page of your blog. It works for me and I do not understand how it works, but i dont need it. So, you can try, but I can't guarantee that it will works for you.

How to create your own configuration:

  1. Download this version of Syntax Highliter. Extract the arhive and find the script folder. 
  2. Open the closure compiler website. (Note, I have some troubles with compiling new version, so I reccomend you download suggested version).
  3. Add the content of compiledScript to textfield on the left. (XML and  Java are already  added) I reccomend to use this version for people, who are not well at Javascript (like me), because you can easy debug your tactic by appending and deleting shBrush*.js.
  4. Add the content of shBrush[language].js file and append it in the textfield. Append it between 2nd and 3d "paragraph". The beginning of 3d paragraph looks like: (function(){function a(){this.regexList=[{regex:new XRegExp("(\\&l ...
  5. Repeat step 4. until all desired languages are added.
  6. Click the compile button. The compiled result is displayed on the right.
  7. On top there is a text "The code may also be accessed at default.js." right click and save the file under the link default.js 
  8. Move the file to your webserver 
  9. Create a new JS File and add
    eval(function()
    {
    try
     {
      doHighlight();
     }
     catch(e)
     {
      var elem = document.createElement('SCRIPT');
      elem.src="[REPLACE ME]";
      var theBody = document.getElementsByTagName('body')[0];
      theBody.appendChild(elem);
     }
    
  10. Replace [REPLACE ME] with the url to the compiled that you just created
  11. Save the the file that you created in step 9 and move it to your webserver.
  12. Install CSS styles (see "How to install CSS")
  13. Paste your source code inside this PRE tag (like in paragraph "How to create post")
  14. Import your own loader at the final of your post;

How To Install CSS:

    To install the CSS styles, required by SyntaxHighlighter, you will need to do this step only once: open the Blogger's Advanced Layout Designer and access the CSS editor. Copy and paste the contents of the following files:

среда, 21 ноября 2012 г.

Прямой ход Гаусса. Наглядная версия


Здесь я опишу наглядно классический способ приведения системы уравнений
$$\begin{cases} \begin{array}{c}
a_{11}x_{1}+a_{12}x_{2}+a_{13}x_{3}+a_{14}x_{4}+...+a_{1n}x_{n}=b_{1}\\
a_{21}x_{1}+a_{22}x_{2}+a_{23}x_{3}+a_{24}x_{4}+...+a_{2n}x_{n}=b_{2}\\
a_{31}x_{1}+a_{32}x_{2}+a_{33}x_{3}+a_{34}x_{4}+...+a_{3n}x_{n}=b_{3}\\
a_{41}x_{1}+a_{42}x_{2}+a_{43}x_{3}+a_{44}x_{4}+...+a_{4n}x_{n}=b_{4}\\
\begin{array}{c}
\cdots\\
a_{i1}x_{1}+a_{i2}x_{2}+a_{i3}x_{3}+a_{i4}x_{i}+...+a_{in}x_{n}=b_{i}\\
\cdots
\end{array}\\
a_{n1}x_{1}+a_{n2}x_{2}+a_{n3}x_{3}+a_{n4}x_{4}+...+a_{nn}x_{n}=b_{n}
\end{array} & \ (0)\end{cases}$$
к треугольному виду. Это не общий способ, но именно его обычно рассказывают на лекциях по численным методам.

Первый шаг

Полагаем, что $a_{11}\neq0$  и разделим на него первое уравнение. Перепишем систему с учетом этого преобразования.
$$\begin{cases}
\begin{array}{c}
{\color{blue}x_{1}+\cfrac{a_{12}}{a_{11}}x_{2}+\cfrac{a_{13}}{a_{11}}x_{3}+\cfrac{a_{14}}{a_{11}}x_{4}+...+\cfrac{a_{1n}}{a_{11}}x_{n}=\cfrac{b_{1}}{a_{11}}}\\
a_{21}x_{1}+a_{22}x_{2}+a_{23}x_{3}+a_{24}x_{4}+...+a_{2n}x_{n}=b_{2}\\
a_{31}x_{1}+a_{32}x_{2}+a_{33}x_{3}+a_{34}x_{4}+...+a_{3n}x_{n}=b_{3}\\
a_{41}x_{1}+a_{42}x_{2}+a_{43}x_{3}+a_{44}x_{4}+...+a_{4n}x_{n}=b_{4}\\
\begin{array}{c}
\cdots\\
a_{i1}x_{1}+a_{i2}x_{2}+a_{i3}x_{3}+a_{i4}x_{i}+...+a_{in}x_{n}=b_{i}\\
\cdots
\end{array}\\
a_{n1}x_{1}+a_{n2}x_{2}+a_{n3}x_{3}+a_{n4}x_{4}+...+a_{nn}x_{n}=b_{n}
\end{array} & \ (1.1)\end{cases}
 $$

Умножим первое уравнение на $a_{i1}$
$$\begin{cases}
\begin{array}{c}
{\color{blue}a_{i1}x_{1}+a_{i1}\cfrac{a_{12}}{a_{11}}x_{2}+a_{i1}\cfrac{a_{13}}{a_{11}}x_{3}+a_{i1}\cfrac{a_{14}}{a_{11}}x_{4}+...+a_{i1}\cfrac{a_{1n}}{a_{11}}x_{n}=a_{i1}\cfrac{b_{1}}{a_{11}}}\\
a_{21}x_{1}+a_{22}x_{2}+a_{23}x_{3}+a_{24}x_{4}+...+a_{2n}x_{n}=b_{2}\\
a_{31}x_{1}+a_{32}x_{2}+a_{33}x_{3}+a_{34}x_{4}+...+a_{3n}x_{n}=b_{3}\\
a_{41}x_{1}+a_{42}x_{2}+a_{43}x_{3}+a_{44}x_{4}+...+a_{4n}x_{n}=b_{4}\\
\begin{array}{c}
\cdots\\
a_{i1}x_{1}+a_{i2}x_{2}+a_{i3}x_{3}+a_{i4}x_{i}+...+a_{in}x_{n}=b_{i}\\
\cdots
\end{array}\\
a_{n1}x_{1}+a_{n2}x_{2}+a_{n3}x_{3}+a_{n4}x_{4}+...+a_{nn}x_{n}=b_{n}
\end{array} & \ (1.2)\end{cases}

 $$

и вычтем его из $i$ -го уравнения преобразованной системы:
$$

\begin{cases}
\begin{array}{c}
a_{i1}x_{1}+a_{i1}\cfrac{a_{12}}{a_{11}}x_{2}+a_{i1}\cfrac{a_{13}}{a_{11}}x_{3}+a_{i1}\cfrac{a_{14}}{a_{11}}x_{4}+...+a_{i1}\cfrac{a_{1n}}{a_{11}}x_{n}=a_{i1}\cfrac{b_{1}}{a_{11}}\\
a_{21}x_{1}+a_{22}x_{2}+a_{23}x_{3}+a_{24}x_{4}+...+a_{2n}x_{n}=b_{2}\\
a_{31}x_{1}+a_{32}x_{2}+a_{33}x_{3}+a_{34}x_{4}+...+a_{3n}x_{n}=b_{3}\\
a_{41}x_{1}+a_{42}x_{2}+a_{43}x_{3}+a_{44}x_{4}+...+a_{4n}x_{n}=b_{4}\\
\begin{array}{c}
\cdots\\
{\color{blue}\left(a_{i1}-a_{i1}\right)x_{1}+\left(a_{i2}-a_{i1}\cfrac{a_{12}}{a_{11}}\right)x_{2}+\left(a_{i4}-a_{i1}\cfrac{a_{14}}{a_{11}}\right)x_{i}+...+\left(a_{in}-a_{i1}\cfrac{a_{1n}}{a_{11}}\right)x_{n}=\left(b_{i}-a_{i1}\cfrac{b_{1}}{a_{11}}\right)}\\
\cdots
\end{array}\\
a_{n1}x_{1}+a_{n2}x_{2}+a_{n3}x_{3}+a_{n4}x_{4}+...+a_{nn}x_{n}=b_{n}
\end{array} & (1.3)\end{cases}


 $$
(немножко преобразуем)
$$



\begin{cases}
\begin{array}{c}
a_{i1}x_{1}+a_{i1}\cfrac{a_{12}}{a_{11}}x_{2}+a_{i1}\cfrac{a_{13}}{a_{11}}x_{3}+a_{i1}\cfrac{a_{14}}{a_{11}}x_{4}+...+a_{i1}\cfrac{a_{1n}}{a_{11}}x_{n}=a_{i1}\cfrac{b_{1}}{a_{11}}\\
a_{21}x_{1}+a_{22}x_{2}+a_{23}x_{3}+a_{24}x_{4}+...+a_{2n}x_{n}=b_{2}\\
a_{31}x_{1}+a_{32}x_{2}+a_{33}x_{3}+a_{34}x_{4}+...+a_{3n}x_{n}=b_{3}\\
a_{41}x_{1}+a_{42}x_{2}+a_{43}x_{3}+a_{44}x_{4}+...+a_{4n}x_{n}=b_{4}\\
\begin{array}{c}
\cdots\\
{\color{blue}\left(a_{i2}-a_{i1}\cfrac{a_{12}}{a_{11}}\right)x_{2}+\left(a_{i4}-a_{i1}\cfrac{a_{14}}{a_{11}}\right)x_{i}+...+\left(a_{in}-a_{i1}\cfrac{a_{1n}}{a_{11}}\right)x_{n}=\left(b_{i}-a_{i1}\cfrac{b_{1}}{a_{11}}\right)}\\
\cdots
\end{array}\\
a_{n1}x_{1}+a_{n2}x_{2}+a_{n3}x_{3}+a_{n4}x_{4}+...+a_{nn}x_{n}=b_{n}
\end{array} & (1.4)\end{cases}




 $$

обозначим $\left(a_{i2}-a_{i1}\cfrac{a_{12}}{a_{11}}\right)$  за $a_{i2}^{(1)}$  , $\left(a_{i3}-a_{i1}\cfrac{a_{13}}{a_{11}}\right)$   за $a_{i3}^{(1)}$  и так далее. Крато это записывается так: $a_{ij}^{(1)}=a_{ij}-a_{i1}\cfrac{a_{1j}}{a_{11}}$ , $i=\overline{2,\, n}$. Так же поступим с $\left(b_{i}-a_{i1}\cfrac{b_{1}}{a_{11}}\right)$, обозначив его за $b_{i}^{(1)}$. И вернем уравнение 1 в предыдущее состояние, чтобы не таскать за собой множитель $a_{i1}$, который мозолит глаза.
Получим систему:
$$\begin{cases}
\begin{array}{c}
{\color{blue}x_{1}+\cfrac{a_{12}}{a_{11}}x_{2}+\cfrac{a_{13}}{a_{11}}x_{3}+\cfrac{a_{14}}{a_{11}}x_{4}+...+\cfrac{a_{1n}}{a_{11}}x_{n}=\cfrac{b_{1}}{a_{11}}}\\
a_{21}x_{1}+a_{22}x_{2}+a_{23}x_{3}+a_{24}x_{4}+...+a_{2n}x_{n}=b_{2}\\
a_{31}x_{1}+a_{32}x_{2}+a_{33}x_{3}+a_{34}x_{4}+...+a_{3n}x_{n}=b_{3}\\
a_{41}x_{1}+a_{42}x_{2}+a_{43}x_{3}+a_{44}x_{4}+...+a_{4n}x_{n}=b_{4}\\
\begin{array}{c}
\cdots\\
{\color{blue}0+a_{i2}^{(1)}x_{2}+a_{i3}^{(1)}x_{3}+a_{i4}^{(1)}x_{i}+...+a_{in}^{(1)}x_{n}=b_{i}^{(1)}}\\
\cdots
\end{array}\\
a_{n1}x_{1}+a_{n2}x_{2}+a_{n3}x_{3}+a_{n4}x_{4}+...+a_{nn}x_{n}=b_{n}
\end{array} & (1.5)\end{cases}

 $$

Теперь распространим все, что мы сделали для $i$ -го уравнения на $p$  уравнений, где $p=\overline{2,\, n}$.

$$

\begin{cases}
\begin{array}{c}
x_{1}+\cfrac{a_{12}}{a_{11}}x_{2}+\cfrac{a_{13}}{a_{11}}x_{3}+\cfrac{a_{14}}{a_{11}}x_{4}+...+\cfrac{a_{1n}}{a_{11}}x_{n}=\cfrac{b_{1}}{a_{11}}\\
{\color{blue}0+a_{22}^{(1)}x_{2}+a_{23}^{(1)}x_{3}+a_{24}^{(1)}x_{4}+...+a_{2n}^{(1)}x_{n}=b_{2}^{(1)}}\\
{\color{blue}0+a_{32}^{(1)}x_{2}+a_{33}^{(1)}x_{3}+a_{34}^{(1)}x_{4}+...+a_{3n}^{(1)}x_{n}=b_{3}^{(1)}}\\
{\color{blue}0+a_{42}^{(1)}x_{2}+a_{43}^{(1)}x_{3}+a_{44}^{(1)}x_{4}+...+a_{4n}^{(1)}x_{n}=b_{4}^{(1)}}\\
\begin{array}{c}
\cdots\\
0+a_{i2}^{(1)}x_{2}+a_{i3}^{(1)}x_{3}+a_{i4}^{(1)}x_{i}+...+a_{in}^{(1)}x_{n}=b_{i}^{(1)}\\
\cdots
\end{array}\\
{\color{blue}0+a_{n2}^{(1)}x_{2}+a_{n3}^{(1)}x_{3}+a_{n4}^{(1)}x_{4}+...+a_{nn}^{(1)}x_{n}=b_{n}^{(1)}}
\end{array} & (1.6)\end{cases}


 $$


Второй шаг


На втором шаге из системы (1.5) исключается $x_{2}$  аналогичным образом.
$$

\begin{cases}
\begin{array}{c}
x_{1}+\cfrac{a_{12}}{a_{11}}x_{2}+\cfrac{a_{13}}{a_{11}}x_{3}+\cfrac{a_{14}}{a_{11}}x_{4}+...+\cfrac{a_{1n}}{a_{11}}x_{n}=\cfrac{b_{1}}{a_{11}}\\
0+a_{22}^{(1)}x_{2}+a_{23}^{(1)}x_{3}+a_{24}^{(1)}x_{4}+...+a_{2n}^{(1)}x_{n}=b_{2}^{(1)}\\
0+a_{32}^{(1)}x_{2}+a_{33}^{(1)}x_{3}+a_{34}^{(1)}x_{4}+...+a_{3n}^{(1)}x_{n}=b_{3}^{(1)}\\
0+a_{42}^{(1)}x_{2}+a_{43}^{(1)}x_{3}+a_{44}^{(1)}x_{4}+...+a_{4n}^{(1)}x_{n}=b_{4}^{(1)}\\
\begin{array}{c}
\cdots\\
0+a_{i2}^{(1)}x_{2}+a_{i3}^{(1)}x_{3}+a_{i4}^{(1)}x_{i}+...+a_{in}^{(1)}x_{n}=b_{i}^{(1)}\\
\cdots
\end{array}\\
0+a_{n2}^{(1)}x_{2}+a_{n3}^{(1)}x_{3}+a_{n4}^{(1)}x_{4}+...+a_{nn}^{(1)}x_{n}=b_{n}^{(1)}
\end{array} & (2.0)\end{cases}
 $$
$$

\begin{cases}
\begin{array}{c}
x_{1}+\cfrac{a_{12}}{a_{11}}x_{2}+\cfrac{a_{13}}{a_{11}}x_{3}+\cfrac{a_{14}}{a_{11}}x_{4}+...+\cfrac{a_{1n}}{a_{11}}x_{n}=\cfrac{b_{1}}{a_{11}}\\
0+x_{2}+\cfrac{a_{23}^{(1)}}{a_{22}^{(1)}}x_{3}+\cfrac{a_{24}^{(1)}}{a_{22}^{(1)}}x_{4}+...+\cfrac{a_{2n}^{(1)}}{a_{22}^{(1)}}x_{n}=\cfrac{b_{2}}{a_{22}^{(1)}}\\
0+0+a_{33}^{(2)}x_{3}+a_{34}^{(2)}x_{4}+...+a_{3n}^{(2)}x_{n}=b_{3}^{(2)}\\
0+0+a_{43}^{(2)}x_{3}+a_{44}^{(2)}x_{4}+...+a_{4n}^{(2)}x_{n}=b_{4}^{(2)}\\
\begin{array}{c}
\cdots\\
0+0+a_{i3}^{(2)}x_{3}+a_{i4}^{(2)}x_{i}+...+a_{in}^{(2)}x_{n}=b_{i}^{(2)}\\
\cdots
\end{array}\\
0+0+a_{n3}^{(2)}x_{3}+a_{n4}^{(2)}x_{4}+...+a_{nn}^{(2)}x_{n}=b_{n}^{(2)}
\end{array} & (2.1)\end{cases}

 $$
$$

a_{ij}^{(2)}=a_{ij}^{(1)}-a_{i2}^{(1)}\cfrac{a_{2j}^{(1)}}{a_{22}^{(1)}},\ b_{i}^{(2)}=b_{i}^{(1)}-a_{i2}^{(1)}\cfrac{b^{2}}{a_{22}^{(1)}};\ i,j=\overline{3,n}

$$
И так, пока не придем к последнему уравнению. Итак, в общих чертах:

1. Выбираем первое уравнение и делим его на $a_{11}$
  •  Выбираем второе уравнение. Копируем первое, умножаем копию на $a_{21}$  и вычитаем копию из второго.
  •  Повторяем предыдущий пункт для остальных уравнений.
2. Выбираем второе уравнение и делим его на $a_{22}$
  • Выбираем третье уравнение. Копируем второе, умножаем копию на $a_{32}$   и вычитаем копию из второго.
  • Повторяем предыдущий пункт для остальных уравнений.
3. Повторяем эти операции до окончания уравнений.








понедельник, 19 ноября 2012 г.

Tk Tutorial (rus) / Руководство по Tk.



Эта статья является любительским переводом этой статьи. Не стоит рассчитывать на 100% точность перевода. Кстати, нет возможности подсвечивать синтаксис Tcl, извините. Сейчас статья еще в процессе перевода, и в основном переводится только советы для Python. 
Содержание


Введение

Руководство разработано для помощи людям быстро освоить построение основного настольного пользовательского интерфейса с Tk, и в частности Tk 8.5, который является необычайно важным этапом в развитии проекта и сильно отличается от более старых версий Tk, которые широко известны народу.

Обратной сторона медали в том, что пока вы не знаете одну или две частные вещи, это фактически не означает значимость выпуска. По причинам обратной совместимости, пока в существующие программы не будут внесены изменения, они не станут сильно отличаться по виду. Таким образом, хотя это руководство безусловно окажется выгодным новичкам Tk, это также поможет существующим Tk разработчикам обновить свои знания. Это клише, но я не могу поверить, как много я узнал в написании этого руководства, и я использую Tk более пятнадцати лет.

Общее состояние документации Tk (вне Tcl-ориентированной справочной документации, которая превосходна), к сожалению, не на высоком уровне в настоящее время. Это особенно верно для разработчиков, использующих Tk из иных языков, чем Tcl, и разработчиков, работающих на различных платформах.

Что ж, это руководство, насколько это возможно, нацеливает разработчиков на три главные платформы (Windows, Mac, Linux), и также быть независимым от языка. Первоначально учебник будет охватывать Tcl, Ruby, Perl и Python. Со временем, могут быть добавлены дополнительные языки. Даже если Ваш язык не входит, скорее всего, вы все еще принести пользу; так как все языки используют те же основные библиотеки Tk, есть очевидно много совпадений.

Это также не справочное руководство, оно не будет охватывать все, только то необходимое, что нужно в 95% приложений. Остальное вы можете найти в справочной документации.

Для кого это руководство

Это руководство написано для разработчиков, которые разрабатывают инструменты и приложения на Tk. Оно также имеет отношение к GUI со кнопками, списками, чекбоксами, полями редактирования, 2D графикой и т. д. Таким образом, если вы ищите способ использования в TK внутреннего С кода, или хотите создать захватывающий 3D интерфейс, то это, вероятно, руководство не для вас.

Это руководство также не научит вас основам языка программирования Python, поэтому вы должны иметь базовое понимание языка к моменту прочтения. Кроме того, вы должны иметь начальные представления о настольных приложениях в целом, и хотя вы не должны быть дизайнером пользовательского интерфейса, некоторые знания дизайна GUI всегда полезны.


Наилучшая современная практика
Это руководство о построении современных Tk GUI, используя текущие инструменты, которые Tk может предложить. Оно о лучшем опыте, который вы должны перенять чтобы строить их.

Для большинства инструментов, вы бы и не подумали сказать что-то вроде этого, но Tk не тот случай. Tk имеет очень длинную эволюцию (смотрите Tk Backgrounder), и любая эволюция имеет тенденцию оставлять вас с кучкой хлама; наряду с тем, насколько много графические интерфейсы и стандарты эволюционировали со временем, вы можете наблюдать что для такого большого и составного как GUI библиотека проекта, обновление и хорошая обратная совместимость вместе - очень сложная задача.

Tk, в последние годы, сурово критиковали, мягко говоря. Частично это было заслуженно, но большинство отнюдь.Как и любой инструмент с графическим интерфейсом, он может быть использован для создания абсолютно ужасного вида и устаревших интерфейсов пользователя, но с соответствующей заботой и вниманием, он также может быть использован для создания невероятно хорошенького интерфейса. Большинство людей знают о плохих примерах; а о многих хороших примерах люди даже не думают, что они сделаны в Tk. В этом руководстве мы собираемся сосредоточиться на том, что вам нужно чтобы построить хорошие пользовательские интерфейсы, что не так трудно, как это было до Tk 8.5.

Так современные настольные графические пользовательские интерфейсы с использованием современных соглашений и чувства дизайна с использованием современных инструментов, предоставляемых Tk 8.5.

Расширения Tk

Когда речь заходит о лучшей современной практике, Tk расширения заслуживают особого слова к сведению. За эти годы некоторые группы предоставили все виды дополнения к Тk, например, добавив новые виджеты не доступные в ядре (или, по крайней мере, не в то время). Некоторые известные и весьма популярные Tk расширения включают BLT, Tix, iWidgets, BWidgets, есть многие, многие другие.

Многие из этих расширений были созданы года назад. Поскольку ядро Tk всегда был очень обратно совместимы, эти расширения в целом продолжают работать с более новыми версиями. Тем не менее, многие из них не были обновлены, или не были существенно обновлены, в течение длительного времени. Они могут не отражать текущее соглашение платформы или стилей и т. д. в то время как они "работают", они могут сделать ваши приложения выгядят очень древними или неуместными.

Если вы решите использовать Tk расширения, то настоятельно рекомендуем вам изучить и рассмотреть свой ​​выбор тщательно.

Лучше двигаться вперед

Tk также дает вам много вариантов выбора. Есть по крайней мере шесть различных способов расположить виджеты на экране, часто множество различных виджеты, которые могли бы сделать то же самое, особенно, если вы учитываете огромный ассортимент расширений к Tk, таких как Tix, BLT, BWidgets, ITK и другие. Большинство из них также постарше, большинство из них не обновляются и, следовательно, хреново выглядят, и во многих случаях они предоставляют средства не нужные при более новых и современных удобствах , недавно встроенных в сам Tk. Но по причине обратной совместимости, большинство этих старых способов делать вещи все еще продолжают работать, год за годом. Это не обязательно означает, что люди все равно должны использовать какие-нибудь из них.

Таким образом, есть много вариантов выбора в Tk, но, честно говоря, весь этот выбор встретится в пути. Если вы хотите изучить и использовать Tk, вам не нужны все варианты, вам нужен правильный выбор, так что вам не придется делать все исследования и делать выбор самостоятельно. Вот что это руководство даст вам. Рассматривайте это как эквивалент документации к упрямому программному обеспечению. Поэтому мы часто используем различные способы делать вещи, чем в другой документации или примерах, часто, это потому, что, когда те были написаны, лучшие способы даже не существовали. Позже, когда вы уже стали экспертом, и вы встретили некоторую дурацкую ситуацию, в которой нормальный выбор не подходит, вы можете пойти вокруг поохотиться на альтернативы.

Как использовать руководство

Хотя руководство предназначено для последовательного изучения, вы можете прыгать по нему туда-сюда как вам необходимо. Мы обычно публикуем ссылки на ресурсы, где вы можете получить больше информации, будь это ссылки на другую документацию на сайте, такую как наша "widget roundup" предоставляющая информацию по использованию каждого Tk виджета, или внешняя документация, такая как полные справочники по конкретным командам.

Руководство позволяет вам также увидеть как Tk используется разными языками, которые сами по себе могут быть интересны и чрезвычайно полезны.


Соглашения
Как это обычно делается, коды листингов, интерпретатора или команды оболочки и ответы будут обозначены шрифтом фиксированной ширины. При показе интерактивной сессии с переводчиком, те части, которые вы вводите, кроме того, будут полужирным шрифтом фиксированной ширины.
Иконки слева от текста используются так:
Этот параграф содержит материал, который специфичен для Tcl связок к Tk.
Этот параграф содержит материал, который специфичен для Ruby связок к Tk.
Этот параграф содержит материал, который специфичен для Perl связок к Tk.
Этот параграф содержит материал, который специфичен для Python связок к Tk.
Эта заметка поможет указать на общие ошибки, которые совершают люди, или предложить полезное, но не обязательно очевидное решение связанное с данной темой.
Эта заметка показывает новый способ делать старые вещи в Tk 8.5, потому что он значительно отличается о раннего. Людям,  знакомым со старыми  версиями Tk, или программами, разработанными со старыми версиями Tk, следует обратить особое внимание.
Этот параграф предоставляет некоторую фоновую информацию, не относящуюся прямо к теме, но помогающую понять немного лучше о том, как и почему вещи делаются этим, а не иным способом.
Эта заметка означает ошибку в самом руководстве, которая еще не была исправлена, или раздел, которые был удален, но не был замещен.
Эта заметка показывает область Tk, которая мило может быть названа как "грубый край". Она может свидетельствовать о плохом или пропущенном API, поэтому нужно идти в обход. Так как исправление этих вещей занимает длительное время, то мы в вашем коде маркируем их с помощью "TODO", и вы можете вспомнить о них позже, и посмотреть, не была ли исправлена данная проблема начисто новым API.